aboutsummaryrefslogtreecommitdiff
path: root/src/netcpu_ntperf.c
blob: 88637fb5307a4aed955c73843a66dde763fcae93 (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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
char   netcpu_ntperf_id[]="\
@(#)netcpu_ntperf.c (c) Copyright 2005-2012, Hewlett-Packard Company, Version 2.6.0";

#if HAVE_CONFIG_H
# include <config.h>
#endif

#include <stdio.h>

#include <process.h>
#include <time.h>

#include <windows.h>
#include <assert.h>

#include <winsock2.h>
// If you are trying to compile on Windows 2000 or NT 4.0 you may
// need to define DONT_IPV6 in the "sources" files.
#ifndef DONT_IPV6
#include <ws2tcpip.h>
#endif

#include "netsh.h"
#include "netlib.h"

//
// System CPU time information class.
// Used to get CPU time information.
//
//     SDK\inc\ntexapi.h
// Function x8:   SystemProcessorPerformanceInformation
// DataStructure: SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
//

#define SystemProcessorPerformanceInformation 0x08

typedef struct
{
        LARGE_INTEGER   IdleTime;
        LARGE_INTEGER   KernelTime;
        LARGE_INTEGER   UserTime;
        LARGE_INTEGER   DpcTime;
        LARGE_INTEGER   InterruptTime;
        LONG                    InterruptCount;
} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, *PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;

//
// Calls to get the information
//
typedef ULONG (__stdcall *NT_QUERY_SYSTEM_INFORMATION)(
                                                                                        ULONG SystemInformationClass,
                                                                                        PVOID SystemInformation,
                                                                                        ULONG SystemInformationLength,
                                                                                        PULONG ReturnLength
                                                                                        );

NT_QUERY_SYSTEM_INFORMATION NtQuerySystemInformation = NULL;


static LARGE_INTEGER TickHz = {{0,0}};

_inline LARGE_INTEGER ReadPerformanceCounter(VOID)
{
        LARGE_INTEGER Counter;
        QueryPerformanceCounter(&Counter);

        return(Counter);
}       // ReadperformanceCounter


/* The NT performance data is accessed through the NtQuerySystemInformation
   call.  References to the PDH.DLL have been deleted.  This structure
   is the root for these data structures. */

typedef struct sPerfObj
{
        LARGE_INTEGER   StartTime;
        LARGE_INTEGER   EndTime;
        SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION StartInfo[MAXCPUS +1];
        SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION EndInfo[MAXCPUS +1];
} PerfObj, *PPerfObj;

static PerfObj *PerfCntrs;

// Forward declarations

PerfObj *InitPerfCntrs();
void RestartPerfCntrs(PerfObj *PerfCntrs);
double ReportPerfCntrs(PerfObj *PerfCntrs);  /* returns CPU utilization */
void ClosePerfCntrs(PerfObj *PerfCntrs);


void
cpu_util_init(void)
{
  if (NtQuerySystemInformation == NULL) {
    // Open the performance counter interface
    PerfCntrs = InitPerfCntrs();
  }
  return;
}

void
cpu_util_terminate(void)
{
  return;
}

int
get_cpu_method(void)
{
  return NT_METHOD;
}

typedef unsigned __int64    uint64_t;

void
get_cpu_idle(uint64_t *res)
{
  RestartPerfCntrs(PerfCntrs);
  return;
}

float
calibrate_idle_rate(int iterations, int interval)
{
  return (float)0.0;
}


/*
  InitPerfCntrs() -

  Changed to no longer access the NT performance registry interfaces.
  A direct call to NtQuerySystemInformation (an undocumented NT API)
  is made instead.  Parameters determined by decompilation of ntkrnlmp
  and ntdll.
*/


PerfObj *InitPerfCntrs()
{
  PerfObj *NewPerfCntrs;
  DWORD NTVersion;
  DWORD status;
  SYSTEM_INFO SystemInfo;

  GetSystemInfo(&SystemInfo);

  NewPerfCntrs = (PerfObj *)GlobalAlloc(GPTR, sizeof(PerfObj));
  assert(NewPerfCntrs != NULL);

  ZeroMemory((PCHAR)NewPerfCntrs, sizeof(PerfObj));

  // get NT version
  NTVersion = GetVersion();
  if (NTVersion >= 0x80000000)
    {
      fprintf(stderr, "Not running on Windows NT\n");
      exit(1);
    }

  // locate the calls we need in NTDLL
  //Lint
  NtQuerySystemInformation =
    (NT_QUERY_SYSTEM_INFORMATION)GetProcAddress( GetModuleHandle("ntdll.dll"),
						 "NtQuerySystemInformation" );

  if ( !(NtQuerySystemInformation) )
    {
      //Lint
      status = GetLastError();
      fprintf(stderr, "GetProcAddressFailed, status: %lX\n", status);
      exit(1);
    }

  // setup to measure timestamps with the high resolution timers.
  if (QueryPerformanceFrequency(&TickHz) == FALSE)
    {
      fprintf(stderr,"MAIN - QueryPerformanceFrequency Failed!\n");
      exit(2);
    }

  RestartPerfCntrs(NewPerfCntrs);

  return(NewPerfCntrs);
}  /* InitPerfCntrs */

/*
  RestartPerfCntrs() -

  The Performance counters must be read twice to produce rate and
  percentage results.  This routine is called before the start of a
  benchmark to establish the initial counters.  It must be called a
  second time after the benchmark completes to collect the final state
  of the performance counters.  ReportPerfCntrs is called to print the
  results after the benchmark completes.
*/

void RestartPerfCntrs(PerfObj *PerfCntrs)
{
  DWORD returnLength = 0;  //Lint
  DWORD returnNumCPUs;  //Lint
  DWORD i;

  DWORD status;
  SYSTEM_INFO SystemInfo;

  GetSystemInfo(&SystemInfo);

  // Move previous data from EndInfo to StartInfo.
  CopyMemory((PCHAR)&PerfCntrs->StartInfo[0],
	     (PCHAR)&PerfCntrs->EndInfo[0],
	     sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)*(MAXCPUS +1));

  PerfCntrs->StartTime = PerfCntrs->EndTime;

  // get the current CPUTIME information
  if ( (status = NtQuerySystemInformation( SystemProcessorPerformanceInformation,
					   (PCHAR)&PerfCntrs->EndInfo[0], sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)*MAXCPUS,
					   &returnLength )) != 0)
    {
      fprintf(stderr, "NtQuery failed, status: %lX\n", status);
      exit(1);
    }

  PerfCntrs->EndTime = ReadPerformanceCounter();

  // Validate that NtQuery returned a reasonable amount of data
  if ((returnLength % sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)) != 0)
    {
      fprintf(stderr, "NtQuery didn't return expected amount of data\n");
      fprintf(stderr, "Expected a multiple of %i, returned %lu\n",
	      sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION), returnLength);
      exit(1);
    }
  returnNumCPUs = returnLength / sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION);

  if (returnNumCPUs != (int)SystemInfo.dwNumberOfProcessors)
    {
      fprintf(stderr, "NtQuery didn't return expected amount of data\n");
      fprintf(stderr, "Expected data for %i CPUs, returned %lu\n",
	      (int)SystemInfo.dwNumberOfProcessors, returnNumCPUs);
      exit(1);
    }

  // Zero entries not returned by NtQuery
  ZeroMemory((PCHAR)&PerfCntrs->EndInfo[returnNumCPUs],
	     sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)*
	     (MAXCPUS +1 - returnNumCPUs));

  // Total all of the CPUs
  //      KernelTime needs to be fixed-up; it includes both idle &
  // true kernel time
  //  Note that kernel time also includes DpcTime & InterruptTime, but
  // I like this.
  for (i=0; i < returnNumCPUs; i++)
    {
      PerfCntrs->EndInfo[i].KernelTime.QuadPart         -= PerfCntrs->EndInfo[i].IdleTime.QuadPart;
      PerfCntrs->EndInfo[MAXCPUS].IdleTime.QuadPart     += PerfCntrs->EndInfo[i].IdleTime.QuadPart;
      PerfCntrs->EndInfo[MAXCPUS].KernelTime.QuadPart   += PerfCntrs->EndInfo[i].KernelTime.QuadPart;
      PerfCntrs->EndInfo[MAXCPUS].UserTime.QuadPart     += PerfCntrs->EndInfo[i].UserTime.QuadPart;
      PerfCntrs->EndInfo[MAXCPUS].DpcTime.QuadPart      += PerfCntrs->EndInfo[i].DpcTime.QuadPart;
      PerfCntrs->EndInfo[MAXCPUS].InterruptTime.QuadPart += PerfCntrs->EndInfo[i].InterruptTime.QuadPart;
      PerfCntrs->EndInfo[MAXCPUS].InterruptCount                += PerfCntrs->EndInfo[i].InterruptCount;
    }

}   /* RestartPerfCntrs */

