1 /*
  2  * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 #include "precompiled.hpp"
 25 #include "memory/allocation.inline.hpp"
 26 #include "memory/resourceArea.hpp"
 27 #include "runtime/os.hpp"
 28 #include "runtime/os_perf.hpp"
 29 #include "runtime/vm_version.hpp"
 30 #include "utilities/globalDefinitions.hpp"
 31 
 32 #ifdef __APPLE__
 33   #import <libproc.h>
 34   #include <sys/time.h>
 35   #include <sys/sysctl.h>
 36   #include <mach/mach.h>
 37   #include <mach/task_info.h>
 38   #include <sys/socket.h>
 39   #include <net/if.h>
 40   #include <net/if_dl.h>
 41   #include <net/route.h>
 42 #endif
 43 
 44 static const double NANOS_PER_SEC = 1000000000.0;
 45 
 46 class CPUPerformanceInterface::CPUPerformance : public CHeapObj<mtInternal> {
 47    friend class CPUPerformanceInterface;
 48  private:
 49 #ifdef __APPLE__
 50   uint64_t _total_cpu_nanos;
 51   uint64_t _total_csr_nanos;
 52   uint64_t _jvm_user_nanos;
 53   uint64_t _jvm_system_nanos;
 54   long _jvm_context_switches;
 55   long _used_ticks;
 56   long _total_ticks;
 57   int  _active_processor_count;
 58 
 59   bool now_in_nanos(uint64_t* resultp) {
 60     struct timespec tp;
 61     int status = clock_gettime(CLOCK_REALTIME, &tp);
 62     assert(status == 0, "clock_gettime error: %s", os::strerror(errno));
 63     if (status != 0) {
 64       return false;
 65     }
 66     *resultp = tp.tv_sec * NANOS_PER_SEC + tp.tv_nsec;
 67     return true;
 68   }
 69 #endif
 70 
 71   double normalize(double value) {
 72     return MIN2<double>(MAX2<double>(value, 0.0), 1.0);
 73   }
 74   int cpu_load(int which_logical_cpu, double* cpu_load);
 75   int context_switch_rate(double* rate);
 76   int cpu_load_total_process(double* cpu_load);
 77   int cpu_loads_process(double* pjvmUserLoad, double* pjvmKernelLoad, double* psystemTotalLoad);
 78 
 79   NONCOPYABLE(CPUPerformance);
 80 
 81  public:
 82   CPUPerformance();
 83   bool initialize();
 84   ~CPUPerformance();
 85 };
 86 
 87 CPUPerformanceInterface::CPUPerformance::CPUPerformance() {
 88 #ifdef __APPLE__
 89   _total_cpu_nanos= 0;
 90   _total_csr_nanos= 0;
 91   _jvm_context_switches = 0;
 92   _jvm_user_nanos = 0;
 93   _jvm_system_nanos = 0;
 94   _used_ticks = 0;
 95   _total_ticks = 0;
 96   _active_processor_count = 0;
 97 #endif
 98 }
 99 
100 bool CPUPerformanceInterface::CPUPerformance::initialize() {
101   return true;
102 }
103 
104 CPUPerformanceInterface::CPUPerformance::~CPUPerformance() {
105 }
106 
107 int CPUPerformanceInterface::CPUPerformance::cpu_load(int which_logical_cpu, double* cpu_load) {
108   return FUNCTIONALITY_NOT_IMPLEMENTED;
109 }
110 
111 int CPUPerformanceInterface::CPUPerformance::cpu_load_total_process(double* cpu_load) {
112 #ifdef __APPLE__
113   host_name_port_t host = mach_host_self();
114   host_flavor_t flavor = HOST_CPU_LOAD_INFO;
115   mach_msg_type_number_t host_info_count = HOST_CPU_LOAD_INFO_COUNT;
116   host_cpu_load_info_data_t cpu_load_info;
117 
118   kern_return_t kr = host_statistics(host, flavor, (host_info_t)&cpu_load_info, &host_info_count);
119   if (kr != KERN_SUCCESS) {
120     return OS_ERR;
121   }
122 
123   long used_ticks  = cpu_load_info.cpu_ticks[CPU_STATE_USER] + cpu_load_info.cpu_ticks[CPU_STATE_NICE] + cpu_load_info.cpu_ticks[CPU_STATE_SYSTEM];
124   long total_ticks = used_ticks + cpu_load_info.cpu_ticks[CPU_STATE_IDLE];
125 
126   if (_used_ticks == 0 || _total_ticks == 0) {
127     // First call, just set the values
128     _used_ticks  = used_ticks;
129     _total_ticks = total_ticks;
130     return OS_ERR;
131   }
132 
133   long used_delta  = used_ticks - _used_ticks;
134   long total_delta = total_ticks - _total_ticks;
135 
136   _used_ticks  = used_ticks;
137   _total_ticks = total_ticks;
138 
139   if (total_delta == 0) {
140     // Avoid division by zero
141     return OS_ERR;
142   }
143 
144   *cpu_load = (double)used_delta / total_delta;
145 
146   return OS_OK;
147 #else
148   return FUNCTIONALITY_NOT_IMPLEMENTED;
149 #endif
150 }
151 
152 int CPUPerformanceInterface::CPUPerformance::cpu_loads_process(double* pjvmUserLoad, double* pjvmKernelLoad, double* psystemTotalLoad) {
153 #ifdef __APPLE__
154   int result = cpu_load_total_process(psystemTotalLoad);
155   mach_port_t task = mach_task_self();
156   mach_msg_type_number_t task_info_count = TASK_INFO_MAX;
157   task_info_data_t task_info_data;
158   kern_return_t kr = task_info(task, TASK_ABSOLUTETIME_INFO, (task_info_t)task_info_data, &task_info_count);
159   if (kr != KERN_SUCCESS) {
160     return OS_ERR;
161   }
162   task_absolutetime_info_t absolutetime_info = (task_absolutetime_info_t)task_info_data;
163 
164   int active_processor_count = os::active_processor_count();
165   uint64_t jvm_user_nanos = absolutetime_info->total_user;
166   uint64_t jvm_system_nanos = absolutetime_info->total_system;
167 
168   uint64_t total_cpu_nanos;
169   if(!now_in_nanos(&total_cpu_nanos)) {
170     return OS_ERR;
171   }
172 
173   if (_total_cpu_nanos == 0 || active_processor_count != _active_processor_count) {
174     // First call or change in active processor count
175     result = OS_ERR;
176   } else {
177     uint64_t delta_nanos = active_processor_count * (total_cpu_nanos - _total_cpu_nanos);
178     if (delta_nanos == 0) {
179       // Avoid division by zero
180       return OS_ERR;
181     }
182 
183     *pjvmUserLoad = normalize((double)(jvm_user_nanos - _jvm_user_nanos)/delta_nanos);
184     *pjvmKernelLoad = normalize((double)(jvm_system_nanos - _jvm_system_nanos)/delta_nanos);
185   }
186 
187   _active_processor_count = active_processor_count;
188   _total_cpu_nanos = total_cpu_nanos;
189   _jvm_user_nanos = jvm_user_nanos;
190   _jvm_system_nanos = jvm_system_nanos;
191 
192   return result;
193 #else
194   return FUNCTIONALITY_NOT_IMPLEMENTED;
195 #endif
196 }
197 
198 int CPUPerformanceInterface::CPUPerformance::context_switch_rate(double* rate) {
199 #ifdef __APPLE__
200   mach_port_t task = mach_task_self();
201   mach_msg_type_number_t task_info_count = TASK_INFO_MAX;
202   task_info_data_t task_info_data;
203   kern_return_t kr = task_info(task, TASK_EVENTS_INFO, (task_info_t)task_info_data, &task_info_count);
204   if (kr != KERN_SUCCESS) {
205     return OS_ERR;
206   }
207 
208   int result = OS_OK;
209   if (_total_csr_nanos == 0 || _jvm_context_switches == 0) {
210     // First call just set initial values.
211     result = OS_ERR;
212   }
213 
214   long jvm_context_switches = ((task_events_info_t)task_info_data)->csw;
215 
216   uint64_t total_csr_nanos;
217   if(!now_in_nanos(&total_csr_nanos)) {
218     return OS_ERR;
219   }
220   double delta_in_sec = (double)(total_csr_nanos - _total_csr_nanos) / NANOS_PER_SEC;
221   if (delta_in_sec == 0.0) {
222     // Avoid division by zero
223     return OS_ERR;
224   }
225 
226   *rate = (jvm_context_switches - _jvm_context_switches) / delta_in_sec;
227 
228   _jvm_context_switches = jvm_context_switches;
229   _total_csr_nanos = total_csr_nanos;
230 
231   return result;
232 #else
233   return FUNCTIONALITY_NOT_IMPLEMENTED;
234 #endif
235 }
236 
237 CPUPerformanceInterface::CPUPerformanceInterface() {
238   _impl = nullptr;
239 }
240 
241 bool CPUPerformanceInterface::initialize() {
242   _impl = new CPUPerformanceInterface::CPUPerformance();
243   return _impl->initialize();
244 }
245 
246 CPUPerformanceInterface::~CPUPerformanceInterface() {
247   if (_impl != nullptr) {
248     delete _impl;
249   }
250 }
251 
252 int CPUPerformanceInterface::cpu_load(int which_logical_cpu, double* cpu_load) const {
253   return _impl->cpu_load(which_logical_cpu, cpu_load);
254 }
255 
256 int CPUPerformanceInterface::cpu_load_total_process(double* cpu_load) const {
257   return _impl->cpu_load_total_process(cpu_load);
258 }
259 
260 int CPUPerformanceInterface::cpu_loads_process(double* pjvmUserLoad, double* pjvmKernelLoad, double* psystemTotalLoad) const {
261   return _impl->cpu_loads_process(pjvmUserLoad, pjvmKernelLoad, psystemTotalLoad);
262 }
263 
264 int CPUPerformanceInterface::context_switch_rate(double* rate) const {
265   return _impl->context_switch_rate(rate);
266 }
267 
268 class SystemProcessInterface::SystemProcesses : public CHeapObj<mtInternal> {
269   friend class SystemProcessInterface;
270  private:
271   SystemProcesses();
272   bool initialize();
273   NONCOPYABLE(SystemProcesses);
274   ~SystemProcesses();
275 
276   //information about system processes
277   int system_processes(SystemProcess** system_processes, int* no_of_sys_processes) const;
278 };
279 
280 SystemProcessInterface::SystemProcesses::SystemProcesses() {
281 }
282 
283 bool SystemProcessInterface::SystemProcesses::initialize() {
284   return true;
285 }
286 
287 SystemProcessInterface::SystemProcesses::~SystemProcesses() {
288 }
289 int SystemProcessInterface::SystemProcesses::system_processes(SystemProcess** system_processes, int* no_of_sys_processes) const {
290   assert(system_processes != nullptr, "system_processes pointer is null!");
291   assert(no_of_sys_processes != nullptr, "system_processes counter pointer is null!");
292 #ifdef __APPLE__
293   pid_t* pids = nullptr;
294   int pid_count = 0;
295   ResourceMark rm;
296 
297   int try_count = 0;
298   while (pids == nullptr) {
299     // Find out buffer size
300     size_t pids_bytes = proc_listpids(PROC_ALL_PIDS, 0, nullptr, 0);
301     if (pids_bytes <= 0) {
302       return OS_ERR;
303     }
304     pid_count = pids_bytes / sizeof(pid_t);
305     pids = NEW_RESOURCE_ARRAY(pid_t, pid_count);
306     memset(pids, 0, pids_bytes);
307 
308     pids_bytes = proc_listpids(PROC_ALL_PIDS, 0, pids, pids_bytes);
309     if (pids_bytes <= 0) {
310        // couldn't fit buffer, retry.
311       FREE_RESOURCE_ARRAY(pid_t, pids, pid_count);
312       pids = nullptr;
313       try_count++;
314       if (try_count > 3) {
315       return OS_ERR;
316       }
317     } else {
318       pid_count = pids_bytes / sizeof(pid_t);
319     }
320   }
321 
322   int process_count = 0;
323   SystemProcess* next = nullptr;
324   for (int i = 0; i < pid_count; i++) {
325     pid_t pid = pids[i];
326     if (pid != 0) {
327       char buffer[PROC_PIDPATHINFO_MAXSIZE];
328       memset(buffer, 0 , sizeof(buffer));
329       if (proc_pidpath(pid, buffer, sizeof(buffer)) != -1) {
330         int length = strlen(buffer);
331         if (length > 0) {
332           SystemProcess* current = new SystemProcess();
333           char * path = NEW_C_HEAP_ARRAY(char, length + 1, mtInternal);
334           strcpy(path, buffer);
335           current->set_path(path);
336           current->set_pid((int)pid);
337           current->set_next(next);
338           next = current;
339           process_count++;
340         }
341       }
342     }
343   }
344 
345   *no_of_sys_processes = process_count;
346   *system_processes = next;
347 
348   return OS_OK;
349 #endif
350   return FUNCTIONALITY_NOT_IMPLEMENTED;
351 }
352 
353 int SystemProcessInterface::system_processes(SystemProcess** system_procs, int* no_of_sys_processes) const {
354   return _impl->system_processes(system_procs, no_of_sys_processes);
355 }
356 
357 SystemProcessInterface::SystemProcessInterface() {
358   _impl = nullptr;
359 }
360 
361 bool SystemProcessInterface::initialize() {
362   _impl = new SystemProcessInterface::SystemProcesses();
363   return _impl->initialize();
364 }
365 
366 SystemProcessInterface::~SystemProcessInterface() {
367   if (_impl != nullptr) {
368     delete _impl;
369  }
370 }
371 
372 CPUInformationInterface::CPUInformationInterface() {
373   _cpu_info = nullptr;
374 }
375 
376 bool CPUInformationInterface::initialize() {
377   _cpu_info = new CPUInformation();
378   VM_Version::initialize_cpu_information();
379   _cpu_info->set_number_of_hardware_threads(VM_Version::number_of_threads());
380   _cpu_info->set_number_of_cores(VM_Version::number_of_cores());
381   _cpu_info->set_number_of_sockets(VM_Version::number_of_sockets());
382   _cpu_info->set_cpu_name(VM_Version::cpu_name());
383   _cpu_info->set_cpu_description(VM_Version::cpu_description());
384   return true;
385 }
386 
387 CPUInformationInterface::~CPUInformationInterface() {
388   if (_cpu_info != nullptr) {
389     if (_cpu_info->cpu_name() != nullptr) {
390       const char* cpu_name = _cpu_info->cpu_name();
391       FREE_C_HEAP_ARRAY(char, cpu_name);
392       _cpu_info->set_cpu_name(nullptr);
393     }
394     if (_cpu_info->cpu_description() != nullptr) {
395       const char* cpu_desc = _cpu_info->cpu_description();
396       FREE_C_HEAP_ARRAY(char, cpu_desc);
397       _cpu_info->set_cpu_description(nullptr);
398     }
399     delete _cpu_info;
400   }
401 }
402 
403 int CPUInformationInterface::cpu_information(CPUInformation& cpu_info) {
404   if (nullptr == _cpu_info) {
405     return OS_ERR;
406   }
407 
408   cpu_info = *_cpu_info; // shallow copy assignment
409   return OS_OK;
410 }
411 
412 class NetworkPerformanceInterface::NetworkPerformance : public CHeapObj<mtInternal> {
413   friend class NetworkPerformanceInterface;
414  private:
415   NetworkPerformance();
416   NONCOPYABLE(NetworkPerformance);
417   bool initialize();
418   ~NetworkPerformance();
419   int network_utilization(NetworkInterface** network_interfaces) const;
420 };
421 
422 NetworkPerformanceInterface::NetworkPerformance::NetworkPerformance() {
423 }
424 
425 bool NetworkPerformanceInterface::NetworkPerformance::initialize() {
426   return true;
427 }
428 
429 NetworkPerformanceInterface::NetworkPerformance::~NetworkPerformance() {
430 }
431 
432 int NetworkPerformanceInterface::NetworkPerformance::network_utilization(NetworkInterface** network_interfaces) const {
433   size_t len;
434   int mib[] = {CTL_NET, PF_ROUTE, /* protocol number */ 0, /* address family */ 0, NET_RT_IFLIST2, /* NET_RT_FLAGS mask*/ 0};
435   if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), nullptr, &len, nullptr, 0) != 0) {
436     return OS_ERR;
437   }
438   uint8_t* buf = NEW_RESOURCE_ARRAY(uint8_t, len);
439   if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &len, nullptr, 0) != 0) {
440     return OS_ERR;
441   }
442 
443   size_t index = 0;
444   NetworkInterface* ret = nullptr;
445   while (index < len) {
446     if_msghdr* msghdr = reinterpret_cast<if_msghdr*>(buf + index);
447     index += msghdr->ifm_msglen;
448 
449     if (msghdr->ifm_type != RTM_IFINFO2) {
450       continue;
451     }
452 
453     if_msghdr2* msghdr2 = reinterpret_cast<if_msghdr2*>(msghdr);
454     sockaddr_dl* sockaddr = reinterpret_cast<sockaddr_dl*>(msghdr2 + 1);
455 
456     // The interface name is not necessarily NUL-terminated
457     char name_buf[128];
458     size_t name_len = MIN2(sizeof(name_buf) - 1, static_cast<size_t>(sockaddr->sdl_nlen));
459     strncpy(name_buf, sockaddr->sdl_data, name_len);
460     name_buf[name_len] = '\0';
461 
462     uint64_t bytes_in = msghdr2->ifm_data.ifi_ibytes;
463     uint64_t bytes_out = msghdr2->ifm_data.ifi_obytes;
464 
465     NetworkInterface* cur = new NetworkInterface(name_buf, bytes_in, bytes_out, ret);
466     ret = cur;
467   }
468 
469   *network_interfaces = ret;
470 
471   return OS_OK;
472 }
473 
474 NetworkPerformanceInterface::NetworkPerformanceInterface() {
475   _impl = nullptr;
476 }
477 
478 NetworkPerformanceInterface::~NetworkPerformanceInterface() {
479   if (_impl != nullptr) {
480     delete _impl;
481   }
482 }
483 
484 bool NetworkPerformanceInterface::initialize() {
485   _impl = new NetworkPerformanceInterface::NetworkPerformance();
486   return _impl->initialize();
487 }
488 
489 int NetworkPerformanceInterface::network_utilization(NetworkInterface** network_interfaces) const {
490   return _impl->network_utilization(network_interfaces);
491 }