1 /*
   2  * Copyright (c) 2011, 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 <stdio.h>
  27 #include <stdint.h>
  28 #include <stdarg.h>
  29 #include <unistd.h>
  30 #include <errno.h>
  31 #include <string.h>
  32 #include <sys/resource.h>
  33 #include <sys/types.h>
  34 #include <dirent.h>
  35 #include <stdlib.h>
  36 #include <dlfcn.h>
  37 #include <pthread.h>
  38 #include "sun_management_OperatingSystemImpl.h"
  39 
  40 struct ticks {
  41     uint64_t  used;
  42     uint64_t  usedKernel;
  43     uint64_t  total;
  44 };
  45 
  46 typedef struct ticks ticks;
  47 
  48 typedef enum {
  49     CPU_LOAD_VM_ONLY,
  50     CPU_LOAD_GLOBAL,
  51 } CpuLoadTarget;
  52 
  53 static struct perfbuf {
  54     int   nProcs;
  55     ticks jvmTicks;
  56     ticks cpuTicks;
  57     ticks *cpus;
  58 } counters;
  59 
  60 #define DEC_64 "%lld"
  61 
  62 static void next_line(FILE *f) {
  63     while (fgetc(f) != '\n');
  64 }
  65 
  66 /**
  67  * Return the total number of ticks since the system was booted.
  68  * If the usedTicks parameter is not NULL, it will be filled with
  69  * the number of ticks spent on actual processes (user, system or
  70  * nice processes) since system boot. Note that this is the total number
  71  * of "executed" ticks on _all_ CPU:s, that is on a n-way system it is
  72  * n times the number of ticks that has passed in clock time.
  73  *
  74  * Returns a negative value if the reading of the ticks failed.
  75  */
  76 static int get_totalticks(int which, ticks *pticks) {
  77     FILE         *fh;
  78     uint64_t        userTicks, niceTicks, systemTicks, idleTicks;
  79     int             n;
  80 
  81     if((fh = fopen("/proc/stat", "r")) == NULL) {
  82         return -1;
  83     }
  84 
  85     n = fscanf(fh, "cpu " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64,
  86            &userTicks, &niceTicks, &systemTicks, &idleTicks);
  87 
  88     // Move to next line
  89     next_line(fh);
  90 
  91     //find the line for requested cpu faster to just iterate linefeeds?
  92     if (which != -1) {
  93         int i;
  94         for (i = 0; i < which; i++) {
  95             if (fscanf(fh, "cpu%*d " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64, &userTicks, &niceTicks, &systemTicks, &idleTicks) != 4) {
  96                 fclose(fh);
  97                 return -2;
  98             }
  99             next_line(fh);
 100         }
 101         n = fscanf(fh, "cpu%*d " DEC_64 " " DEC_64 " " DEC_64 " " DEC_64 "\n",
 102            &userTicks, &niceTicks, &systemTicks, &idleTicks);
 103     }
 104 
 105     fclose(fh);
 106     if (n != 4) {
 107         return -2;
 108     }
 109 
 110     pticks->used       = userTicks + niceTicks;
 111     pticks->usedKernel = systemTicks;
 112     pticks->total      = userTicks + niceTicks + systemTicks + idleTicks;
 113 
 114     return 0;
 115 }
 116 
 117 static int vread_statdata(const char *procfile, const char *fmt, va_list args) {
 118     FILE    *f;
 119     int     n;
 120     char     buf[2048];
 121 
 122     if ((f = fopen(procfile, "r")) == NULL) {
 123         return -1;
 124     }
 125 
 126     if ((n = fread(buf, 1, sizeof(buf), f)) != -1) {
 127     char *tmp;
 128 
 129     buf[n-1] = '\0';
 130     /** skip through pid and exec name. the exec name _could be wacky_ (renamed) and
 131      *  make scanf go mupp.
 132      */
 133     if ((tmp = strrchr(buf, ')')) != NULL) {
 134         // skip the ')' and the following space but check that the buffer is long enough
 135         tmp += 2;
 136         if (tmp < buf + n) {
 137         n = vsscanf(tmp, fmt, args);
 138         }
 139     }
 140     }
 141 
 142     fclose(f);
 143 
 144     return n;
 145 }
 146 
 147 static int read_statdata(const char *procfile, const char *fmt, ...) {
 148     int       n;
 149     va_list args;
 150 
 151     va_start(args, fmt);
 152     n = vread_statdata(procfile, fmt, args);
 153     va_end(args);
 154     return n;
 155 }
 156 
 157 /** read user and system ticks from a named procfile, assumed to be in 'stat' format then. */
 158 static int read_ticks(const char *procfile, uint64_t *userTicks, uint64_t *systemTicks) {
 159     return read_statdata(procfile, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u "DEC_64" "DEC_64,
 160              userTicks, systemTicks
 161              );
 162 }
 163 
 164 /**
 165  * Return the number of ticks spent in any of the processes belonging
 166  * to the JVM on any CPU.
 167  */
 168 static int get_jvmticks(ticks *pticks) {
 169     uint64_t userTicks;
 170     uint64_t systemTicks;
 171 
 172     if (read_ticks("/proc/self/stat", &userTicks, &systemTicks) < 0) {
 173         return -1;
 174     }
 175 
 176     // get the total
 177     if (get_totalticks(-1, pticks) < 0) {
 178         return -1;
 179     }
 180 
 181     pticks->used       = userTicks;
 182     pticks->usedKernel = systemTicks;
 183 
 184     return 0;
 185 }
 186 
 187 /**
 188  * This method must be called first, before any data can be gathererd.
 189  */
 190 int perfInit() {
 191     static int initialized=1;
 192 
 193     if (!initialized) {
 194         int  i;
 195 
 196         int n = sysconf(_SC_NPROCESSORS_ONLN);
 197         if (n <= 0) {
 198             n = 1;
 199         }
 200 
 201         counters.cpus = calloc(n,sizeof(ticks));
 202         if (counters.cpus != NULL)  {
 203             // For the CPU load
 204             get_totalticks(-1, &counters.cpuTicks);
 205 
 206             for (i = 0; i < n; i++) {
 207                 get_totalticks(i, &counters.cpus[i]);
 208             }
 209             // For JVM load
 210             get_jvmticks(&counters.jvmTicks);
 211             initialized = 1;
 212         }
 213     }
 214 
 215     return initialized ? 0 : -1;
 216 }
 217 
 218 #define MAX(a,b) (a>b?a:b)
 219 #define MIN(a,b) (a<b?a:b)
 220 
 221 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
 222 
 223 /**
 224  * Return the load of the CPU as a double. 1.0 means the CPU process uses all
 225  * available time for user or system processes, 0.0 means the CPU uses all time
 226  * being idle.
 227  *
 228  * Returns a negative value if there is a problem in determining the CPU load.
 229  */
 230 
 231 static double get_cpuload_internal(int which, double *pkernelLoad, CpuLoadTarget target) {
 232     uint64_t udiff, kdiff, tdiff;
 233     ticks *pticks, tmp;
 234     double user_load = -1.0;
 235     int failed = 0;
 236 
 237     *pkernelLoad = 0.0;
 238 
 239     pthread_mutex_lock(&lock);
 240 
 241     if(perfInit() == 0) {
 242 
 243         if (target == CPU_LOAD_VM_ONLY) {
 244             pticks = &counters.jvmTicks;
 245         } else if (which == -1) {
 246             pticks = &counters.cpuTicks;
 247         } else {
 248             pticks = &counters.cpus[which];
 249         }
 250 
 251         tmp = *pticks;
 252 
 253         if (target == CPU_LOAD_VM_ONLY) {
 254             if (get_jvmticks(pticks) != 0) {
 255                 failed = 1;
 256             }
 257         } else if (get_totalticks(which, pticks) < 0) {
 258             failed = 1;
 259         }
 260 
 261         if(!failed) {
 262             // seems like we sometimes end up with less kernel ticks when
 263             // reading /proc/self/stat a second time, timing issue between cpus?
 264             if (pticks->usedKernel < tmp.usedKernel) {
 265                 kdiff = 0;
 266             } else {
 267                 kdiff = pticks->usedKernel - tmp.usedKernel;
 268             }
 269             tdiff = pticks->total - tmp.total;
 270             udiff = pticks->used - tmp.used;
 271 
 272             if (tdiff == 0) {
 273                 user_load = 0;
 274             } else {
 275                 if (tdiff < (udiff + kdiff)) {
 276                     tdiff = udiff + kdiff;
 277                 }
 278                 *pkernelLoad = (kdiff / (double)tdiff);
 279                 // BUG9044876, normalize return values to sane values
 280                 *pkernelLoad = MAX(*pkernelLoad, 0.0);
 281                 *pkernelLoad = MIN(*pkernelLoad, 1.0);
 282 
 283                 user_load = (udiff / (double)tdiff);
 284                 user_load = MAX(user_load, 0.0);
 285                 user_load = MIN(user_load, 1.0);
 286             }
 287         }
 288     }
 289     pthread_mutex_unlock(&lock);
 290     return user_load;
 291 }
 292 
 293 double get_cpu_load(int which) {
 294     double u, s;
 295     u = get_cpuload_internal(which, &s, CPU_LOAD_GLOBAL);
 296     if (u < 0) {
 297         return -1.0;
 298     }
 299     // Cap total systemload to 1.0
 300     return MIN((u + s), 1.0);
 301 }
 302 
 303 double get_process_load() {
 304     double u, s;
 305     u = get_cpuload_internal(-1, &s, CPU_LOAD_VM_ONLY);
 306     if (u < 0) {
 307         return -1.0;
 308     }
 309     return u + s;
 310 }
 311 
 312 JNIEXPORT jdouble JNICALL
 313 Java_sun_management_OperatingSystemImpl_getSystemCpuLoad
 314 (JNIEnv *env, jobject dummy)
 315 {
 316     if(perfInit() == 0) {
 317         return get_cpu_load(-1);
 318     } else {
 319         return -1.0;
 320     }
 321 }
 322 
 323 JNIEXPORT jdouble JNICALL
 324 Java_sun_management_OperatingSystemImpl_getProcessCpuLoad
 325 (JNIEnv *env, jobject dummy)
 326 {
 327     if(perfInit() == 0) {
 328         return get_process_load();
 329     } else {
 330         return -1.0;
 331     }
 332 }