/*
  ReportPerfCntrs() -
  This routine reports the results of the various performance
  counters.
*/

double ReportPerfCntrs(PerfObj *PerfCntrs)
{
  double tot_CPU_Util;
  int i;
  double duration;  // in milliseconds

  LARGE_INTEGER ActualDuration;

  SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION        DeltaInfo[MAXCPUS +1];

  LARGE_INTEGER   TotalCPUTime[MAXCPUS +1];

  SYSTEM_INFO SystemInfo;

  GetSystemInfo(&SystemInfo);

  for (i=0; i <= MAXCPUS; i++)
    {
      DeltaInfo[i].IdleTime.QuadPart    = PerfCntrs->EndInfo[i].IdleTime.QuadPart -
	PerfCntrs->StartInfo[i].IdleTime.QuadPart;
      DeltaInfo[i].KernelTime.QuadPart          = PerfCntrs->EndInfo[i].KernelTime.QuadPart -
	PerfCntrs->StartInfo[i].KernelTime.QuadPart;
      DeltaInfo[i].UserTime.QuadPart    = PerfCntrs->EndInfo[i].UserTime.QuadPart -
	PerfCntrs->StartInfo[i].UserTime.QuadPart;
      DeltaInfo[i].DpcTime.QuadPart     = PerfCntrs->EndInfo[i].DpcTime.QuadPart -
	PerfCntrs->StartInfo[i].DpcTime.QuadPart;
      DeltaInfo[i].InterruptTime.QuadPart = PerfCntrs->EndInfo[i].InterruptTime.QuadPart -
	PerfCntrs->StartInfo[i].InterruptTime.QuadPart;
      DeltaInfo[i].InterruptCount               = PerfCntrs->EndInfo[i].InterruptCount -
	PerfCntrs->StartInfo[i].InterruptCount;

      TotalCPUTime[i].QuadPart =
	DeltaInfo[i].IdleTime.QuadPart +
	DeltaInfo[i].KernelTime.QuadPart +
	DeltaInfo[i].UserTime.QuadPart;
      // KernelTime already includes DpcTime & InterruptTime!
      // + DeltaInfo[i].DpcTime.QuadPart  +
      //  DeltaInfo[i].InterruptTime.QuadPart;
    }

  tot_CPU_Util = 100.0*(1.0 - (double)DeltaInfo[MAXCPUS].IdleTime.QuadPart/(double)TotalCPUTime[MAXCPUS].QuadPart);  //Lint

  // Re-calculate duration, since we may have stoped early due to cntr-C.
  ActualDuration.QuadPart = PerfCntrs->EndTime.QuadPart -
    PerfCntrs->StartTime.QuadPart;

  // convert to 100 usec (1/10th milliseconds) timebase.
  ActualDuration.QuadPart = (ActualDuration.QuadPart*10000)/TickHz.QuadPart;
  duration = (double)ActualDuration.QuadPart/10.0;  // duration in ms

  if (verbosity > 1)
    {
      fprintf(where,"ActualDuration (ms): %d\n", (int)duration);
    }

  if (verbosity > 1)
    {
      fprintf(where, "%% CPU    _Total");
      if ((int)SystemInfo.dwNumberOfProcessors > 1)
	{
	  for (i=0; i < (int)SystemInfo.dwNumberOfProcessors; i++)
	    {
	      fprintf(where, "\t CPU %i", i);
	    }
	}
      fprintf(where, "\n");

      fprintf(where, "Busy      %5.2f", tot_CPU_Util);
      if ((int)SystemInfo.dwNumberOfProcessors > 1)
	{
	  for (i=0; i < (int)SystemInfo.dwNumberOfProcessors; i++)
	    {
	      fprintf(where, "\t %5.2f",
		      100.0*(1.0 - (double)DeltaInfo[i].IdleTime.QuadPart/(double)TotalCPUTime[i].QuadPart));  //Lint
	    }
	}
      fprintf(where, "\n");

      fprintf(where, "Kernel    %5.2f",
	      100.0*(double)DeltaInfo[MAXCPUS].KernelTime.QuadPart/(double)TotalCPUTime[MAXCPUS].QuadPart);  //Lint

      if ((int)SystemInfo.dwNumberOfProcessors > 1)
	{
	  for (i=0; i < (int)SystemInfo.dwNumberOfProcessors; i++)
	    {
	      fprintf(where, "\t %5.2f",
		      100.0*(double)DeltaInfo[i].KernelTime.QuadPart/(double)TotalCPUTime[i].QuadPart);  //Lint
	    }
	}
      fprintf(where, "\n");

      fprintf(where, "User      %5.2f",
	      100.0*(double)DeltaInfo[MAXCPUS].UserTime.QuadPart/(double)TotalCPUTime[MAXCPUS].QuadPart);

      if ((int)SystemInfo.dwNumberOfProcessors > 1)
	{
	  for (i=0; i < (int)SystemInfo.dwNumberOfProcessors; i++)
	    {
	      fprintf(where, "\t %5.2f",
		      100.0*(double)DeltaInfo[i].UserTime.QuadPart/TotalCPUTime[i].QuadPart);  //Lint
	    }
	}
      fprintf(where, "\n");

      fprintf(where, "Dpc       %5.2f",
	      100.0*(double)DeltaInfo[MAXCPUS].DpcTime.QuadPart/(double)TotalCPUTime[MAXCPUS].QuadPart);  //Lint

      if ((int)SystemInfo.dwNumberOfProcessors > 1)
	{
	  for (i=0; i < (int)SystemInfo.dwNumberOfProcessors; i++)
	    {
	      fprintf(where, "\t %5.2f",
		      100.0*(double)DeltaInfo[i].DpcTime.QuadPart/(double)TotalCPUTime[i].QuadPart);  //Lint
	    }
	}
      fprintf(where, "\n");

      fprintf(where, "Interrupt %5.2f",
	      100.0*(double)DeltaInfo[MAXCPUS].InterruptTime.QuadPart/(double)TotalCPUTime[MAXCPUS].QuadPart);  //Lint

      if ((int)SystemInfo.dwNumberOfProcessors > 1)
	{
	  for (i=0; i < (int)SystemInfo.dwNumberOfProcessors; i++)
	    {
	      fprintf(where, "\t %5.2f",
		      100.0*(double)DeltaInfo[i].InterruptTime.QuadPart/TotalCPUTime[i].QuadPart);  //Lint
	    }
	}
      fprintf(where, "\n\n");

      fprintf(where, "Interrupt/Sec. %5.1f",
	      (double)DeltaInfo[MAXCPUS].InterruptCount*1000.0/duration);

      if ((int)SystemInfo.dwNumberOfProcessors > 1)
	{
	  for (i=0; i < (int)SystemInfo.dwNumberOfProcessors; i++)
	    {
	      fprintf(where, "\t %5.1f",
		      (double)DeltaInfo[i].InterruptCount*1000.0/duration);
	    }
	}
      fprintf(where, "\n\n");
      fflush(where);
    }

  return (tot_CPU_Util);

}  /* ReportPerfCntrs */

