0N/A/*
4162N/A * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A#include "jni.h"
0N/A#include "jni_util.h"
0N/A#include "jlong.h"
0N/A#include "jvm.h"
0N/A#include "management.h"
0N/A#include "com_sun_management_OperatingSystem.h"
0N/A
3901N/A#include <psapi.h>
0N/A#include <errno.h>
0N/A#include <stdlib.h>
0N/A
4162N/A#include <malloc.h>
4162N/A#pragma warning (push,0)
4162N/A#include <windows.h>
4162N/A#pragma warning (pop)
4162N/A#include <stdio.h>
4162N/A#include <time.h>
4162N/A#include <stdint.h>
4162N/A#include <assert.h>
4162N/A
4162N/A/* Disable warnings due to broken header files from Microsoft... */
4162N/A#pragma warning(push, 3)
4162N/A#include <pdh.h>
4162N/A#include <pdhmsg.h>
4162N/A#include <process.h>
4162N/A#pragma warning(pop)
4162N/A
0N/Atypedef unsigned __int32 juint;
0N/Atypedef unsigned __int64 julong;
0N/A
4162N/Atypedef enum boolean_values { false=0, true=1};
4162N/A
0N/Astatic void set_low(jlong* value, jint low) {
0N/A *value &= (jlong)0xffffffff << 32;
0N/A *value |= (jlong)(julong)(juint)low;
0N/A}
0N/A
0N/Astatic void set_high(jlong* value, jint high) {
0N/A *value &= (jlong)(julong)(juint)0xffffffff;
0N/A *value |= (jlong)high << 32;
0N/A}
0N/A
0N/Astatic jlong jlong_from(jint h, jint l) {
0N/A jlong result = 0; // initialization to avoid warning
0N/A set_high(&result, h);
0N/A set_low(&result, l);
0N/A return result;
0N/A}
0N/A
0N/Astatic HANDLE main_process;
0N/A
4162N/Aint perfiInit(void);
4162N/A
0N/AJNIEXPORT void JNICALL
0N/AJava_com_sun_management_OperatingSystem_initialize
0N/A (JNIEnv *env, jclass cls)
0N/A{
0N/A main_process = GetCurrentProcess();
4162N/A perfiInit();
0N/A}
0N/A
0N/AJNIEXPORT jlong JNICALL
0N/AJava_com_sun_management_OperatingSystem_getCommittedVirtualMemorySize0
0N/A (JNIEnv *env, jobject mbean)
0N/A{
0N/A PROCESS_MEMORY_COUNTERS pmc;
3901N/A if (GetProcessMemoryInfo(main_process, &pmc, sizeof(PROCESS_MEMORY_COUNTERS)) == 0) {
3901N/A return (jlong)-1L;
3901N/A } else {
3901N/A return (jlong) pmc.PagefileUsage;
0N/A }
0N/A}
0N/A
0N/AJNIEXPORT jlong JNICALL
0N/AJava_com_sun_management_OperatingSystem_getTotalSwapSpaceSize
0N/A (JNIEnv *env, jobject mbean)
0N/A{
0N/A MEMORYSTATUS ms;
0N/A GlobalMemoryStatus(&ms);
0N/A return (jlong)ms.dwTotalPageFile;
0N/A}
0N/A
0N/AJNIEXPORT jlong JNICALL
0N/AJava_com_sun_management_OperatingSystem_getFreeSwapSpaceSize
0N/A (JNIEnv *env, jobject mbean)
0N/A{
0N/A MEMORYSTATUS ms;
0N/A GlobalMemoryStatus(&ms);
0N/A return (jlong)ms.dwAvailPageFile;
0N/A}
0N/A
0N/AJNIEXPORT jlong JNICALL
0N/AJava_com_sun_management_OperatingSystem_getProcessCpuTime
0N/A (JNIEnv *env, jobject mbean)
0N/A{
0N/A
0N/A FILETIME process_creation_time, process_exit_time,
0N/A process_user_time, process_kernel_time;
0N/A
3901N/A // Using static variables declared above
3901N/A // Units are 100-ns intervals. Convert to ns.
3901N/A GetProcessTimes(main_process, &process_creation_time,
3901N/A &process_exit_time,
3901N/A &process_kernel_time, &process_user_time);
3901N/A return (jlong_from(process_user_time.dwHighDateTime,
3901N/A process_user_time.dwLowDateTime) +
3901N/A jlong_from(process_kernel_time.dwHighDateTime,
3901N/A process_kernel_time.dwLowDateTime)) * 100;
0N/A}
0N/A
0N/AJNIEXPORT jlong JNICALL
0N/AJava_com_sun_management_OperatingSystem_getFreePhysicalMemorySize
0N/A (JNIEnv *env, jobject mbean)
0N/A{
0N/A MEMORYSTATUS ms;
0N/A GlobalMemoryStatus(&ms);
0N/A return (jlong) ms.dwAvailPhys;
0N/A}
0N/A
0N/AJNIEXPORT jlong JNICALL
0N/AJava_com_sun_management_OperatingSystem_getTotalPhysicalMemorySize
0N/A (JNIEnv *env, jobject mbean)
0N/A{
0N/A MEMORYSTATUS ms;
0N/A // also returns dwAvailPhys (free physical memory bytes),
0N/A // dwTotalVirtual, dwAvailVirtual,
0N/A // dwMemoryLoad (% of memory in use)
0N/A GlobalMemoryStatus(&ms);
0N/A return ms.dwTotalPhys;
0N/A}
4162N/A
4162N/A// Seems WinXP PDH returns PDH_MORE_DATA whenever we send in a NULL buffer.
4162N/A// Let's just ignore it, since we make sure we have enough buffer anyway.
4162N/Astatic int
4162N/Apdh_fail(PDH_STATUS pdhStat) {
4162N/A return pdhStat != ERROR_SUCCESS && pdhStat != PDH_MORE_DATA;
4162N/A}
4162N/A
4162N/A// INFO: Using PDH APIs Correctly in a Localized Language (Q287159)
4162N/A// http://support.microsoft.com/default.aspx?scid=kb;EN-US;q287159
4162N/A// The index value for the base system counters and objects like processor,
4162N/A// process, thread, memory, and so forth are always the same irrespective
4162N/A// of the localized version of the operating system or service pack installed.
4162N/A#define PDH_PROCESSOR_IDX ((DWORD) 238)
4162N/A#define PDH_PROCESSOR_TIME_IDX ((DWORD) 6)
4162N/A#define PDH_PRIV_PROCESSOR_TIME_IDX ((DWORD) 144)
4162N/A#define PDH_PROCESS_IDX ((DWORD) 230)
4162N/A#define PDH_ID_PROCESS_IDX ((DWORD) 784)
4162N/A#define PDH_CONTEXT_SWITCH_RATE_IDX ((DWORD) 146)
4162N/A#define PDH_SYSTEM_IDX ((DWORD) 2)
4162N/A#define PDH_VIRTUAL_BYTES_IDX ((DWORD) 174)
4162N/A
4162N/Atypedef PDH_STATUS (WINAPI *PdhAddCounterFunc)(
4162N/A HQUERY hQuery,
4162N/A LPCSTR szFullCounterPath,
4162N/A DWORD dwUserData,
4162N/A HCOUNTER *phCounter
4162N/A );
4162N/Atypedef PDH_STATUS (WINAPI *PdhOpenQueryFunc)(
4162N/A LPCWSTR szDataSource,
4162N/A DWORD dwUserData,
4162N/A HQUERY *phQuery
4162N/A );
4162N/Atypedef DWORD (WINAPI *PdhCloseQueryFunc)(
4162N/A HQUERY hQuery
4162N/A );
4162N/Atypedef PDH_STATUS (WINAPI *PdhCollectQueryDataFunc)(
4162N/A HQUERY hQuery
4162N/A );
4162N/Atypedef DWORD (WINAPI *PdhGetFormattedCounterValueFunc)(
4162N/A HCOUNTER hCounter,
4162N/A DWORD dwFormat,
4162N/A LPDWORD lpdwType,
4162N/A PPDH_FMT_COUNTERVALUE pValue
4162N/A );
4162N/Atypedef PDH_STATUS (WINAPI *PdhEnumObjectItemsFunc)(
4162N/A LPCTSTR szDataSource,
4162N/A LPCTSTR szMachineName,
4162N/A LPCTSTR szObjectName,
4162N/A LPTSTR mszCounterList,
4162N/A LPDWORD pcchCounterListLength,
4162N/A LPTSTR mszInstanceList,
4162N/A LPDWORD pcchInstanceListLength,
4162N/A DWORD dwDetailLevel,
4162N/A DWORD dwFlags
4162N/A );
4162N/Atypedef PDH_STATUS (WINAPI *PdhRemoveCounterFunc)(
4162N/A HCOUNTER hCounter
4162N/A );
4162N/Atypedef PDH_STATUS (WINAPI *PdhLookupPerfNameByIndexFunc)(
4162N/A LPCSTR szMachineName,
4162N/A DWORD dwNameIndex,
4162N/A LPSTR szNameBuffer,
4162N/A LPDWORD pcchNameBufferSize
4162N/A );
4162N/Atypedef PDH_STATUS (WINAPI *PdhMakeCounterPathFunc)(
4162N/A PDH_COUNTER_PATH_ELEMENTS *pCounterPathElements,
4162N/A LPTSTR szFullPathBuffer,
4162N/A LPDWORD pcchBufferSize,
4162N/A DWORD dwFlags
4162N/A );
4162N/A
4162N/Astatic PdhAddCounterFunc PdhAddCounter_i;
4162N/Astatic PdhOpenQueryFunc PdhOpenQuery_i;
4162N/Astatic PdhCloseQueryFunc PdhCloseQuery_i;
4162N/Astatic PdhCollectQueryDataFunc PdhCollectQueryData_i;
4162N/Astatic PdhGetFormattedCounterValueFunc PdhGetFormattedCounterValue_i;
4162N/Astatic PdhEnumObjectItemsFunc PdhEnumObjectItems_i;
4162N/Astatic PdhRemoveCounterFunc PdhRemoveCounter_i;
4162N/Astatic PdhLookupPerfNameByIndexFunc PdhLookupPerfNameByIndex_i;
4162N/Astatic PdhMakeCounterPathFunc PdhMakeCounterPath_i;
4162N/A
4162N/Astatic HANDLE thisProcess;
4162N/Astatic double cpuFactor;
4162N/Astatic DWORD num_cpus;
4162N/A
4162N/A#define FT2JLONG(X) ((((jlong)X.dwHighDateTime) << 32) | ((jlong)X.dwLowDateTime))
4162N/A#define COUNTER_BUF_SIZE 256
4162N/A// Min time between query updates.
4162N/A#define MIN_UPDATE_INTERVAL 500
4162N/A#define CONFIG_SUCCESSFUL 0
4162N/A
4162N/A/**
4162N/A * Struct for PDH queries.
4162N/A */
4162N/Atypedef struct {
4162N/A HQUERY query;
4162N/A uint64_t lastUpdate; // Last time query was updated (current millis).
4162N/A} UpdateQueryS, *UpdateQueryP;
4162N/A
4162N/A/**
4162N/A * Struct for the processor load counters.
4162N/A */
4162N/Atypedef struct {
4162N/A UpdateQueryS query;
4162N/A HCOUNTER* counters;
4162N/A int noOfCounters;
4162N/A} MultipleCounterQueryS, *MultipleCounterQueryP;
4162N/A
4162N/A/**
4162N/A * Struct for the jvm process load counter.
4162N/A */
4162N/Atypedef struct {
4162N/A UpdateQueryS query;
4162N/A HCOUNTER counter;
4162N/A} SingleCounterQueryS, *SingleCounterQueryP;
4162N/A
4162N/Astatic char* getProcessPDHHeader(void);
4162N/A
4162N/A/**
4162N/A * Currently available counters.
4162N/A */
4162N/Astatic SingleCounterQueryS cntCtxtSwitchRate;
4162N/Astatic SingleCounterQueryS cntVirtualSize;
4162N/Astatic SingleCounterQueryS cntProcLoad;
4162N/Astatic SingleCounterQueryS cntProcSystemLoad;
4162N/Astatic MultipleCounterQueryS multiCounterCPULoad;
4162N/A
4162N/Astatic CRITICAL_SECTION processHeaderLock;
4162N/Astatic CRITICAL_SECTION initializationLock;
4162N/A
4162N/A/**
4162N/A * Initialize the perf module at startup.
4162N/A */
4162N/Aint
4162N/AperfiInit(void)
4162N/A{
4162N/A InitializeCriticalSection(&processHeaderLock);
4162N/A InitializeCriticalSection(&initializationLock);
4162N/A return 0;
4162N/A}
4162N/A
4162N/A/**
4162N/A * Dynamically sets up function pointers to the PDH library.
4162N/A *
4162N/A * @return CONFIG_SUCCESSFUL on success, negative on failure.
4162N/A */
4162N/Astatic int
4162N/Aget_functions(HMODULE h, char *ebuf, size_t elen) {
4162N/A // The 'A' at the end means the ANSI (not the UNICODE) vesions of the methods
4162N/A PdhAddCounter_i = (PdhAddCounterFunc)GetProcAddress(h, "PdhAddCounterA");
4162N/A PdhOpenQuery_i = (PdhOpenQueryFunc)GetProcAddress(h, "PdhOpenQueryA");
4162N/A PdhCloseQuery_i = (PdhCloseQueryFunc)GetProcAddress(h, "PdhCloseQuery");
4162N/A PdhCollectQueryData_i = (PdhCollectQueryDataFunc)GetProcAddress(h, "PdhCollectQueryData");
4162N/A PdhGetFormattedCounterValue_i = (PdhGetFormattedCounterValueFunc)GetProcAddress(h, "PdhGetFormattedCounterValue");
4162N/A PdhEnumObjectItems_i = (PdhEnumObjectItemsFunc)GetProcAddress(h, "PdhEnumObjectItemsA");
4162N/A PdhRemoveCounter_i = (PdhRemoveCounterFunc)GetProcAddress(h, "PdhRemoveCounter");
4162N/A PdhLookupPerfNameByIndex_i = (PdhLookupPerfNameByIndexFunc)GetProcAddress(h, "PdhLookupPerfNameByIndexA");
4162N/A PdhMakeCounterPath_i = (PdhMakeCounterPathFunc)GetProcAddress(h, "PdhMakeCounterPathA");
4162N/A
4162N/A if (PdhAddCounter_i == NULL || PdhOpenQuery_i == NULL ||
4162N/A PdhCloseQuery_i == NULL || PdhCollectQueryData_i == NULL ||
4162N/A PdhGetFormattedCounterValue_i == NULL || PdhEnumObjectItems_i == NULL ||
4162N/A PdhRemoveCounter_i == NULL || PdhLookupPerfNameByIndex_i == NULL || PdhMakeCounterPath_i == NULL)
4162N/A {
4162N/A _snprintf(ebuf, elen, "Required method could not be found.");
4162N/A return -1;
4162N/A }
4162N/A return CONFIG_SUCCESSFUL;
4162N/A}
4162N/A
4162N/A/**
4162N/A * Returns the counter value as a double for the specified query.
4162N/A * Will collect the query data and update the counter values as necessary.
4162N/A *
4162N/A * @param query the query to update (if needed).
4162N/A * @param c the counter to read.
4162N/A * @param value where to store the formatted value.
4162N/A * @param format the format to use (i.e. PDH_FMT_DOUBLE, PDH_FMT_LONG etc)
4162N/A * @return CONFIG_SUCCESSFUL if no error
4162N/A * -1 if PdhCollectQueryData fails
4162N/A * -2 if PdhGetFormattedCounterValue fails
4162N/A */
4162N/Astatic int
4162N/AgetPerformanceData(UpdateQueryP query, HCOUNTER c, PDH_FMT_COUNTERVALUE* value, DWORD format) {
4162N/A clock_t now;
4162N/A now = clock();
4162N/A
4162N/A // Need to limit how often we update the query
4162N/A // to mimise the heisenberg effect.
4162N/A // (PDH behaves erratically if the counters are
4162N/A // queried too often, especially counters that
4162N/A // store and use values from two consecutive updates,
4162N/A // like cpu load.)
4162N/A if (now - query->lastUpdate > MIN_UPDATE_INTERVAL) {
4162N/A if (PdhCollectQueryData_i(query->query) != ERROR_SUCCESS) {
4162N/A return -1;
4162N/A }
4162N/A query->lastUpdate = now;
4162N/A }
4162N/A
4162N/A if (PdhGetFormattedCounterValue_i(c, format, NULL, value) != ERROR_SUCCESS) {
4162N/A return -2;
4162N/A }
4162N/A return CONFIG_SUCCESSFUL;
4162N/A}
4162N/A
4162N/A/**
4162N/A * Places the resolved counter name of the counter at the specified index in the
4162N/A * supplied buffer. There must be enough space in the buffer to hold the counter name.
4162N/A *
4162N/A * @param index the counter index as specified in the registry.
4162N/A * @param buf the buffer in which to place the counter name.
4162N/A * @param size the size of the counter name buffer.
4162N/A * @param ebuf the error message buffer.
4162N/A * @param elen the length of the error buffer.
4162N/A * @return CONFIG_SUCCESSFUL if successful, negative on failure.
4162N/A */
4162N/Astatic int
4162N/Afind_name(DWORD index, char *buf, DWORD size) {
4162N/A PDH_STATUS res;
4162N/A
4162N/A if ((res = PdhLookupPerfNameByIndex_i(NULL, index, buf, &size)) != ERROR_SUCCESS) {
4162N/A
4162N/A /* printf("Could not open counter %d: error=0x%08x", index, res); */
4162N/A /* if (res == PDH_CSTATUS_NO_MACHINE) { */
4162N/A /* printf("User probably does not have sufficient privileges to use"); */
4162N/A /* printf("performance counters. If you are running on Windows 2003"); */
4162N/A /* printf("or Windows Vista, make sure the user is in the"); */
4162N/A /* printf("Performance Logs user group."); */
4162N/A /* } */
4162N/A return -1;
4162N/A }
4162N/A
4162N/A if (size == 0) {
4162N/A /* printf("Failed to get counter name for %d: empty string", index); */
4162N/A return -1;
4162N/A }
4162N/A
4162N/A // windows vista does not null-terminate the string (allthough the docs says it will)
4162N/A buf[size - 1] = '\0';
4162N/A return CONFIG_SUCCESSFUL;
4162N/A}
4162N/A
4162N/A/**
4162N/A * Sets up the supplied SingleCounterQuery to listen for the specified counter.
4162N/A * initPDH() must have been run prior to calling this function!
4162N/A *
4162N/A * @param counterQuery the counter query to set up.
4162N/A * @param counterString the string specifying the path to the counter.
4162N/A * @param ebuf the error buffer.
4162N/A * @param elen the length of the error buffer.
4162N/A * @returns CONFIG_SUCCESSFUL if successful, negative on failure.
4162N/A */
4162N/Astatic int
4162N/AinitSingleCounterQuery(SingleCounterQueryP counterQuery, char *counterString) {
4162N/A if (PdhOpenQuery_i(NULL, 0, &counterQuery->query.query) != ERROR_SUCCESS) {
4162N/A /* printf("Could not open query for %s", counterString); */
4162N/A return -1;
4162N/A }
4162N/A if (PdhAddCounter_i(counterQuery->query.query, counterString, 0, &counterQuery->counter) != ERROR_SUCCESS) {
4162N/A /* printf("Could not add counter %s for query", counterString); */
4162N/A if (counterQuery->counter != NULL) {
4162N/A PdhRemoveCounter_i(counterQuery->counter);
4162N/A }
4162N/A if (counterQuery->query.query != NULL) {
4162N/A PdhCloseQuery_i(counterQuery->query.query);
4162N/A }
4162N/A memset(counterQuery, 0, sizeof(SingleCounterQueryS));
4162N/A return -1;
4162N/A }
4162N/A return CONFIG_SUCCESSFUL;
4162N/A}
4162N/A
4162N/A/**
4162N/A * Sets up the supplied SingleCounterQuery to listen for the time spent
4162N/A * by the HotSpot process.
4162N/A *
4162N/A * @param counterQuery the counter query to set up as a process counter.
4162N/A * @param ebuf the error buffer.
4162N/A * @param elen the length of the error buffer.
4162N/A * @returns CONFIG_SUCCESSFUL if successful, negative on failure.
4162N/A */
4162N/Astatic int
4162N/AinitProcLoadCounter(void) {
4162N/A char time[COUNTER_BUF_SIZE];
4162N/A char counter[COUNTER_BUF_SIZE*2];
4162N/A
4162N/A if (find_name(PDH_PROCESSOR_TIME_IDX, time, sizeof(time)-1) < 0) {
4162N/A return -1;
4162N/A }
4162N/A _snprintf(counter, sizeof(counter)-1, "%s\\%s", getProcessPDHHeader(), time);
4162N/A return initSingleCounterQuery(&cntProcLoad, counter);
4162N/A}
4162N/A
4162N/Astatic int
4162N/AinitProcSystemLoadCounter(void) {
4162N/A char time[COUNTER_BUF_SIZE];
4162N/A char counter[COUNTER_BUF_SIZE*2];
4162N/A
4162N/A if (find_name(PDH_PRIV_PROCESSOR_TIME_IDX, time, sizeof(time)-1) < 0) {
4162N/A return -1;
4162N/A }
4162N/A _snprintf(counter, sizeof(counter)-1, "%s\\%s", getProcessPDHHeader(), time);
4162N/A return initSingleCounterQuery(&cntProcSystemLoad, counter);
4162N/A}
4162N/A
4162N/A/**
4162N/A * Sets up the supplied MultipleCounterQuery to check on the processors.
4162N/A * (Comment: Refactor and prettify as with the the SingleCounter queries
4162N/A * if more MultipleCounterQueries are discovered.)
4162N/A *
4162N/A * initPDH() must have been run prior to calling this function.
4162N/A *
4162N/A * @param multiQuery a pointer to a MultipleCounterQueryS, will be filled in with
4162N/A * the necessary info to check the PDH processor counters.
4162N/A * @return CONFIG_SUCCESSFUL if successful, negative on failure.
4162N/A */
4162N/Astatic int
4162N/AinitProcessorCounters(void) {
4162N/A char processor[COUNTER_BUF_SIZE]; //'Processor' == #238
4162N/A char time[COUNTER_BUF_SIZE]; //'Time' == 6
4162N/A DWORD c_size, i_size;
4162N/A HQUERY tmpQuery;
4162N/A DWORD i, p_count;
4162N/A BOOL error;
4162N/A char *instances, *tmp;
4162N/A PDH_STATUS pdhStat;
4162N/A
4162N/A c_size = i_size = 0;
4162N/A tmpQuery = NULL;
4162N/A error = false;
4162N/A
4162N/A // This __try / __except stuff is there since Windows 2000 beta (or so) sometimes triggered
4162N/A // an access violation when the user had insufficient privileges to use the performance
4162N/A // counters. This was previously guarded by a very ugly piece of code which disabled the
4162N/A // global trap handling in JRockit. Don't know if this really is needed anymore, but otoh,
4162N/A // if we keep it we don't crash on Win2k beta. /Ihse, 2005-05-30
4162N/A __try {
4162N/A if (find_name(PDH_PROCESSOR_IDX, processor, sizeof(processor)-1) < 0) {
4162N/A return -1;
4162N/A }
4162N/A } __except (EXCEPTION_EXECUTE_HANDLER) { // We'll catch all exceptions here.
4162N/A /* printf("User does not have sufficient privileges to use performance counters"); */
4162N/A return -1;
4162N/A }
4162N/A
4162N/A if (find_name(PDH_PROCESSOR_TIME_IDX, time, sizeof(time)-1) < 0) {
4162N/A return -1;
4162N/A }
4162N/A //ok, now we have enough to enumerate all processors.
4162N/A pdhStat = PdhEnumObjectItems_i (
4162N/A NULL, // reserved
4162N/A NULL, // local machine
4162N/A processor, // object to enumerate
4162N/A NULL, // pass in NULL buffers
4162N/A &c_size, // and 0 length to get
4162N/A NULL, // required size
4162N/A &i_size, // of the buffers in chars
4162N/A PERF_DETAIL_WIZARD, // counter detail level
4162N/A 0);
4162N/A if (pdh_fail(pdhStat)) {
4162N/A /* printf("could not enumerate processors (1) error=%d", pdhStat); */
4162N/A return -1;
4162N/A }
4162N/A
4162N/A // use calloc because windows vista does not null terminate the instance names (allthough the docs says it will)
4162N/A instances = calloc(i_size, 1);
4162N/A if (instances == NULL) {
4162N/A /* printf("could not allocate memory (1) %d bytes", i_size); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A
4162N/A c_size = 0;
4162N/A pdhStat = PdhEnumObjectItems_i (
4162N/A NULL, // reserved
4162N/A NULL, // local machine
4162N/A processor, // object to enumerate
4162N/A NULL, // pass in NULL buffers
4162N/A &c_size, // and 0 length to get
4162N/A instances, // required size
4162N/A &i_size, // of the buffers in chars
4162N/A PERF_DETAIL_WIZARD, // counter detail level
4162N/A 0);
4162N/A
4162N/A if (pdh_fail(pdhStat)) {
4162N/A /* printf("could not enumerate processors (2) error=%d", pdhStat); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A //count perf count instances.
4162N/A for (p_count = 0, tmp = instances; *tmp != 0; tmp = &tmp[lstrlen(tmp)+1], p_count++);
4162N/A
4162N/A //is this correct for HT?
4162N/A assert(p_count == num_cpus+1);
4162N/A
4162N/A //ok, have number of perf counters.
4162N/A multiCounterCPULoad.counters = calloc(p_count, sizeof(HCOUNTER));
4162N/A if (multiCounterCPULoad.counters == NULL) {
4162N/A /* printf("could not allocate memory (2) count=%d", p_count); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A
4162N/A multiCounterCPULoad.noOfCounters = p_count;
4162N/A
4162N/A if (PdhOpenQuery_i(NULL, 0, &multiCounterCPULoad.query.query) != ERROR_SUCCESS) {
4162N/A /* printf("could not create query"); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A //now, fetch the counters.
4162N/A for (i = 0, tmp = instances; *tmp != '\0'; tmp = &tmp[lstrlen(tmp)+1], i++) {
4162N/A char counter[2*COUNTER_BUF_SIZE];
4162N/A
4162N/A _snprintf(counter, sizeof(counter)-1, "\\%s(%s)\\%s", processor, tmp, time);
4162N/A
4162N/A if (PdhAddCounter_i(multiCounterCPULoad.query.query, counter, 0, &multiCounterCPULoad.counters[i]) != ERROR_SUCCESS) {
4162N/A /* printf("error adding processor counter %s", counter); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A }
4162N/A
4162N/A free(instances);
4162N/A instances = NULL;
4162N/A
4162N/A // Query once to initialize the counters needing at least two queries
4162N/A // (like the % CPU usage) to calculate correctly.
4162N/A if (PdhCollectQueryData_i(multiCounterCPULoad.query.query) != ERROR_SUCCESS)
4162N/A error = true;
4162N/A
4162N/A end:
4162N/A if (instances != NULL) {
4162N/A free(instances);
4162N/A }
4162N/A if (tmpQuery != NULL) {
4162N/A PdhCloseQuery_i(tmpQuery);
4162N/A }
4162N/A if (error) {
4162N/A int i;
4162N/A
4162N/A if (multiCounterCPULoad.counters != NULL) {
4162N/A for (i = 0; i < multiCounterCPULoad.noOfCounters; i++) {
4162N/A if (multiCounterCPULoad.counters[i] != NULL) {
4162N/A PdhRemoveCounter_i(multiCounterCPULoad.counters[i]);
4162N/A }
4162N/A }
4162N/A free(multiCounterCPULoad.counters[i]);
4162N/A }
4162N/A if (multiCounterCPULoad.query.query != NULL) {
4162N/A PdhCloseQuery_i(multiCounterCPULoad.query.query);
4162N/A }
4162N/A memset(&multiCounterCPULoad, 0, sizeof(MultipleCounterQueryS));
4162N/A return -1;
4162N/A }
4162N/A return CONFIG_SUCCESSFUL;
4162N/A}
4162N/A
4162N/A/**
4162N/A * Help function that initializes the PDH process header for the JRockit process.
4162N/A * (You should probably use getProcessPDHHeader() instead!)
4162N/A *
4162N/A * initPDH() must have been run prior to calling this function.
4162N/A *
4162N/A * @param ebuf the error buffer.
4162N/A * @param elen the length of the error buffer.
4162N/A *
4162N/A * @return the PDH instance description corresponding to the JVM process.
4162N/A */
4162N/Astatic char*
4162N/AinitProcessPDHHeader(void) {
4162N/A static char hotspotheader[2*COUNTER_BUF_SIZE];
4162N/A
4162N/A char counter[2*COUNTER_BUF_SIZE];
4162N/A char processes[COUNTER_BUF_SIZE]; //'Process' == #230
4162N/A char pid[COUNTER_BUF_SIZE]; //'ID Process' == 784
4162N/A char module_name[MAX_PATH];
4162N/A PDH_STATUS pdhStat;
4162N/A DWORD c_size = 0, i_size = 0;
4162N/A HQUERY tmpQuery = NULL;
4162N/A int i, myPid = _getpid();
4162N/A BOOL error = false;
4162N/A char *instances, *tmp, *instance_name, *dot_pos;
4162N/A
4162N/A tmpQuery = NULL;
4162N/A myPid = _getpid();
4162N/A error = false;
4162N/A
4162N/A if (find_name(PDH_PROCESS_IDX, processes, sizeof(processes) - 1) < 0) {
4162N/A return NULL;
4162N/A }
4162N/A
4162N/A if (find_name(PDH_ID_PROCESS_IDX, pid, sizeof(pid) - 1) < 0) {
4162N/A return NULL;
4162N/A }
4162N/A //time is same.
4162N/A
4162N/A c_size = 0;
4162N/A i_size = 0;
4162N/A
4162N/A pdhStat = PdhEnumObjectItems_i (
4162N/A NULL, // reserved
4162N/A NULL, // local machine
4162N/A processes, // object to enumerate
4162N/A NULL, // pass in NULL buffers
4162N/A &c_size, // and 0 length to get
4162N/A NULL, // required size
4162N/A &i_size, // of the buffers in chars
4162N/A PERF_DETAIL_WIZARD, // counter detail level
4162N/A 0);
4162N/A
4162N/A //ok, now we have enough to enumerate all processes
4162N/A if (pdh_fail(pdhStat)) {
4162N/A /* printf("Could not enumerate processes (1) error=%d", pdhStat); */
4162N/A return NULL;
4162N/A }
4162N/A
4162N/A // use calloc because windows vista does not null terminate the instance names (allthough the docs says it will)
4162N/A if ((instances = calloc(i_size, 1)) == NULL) {
4162N/A /* printf("Could not allocate memory %d bytes", i_size); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A
4162N/A c_size = 0;
4162N/A
4162N/A pdhStat = PdhEnumObjectItems_i (
4162N/A NULL, // reserved
4162N/A NULL, // local machine
4162N/A processes, // object to enumerate
4162N/A NULL, // pass in NULL buffers
4162N/A &c_size, // and 0 length to get
4162N/A instances, // required size
4162N/A &i_size, // of the buffers in chars
4162N/A PERF_DETAIL_WIZARD, // counter detail level
4162N/A 0);
4162N/A
4162N/A // ok, now we have enough to enumerate all processes
4162N/A if (pdh_fail(pdhStat)) {
4162N/A /* printf("Could not enumerate processes (2) error=%d", pdhStat); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A
4162N/A if (PdhOpenQuery_i(NULL, 0, &tmpQuery) != ERROR_SUCCESS) {
4162N/A /* printf("Could not create temporary query"); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A
4162N/A // Find our module name and use it to extract the instance name used by PDH
4162N/A if (GetModuleFileName(NULL, module_name, MAX_PATH) >= MAX_PATH-1) {
4162N/A /* printf("Module name truncated"); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A instance_name = strrchr(module_name, '\\'); //drop path
4162N/A instance_name++; //skip slash
4162N/A dot_pos = strchr(instance_name, '.'); //drop .exe
4162N/A dot_pos[0] = '\0';
4162N/A
4162N/A //now, fetch the counters.
4162N/A for (tmp = instances; *tmp != 0 && !error; tmp = &tmp[lstrlen(tmp)+1]) {
4162N/A HCOUNTER hc = NULL;
4162N/A BOOL done = false;
4162N/A
4162N/A // Skip until we find our own process name
4162N/A if (strcmp(tmp, instance_name) != 0) {
4162N/A continue;
4162N/A }
4162N/A
4162N/A // iterate over all instance indexes and try to find our own pid
4162N/A for (i = 0; !done && !error; i++){
4162N/A PDH_STATUS res;
4162N/A _snprintf(counter, sizeof(counter)-1, "\\%s(%s#%d)\\%s", processes, tmp, i, pid);
4162N/A
4162N/A if (PdhAddCounter_i(tmpQuery, counter, 0, &hc) != ERROR_SUCCESS) {
4162N/A /* printf("Failed to create process id query"); */
4162N/A error = true;
4162N/A goto end;
4162N/A }
4162N/A
4162N/A res = PdhCollectQueryData_i(tmpQuery);
4162N/A
4162N/A if (res == PDH_INVALID_HANDLE) {
4162N/A /* printf("Failed to query process id"); */
4162N/A res = -1;
4162N/A done = true;
4162N/A } else if (res == PDH_NO_DATA) {
4162N/A done = true;
4162N/A } else {
4162N/A PDH_FMT_COUNTERVALUE cv;
4162N/A
4162N/A PdhGetFormattedCounterValue_i(hc, PDH_FMT_LONG, NULL, &cv);
4162N/A /*
4162N/A * This check seems to be needed for Win2k SMP boxes, since
4162N/A * they for some reason don't return PDH_NO_DATA for non existing
4162N/A * counters.
4162N/A */
4162N/A if (cv.CStatus != PDH_CSTATUS_VALID_DATA) {
4162N/A done = true;
4162N/A } else if (cv.longValue == myPid) {
4162N/A _snprintf(hotspotheader, sizeof(hotspotheader)-1, "\\%s(%s#%d)\0", processes, tmp, i);
4162N/A PdhRemoveCounter_i(hc);
4162N/A goto end;
4162N/A }
4162N/A }
4162N/A PdhRemoveCounter_i(hc);
4162N/A }
4162N/A }
4162N/A end:
4162N/A if (instances != NULL) {
4162N/A free(instances);
4162N/A }
4162N/A if (tmpQuery != NULL) {
4162N/A PdhCloseQuery_i(tmpQuery);
4162N/A }
4162N/A if (error) {
4162N/A return NULL;
4162N/A }
4162N/A return hotspotheader;
4162N/A}
4162N/A
4162N/A/**
4162N/A * Returns the PDH string prefix identifying the HotSpot process. Use this prefix when getting
4162N/A * counters from the PDH process object representing HotSpot.
4162N/A *
4162N/A * Note: this call may take some time to complete.
4162N/A *
4162N/A * @param ebuf error buffer.
4162N/A * @param elen error buffer length.
4162N/A *
4162N/A * @return the header to be used when retrieving PDH counters from the HotSpot process.
4162N/A * Will return NULL if the call failed.
4162N/A */
4162N/Astatic char *
4162N/AgetProcessPDHHeader(void) {
4162N/A static char *processHeader = NULL;
4162N/A
4162N/A EnterCriticalSection(&processHeaderLock); {
4162N/A if (processHeader == NULL) {
4162N/A processHeader = initProcessPDHHeader();
4162N/A }
4162N/A } LeaveCriticalSection(&processHeaderLock);
4162N/A return processHeader;
4162N/A}
4162N/A
4162N/Aint perfInit(void);
4162N/A
4162N/Adouble
4162N/AperfGetCPULoad(int which)
4162N/A{
4162N/A PDH_FMT_COUNTERVALUE cv;
4162N/A HCOUNTER c;
4162N/A
4162N/A if (perfInit() < 0) {
4162N/A // warn?
4162N/A return -1.0;
4162N/A }
4162N/A
4162N/A if (multiCounterCPULoad.query.query == NULL) {
4162N/A // warn?
4162N/A return -1.0;
4162N/A }
4162N/A
4162N/A if (which == -1) {
4162N/A c = multiCounterCPULoad.counters[multiCounterCPULoad.noOfCounters - 1];
4162N/A } else {
4162N/A if (which < multiCounterCPULoad.noOfCounters) {
4162N/A c = multiCounterCPULoad.counters[which];
4162N/A } else {
4162N/A return -1.0;
4162N/A }
4162N/A }
4162N/A if (getPerformanceData(&multiCounterCPULoad.query, c, &cv, PDH_FMT_DOUBLE ) == CONFIG_SUCCESSFUL) {
4162N/A return cv.doubleValue / 100;
4162N/A }
4162N/A return -1.0;
4162N/A}
4162N/A
4162N/Adouble
4162N/AperfGetProcessLoad(void)
4162N/A{
4162N/A PDH_FMT_COUNTERVALUE cv;
4162N/A
4162N/A if (perfInit() < 0) {
4162N/A // warn?
4162N/A return -1.0;
4162N/A }
4162N/A
4162N/A if (cntProcLoad.query.query == NULL) {
4162N/A // warn?
4162N/A return -1.0;
4162N/A }
4162N/A
4162N/A if (getPerformanceData(&cntProcLoad.query, cntProcLoad.counter, &cv, PDH_FMT_DOUBLE | PDH_FMT_NOCAP100) == CONFIG_SUCCESSFUL) {
4162N/A double d = cv.doubleValue / cpuFactor;
4162N/A d = min(1, d);
4162N/A d = max(0, d);
4162N/A return d;
4162N/A }
4162N/A return -1.0;
4162N/A}
4162N/A
4162N/A/**
4162N/A * Helper to initialize the PDH library. Loads the library and sets up the functions.
4162N/A * Note that once loaded, we will never unload the PDH library.
4162N/A *
4162N/A * @return CONFIG_SUCCESSFUL if successful, negative on failure.
4162N/A */
4162N/Aint
4162N/AperfInit(void) {
4162N/A static HMODULE h;
4162N/A static BOOL running, inited;
4162N/A
4162N/A int error;
4162N/A
4162N/A if (running) {
4162N/A return CONFIG_SUCCESSFUL;
4162N/A }
4162N/A
4162N/A error = CONFIG_SUCCESSFUL;
4162N/A
4162N/A // this is double checked locking again, but we try to bypass the worst by
4162N/A // implicit membar at end of lock.
4162N/A EnterCriticalSection(&initializationLock); {
4162N/A if (!inited) {
4162N/A char buf[64] = "";
4162N/A SYSTEM_INFO si;
4162N/A
4162N/A // CMH. But windows will not care about our affinity when giving
4162N/A // us measurements. Need the real, raw num cpus.
4162N/A
4162N/A GetSystemInfo(&si);
4162N/A num_cpus = si.dwNumberOfProcessors;
4162N/A // Initialize the denominator for the jvm load calculations
4162N/A cpuFactor = num_cpus * 100;
4162N/A
4162N/A /**
4162N/A * Do this dynamically, so we don't fail to start on systems without pdh.
4162N/A */
4162N/A if ((h = LoadLibrary("pdh.dll")) == NULL) {
4162N/A /* printf("Could not load pdh.dll (%d)", GetLastError()); */
4162N/A error = -2;
4162N/A } else if (get_functions(h, buf, sizeof(buf)) < 0) {
4162N/A FreeLibrary(h);
4162N/A h = NULL;
4162N/A error = -2;
4162N/A /* printf("Failed to init pdh functions: %s.\n", buf); */
4162N/A } else {
4162N/A if (initProcessorCounters() != 0) {
4162N/A /* printf("Failed to init system load counters.\n"); */
4162N/A } else if (initProcLoadCounter() != 0) {
4162N/A /* printf("Failed to init process load counter.\n"); */
4162N/A } else if (initProcSystemLoadCounter() != 0) {
4162N/A /* printf("Failed to init process system load counter.\n"); */
4162N/A } else {
4162N/A inited = true;
4162N/A }
4162N/A }
4162N/A }
4162N/A } LeaveCriticalSection(&initializationLock);
4162N/A
4162N/A if (inited && error == CONFIG_SUCCESSFUL) {
4162N/A running = true;
4162N/A }
4162N/A
4162N/A return error;
4162N/A}
4162N/A
4162N/AJNIEXPORT jdouble JNICALL
4162N/AJava_com_sun_management_OperatingSystem_getSystemCpuLoad
4162N/A(JNIEnv *env, jobject dummy)
4162N/A{
4162N/A return perfGetCPULoad(-1);
4162N/A}
4162N/A
4162N/AJNIEXPORT jdouble JNICALL
4162N/AJava_com_sun_management_OperatingSystem_getProcessCpuLoad
4162N/A(JNIEnv *env, jobject dummy)
4162N/A{
4162N/A return perfGetProcessLoad();
4162N/A}