1 /*
   2  * Copyright (c) 2001, 2024, 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_RUNTIME_PERFDATA_HPP
  26 #define SHARE_RUNTIME_PERFDATA_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "runtime/perfDataTypes.hpp"
  30 #include "runtime/perfMemory.hpp"
  31 #include "runtime/timer.hpp"
  32 
  33 template <typename T> class GrowableArray;
  34 
  35 /* jvmstat global and subsystem counter name space - enumeration value
  36  * serve as an index into the PerfDataManager::_name_space[] array
  37  * containing the corresponding name space string. Only the top level
  38  * subsystem name spaces are represented here.
  39  */
  40 enum CounterNS {
  41   // top level name spaces
  42   JAVA_NS,
  43   COM_NS,
  44   SUN_NS,
  45   // subsystem name spaces
  46   JAVA_GC,              // Garbage Collection name spaces
  47   COM_GC,
  48   SUN_GC,
  49   JAVA_CI,              // Compiler name spaces
  50   COM_CI,
  51   SUN_CI,
  52   JAVA_CLS,             // Class Loader name spaces
  53   COM_CLS,
  54   SUN_CLS,
  55   JAVA_RT,              // Runtime name spaces
  56   COM_RT,
  57   SUN_RT,
  58   JAVA_OS,              // Operating System name spaces
  59   COM_OS,
  60   SUN_OS,
  61   JAVA_THREADS,         // Threads System name spaces
  62   COM_THREADS,
  63   SUN_THREADS,
  64   JAVA_THREADS_CPUTIME, // Thread CPU time name spaces
  65   COM_THREADS_CPUTIME,
  66   SUN_THREADS_CPUTIME,
  67   JAVA_PROPERTY,        // Java Property name spaces
  68   COM_PROPERTY,
  69   SUN_PROPERTY,
  70   NULL_NS,
  71   COUNTERNS_LAST = NULL_NS
  72 };
  73 
  74 /*
  75  * Classes to support access to production performance data
  76  *
  77  * The PerfData class structure is provided for creation, access, and update
  78  * of performance data (a.k.a. instrumentation) in a specific memory region
  79  * which is possibly accessible as shared memory. Although not explicitly
  80  * prevented from doing so, developers should not use the values returned
  81  * by accessor methods to make algorithmic decisions as they are potentially
  82  * extracted from a shared memory region. Although any shared memory region
  83  * created is with appropriate access restrictions, allowing read-write access
  84  * only to the principal that created the JVM, it is believed that the
  85  * shared memory region facilitates an easier attack path than attacks
  86  * launched through mechanisms such as /proc. For this reason, it is
  87  * recommended that data returned by PerfData accessor methods be used
  88  * cautiously.
  89  *
  90  * There are three variability classifications of performance data
  91  *   Constants  -  value is written to the PerfData memory once, on creation
  92  *   Variables  -  value is modifiable, with no particular restrictions
  93  *   Counters   -  value is monotonically changing (increasing or decreasing)
  94  *
  95  * The performance data items can also have various types. The class
  96  * hierarchy and the structure of the memory region are designed to
  97  * accommodate new types as they are needed. Types are specified in
  98  * terms of Java basic types, which accommodates client applications
  99  * written in the Java programming language. The class hierarchy is:
 100  *
 101  * - PerfData (Abstract)
 102  *     - PerfLong (Abstract)
 103  *         - PerfLongConstant        (alias: PerfConstant)
 104  *         - PerfLongVariant (Abstract)
 105  *             - PerfLongVariable    (alias: PerfVariable)
 106  *             - PerfLongCounter     (alias: PerfCounter)
 107  *
 108  *     - PerfByteArray (Abstract)
 109  *         - PerfString (Abstract)
 110  *             - PerfStringVariable
 111  *             - PerfStringConstant
 112  *
 113  *
 114  * As seen in the class hierarchy, the initially supported types are:
 115  *
 116  *    Long      - performance data holds a Java long type
 117  *    ByteArray - performance data holds an array of Java bytes
 118  *                used for holding C++ char arrays.
 119  *
 120  * The String type is derived from the ByteArray type.
 121  *
 122  * A PerfData subtype is not required to provide an implementation for
 123  * each variability classification. For example, the String type provides
 124  * Variable and Constant variability classifications in the PerfStringVariable
 125  * and PerfStringConstant classes, but does not provide a counter type.
 126  *
 127  * Performance data are also described by a unit of measure. Units allow
 128  * client applications to make reasonable decisions on how to treat
 129  * performance data generically, preventing the need to hard-code the
 130  * specifics of a particular data item in client applications. The current
 131  * set of units are:
 132  *
 133  *   None        - the data has no units of measure
 134  *   Bytes       - data is measured in bytes
 135  *   Ticks       - data is measured in clock ticks
 136  *   Events      - data is measured in events. For example,
 137  *                 the number of garbage collection events or the
 138  *                 number of methods compiled.
 139  *   String      - data is not numerical. For example,
 140  *                 the java command line options
 141  *   Hertz       - data is a frequency
 142  *
 143  * The performance counters also provide a support attribute, indicating
 144  * the stability of the counter as a programmatic interface. The support
 145  * level is also implied by the name space in which the counter is created.
 146  * The counter name space support conventions follow the Java package, class,
 147  * and property support conventions:
 148  *
 149  *    java.*          - stable, supported interface
 150  *    com.sun.*       - unstable, supported interface
 151  *    sun.*           - unstable, unsupported interface
 152  *
 153  * In the above context, unstable is a measure of the interface support
 154  * level, not the implementation stability level.
 155  *
 156  * Currently, instances of PerfData subtypes are considered to have
 157  * a life time equal to that of the VM and are managed by the
 158  * PerfDataManager class. All constructors for the PerfData class and
 159  * its subtypes have protected constructors. Creation of PerfData
 160  * instances is performed by invoking various create methods on the
 161  * PerfDataManager class. Users should not attempt to delete these
 162  * instances as the PerfDataManager class expects to perform deletion
 163  * operations on exit of the VM.
 164  *
 165  * Examples:
 166  *
 167  * Creating performance counter that holds a monotonically increasing
 168  * long data value with units specified in U_Bytes in the "java.gc.*"
 169  * name space.
 170  *
 171  *   PerfLongCounter* foo_counter;
 172  *
 173  *   foo_counter = PerfDataManager::create_long_counter(JAVA_GC, "foo",
 174  *                                                       PerfData::U_Bytes,
 175  *                                                       optionalInitialValue,
 176  *                                                       CHECK);
 177  *   foo_counter->inc();
 178  *
 179  * Creating a performance counter that holds a variably change long
 180  * data value with units specified in U_Bytes in the "com.sun.ci
 181  * name space.
 182  *
 183  *   PerfLongVariable* bar_variable;
 184  *   bar_variable = PerfDataManager::create_long_variable(COM_CI, "bar",
 185 .*                                                        PerfData::U_Bytes,
 186  *                                                        optionalInitialValue,
 187  *                                                        CHECK);
 188  *
 189  *   bar_variable->inc();
 190  *   bar_variable->set_value(0);
 191  *
 192  * Creating a performance counter that holds a constant string value in
 193  * the "sun.cls.*" name space.
 194  *
 195  *   PerfDataManager::create_string_constant(SUN_CLS, "foo", string, CHECK);
 196  *
 197  *   Although the create_string_constant() factory method returns a pointer
 198  *   to the PerfStringConstant object, it can safely be ignored. Developers
 199  *   are not encouraged to access the string constant's value via this
 200  *   pointer at this time due to security concerns.
 201  *
 202  * Creating a performance counter in an arbitrary name space that holds a
 203  * value that is sampled by the StatSampler periodic task.
 204  *
 205  *    PerfDataManager::create_counter("foo.sampled", PerfData::U_Events,
 206  *                                    &my_jlong, CHECK);
 207  *
 208  *    In this example, the PerfData pointer can be ignored as the caller
 209  *    is relying on the StatSampler PeriodicTask to sample the given
 210  *    address at a regular interval. The interval is defined by the
 211  *    PerfDataSamplingInterval global variable, and is applied on
 212  *    a system wide basis, not on an per-counter basis.
 213  *
 214  * Creating a performance counter in an arbitrary name space that utilizes
 215  * a helper object to return a value to the StatSampler via the take_sample()
 216  * method.
 217  *
 218  *     class MyTimeSampler : public PerfLongSampleHelper {
 219  *       public:
 220  *         jlong take_sample() { return os::elapsed_counter(); }
 221  *     };
 222  *
 223  *     PerfDataManager::create_counter(SUN_RT, "helped",
 224  *                                     PerfData::U_Ticks,
 225  *                                     new MyTimeSampler(), CHECK);
 226  *
 227  *     In this example, a subtype of PerfLongSampleHelper is instantiated
 228  *     and its take_sample() method is overridden to perform whatever
 229  *     operation is necessary to generate the data sample. This method
 230  *     will be called by the StatSampler at a regular interval, defined
 231  *     by the PerfDataSamplingInterval global variable.
 232  *
 233  *     As before, PerfSampleHelper is an alias for PerfLongSampleHelper.
 234  *
 235  * For additional uses of PerfData subtypes, see the utility classes
 236  * PerfTraceTime and PerfTraceTimedEvent below.
 237  *
 238  * Always-on non-sampled counters can be created independent of
 239  * the UsePerfData flag. Counters will be created on the c-heap
 240  * if UsePerfData is false.
 241  *
 242  * Until further notice, all PerfData objects should be created and
 243  * manipulated within a guarded block. The guard variable is
 244  * UsePerfData, a product flag set to true by default. This flag may
 245  * be removed from the product in the future.
 246  *
 247  */
 248 class PerfData : public CHeapObj<mtInternal> {
 249 
 250   friend class StatSampler;      // for access to protected void sample()
 251   friend class PerfDataManager;  // for access to protected destructor
 252   friend class VMStructs;
 253 
 254   public:
 255 
 256     // the Variability enum must be kept in synchronization with the
 257     // the com.sun.hotspot.perfdata.Variability class
 258     enum Variability {
 259       V_Constant = 1,
 260       V_Monotonic = 2,
 261       V_Variable = 3,
 262       V_last = V_Variable
 263     };
 264 
 265     // the Units enum must be kept in synchronization with the
 266     // the com.sun.hotspot.perfdata.Units class
 267     enum Units {
 268       U_None = 1,
 269       U_Bytes = 2,
 270       U_Ticks = 3,
 271       U_Events = 4,
 272       U_String = 5,
 273       U_Hertz = 6,
 274       U_Last = U_Hertz
 275     };
 276 
 277     // Miscellaneous flags
 278     enum Flags {
 279       F_None = 0x0,
 280       F_Supported = 0x1    // interface is supported - java.* and com.sun.*
 281     };
 282 
 283   private:
 284     char* _name;
 285     Variability _v;
 286     Units _u;
 287     bool _on_c_heap;
 288     Flags _flags;
 289 
 290     PerfDataEntry* _pdep;
 291 
 292   protected:
 293 
 294     void *_valuep;
 295 
 296     PerfData(CounterNS ns, const char* name, Units u, Variability v);
 297     virtual ~PerfData();
 298 
 299     // create the entry for the PerfData item in the PerfData memory region.
 300     // this region is maintained separately from the PerfData objects to
 301     // facilitate its use by external processes.
 302     void create_entry(BasicType dtype, size_t dsize, size_t dlen = 0);
 303 
 304     // sample the data item given at creation time and write its value
 305     // into the its corresponding PerfMemory location.
 306     virtual void sample() = 0;
 307 
 308   public:
 309 
 310     // returns a boolean indicating the validity of this object.
 311     // the object is valid if and only if memory in PerfMemory
 312     // region was successfully allocated.
 313     inline bool is_valid() { return _valuep != nullptr; }
 314 
 315     // returns a boolean indicating whether the underlying object
 316     // was allocated in the PerfMemory region or on the C heap.
 317     inline bool is_on_c_heap() { return _on_c_heap; }
 318 
 319     // returns a pointer to a char* containing the name of the item.
 320     // The pointer returned is the pointer to a copy of the name
 321     // passed to the constructor, not the pointer to the name in the
 322     // PerfData memory region. This redundancy is maintained for
 323     // security reasons as the PerfMemory region may be in shared
 324     // memory.
 325     const char* name() const { return _name; }
 326     bool name_equals(const char* name) const;
 327 
 328     // returns the variability classification associated with this item
 329     Variability variability() { return _v; }
 330 
 331     // returns the units associated with this item.
 332     Units units() { return _u; }
 333 
 334     // returns the flags associated with this item.
 335     Flags flags() { return _flags; }
 336 
 337     // returns the address of the data portion of the item in the
 338     // PerfData memory region.
 339     inline void* get_address() { return _valuep; }
 340 };
 341 
 342 /*
 343  * PerfLongSampleHelper, and its alias PerfSamplerHelper, is a base class
 344  * for helper classes that rely upon the StatSampler periodic task to
 345  * invoke the take_sample() method and write the value returned to its
 346  * appropriate location in the PerfData memory region.
 347  */
 348 class PerfLongSampleHelper : public CHeapObj<mtInternal> {
 349   public:
 350     virtual jlong take_sample() = 0;
 351 };
 352 
 353 /*
 354  * PerfLong is the base class for the various Long PerfData subtypes.
 355  * it contains implementation details that are common among its derived
 356  * types.
 357  */
 358 class PerfLong : public PerfData {
 359 
 360   protected:
 361 
 362     PerfLong(CounterNS ns, const char* namep, Units u, Variability v);
 363 
 364   public:
 365     // returns the value of the data portion of the item in the
 366     // PerfData memory region.
 367     inline jlong get_value() { return *(jlong*)_valuep; }
 368 };
 369 
 370 /*
 371  * The PerfLongConstant class, and its alias PerfConstant, implement
 372  * a PerfData subtype that holds a jlong data value that is set upon
 373  * creation of an instance of this class. This class provides no
 374  * methods for changing the data value stored in PerfData memory region.
 375  */
 376 class PerfLongConstant : public PerfLong {
 377 
 378   friend class PerfDataManager; // for access to protected constructor
 379 
 380   private:
 381     // hide sample() - no need to sample constants
 382     void sample() { }
 383 
 384   protected:
 385 
 386     PerfLongConstant(CounterNS ns, const char* namep, Units u,
 387                      jlong initial_value=0)
 388                     : PerfLong(ns, namep, u, V_Constant) {
 389 
 390        if (is_valid()) *(jlong*)_valuep = initial_value;
 391     }
 392 };
 393 
 394 /*
 395  * The PerfLongVariant class, and its alias PerfVariant, implement
 396  * a PerfData subtype that holds a jlong data value that can be modified
 397  * in an unrestricted manner. This class provides the implementation details
 398  * for common functionality among its derived types.
 399  */
 400 class PerfLongVariant : public PerfLong {
 401 
 402   protected:
 403     PerfLongSampleHelper* _sample_helper;
 404 
 405     PerfLongVariant(CounterNS ns, const char* namep, Units u, Variability v,
 406                     jlong initial_value=0)
 407                    : PerfLong(ns, namep, u, v) {
 408       if (is_valid()) *(jlong*)_valuep = initial_value;
 409     }
 410 
 411     PerfLongVariant(CounterNS ns, const char* namep, Units u, Variability v,
 412                     PerfLongSampleHelper* sample_helper);
 413 
 414     void sample();
 415 
 416   public:
 417     inline void inc() { (*(jlong*)_valuep)++; }
 418     inline void inc(jlong val) { (*(jlong*)_valuep) += val; }
 419     inline void dec(jlong val) { inc(-val); }
 420     inline void reset() { (*(jlong*)_valuep) = 0; }
 421 };
 422 
 423 /*
 424  * The PerfLongCounter class, and its alias PerfCounter, implement
 425  * a PerfData subtype that holds a jlong data value that can (should)
 426  * be modified in a monotonic manner. The inc(jlong) and add(jlong)
 427  * methods can be passed negative values to implement a monotonically
 428  * decreasing value. However, we rely upon the programmer to honor
 429  * the notion that this counter always moves in the same direction -
 430  * either increasing or decreasing.
 431  */
 432 class PerfLongCounter : public PerfLongVariant {
 433 
 434   friend class PerfDataManager; // for access to protected constructor
 435 
 436   protected:
 437 
 438     PerfLongCounter(CounterNS ns, const char* namep, Units u,
 439                     jlong initial_value=0)
 440                    : PerfLongVariant(ns, namep, u, V_Monotonic,
 441                                      initial_value) { }
 442 
 443     PerfLongCounter(CounterNS ns, const char* namep, Units u,
 444                     PerfLongSampleHelper* sample_helper)
 445                    : PerfLongVariant(ns, namep, u, V_Monotonic,
 446                                      sample_helper) { }
 447 };
 448 
 449 /*
 450  * The PerfLongVariable class, and its alias PerfVariable, implement
 451  * a PerfData subtype that holds a jlong data value that can
 452  * be modified in an unrestricted manner.
 453  */
 454 class PerfLongVariable : public PerfLongVariant {
 455 
 456   friend class PerfDataManager; // for access to protected constructor
 457 
 458   protected:
 459 
 460     PerfLongVariable(CounterNS ns, const char* namep, Units u,
 461                      jlong initial_value=0)
 462                     : PerfLongVariant(ns, namep, u, V_Variable,
 463                                       initial_value) { }
 464 
 465     PerfLongVariable(CounterNS ns, const char* namep, Units u,
 466                      PerfLongSampleHelper* sample_helper)
 467                     : PerfLongVariant(ns, namep, u, V_Variable,
 468                                       sample_helper) { }
 469 
 470   public:
 471     inline void set_value(jlong val) { (*(jlong*)_valuep) = val; }
 472 };
 473 
 474 /*
 475  * The PerfByteArray provides a PerfData subtype that allows the creation
 476  * of a contiguous region of the PerfData memory region for storing a vector
 477  * of bytes. This class is currently intended to be a base class for
 478  * the PerfString class, and cannot be instantiated directly.
 479  */
 480 class PerfByteArray : public PerfData {
 481 
 482   protected:
 483     jint _length;
 484 
 485     PerfByteArray(CounterNS ns, const char* namep, Units u, Variability v,
 486                   jint length);
 487 };
 488 
 489 class PerfString : public PerfByteArray {
 490 
 491   protected:
 492 
 493     void set_string(const char* s2);
 494 
 495     PerfString(CounterNS ns, const char* namep, Variability v, jint length,
 496                const char* initial_value)
 497               : PerfByteArray(ns, namep, U_String, v, length) {
 498        if (is_valid()) set_string(initial_value);
 499     }
 500 
 501 };
 502 
 503 /*
 504  * The PerfStringConstant class provides a PerfData sub class that
 505  * allows a null terminated string of single byte characters to be
 506  * stored in the PerfData memory region.
 507  */
 508 class PerfStringConstant : public PerfString {
 509 
 510   friend class PerfDataManager; // for access to protected constructor
 511 
 512   private:
 513 
 514     // hide sample() - no need to sample constants
 515     void sample() { }
 516 
 517   protected:
 518 
 519     // Restrict string constant lengths to be <= PerfMaxStringConstLength.
 520     // This prevents long string constants, as can occur with very
 521     // long classpaths or java command lines, from consuming too much
 522     // PerfData memory.
 523     PerfStringConstant(CounterNS ns, const char* namep,
 524                        const char* initial_value);
 525 };
 526 
 527 /*
 528  * The PerfStringVariable class provides a PerfData sub class that
 529  * allows a null terminated string of single byte character data
 530  * to be stored in PerfData memory region. The string value can be reset
 531  * after initialization. If the string value is >= max_length, then
 532  * it will be truncated to max_length characters. The copied string
 533  * is always null terminated.
 534  */
 535 class PerfStringVariable : public PerfString {
 536 
 537   friend class PerfDataManager; // for access to protected constructor
 538 
 539   protected:
 540 
 541     // sampling of string variables are not yet supported
 542     void sample() { }
 543 
 544     PerfStringVariable(CounterNS ns, const char* namep, jint max_length,
 545                        const char* initial_value)
 546                       : PerfString(ns, namep, V_Variable, max_length+1,
 547                                    initial_value) { }
 548 
 549   public:
 550     inline void set_value(const char* val) { set_string(val); }
 551 };
 552 
 553 
 554 /*
 555  * The PerfDataList class is a container class for managing lists
 556  * of PerfData items. The intention of this class is to allow for
 557  * alternative implementations for management of list of PerfData
 558  * items without impacting the code that uses the lists.
 559  *
 560  * The initial implementation is based upon GrowableArray. Searches
 561  * on GrowableArray types is linear in nature and this may become
 562  * a performance issue for creation of PerfData items, particularly
 563  * from Java code where a test for existence is implemented as a
 564  * search over all existing PerfData items.
 565  *
 566  * The abstraction is not complete. A more general container class
 567  * would provide an Iterator abstraction that could be used to
 568  * traverse the lists. This implementation still relies upon integer
 569  * iterators and the at(int index) method. However, the GrowableArray
 570  * is not directly visible outside this class and can be replaced by
 571  * some other implementation, as long as that implementation provides
 572  * a mechanism to iterate over the container by index.
 573  */
 574 class PerfDataList : public CHeapObj<mtInternal> {
 575 
 576   private:
 577 
 578     // GrowableArray implementation
 579     typedef GrowableArray<PerfData*> PerfDataArray;
 580 
 581     PerfDataArray* _set;
 582 
 583     // method to search for a instrumentation object by name
 584     static bool by_name(const char* name, PerfData* pd);
 585 
 586   protected:
 587     // we expose the implementation here to facilitate the clone
 588     // method.
 589     PerfDataArray* get_impl() { return _set; }
 590 
 591   public:
 592 
 593     // create a PerfDataList with the given initial length
 594     PerfDataList(int length);
 595 
 596     // create a PerfDataList as a shallow copy of the given PerfDataList
 597     PerfDataList(PerfDataList* p);
 598 
 599     ~PerfDataList();
 600 
 601     // return the PerfData item indicated by name,
 602     // or null if it doesn't exist.
 603     PerfData* find_by_name(const char* name);
 604 
 605     // return true if a PerfData item with the name specified in the
 606     // argument exists, otherwise return false.
 607     bool contains(const char* name) { return find_by_name(name) != nullptr; }
 608 
 609     // return the number of PerfData items in this list
 610     inline int length();
 611 
 612     // add a PerfData item to this list
 613     inline void append(PerfData *p);
 614 
 615     // create a new PerfDataList from this list. The new list is
 616     // a shallow copy of the original list and care should be taken
 617     // with respect to delete operations on the elements of the list
 618     // as the are likely in use by another copy of the list.
 619     PerfDataList* clone();
 620 
 621     // for backward compatibility with GrowableArray - need to implement
 622     // some form of iterator to provide a cleaner abstraction for
 623     // iteration over the container.
 624     inline PerfData* at(int index);
 625 };
 626 
 627 class PerfTickCounters : public CHeapObj<mtInternal> {
 628 private:
 629   const char* _name;
 630   PerfCounter* const _elapsed_counter;
 631   PerfCounter* const _thread_counter;
 632 public:
 633   PerfTickCounters(const char* name, PerfCounter* elapsed_counter, PerfCounter* thread_counter) :
 634                    _name(name), _elapsed_counter(elapsed_counter), _thread_counter(thread_counter) {
 635   }
 636 
 637   const char* name() { return _name; }
 638 
 639   PerfCounter* elapsed_counter() const {
 640     return _elapsed_counter;
 641   }
 642   long elapsed_counter_value() const {
 643     return _elapsed_counter->get_value();
 644   }
 645   inline jlong elapsed_counter_value_ms() const;
 646   inline jlong elapsed_counter_value_us() const;
 647 
 648   PerfCounter* thread_counter() const {
 649     return _thread_counter;
 650   }
 651   jlong thread_counter_value() const {
 652     return _thread_counter->get_value();
 653   }
 654   inline jlong thread_counter_value_ms() const;
 655   inline jlong thread_counter_value_us() const;
 656 
 657   void reset() {
 658     _elapsed_counter->reset();
 659     _thread_counter->reset();
 660   }
 661 };
 662 
 663 /*
 664  * The PerfDataManager class is responsible for creating PerfData
 665  * subtypes via a set a factory methods and for managing lists
 666  * of the various PerfData types.
 667  */
 668 class PerfDataManager : AllStatic {
 669 
 670   friend class StatSampler;   // for access to protected PerfDataList methods
 671 
 672   private:
 673     static PerfDataList* _all;
 674     static PerfDataList* _sampled;
 675     static PerfDataList* _constants;
 676     static const char* _name_spaces[];
 677     static volatile bool _has_PerfData;
 678 
 679     // add a PerfData item to the list(s) of know PerfData objects
 680     static void add_item(PerfData* p, bool sampled);
 681 
 682   protected:
 683 
 684     // return the list of all known PerfData items that are to be
 685     // sampled by the StatSampler.
 686     static PerfDataList* sampled();
 687 
 688   public:
 689 
 690     // method to check for the existence of a PerfData item with
 691     // the given name.
 692     static inline bool exists(const char* name);
 693 
 694     // method to map a CounterNS enumeration to a namespace string
 695     static const char* ns_to_string(CounterNS ns) {
 696       return _name_spaces[ns];
 697     }
 698 
 699     // methods to test the interface stability of a given counter namespace
 700     //
 701     static bool is_stable_supported(CounterNS ns) {
 702       return (ns != NULL_NS) && ((ns % 3) == JAVA_NS);
 703     }
 704     static bool is_unstable_supported(CounterNS ns) {
 705       return (ns != NULL_NS) && ((ns % 3) == COM_NS);
 706     }
 707 
 708     // methods to test the interface stability of a given counter name
 709     //
 710     static bool is_stable_supported(const char* name) {
 711       const char* javadot = "java.";
 712       return strncmp(name, javadot, strlen(javadot)) == 0;
 713     }
 714     static bool is_unstable_supported(const char* name) {
 715       const char* comdot = "com.sun.";
 716       return strncmp(name, comdot, strlen(comdot)) == 0;
 717     }
 718 
 719     // method to construct counter name strings in a given name space.
 720     // The string object is allocated from the Resource Area and calls
 721     // to this method must be made within a ResourceMark.
 722     //
 723     static char* counter_name(const char* name_space, const char* name);
 724 
 725     // method to construct name space strings in a given name space.
 726     // The string object is allocated from the Resource Area and calls
 727     // to this method must be made within a ResourceMark.
 728     //
 729     static char* name_space(const char* name_space, const char* sub_space) {
 730       return counter_name(name_space, sub_space);
 731     }
 732 
 733     // same as above, but appends the instance number to the name space
 734     //
 735     static char* name_space(const char* name_space, const char* sub_space,
 736                             int instance);
 737     static char* name_space(const char* name_space, int instance);
 738 
 739 
 740     // these methods provide the general interface for creating
 741     // performance data resources. The types of performance data
 742     // resources can be extended by adding additional create<type>
 743     // methods.
 744 
 745     // Constant Types
 746     static PerfStringConstant* create_string_constant(CounterNS ns,
 747                                                       const char* name,
 748                                                       const char *s, TRAPS);
 749 
 750     static PerfLongConstant* create_long_constant(CounterNS ns,
 751                                                   const char* name,
 752                                                   PerfData::Units u,
 753                                                   jlong val, TRAPS);
 754 
 755 
 756     // Variable Types
 757     static PerfStringVariable* create_string_variable(CounterNS ns,
 758                                                       const char* name,
 759                                                       int max_length,
 760                                                       const char *s, TRAPS);
 761 
 762     static PerfLongVariable* create_long_variable(CounterNS ns,
 763                                                   const char* name,
 764                                                   PerfData::Units u,
 765                                                   jlong ival, TRAPS);
 766 
 767     static PerfLongVariable* create_long_variable(CounterNS ns,
 768                                                   const char* name,
 769                                                   PerfData::Units u, TRAPS) {
 770       return create_long_variable(ns, name, u, (jlong)0, THREAD);
 771     };
 772 
 773     static PerfLongVariable* create_long_variable(CounterNS ns,
 774                                                   const char* name,
 775                                                   PerfData::Units u,
 776                                                   PerfLongSampleHelper* sh,
 777                                                   TRAPS);
 778 
 779 
 780     // Counter Types
 781     static PerfLongCounter* create_long_counter(CounterNS ns, const char* name,
 782                                                 PerfData::Units u,
 783                                                 jlong ival, TRAPS);
 784 
 785     static PerfLongCounter* create_long_counter(CounterNS ns, const char* name,
 786                                                 PerfData::Units u,
 787                                                 PerfLongSampleHelper* sh,
 788                                                 TRAPS);
 789 
 790 
 791     // these creation methods are provided for ease of use. These allow
 792     // Long performance data types to be created with a shorthand syntax.
 793 
 794     static PerfConstant* create_constant(CounterNS ns, const char* name,
 795                                          PerfData::Units u, jlong val, TRAPS) {
 796       return create_long_constant(ns, name, u, val, THREAD);
 797     }
 798 
 799     static PerfVariable* create_variable(CounterNS ns, const char* name,
 800                                          PerfData::Units u, jlong ival, TRAPS) {
 801       return create_long_variable(ns, name, u, ival, THREAD);
 802     }
 803 
 804     static PerfVariable* create_variable(CounterNS ns, const char* name,
 805                                          PerfData::Units u, TRAPS) {
 806       return create_long_variable(ns, name, u, (jlong)0, THREAD);
 807     }
 808 
 809     static PerfVariable* create_variable(CounterNS ns, const char* name,
 810                                          PerfData::Units u,
 811                                          PerfSampleHelper* sh, TRAPS) {
 812       return create_long_variable(ns, name, u, sh, THREAD);
 813     }
 814 
 815     static PerfCounter* create_counter(CounterNS ns, const char* name,
 816                                        PerfData::Units u, TRAPS) {
 817       return create_long_counter(ns, name, u, (jlong)0, THREAD);
 818     }
 819 
 820     static PerfCounter* create_counter(CounterNS ns, const char* name,
 821                                        PerfData::Units u,
 822                                        PerfSampleHelper* sh, TRAPS) {
 823       return create_long_counter(ns, name, u, sh, THREAD);
 824     }
 825 
 826     static PerfTickCounters* create_tick_counters(CounterNS ns,
 827                                                   const char* counter_name,
 828                                                   const char* elapsed_counter_name,
 829                                                   const char* thread_counter_name,
 830                                                   PerfData::Units u, TRAPS) {
 831       PerfCounter* elapsed_counter = create_long_counter(ns, elapsed_counter_name, u, (jlong)0, THREAD);
 832       PerfCounter* thread_counter = create_long_counter(ns, thread_counter_name, u, (jlong)0, THREAD);
 833 
 834       PerfTickCounters* counters = new PerfTickCounters(counter_name, elapsed_counter, thread_counter);
 835       return counters;
 836     }
 837 
 838     static void destroy();
 839     static bool has_PerfData() { return _has_PerfData; }
 840 };
 841 
 842 // Useful macros to create the performance counters
 843 #define NEWPERFTICKCOUNTER(counter, counter_ns, counter_name)  \
 844   {counter = PerfDataManager::create_counter(counter_ns, counter_name, \
 845                                              PerfData::U_Ticks,CHECK);}
 846 
 847 #define NEWPERFEVENTCOUNTER(counter, counter_ns, counter_name)  \
 848   {counter = PerfDataManager::create_counter(counter_ns, counter_name, \
 849                                              PerfData::U_Events,CHECK);}
 850 
 851 #define NEWPERFBYTECOUNTER(counter, counter_ns, counter_name)  \
 852   {counter = PerfDataManager::create_counter(counter_ns, counter_name, \
 853                                              PerfData::U_Bytes,CHECK);}
 854 
 855 #define NEWPERFTICKCOUNTERS(counter, counter_ns, counter_name)  \
 856   {counter = PerfDataManager::create_tick_counters(counter_ns, counter_name, counter_name "_elapsed_time", \
 857                                              counter_name "_thread_time", PerfData::U_Ticks,CHECK);}
 858 
 859 // Utility Classes
 860 
 861 /* PerfTraceElapsedTime and PerfTraceThreadTime will administer a PerfCounter used as a time accumulator
 862  * for a basic block much like the TraceTime class.
 863  * PerfTraceElapsedTime uses elapsedTimer to measure time which reflects the elapsed time,
 864  * and PerfTraceThreadTime uses ThreadTimer which reflects thread cpu time.
 865  *
 866  * Example:
 867  *
 868  *    static PerfCounter* my_time_counter = PerfDataManager::create_counter("my.time.counter", PerfData::U_Ticks, 0LL, CHECK);
 869  *
 870  *    {
 871  *      PerfTraceElapsedTime ptt(my_time_counter);
 872  *      // perform the operation you want to measure
 873  *    }
 874  *
 875  * Note: use of this class does not need to occur within a guarded
 876  * block. The UsePerfData guard is used with the implementation
 877  * of this class.
 878  */
 879 
 880 class PerfTraceTimeBase : public StackObj {
 881   friend class PerfPauseTimer;
 882   private:
 883     BaseTimer* _t;
 884   protected:
 885     PerfLongCounter* _counter;
 886 
 887   public:
 888     inline PerfTraceTimeBase(BaseTimer* t, PerfLongCounter* counter) : _t(t), _counter(counter) {}
 889 
 890     ~PerfTraceTimeBase();
 891 
 892     jlong active_ticks() { return _t->active_ticks(); }
 893 
 894     const char* name() { return _counter->name(); }
 895     BaseTimer* timer() { return _t; }
 896 };
 897 
 898 class PerfTraceElapsedTime: public PerfTraceTimeBase {
 899   protected:
 900     elapsedTimer _t;
 901 
 902   public:
 903     inline PerfTraceElapsedTime(PerfCounter* counter) : PerfTraceTimeBase(&_t, counter) {
 904       if (!UsePerfData || counter == nullptr) { return; }
 905       _t.start();
 906     }
 907 };
 908 
 909 class PerfTraceThreadTime: public PerfTraceTimeBase {
 910   protected:
 911     ThreadTimer _t;
 912 
 913   public:
 914     inline PerfTraceThreadTime(PerfCounter* counter) : PerfTraceTimeBase(&_t, counter) {
 915       if (!UsePerfData || !TraceThreadTime || counter == nullptr) { return; }
 916       _t.start();
 917     }
 918 };
 919 
 920 // PerfTraceTime is a utility class to provide the ability to measure both elapsed and thread cpu time using a single object.
 921 class PerfTraceTime : public StackObj {
 922   friend class PerfPauseTimer;
 923   private:
 924     PerfTickCounters* _counters;
 925     PerfTraceElapsedTime _elapsed_timer;
 926     PerfTraceThreadTime _thread_timer;
 927 
 928   public:
 929     inline PerfTraceTime(PerfTickCounters* counters, bool is_on = true):
 930                          _counters(counters),
 931                          _elapsed_timer(counters != nullptr ? counters->elapsed_counter() : nullptr),
 932                          _thread_timer(counters != nullptr ? counters->thread_counter() : nullptr) {}
 933 
 934     const char* name() { return _counters->name(); }
 935     PerfTraceTimeBase* elapsed_timer() { return &_elapsed_timer; }
 936     PerfTraceTimeBase* thread_timer() { return &_thread_timer; }
 937 
 938     jlong elapsed_timer_active_ticks() {
 939       return _elapsed_timer.active_ticks();
 940     }
 941 
 942     jlong thread_timer_active_ticks() {
 943       return _thread_timer.active_ticks();
 944     }
 945 };
 946 
 947 class PerfPauseTimerBase : public StackObj {
 948   protected:
 949     bool _is_active;
 950     BaseTimer* _timer;
 951 
 952   public:
 953     inline PerfPauseTimerBase(PerfTraceTimeBase* timer, bool is_on) : _is_active(false), _timer(nullptr) {
 954       _is_active = (is_on && timer != nullptr);
 955       if (UsePerfData && _is_active) {
 956         _timer = timer->timer();
 957         _timer->stop(); // pause
 958       }
 959     }
 960 
 961     inline ~PerfPauseTimerBase() {
 962       if (UsePerfData && _is_active) {
 963         assert(_timer != nullptr, "");
 964         _timer->start(); // resume
 965       }
 966     }
 967 };
 968 
 969 class PerfPauseTimer : public StackObj {
 970   private:
 971     PerfPauseTimerBase _elapsed_timer_pause;
 972     PerfPauseTimerBase _thread_timer_pause;
 973 
 974   public:
 975     inline PerfPauseTimer(PerfTraceTime* timer, bool is_on) :
 976                           _elapsed_timer_pause(timer != nullptr ? timer->elapsed_timer() : nullptr, is_on),
 977                           _thread_timer_pause(timer != nullptr ? timer->thread_timer() : nullptr, is_on) {}
 978 };
 979 
 980 /* The PerfTraceElapsedTimeEvent class is responsible for counting the
 981  * occurrence of some event and measuring the elapsed time of
 982  * the event in two separate PerfCounter instances.
 983  *
 984  * Example:
 985  *
 986  *    static PerfCounter* my_time_counter = PerfDataManager::create_counter("my.time.counter", PerfData::U_Ticks, CHECK);
 987  *    static PerfCounter* my_event_counter = PerfDataManager::create_counter("my.event.counter", PerfData::U_Events, CHECK);
 988  *
 989  *    {
 990  *      PerfTraceElapsedTimeEvent ptte(my_time_counter, my_event_counter);
 991  *      // perform the operation you want to count and measure
 992  *    }
 993  *
 994  * Note: use of this class does not need to occur within a guarded
 995  * block. The UsePerfData guard is used with the implementation
 996  * of this class.
 997  *
 998  * Similarly, PerfTraceThreadTimeEvent can count the occurrence of some event and measure the thread cpu time of the event.
 999  * PerfTraceTimedEvent can count the occurrence of some event and measure both the elapsed time and the thread cpu time of the event.
1000  */
1001 class PerfTraceElapsedTimeEvent: public PerfTraceElapsedTime {
1002   protected:
1003     PerfLongCounter* _eventp;
1004 
1005   public:
1006     inline PerfTraceElapsedTimeEvent(PerfCounter* counter, PerfLongCounter* eventp) : PerfTraceElapsedTime(counter), _eventp(eventp) {
1007       if (!UsePerfData || counter == nullptr) return;
1008       _eventp->inc();
1009     }
1010 };
1011 
1012 class PerfTraceThreadTimeEvent: public PerfTraceThreadTime {
1013   protected:
1014     PerfLongCounter* _eventp;
1015 
1016   public:
1017     inline PerfTraceThreadTimeEvent(PerfCounter* counter, PerfLongCounter* eventp) : PerfTraceThreadTime(counter), _eventp(eventp) {
1018       if (!UsePerfData || counter == nullptr) return;
1019       _eventp->inc();
1020     }
1021 };
1022 
1023 class PerfTraceTimedEvent : public PerfTraceTime {
1024   protected:
1025     PerfLongCounter* _eventp;
1026 
1027   public:
1028     inline PerfTraceTimedEvent(PerfTickCounters* counters, PerfLongCounter* eventp, bool is_on = true) : PerfTraceTime(counters, is_on), _eventp(eventp) {
1029       if (!UsePerfData || !is_on || counters == nullptr) return;
1030       _eventp->inc();
1031     }
1032 };
1033 #endif // SHARE_RUNTIME_PERFDATA_HPP