/*
  ClosePerfCntrs() -

  This routine cleans up the performance counter APIs.
*/

void ClosePerfCntrs(PerfObj *PerfCntrs)
{
        GlobalFree(PerfCntrs);

        NtQuerySystemInformation = NULL;
}   /* ClosePerfCntrs */

void
cpu_start_internal(void)
{
  RestartPerfCntrs(PerfCntrs);
}

void
cpu_stop_internal(void)
{
  RestartPerfCntrs(PerfCntrs);
}

float
calc_cpu_util_internal(float elapsed_time)
{
  float correction_factor;

  memset(&lib_local_cpu_stats, 0, sizeof(lib_local_cpu_stats));

  /* It is possible that the library measured a time other than */
  /* the one that the user want for the cpu utilization */
  /* calculations - for example, tests that were ended by */
  /* watchdog timers such as the udp stream test. We let these */
  /* tests tell up what the elapsed time should be. */

  if (elapsed_time != 0.0) {
    correction_factor = (float) 1.0 +
      ((lib_elapsed - elapsed_time) / elapsed_time);
  }
  else {
    correction_factor = (float) 1.0;
  }

  if (debug) {
    fprintf(where, "correction factor: %f\n", correction_factor);
  }

  lib_local_cpu_stats.cpu_util = (float)ReportPerfCntrs(PerfCntrs);
  lib_local_cpu_stats.cpu_util *= correction_factor;
  return lib_local_cpu_stats.cpu_util;

}