1 /*
   2  * Copyright (c) 2012, 2019, 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 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/classLoaderStats.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "code/codeCache.hpp"
  30 #include "compiler/compileBroker.hpp"
  31 #include "gc_implementation/shared/gcConfiguration.hpp"
  32 #include "gc_implementation/shared/gcTrace.hpp"
  33 #include "gc_implementation/shared/objectCountEventSender.hpp"
  34 #include "gc_implementation/shared/vmGCOperations.hpp"
  35 #include "jfr/periodic/jfrOSInterface.hpp"
  36 #include "jfr/periodic/jfrThreadCPULoadEvent.hpp"
  37 #include "jfr/periodic/jfrThreadDumpEvent.hpp"
  38 #include "jfr/recorder/jfrRecorder.hpp"
  39 #include "jfr/utilities/jfrTraceTime.hpp"
  40 #include "jfr/utilities/jfrLog.hpp"
  41 #include "memory/heapInspection.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "runtime/arguments.hpp"
  45 #include "runtime/globals.hpp"
  46 #include "runtime/os.hpp"
  47 #include "runtime/os_perf.hpp"
  48 #include "runtime/thread.inline.hpp"
  49 #include "runtime/sweeper.hpp"
  50 #include "runtime/vmThread.hpp"
  51 #include "services/classLoadingService.hpp"
  52 #include "services/management.hpp"
  53 #include "services/threadService.hpp"
  54 #include "trace/tracing.hpp"
  55 #include "tracefiles/tracePeriodic.hpp"
  56 #include "utilities/exceptions.hpp"
  57 #include "utilities/globalDefinitions.hpp"
  58 
  59 /**
  60  *  JfrPeriodic class
  61  *  Implementation of declarations in
  62  *  xsl generated traceRequestables.hpp
  63  */
  64 #define TRACE_REQUEST_FUNC(id)    void JfrPeriodicEventSet::request##id(void)
  65 
  66 TRACE_REQUEST_FUNC(JVMInformation) {
  67   ResourceMark rm;
  68   EventJVMInformation event;
  69   event.set_jvmName(VM_Version::vm_name());
  70   event.set_jvmVersion(VM_Version::internal_vm_info_string());
  71   event.set_javaArguments(Arguments::java_command());
  72   event.set_jvmArguments(Arguments::jvm_args());
  73   event.set_jvmFlags(Arguments::jvm_flags());
  74   event.set_jvmStartTime(Management::vm_init_done_time());
  75   event.commit();
  76  }
  77 
  78 TRACE_REQUEST_FUNC(OSInformation) {
  79   ResourceMark rm;
  80   char* os_name = NEW_RESOURCE_ARRAY(char, 2048);
  81   JfrOSInterface::os_version(&os_name);
  82   EventOSInformation event;
  83   event.set_osVersion(os_name);
  84   event.commit();
  85 }
  86 
  87 /*
  88  * This is left empty on purpose, having ExecutionSample as a requestable
  89  * is a way of getting the period. The period is passed to ThreadSampling::update_period.
  90  * Implementation in jfrSamples.cpp
  91  */
  92 TRACE_REQUEST_FUNC(ExecutionSample) {
  93 }
  94 TRACE_REQUEST_FUNC(NativeMethodSample) {
  95 }
  96 
  97 TRACE_REQUEST_FUNC(ThreadDump) {
  98   ResourceMark rm;
  99   EventThreadDump event;
 100   event.set_result(JfrDcmdEvent::thread_dump());
 101   event.commit();
 102 }
 103 
 104 static int _native_library_callback(const char* name, address base, address top, void *param) {
 105   EventNativeLibrary event(UNTIMED);
 106   event.set_name(name);
 107   event.set_baseAddress((u8)base);
 108   event.set_topAddress((u8)top);
 109   event.set_endtime(*(JfrTraceTime*) param);
 110   event.commit();
 111   return 0;
 112 }
 113 
 114 TRACE_REQUEST_FUNC(NativeLibrary) {
 115   JfrTraceTime ts(Tracing::time());
 116   os::get_loaded_modules_info(&_native_library_callback, (void *)&ts);
 117 }
 118 
 119 TRACE_REQUEST_FUNC(InitialEnvironmentVariable) {
 120   JfrOSInterface::generate_initial_environment_variable_events();
 121 }
 122 
 123 TRACE_REQUEST_FUNC(CPUInformation) {
 124   CPUInformation cpu_info;
 125   int ret_val = JfrOSInterface::cpu_information(cpu_info);
 126   if (ret_val == OS_ERR) {
 127     log_debug(jfr, system)( "Unable to generate requestable event CPUInformation");
 128     return;
 129   }
 130   if (ret_val == FUNCTIONALITY_NOT_IMPLEMENTED) {
 131      return;
 132   }
 133   if (ret_val == OS_OK) {
 134     EventCPUInformation event;
 135     event.set_cpu(cpu_info.cpu_name());
 136     event.set_description(cpu_info.cpu_description());
 137     event.set_sockets(cpu_info.number_of_sockets());
 138     event.set_cores(cpu_info.number_of_cores());
 139     event.set_hwThreads(cpu_info.number_of_hardware_threads());
 140     event.commit();
 141   }
 142 }
 143 
 144 TRACE_REQUEST_FUNC(CPULoad) {
 145   double u = 0; // user time
 146   double s = 0; // kernel time
 147   double t = 0; // total time
 148   int ret_val = JfrOSInterface::cpu_loads_process(&u, &s, &t);
 149   if (ret_val == OS_ERR) {
 150     log_debug(jfr, system)( "Unable to generate requestable event CPULoad");
 151     return;
 152   }
 153   if (ret_val == OS_OK) {
 154     EventCPULoad event;
 155     event.set_jvmUser((float)u);
 156     event.set_jvmSystem((float)s);
 157     event.set_machineTotal((float)t);
 158     event.commit();
 159   }
 160 }
 161 
 162 TRACE_REQUEST_FUNC(ThreadCPULoad) {
 163   JfrThreadCPULoadEvent::send_events();
 164 }
 165 
 166 TRACE_REQUEST_FUNC(CPUTimeStampCounter) {
 167   EventCPUTimeStampCounter event;
 168   event.set_fastTimeEnabled(JfrTraceTime::is_ft_enabled());
 169   event.set_fastTimeAutoEnabled(JfrTraceTime::is_ft_supported());
 170   event.set_osFrequency(os::elapsed_frequency());
 171   event.set_fastTimeFrequency(JfrTraceTime::frequency());
 172   event.commit();
 173 }
 174 
 175 TRACE_REQUEST_FUNC(SystemProcess) {
 176   char pid_buf[16];
 177   SystemProcess* processes = NULL;
 178   int num_of_processes = 0;
 179   JfrTraceTime start_time(Tracing::time());
 180   int ret_val = JfrOSInterface::system_processes(&processes, &num_of_processes);
 181   if (ret_val == OS_ERR) {
 182     log_debug(jfr, system)( "Unable to generate requestable event SystemProcesses");
 183     return;
 184   }
 185   JfrTraceTime end_time(Tracing::time());
 186   if (ret_val == FUNCTIONALITY_NOT_IMPLEMENTED) {
 187     return;
 188   }
 189   if (ret_val == OS_OK) {
 190     // feature is implemented, write real event
 191     while (processes != NULL) {
 192       SystemProcess* tmp = processes;
 193       const char* info = processes->command_line();
 194       if (info == NULL) {
 195          info = processes->path();
 196       }
 197       if (info == NULL) {
 198          info = processes->name();
 199       }
 200       if (info == NULL) {
 201          info = "?";
 202       }
 203       jio_snprintf(pid_buf, sizeof(pid_buf), "%d", processes->pid());
 204       EventSystemProcess event(UNTIMED);
 205       event.set_pid(pid_buf);
 206       event.set_commandLine(info);
 207       event.set_starttime(start_time);
 208       event.set_endtime(end_time);
 209       event.commit();
 210       processes = processes->next();
 211       delete tmp;
 212     }
 213   }
 214 }
 215 
 216 TRACE_REQUEST_FUNC(ThreadContextSwitchRate) {
 217   double rate = 0.0;
 218   int ret_val = JfrOSInterface::context_switch_rate(&rate);
 219   if (ret_val == OS_ERR) {
 220     log_debug(jfr, system)( "Unable to generate requestable event ThreadContextSwitchRate");
 221     return;
 222   }
 223   if (ret_val == FUNCTIONALITY_NOT_IMPLEMENTED) {
 224     return;
 225   }
 226   if (ret_val == OS_OK) {
 227     EventThreadContextSwitchRate event;
 228     event.set_switchRate((float)rate + 0.0f);
 229     event.commit();
 230   }
 231 }
 232 
 233 #define SEND_FLAGS_OF_TYPE(eventType, flagType)                   \
 234   do {                                                            \
 235     Flag *flag = Flag::flags;                                     \
 236     while (flag->_name != NULL) {                                 \
 237       if (flag->is_ ## flagType()) {                              \
 238         if (flag->is_unlocked()) {                                \
 239           Event ## eventType event;                               \
 240           event.set_name(flag->_name);                            \
 241           event.set_value(flag->get_ ## flagType());              \
 242           event.set_origin(flag->get_origin());                   \
 243           event.commit();                                         \
 244         }                                                         \
 245       }                                                           \
 246       ++flag;                                                     \
 247     }                                                             \
 248   } while (0)
 249 
 250 TRACE_REQUEST_FUNC(IntFlag) {
 251   SEND_FLAGS_OF_TYPE(IntFlag, int);
 252 }
 253 
 254 TRACE_REQUEST_FUNC(UnsignedIntFlag) {
 255   SEND_FLAGS_OF_TYPE(UnsignedIntFlag, uint);
 256 }
 257 
 258 TRACE_REQUEST_FUNC(LongFlag) {
 259   SEND_FLAGS_OF_TYPE(LongFlag, intx);
 260 }
 261 
 262 TRACE_REQUEST_FUNC(UnsignedLongFlag) {
 263   SEND_FLAGS_OF_TYPE(UnsignedLongFlag, uintx);
 264   SEND_FLAGS_OF_TYPE(UnsignedLongFlag, uint64_t);
 265   SEND_FLAGS_OF_TYPE(UnsignedLongFlag, size_t);
 266 }
 267 
 268 TRACE_REQUEST_FUNC(DoubleFlag) {
 269   SEND_FLAGS_OF_TYPE(DoubleFlag, double);
 270 }
 271 
 272 TRACE_REQUEST_FUNC(BooleanFlag) {
 273   SEND_FLAGS_OF_TYPE(BooleanFlag, bool);
 274 }
 275 
 276 TRACE_REQUEST_FUNC(StringFlag) {
 277   SEND_FLAGS_OF_TYPE(StringFlag, ccstr);
 278 }
 279 
 280 class VM_GC_SendObjectCountEvent : public VM_GC_HeapInspection {
 281  public:
 282   VM_GC_SendObjectCountEvent() : VM_GC_HeapInspection(NULL, true) {}
 283   virtual void doit() {
 284     ObjectCountEventSender::enable_requestable_event();
 285     collect();
 286     ObjectCountEventSender::disable_requestable_event();
 287   }
 288 };
 289 
 290 TRACE_REQUEST_FUNC(ObjectCount) {
 291   VM_GC_SendObjectCountEvent op;
 292   VMThread::execute(&op);
 293 }
 294 
 295 
 296 // Java Mission Control (JMC) uses (Java) Long.MIN_VALUE to describe that a
 297 // long value is undefined.
 298 static jlong jmc_undefined_long = min_jlong;
 299 
 300 TRACE_REQUEST_FUNC(GCConfiguration) {
 301   GCConfiguration conf;
 302   jlong pause_target = conf.has_pause_target_default_value() ? jmc_undefined_long : conf.pause_target();
 303   EventGCConfiguration event;
 304   event.set_youngCollector(conf.young_collector());
 305   event.set_oldCollector(conf.old_collector());
 306   event.set_parallelGCThreads(conf.num_parallel_gc_threads());
 307   event.set_concurrentGCThreads(conf.num_concurrent_gc_threads());
 308   event.set_usesDynamicGCThreads(conf.uses_dynamic_gc_threads());
 309   event.set_isExplicitGCConcurrent(conf.is_explicit_gc_concurrent());
 310   event.set_isExplicitGCDisabled(conf.is_explicit_gc_disabled());
 311   event.set_gcTimeRatio(conf.gc_time_ratio());
 312   event.set_pauseTarget((s8)pause_target);
 313   event.commit();
 314 }
 315 
 316 TRACE_REQUEST_FUNC(GCTLABConfiguration) {
 317   GCTLABConfiguration conf;
 318   EventGCTLABConfiguration event;
 319   event.set_usesTLABs(conf.uses_tlabs());
 320   event.set_minTLABSize(conf.min_tlab_size());
 321   event.set_tlabRefillWasteLimit(conf.tlab_refill_waste_limit());
 322   event.commit();
 323 }
 324 
 325 TRACE_REQUEST_FUNC(GCSurvivorConfiguration) {
 326   GCSurvivorConfiguration conf;
 327   EventGCSurvivorConfiguration event;
 328   event.set_maxTenuringThreshold(conf.max_tenuring_threshold());
 329   event.set_initialTenuringThreshold(conf.initial_tenuring_threshold());
 330   event.commit();
 331 }
 332 
 333 TRACE_REQUEST_FUNC(GCHeapConfiguration) {
 334   GCHeapConfiguration conf;
 335   EventGCHeapConfiguration event;
 336   event.set_minSize(conf.min_size());
 337   event.set_maxSize(conf.max_size());
 338   event.set_initialSize(conf.initial_size());
 339   event.set_usesCompressedOops(conf.uses_compressed_oops());
 340   event.set_compressedOopsMode(conf.narrow_oop_mode());
 341   event.set_objectAlignment(conf.object_alignment_in_bytes());
 342   event.set_heapAddressBits(conf.heap_address_size_in_bits());
 343   event.commit();
 344 }
 345 
 346 TRACE_REQUEST_FUNC(YoungGenerationConfiguration) {
 347   GCYoungGenerationConfiguration conf;
 348   jlong max_size = conf.has_max_size_default_value() ? jmc_undefined_long : conf.max_size();
 349   EventYoungGenerationConfiguration event;
 350   event.set_maxSize((u8)max_size);
 351   event.set_minSize(conf.min_size());
 352   event.set_newRatio(conf.new_ratio());
 353   event.commit();
 354 }
 355 
 356 TRACE_REQUEST_FUNC(InitialSystemProperty) {
 357   SystemProperty* p = Arguments::system_properties();
 358   JfrTraceTime time_stamp(Tracing::time());
 359   while (p !=  NULL) {
 360     if (!p->internal()) {
 361       EventInitialSystemProperty event(UNTIMED);
 362       event.set_key(p->key());
 363       event.set_value(p->value());
 364       event.set_endtime(time_stamp);
 365       event.commit();
 366     }
 367     p = p->next();
 368   }
 369 }
 370 
 371 TRACE_REQUEST_FUNC(ThreadAllocationStatistics) {
 372   ResourceMark rm;
 373   int initial_size = Threads::number_of_threads();
 374   GrowableArray<jlong> allocated(initial_size);
 375   GrowableArray<traceid> thread_ids(initial_size);
 376   JfrTraceTime time_stamp(Tracing::time());
 377   {
 378     // Collect allocation statistics while holding threads lock
 379     MutexLockerEx ml(Threads_lock);
 380     JavaThread *jt = Threads::first();
 381     while (jt) {
 382       allocated.append(jt->cooked_allocated_bytes());
 383       thread_ids.append(THREAD_TRACE_ID(jt));
 384       jt = jt->next();
 385     }
 386   }
 387 
 388   // Write allocation statistics to buffer.
 389   for(int i = 0; i < thread_ids.length(); i++) {
 390     EventThreadAllocationStatistics event(UNTIMED);
 391     event.set_allocated(allocated.at(i));
 392     event.set_thread(thread_ids.at(i));
 393     event.set_endtime(time_stamp);
 394     event.commit();
 395   }
 396 }
 397 
 398 /**
 399  *  PhysicalMemory event represents:
 400  *
 401  *  @totalSize == The amount of physical memory (hw) installed and reported by the OS, in bytes.
 402  *  @usedSize  == The amount of physical memory currently in use in the system (reserved/committed), in bytes.
 403  *
 404  *  Both fields are systemwide, i.e. represents the entire OS/HW environment.
 405  *  These fields do not include virtual memory.
 406  *
 407  *  If running inside a guest OS on top of a hypervisor in a virtualized environment,
 408  *  the total memory reported is the amount of memory configured for the guest OS by the hypervisor.
 409  */
 410 TRACE_REQUEST_FUNC(PhysicalMemory) {
 411   u8 totalPhysicalMemory = os::physical_memory();
 412   EventPhysicalMemory event;
 413   event.set_totalSize(totalPhysicalMemory);
 414   event.set_usedSize(totalPhysicalMemory - os::available_memory());
 415   event.commit();
 416 }
 417 
 418 TRACE_REQUEST_FUNC(JavaThreadStatistics) {
 419   EventJavaThreadStatistics event;
 420   event.set_activeCount(ThreadService::get_live_thread_count());
 421   event.set_daemonCount(ThreadService::get_daemon_thread_count());
 422   event.set_accumulatedCount(ThreadService::get_total_thread_count());
 423   event.set_peakCount(ThreadService::get_peak_thread_count());
 424   event.commit();
 425 }
 426 
 427 TRACE_REQUEST_FUNC(ClassLoadingStatistics) {
 428   EventClassLoadingStatistics event;
 429   event.set_loadedClassCount(ClassLoadingService::loaded_class_count());
 430   event.set_unloadedClassCount(ClassLoadingService::unloaded_class_count());
 431   event.commit();
 432 }
 433 
 434 class JfrClassLoaderStatsClosure : public ClassLoaderStatsClosure {
 435 public:
 436   JfrClassLoaderStatsClosure() : ClassLoaderStatsClosure(NULL) {}
 437 
 438   bool do_entry(oop const& key, ClassLoaderStats* const& cls) {
 439     const ClassLoaderData* this_cld = cls->_class_loader != NULL ?
 440       java_lang_ClassLoader::loader_data(cls->_class_loader) : (ClassLoaderData*)NULL;
 441     const ClassLoaderData* parent_cld = cls->_parent != NULL ?
 442       java_lang_ClassLoader::loader_data(cls->_parent) : (ClassLoaderData*)NULL;
 443     EventClassLoaderStatistics event;
 444     event.set_classLoader(this_cld);
 445     event.set_parentClassLoader(parent_cld);
 446     event.set_classLoaderData((intptr_t)cls->_cld);
 447     event.set_classCount(cls->_classes_count);
 448     event.set_chunkSize(cls->_chunk_sz);
 449     event.set_blockSize(cls->_block_sz);
 450     event.set_anonymousClassCount(cls->_anon_classes_count);
 451     event.set_anonymousChunkSize(cls->_anon_chunk_sz);
 452     event.set_anonymousBlockSize(cls->_anon_block_sz);
 453     event.commit();
 454     return true;
 455   }
 456 
 457   void createEvents(void) {
 458     _stats->iterate(this);
 459   }
 460 };
 461 
 462 class JfrClassLoaderStatsVMOperation : public ClassLoaderStatsVMOperation {
 463  public:
 464   JfrClassLoaderStatsVMOperation() : ClassLoaderStatsVMOperation(NULL) { }
 465 
 466   void doit() {
 467     JfrClassLoaderStatsClosure clsc;
 468     ClassLoaderDataGraph::cld_do(&clsc);
 469     clsc.createEvents();
 470   }
 471 };
 472 
 473 TRACE_REQUEST_FUNC(ClassLoaderStatistics) {
 474   JfrClassLoaderStatsVMOperation op;
 475   VMThread::execute(&op);
 476 }
 477 
 478 TRACE_REQUEST_FUNC(CompilerStatistics) {
 479   EventCompilerStatistics event;
 480   event.set_compileCount(CompileBroker::get_total_compile_count());
 481   event.set_bailoutCount(CompileBroker::get_total_bailout_count());
 482   event.set_invalidatedCount(CompileBroker::get_total_invalidated_count());
 483   event.set_osrCompileCount(CompileBroker::get_total_osr_compile_count());
 484   event.set_standardCompileCount(CompileBroker::get_total_standard_compile_count());
 485   event.set_osrBytesCompiled(CompileBroker::get_sum_osr_bytes_compiled());
 486   event.set_standardBytesCompiled(CompileBroker::get_sum_standard_bytes_compiled());
 487   event.set_nmetodsSize(CompileBroker::get_sum_nmethod_size());
 488   event.set_nmetodCodeSize(CompileBroker::get_sum_nmethod_code_size());
 489   event.set_peakTimeSpent(CompileBroker::get_peak_compilation_time());
 490   event.set_totalTimeSpent(CompileBroker::get_total_compilation_time());
 491   event.commit();
 492 }
 493 
 494 TRACE_REQUEST_FUNC(CompilerConfiguration) {
 495   EventCompilerConfiguration event;
 496   event.set_threadCount(CICompilerCount);
 497   event.set_tieredCompilation(TieredCompilation);
 498   event.commit();
 499 }
 500 
 501 TRACE_REQUEST_FUNC(CodeCacheStatistics) {
 502   // Emit stats for all available code heaps
 503   EventCodeCacheStatistics event;
 504   event.set_codeBlobType((u1)CodeBlobType::All);
 505   event.set_startAddress((u8)CodeCache::low_bound());
 506   event.set_reservedTopAddress((u8)CodeCache::high_bound());
 507   event.set_entryCount(CodeCache::nof_blobs());
 508   event.set_methodCount(CodeCache::nof_nmethods());
 509   event.set_adaptorCount(CodeCache::nof_adapters());
 510   event.set_unallocatedCapacity(CodeCache::unallocated_capacity());
 511   event.set_fullCount(CodeCache::get_codemem_full_count());
 512   event.commit();
 513 }
 514 
 515 TRACE_REQUEST_FUNC(CodeCacheConfiguration) {
 516   EventCodeCacheConfiguration event;
 517   event.set_initialSize(InitialCodeCacheSize);
 518   event.set_reservedSize(ReservedCodeCacheSize);
 519   event.set_expansionSize(CodeCacheExpansionSize);
 520   event.set_minBlockLength(CodeCacheMinBlockLength);
 521   event.set_startAddress((u8)CodeCache::low_bound());
 522   event.set_reservedTopAddress((u8)CodeCache::high_bound());
 523   event.commit();
 524 }
 525 
 526 TRACE_REQUEST_FUNC(CodeSweeperConfiguration) {
 527   EventCodeSweeperConfiguration event;
 528   event.set_sweeperEnabled(MethodFlushing);
 529   event.set_flushingEnabled(UseCodeCacheFlushing);
 530   event.commit();
 531 }