summaryrefslogtreecommitdiff
path: root/plugins/AutoShutdown/src/cpuusage.cpp
blob: 8ab1fa91c03e27cdaaa9d0d17bdd0be83688febb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*

'AutoShutdown'-Plugin for Miranda IM

Copyright 2004-2007 H. Herkenrath

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program (Shutdown-License.txt); if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include "common.h"

/************************* Stat Switch ********************************/

#define Li2Double(x) ((double)((x).HighPart)*4.294967296E9+(double)((x).LowPart)) 

static BOOL WinNT_PerfStatsSwitch(TCHAR *pszServiceName,BOOL fDisable)
{ 
	HKEY hKeyServices,hKeyService,hKeyPerf;
	DWORD dwData,dwDataSize;
	BOOL fSwitched=FALSE;
	/* Win2000+ */
	if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("System\\CurrentControlSet\\Services"),0,KEY_QUERY_VALUE|KEY_SET_VALUE,&hKeyServices)) {
		if(!RegOpenKeyEx(hKeyServices,pszServiceName,0,KEY_QUERY_VALUE|KEY_SET_VALUE,&hKeyService)) {
			if(!RegOpenKeyEx(hKeyService,_T("Performance"),0,KEY_QUERY_VALUE|KEY_SET_VALUE,&hKeyPerf)) {
				dwDataSize=sizeof(DWORD);
				if(!RegQueryValueEx(hKeyPerf,_T("Disable Performance Counters"),NULL,NULL,(BYTE*)&dwData,&dwDataSize))
					if((dwData!=0)!=fDisable)
						fSwitched=!RegSetValueEx(hKeyPerf,_T("Disable Performance Counters"),0,REG_DWORD,(BYTE*)&fDisable,dwDataSize);
				RegCloseKey(hKeyPerf);
			}
			RegCloseKey(hKeyService);
		}
		RegCloseKey(hKeyServices);
	}
	return fSwitched;
}

/************************* Poll Thread ********************************/
struct CpuUsageThreadParams {
	DWORD dwDelayMillis;
	CPUUSAGEAVAILPROC pfnDataAvailProc;
	LPARAM lParam;
	HANDLE hFirstEvent;
	DWORD *pidThread;
};

static BOOL CallBackAndWait(struct CpuUsageThreadParams *param,BYTE nCpuUsage)
{
	if(param->hFirstEvent!=NULL) {
		/* return value for PollCpuUsage() */
		*param->pidThread=GetCurrentThreadId();
		SetEvent(param->hFirstEvent);
		param->hFirstEvent=NULL;
		/* lower priority after first call */
		SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_IDLE);
	}
	if(!param->pfnDataAvailProc(nCpuUsage,param->lParam)) return FALSE;
	SleepEx(param->dwDelayMillis,TRUE);
	return !Miranda_Terminated();
}

