1 /*
   2  * Copyright (c) 2003, 2018, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include "jni.h"
  27 #include "jni_util.h"
  28 #include "jlong.h"
  29 #include "jvm.h"
  30 #include "management_ext.h"
  31 #include "com_sun_management_internal_OperatingSystemImpl.h"
  32 
  33 #include <sys/types.h>
  34 #include <sys/stat.h>
  35 #if defined(_ALLBSD_SOURCE)
  36 #include <sys/sysctl.h>
  37 #ifdef __APPLE__
  38 #include <sys/param.h>
  39 #include <sys/mount.h>
  40 #include <mach/mach.h>
  41 #include <sys/proc_info.h>
  42 #include <libproc.h>
  43 #endif
  44 #elif !defined(_AIX)
  45 #include <sys/swap.h>
  46 #endif
  47 #include <sys/resource.h>
  48 #include <sys/times.h>
  49 #ifndef _ALLBSD_SOURCE
  50 #include <sys/sysinfo.h>
  51 #endif
  52 #include <ctype.h>
  53 #include <dirent.h>
  54 #include <errno.h>
  55 #include <fcntl.h>
  56 #include <limits.h>
  57 #include <stdlib.h>
  58 #include <unistd.h>
  59 
  60 #if defined(_AIX)
  61 #include <libperfstat.h>
  62 #endif
  63 
  64 static jlong page_size = 0;
  65 
  66 #if defined(_ALLBSD_SOURCE) || defined(_AIX)
  67 #define MB      (1024UL * 1024UL)
  68 #else
  69 
  70 /* This gets us the new structured proc interfaces of 5.6 & later */
  71 /* - see comment in <sys/procfs.h> */
  72 #define _STRUCTURED_PROC 1
  73 #include <sys/procfs.h>
  74 
  75 #endif /* _ALLBSD_SOURCE */
  76 
  77 // true = get available swap in bytes
  78 // false = get total swap in bytes
  79 static jlong get_total_or_available_swap_space_size(JNIEnv* env, jboolean available) {
  80 #ifdef __solaris__
  81     long total, avail;
  82     int nswap, i, count;
  83     swaptbl_t *stbl;
  84     char *strtab;
  85 
  86     // First get the number of swap resource entries
  87     if ((nswap = swapctl(SC_GETNSWP, NULL)) == -1) {
  88         throw_internal_error(env, "swapctl failed to get nswap");
  89         return -1;
  90     }
  91     if (nswap == 0) {
  92         return 0;
  93     }
  94 
  95     // Allocate storage for resource entries
  96     stbl = (swaptbl_t*) malloc(nswap * sizeof(swapent_t) +
  97                                sizeof(struct swaptable));
  98     if (stbl == NULL) {
  99         JNU_ThrowOutOfMemoryError(env, 0);
 100         return -1;
 101     }
 102 
 103     // Allocate storage for the table
 104     strtab = (char*) malloc((nswap + 1) * MAXPATHLEN);
 105     if (strtab == NULL) {
 106         free(stbl);
 107         JNU_ThrowOutOfMemoryError(env, 0);
 108         return -1;
 109     }
 110 
 111     for (i = 0; i < (nswap + 1); i++) {
 112       stbl->swt_ent[i].ste_path = strtab + (i * MAXPATHLEN);
 113     }
 114     stbl->swt_n = nswap + 1;
 115 
 116     // Get the entries
 117     if ((count = swapctl(SC_LIST, stbl)) < 0) {
 118         free(stbl);
 119         free(strtab);
 120         throw_internal_error(env, "swapctl failed to get swap list");
 121         return -1;
 122     }
 123 
 124     // Sum the entries to get total and free swap
 125     total = 0;
 126     avail = 0;
 127     for (i = 0; i < count; i++) {
 128       total += stbl->swt_ent[i].ste_pages;
 129       avail += stbl->swt_ent[i].ste_free;
 130     }
 131 
 132     free(stbl);
 133     free(strtab);
 134     return available ? ((jlong)avail * page_size) :
 135                        ((jlong)total * page_size);
 136 #elif defined(__linux__)
 137     int ret;
 138     FILE *fp;
 139     jlong total = 0, avail = 0;
 140 
 141     struct sysinfo si;
 142     ret = sysinfo(&si);
 143     if (ret != 0) {
 144         throw_internal_error(env, "sysinfo failed to get swap size");
 145     }
 146     total = (jlong)si.totalswap * si.mem_unit;
 147     avail = (jlong)si.freeswap * si.mem_unit;
 148 
 149     return available ? avail : total;
 150 #elif defined(__APPLE__)
 151     struct xsw_usage vmusage;
 152     size_t size = sizeof(vmusage);
 153     if (sysctlbyname("vm.swapusage", &vmusage, &size, NULL, 0) != 0) {
 154         throw_internal_error(env, "sysctlbyname failed");
 155     }
 156     return available ? (jlong)vmusage.xsu_avail : (jlong)vmusage.xsu_total;
 157 #else /* _ALLBSD_SOURCE */
 158     /*
 159      * XXXBSD: there's no way available to get swap info in
 160      *         FreeBSD.  Usage of libkvm is not an option here
 161      */
 162     // throw_internal_error(env, "Unimplemented in FreeBSD");
 163     return (0);
 164 #endif
 165 }
 166 
 167 JNIEXPORT void JNICALL
 168 Java_com_sun_management_internal_OperatingSystemImpl_initialize0
 169   (JNIEnv *env, jclass cls)
 170 {
 171     page_size = sysconf(_SC_PAGESIZE);
 172 }
 173 
 174 JNIEXPORT jlong JNICALL
 175 Java_com_sun_management_internal_OperatingSystemImpl_getCommittedVirtualMemorySize0
 176   (JNIEnv *env, jobject mbean)
 177 {
 178 #ifdef __solaris__
 179     psinfo_t psinfo;
 180     ssize_t result;
 181     size_t remaining;
 182     char* addr;
 183     int fd;
 184 
 185     fd = open64("/proc/self/psinfo", O_RDONLY, 0);
 186     if (fd < 0) {
 187         throw_internal_error(env, "Unable to open /proc/self/psinfo");
 188         return -1;
 189     }
 190 
 191     addr = (char *)&psinfo;
 192     for (remaining = sizeof(psinfo_t); remaining > 0;) {
 193         result = read(fd, addr, remaining);
 194         if (result < 0) {
 195             if (errno != EINTR) {
 196                 close(fd);
 197                 throw_internal_error(env, "Unable to read /proc/self/psinfo");
 198                 return -1;
 199             }
 200         } else {
 201             remaining -= result;
 202             addr += result;
 203         }
 204     }
 205 
 206     close(fd);
 207     return (jlong) psinfo.pr_size * 1024;
 208 #elif defined(__linux__)
 209     FILE *fp;
 210     unsigned long vsize = 0;
 211 
 212     if ((fp = fopen("/proc/self/stat", "r")) == NULL) {
 213         throw_internal_error(env, "Unable to open /proc/self/stat");
 214         return -1;
 215     }
 216 
 217     // Ignore everything except the vsize entry
 218     if (fscanf(fp, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*d %*d %*d %*d %*d %*d %*u %*u %*d %lu %*[^\n]\n", &vsize) == EOF) {
 219         throw_internal_error(env, "Unable to get virtual memory usage");
 220         fclose(fp);
 221         return -1;
 222     }
 223 
 224     fclose(fp);
 225     return (jlong)vsize;
 226 #elif defined(__APPLE__)
 227     struct task_basic_info t_info;
 228     mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
 229 
 230     kern_return_t res = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
 231     if (res != KERN_SUCCESS) {
 232         throw_internal_error(env, "task_info failed");
 233     }
 234     return t_info.virtual_size;
 235 #else /* _ALLBSD_SOURCE */
 236     /*
 237      * XXXBSD: there's no way available to do it in FreeBSD, AFAIK.
 238      */
 239     // throw_internal_error(env, "Unimplemented in FreeBSD");
 240     return (64 * MB);
 241 #endif
 242 }
 243 
 244 JNIEXPORT jlong JNICALL
 245 Java_com_sun_management_internal_OperatingSystemImpl_getTotalSwapSpaceSize0
 246   (JNIEnv *env, jobject mbean)
 247 {
 248     return get_total_or_available_swap_space_size(env, JNI_FALSE);
 249 }
 250 
 251 JNIEXPORT jlong JNICALL
 252 Java_com_sun_management_internal_OperatingSystemImpl_getFreeSwapSpaceSize0
 253   (JNIEnv *env, jobject mbean)
 254 {
 255     return get_total_or_available_swap_space_size(env, JNI_TRUE);
 256 }
 257 
 258 JNIEXPORT jlong JNICALL
 259 Java_com_sun_management_internal_OperatingSystemImpl_getProcessCpuTime0
 260   (JNIEnv *env, jobject mbean)
 261 {
 262 #ifdef __APPLE__
 263     struct rusage usage;
 264     if (getrusage(RUSAGE_SELF, &usage) != 0) {
 265         throw_internal_error(env, "getrusage failed");
 266         return -1;
 267     }
 268     jlong microsecs =
 269         usage.ru_utime.tv_sec * 1000 * 1000 + usage.ru_utime.tv_usec +
 270         usage.ru_stime.tv_sec * 1000 * 1000 + usage.ru_stime.tv_usec;
 271     return microsecs * 1000;
 272 #else
 273     jlong clk_tck, ns_per_clock_tick;
 274     jlong cpu_time_ns;
 275     struct tms time;
 276 
 277     /*
 278      * BSDNOTE: FreeBSD implements _SC_CLK_TCK since FreeBSD 5, so
 279      *          add a magic to handle it
 280      */
 281 #if defined(__solaris__) || defined(_SC_CLK_TCK)
 282     clk_tck = (jlong) sysconf(_SC_CLK_TCK);
 283 #elif defined(__linux__) || defined(_ALLBSD_SOURCE)
 284     clk_tck = 100;
 285 #endif
 286     if (clk_tck == -1) {
 287         throw_internal_error(env,
 288                              "sysconf failed - not able to get clock tick");
 289         return -1;
 290     }
 291 
 292     times(&time);
 293     ns_per_clock_tick = (jlong) 1000 * 1000 * 1000 / (jlong) clk_tck;
 294     cpu_time_ns = ((jlong)time.tms_utime + (jlong) time.tms_stime) *
 295                       ns_per_clock_tick;
 296     return cpu_time_ns;
 297 #endif
 298 }
 299 
 300 JNIEXPORT jlong JNICALL
 301 Java_com_sun_management_internal_OperatingSystemImpl_getFreePhysicalMemorySize0
 302   (JNIEnv *env, jobject mbean)
 303 {
 304 #ifdef __APPLE__
 305     mach_msg_type_number_t count;
 306     vm_statistics_data_t vm_stats;
 307     kern_return_t res;
 308 
 309     count = HOST_VM_INFO_COUNT;
 310     res = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vm_stats, &count);
 311     if (res != KERN_SUCCESS) {
 312         throw_internal_error(env, "host_statistics failed");
 313         return -1;
 314     }
 315     return (jlong)vm_stats.free_count * page_size;
 316 #elif defined(_ALLBSD_SOURCE)
 317     /*
 318      * XXBSDL no way to do it in FreeBSD
 319      */
 320     // throw_internal_error(env, "unimplemented in FreeBSD")
 321     return (128 * MB);
 322 #elif defined(_AIX)
 323     perfstat_memory_total_t memory_info;
 324     if (-1 != perfstat_memory_total(NULL, &memory_info, sizeof(perfstat_memory_total_t), 1)) {
 325         return (jlong)(memory_info.real_free * 4L * 1024L);
 326     }
 327     return -1;
 328 #else // solaris / linux
 329     jlong num_avail_physical_pages = sysconf(_SC_AVPHYS_PAGES);
 330     return (num_avail_physical_pages * page_size);
 331 #endif
 332 }
 333 
 334 JNIEXPORT jlong JNICALL
 335 Java_com_sun_management_internal_OperatingSystemImpl_getTotalPhysicalMemorySize0
 336   (JNIEnv *env, jobject mbean)
 337 {
 338 #ifdef _ALLBSD_SOURCE
 339     jlong result = 0;
 340     int mib[2];
 341     size_t rlen;
 342 
 343     mib[0] = CTL_HW;
 344     mib[1] = HW_MEMSIZE;
 345     rlen = sizeof(result);
 346     if (sysctl(mib, 2, &result, &rlen, NULL, 0) != 0) {
 347         throw_internal_error(env, "sysctl failed");
 348         return -1;
 349     }
 350     return result;
 351 #elif defined(_AIX)
 352     perfstat_memory_total_t memory_info;
 353     if (-1 != perfstat_memory_total(NULL, &memory_info, sizeof(perfstat_memory_total_t), 1)) {
 354         return (jlong)(memory_info.real_total * 4L * 1024L);
 355     }
 356     return -1;
 357 #else // solaris / linux
 358     jlong num_physical_pages = sysconf(_SC_PHYS_PAGES);
 359     return (num_physical_pages * page_size);
 360 #endif
 361 }
 362 
 363 
 364 
 365 JNIEXPORT jlong JNICALL
 366 Java_com_sun_management_internal_OperatingSystemImpl_getOpenFileDescriptorCount0
 367   (JNIEnv *env, jobject mbean)
 368 {
 369 #ifdef __APPLE__
 370     // This code is influenced by the darwin lsof source
 371     pid_t my_pid;
 372     struct proc_bsdinfo bsdinfo;
 373     struct proc_fdinfo *fds;
 374     int nfiles;
 375     kern_return_t kres;
 376     int res;
 377     size_t fds_size;
 378 
 379     kres = pid_for_task(mach_task_self(), &my_pid);
 380     if (kres != KERN_SUCCESS) {
 381         throw_internal_error(env, "pid_for_task failed");
 382         return -1;
 383     }
 384 
 385     // get the maximum number of file descriptors
 386     res = proc_pidinfo(my_pid, PROC_PIDTBSDINFO, 0, &bsdinfo, PROC_PIDTBSDINFO_SIZE);
 387     if (res <= 0) {
 388         throw_internal_error(env, "proc_pidinfo with PROC_PIDTBSDINFO failed");
 389         return -1;
 390     }
 391 
 392     // allocate memory to hold the fd information (we don't acutally use this information
 393     // but need it to get the number of open files)
 394     fds_size = bsdinfo.pbi_nfiles * sizeof(struct proc_fdinfo);
 395     fds = malloc(fds_size);
 396     if (fds == NULL) {
 397         JNU_ThrowOutOfMemoryError(env, "could not allocate space for file descriptors");
 398         return -1;
 399     }
 400 
 401     // get the list of open files - the return value is the number of bytes
 402     // proc_pidinfo filled in
 403     res = proc_pidinfo(my_pid, PROC_PIDLISTFDS, 0, fds, fds_size);
 404     if (res <= 0) {
 405         free(fds);
 406         throw_internal_error(env, "proc_pidinfo failed for PROC_PIDLISTFDS");
 407         return -1;
 408     }
 409     nfiles = res / sizeof(struct proc_fdinfo);
 410     free(fds);
 411 
 412     return nfiles;
 413 #elif defined(_ALLBSD_SOURCE)
 414     /*
 415      * XXXBSD: there's no way available to do it in FreeBSD, AFAIK.
 416      */
 417     // throw_internal_error(env, "Unimplemented in FreeBSD");
 418     return (100);
 419 #else /* solaris/linux */
 420     DIR *dirp;
 421     struct dirent* dentp;
 422     jlong fds = 0;
 423 
 424 #if defined(_AIX)
 425 /* AIX does not understand '/proc/self' - it requires the real process ID */
 426 #define FD_DIR aix_fd_dir
 427     char aix_fd_dir[32];     /* the pid has at most 19 digits */
 428     snprintf(aix_fd_dir, 32, "/proc/%d/fd", getpid());
 429 #else
 430 #define FD_DIR "/proc/self/fd"
 431 #endif
 432 
 433     dirp = opendir(FD_DIR);
 434     if (dirp == NULL) {
 435         throw_internal_error(env, "Unable to open directory /proc/self/fd");
 436         return -1;
 437     }
 438 
 439     // iterate through directory entries, skipping '.' and '..'
 440     // each entry represents an open file descriptor.
 441     while ((dentp = readdir(dirp)) != NULL) {
 442         if (isdigit(dentp->d_name[0])) {
 443             fds++;
 444         }
 445     }
 446 
 447     closedir(dirp);
 448     // subtract by 1 which was the fd open for this implementation
 449     return (fds - 1);
 450 #endif
 451 }
 452 
 453 JNIEXPORT jlong JNICALL
 454 Java_com_sun_management_internal_OperatingSystemImpl_getMaxFileDescriptorCount0
 455   (JNIEnv *env, jobject mbean)
 456 {
 457     struct rlimit rlp;
 458 
 459     if (getrlimit(RLIMIT_NOFILE, &rlp) == -1) {
 460         throw_internal_error(env, "getrlimit failed");
 461         return -1;
 462     }
 463     return (jlong) rlp.rlim_cur;
 464 }