static void WinNT_PollThread(void *vparam)
{
	CpuUsageThreadParams *param = (CpuUsageThreadParams*)vparam;

	DWORD dwBufferSize=0,dwCount;
	BYTE *pBuffer=NULL;
	PERF_DATA_BLOCK *pPerfData=NULL; 
	LONG res,lCount;
	PERF_OBJECT_TYPE *pPerfObj;
	PERF_COUNTER_DEFINITION *pPerfCounter; 
	PERF_INSTANCE_DEFINITION *pPerfInstance; 
	PERF_COUNTER_BLOCK *pPerfCounterBlock;
	DWORD dwObjectId,dwCounterId; 
	WCHAR wszValueName[11],*pwszInstanceName;
	BYTE nCpuUsage;
	BOOL fSwitched,fFound,fIsFirst=FALSE;
	LARGE_INTEGER liPrevCounterValue={0},liCurrentCounterValue={0},liPrevPerfTime100nSec={0};

	/* init */
	dwObjectId=238;             /*'Processor' object */
	dwCounterId=6;              /* '% processor time' counter */
	pwszInstanceName=L"_Total"; /* '_Total' instance */
	_itot_s(dwObjectId, wszValueName, 10);
	fSwitched = WinNT_PerfStatsSwitch(_T("PerfOS"), FALSE);

	/* poll */
	for(;;) {
		/* retrieve data for given object */
		res=RegQueryValueExW(HKEY_PERFORMANCE_DATA,wszValueName,NULL,NULL,(BYTE*)pPerfData,&dwBufferSize);
		while(!pBuffer || res==ERROR_MORE_DATA) {
			pBuffer=(BYTE*)mir_realloc(pPerfData,dwBufferSize+=256);
			if(!pBuffer) break;
			pPerfData=(PERF_DATA_BLOCK*)pBuffer;
			res=RegQueryValueExW(HKEY_PERFORMANCE_DATA,wszValueName,NULL,NULL,pBuffer,&dwBufferSize);
		}
		if(res!=ERROR_SUCCESS) break;

		/* find object in data */
		fFound=FALSE;
		/* first object */
		pPerfObj=(PERF_OBJECT_TYPE*)((BYTE*)pPerfData+pPerfData->HeaderLength);
		for(dwCount=0;dwCount<pPerfData->NumObjectTypes;++dwCount) {
			if(pPerfObj->ObjectNameTitleIndex==dwObjectId) {
				/* find counter in object data */
				/* first counter */
				pPerfCounter=(PERF_COUNTER_DEFINITION*)((BYTE*)pPerfObj+pPerfObj->HeaderLength);
				for(dwCount=0;dwCount<(pPerfObj->NumCounters);++dwCount) { 
					if(pPerfCounter->CounterNameTitleIndex==dwCounterId) {
						/* find instance in counter data */
						if(pPerfObj->NumInstances==PERF_NO_INSTANCES) { 
							pPerfCounterBlock=(PERF_COUNTER_BLOCK*)((BYTE*)pPerfObj+pPerfObj->DefinitionLength);
							liCurrentCounterValue=*(LARGE_INTEGER*)((BYTE*)pPerfCounterBlock+pPerfCounter->CounterOffset);
							fFound=TRUE;
						}
						else {
							/* first instance */
							pPerfInstance=(PERF_INSTANCE_DEFINITION*)((BYTE*)pPerfObj+pPerfObj->DefinitionLength);
							for(lCount=0;lCount<(pPerfObj->NumInstances);++lCount) {
								pPerfCounterBlock=(PERF_COUNTER_BLOCK*)((BYTE*)pPerfInstance+pPerfInstance->ByteLength);
								if(!lstrcmpiW(pwszInstanceName,(WCHAR*)((BYTE*)pPerfInstance+pPerfInstance->NameOffset)) || !pwszInstanceName) {
									liCurrentCounterValue=*(LARGE_INTEGER*)((BYTE*)pPerfCounterBlock+pPerfCounter->CounterOffset);
									fFound=TRUE;
									break;
								}
								/* next instance */
								pPerfInstance=(PPERF_INSTANCE_DEFINITION)((BYTE*)pPerfCounterBlock+pPerfCounterBlock->ByteLength);
							} 
						} 
						break;
					}
					/* next counter */
					pPerfCounter=(PERF_COUNTER_DEFINITION*)((BYTE*)pPerfCounter+pPerfCounter->ByteLength);
				}
				break; 
			} 
			/* next object */
			pPerfObj=(PERF_OBJECT_TYPE*)((BYTE*)pPerfObj+pPerfObj->TotalByteLength);
		}
		if(!fFound) break;

		/* calc val from data, we need two samplings
		 * counter type: PERF_100NSEC_TIMER_INV
		 * calc: time base=100Ns, value=100*(1-(data_diff)/(100NsTime_diff)) */
		if(!fIsFirst) {
			nCpuUsage=(BYTE)((1.0-(Li2Double(liCurrentCounterValue)-Li2Double(liPrevCounterValue))/(Li2Double(pPerfData->PerfTime100nSec)-Li2Double(liPrevPerfTime100nSec)))*100.0+0.5);
			if(!CallBackAndWait(param,nCpuUsage)) break;
		}
		else fIsFirst=FALSE;
		/* store current sampling for next */
		CopyMemory(&liPrevCounterValue,&liCurrentCounterValue,sizeof(LARGE_INTEGER)); 
		CopyMemory(&liPrevPerfTime100nSec,&pPerfData->PerfTime100nSec,sizeof(LARGE_INTEGER)); 
	}

	/* uninit */
	if(pPerfData) mir_free(pPerfData);
	if(fSwitched) WinNT_PerfStatsSwitch(_T("PerfOS"),TRUE);

	/* return error for PollCpuUsage() if never succeeded */
	if(param->hFirstEvent!=NULL) SetEvent(param->hFirstEvent);
	mir_free(param);
} 

/************************* Start Thread *******************************/

// returns poll thread id on success
DWORD PollCpuUsage(CPUUSAGEAVAILPROC pfnDataAvailProc,LPARAM lParam,DWORD dwDelayMillis)
{
	struct CpuUsageThreadParams *param;
	DWORD idThread=0;
	HANDLE hFirstEvent;

	/* init params */
	param=(struct CpuUsageThreadParams*)mir_alloc(sizeof(struct CpuUsageThreadParams));
	if(param==NULL) return FALSE;
	param->dwDelayMillis=dwDelayMillis;
	param->pfnDataAvailProc=pfnDataAvailProc;
	param->lParam=lParam;
	param->pidThread=&idThread;
	param->hFirstEvent=hFirstEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
	if(hFirstEvent==NULL) {
		mir_free(param);
		return 0;
	}
	/* start thread */
	if((int)mir_forkthread(WinNT_PollThread, param) != -1)
		WaitForSingleObject(hFirstEvent,INFINITE); /* wait for first success */
	else
		mir_free(param); /* thread not started */
	CloseHandle(hFirstEvent);
	return idThread;
}