2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2005, 2006, 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file testbed/gnunet-service-testbed_cpustatus.c
23 * @brief calls to determine current CPU load
24 * @author Tzvetan Horozov
25 * @author Christian Grothoff
26 * @author Igor Wronsky
27 * @author Alex Harper (OS X portion)
28 * @author Sree Harsha Totakura
32 #include "gnunet_util_lib.h"
38 #if HAVE_SYS_SYSINFO_H
39 #include <sys/sysinfo.h>
52 #include <mach/mach.h>
54 static processor_cpu_load_info_t prev_cpu_load;
57 #define DEBUG_STATUSCALLS GNUNET_NO
60 static FILE *proc_stat;
64 * Current CPU load, as percentage of CPU cycles not idle or
67 static int currentCPULoad;
69 static double agedCPULoad = -1;
72 * Current IO load, as percentage of CPU cycles blocked on IO.
74 static int currentIOLoad;
76 static double agedIOLoad = -1;
82 unsigned int cpu_count;
83 processor_cpu_load_info_t cpu_load;
84 mach_msg_type_number_t cpu_msg_count;
88 kret = host_processor_info (mach_host_self (),
89 PROCESSOR_CPU_LOAD_INFO,
91 (processor_info_array_t *) & cpu_load,
93 if (kret != KERN_SUCCESS)
96 GNUNET_GE_ERROR | GNUNET_GE_USER | GNUNET_GE_ADMIN |
97 GNUNET_GE_BULK, "host_processor_info failed.");
100 prev_cpu_load = GNUNET_malloc (cpu_count * sizeof (*prev_cpu_load));
101 for (i = 0; i < cpu_count; i++)
103 for (j = 0; j < CPU_STATE_MAX; j++)
105 prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
108 vm_deallocate (mach_task_self (),
109 (vm_address_t) cpu_load,
110 (vm_size_t) (cpu_msg_count * sizeof (*cpu_load)));
116 * Update the currentCPU and currentIO load values.
118 * Before its first invocation the method initStatusCalls() must be called.
119 * If there is an error the method returns -1.
127 /* under linux, first try %idle/usage using /proc/stat;
128 if that does not work, disable /proc/stat for the future
129 by closing the file and use the next-best method. */
130 if (proc_stat != NULL)
132 static unsigned long long last_cpu_results[5] = { 0, 0, 0, 0, 0 };
133 static int have_last_cpu = GNUNET_NO;
136 unsigned long long user_read, system_read, nice_read, idle_read,
138 unsigned long long user, system, nice, idle, iowait;
139 unsigned long long usage_time = 0, total_time = 1;
141 /* Get the first line with the data */
144 if (NULL == fgets (line, 256, proc_stat))
146 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
147 "fgets", "/proc/stat");
148 proc_stat = NULL; /* don't try again */
153 ret = sscanf (line, "%*s %llu %llu %llu %llu %llu",
155 &system_read, &nice_read, &idle_read, &iowait_read);
158 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
159 "fgets-sscanf", "/proc/stat");
161 proc_stat = NULL; /* don't try again */
162 have_last_cpu = GNUNET_NO;
166 /* Store the current usage */
167 user = user_read - last_cpu_results[0];
168 system = system_read - last_cpu_results[1];
169 nice = nice_read - last_cpu_results[2];
170 idle = idle_read - last_cpu_results[3];
171 iowait = iowait_read - last_cpu_results[4];
172 /* Calculate the % usage */
173 usage_time = user + system + nice;
174 total_time = usage_time + idle + iowait;
175 if ((total_time > 0) && (have_last_cpu == GNUNET_YES))
177 currentCPULoad = (int) (100L * usage_time / total_time);
179 currentIOLoad = (int) (100L * iowait / total_time);
181 currentIOLoad = -1; /* 2.4 kernel */
183 /* Store the values for the next calculation */
184 last_cpu_results[0] = user_read;
185 last_cpu_results[1] = system_read;
186 last_cpu_results[2] = nice_read;
187 last_cpu_results[3] = idle_read;
188 last_cpu_results[4] = iowait_read;
189 have_last_cpu = GNUNET_YES;
198 unsigned int cpu_count;
199 processor_cpu_load_info_t cpu_load;
200 mach_msg_type_number_t cpu_msg_count;
201 unsigned long long t_sys, t_user, t_nice, t_idle, t_total;
202 unsigned long long t_idle_all, t_total_all;
206 t_idle_all = t_total_all = 0;
207 kret = host_processor_info (mach_host_self (), PROCESSOR_CPU_LOAD_INFO,
209 (processor_info_array_t *) & cpu_load,
211 if (kret == KERN_SUCCESS)
213 for (i = 0; i < cpu_count; i++)
215 if (cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] >=
216 prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM])
218 t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] -
219 prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM];
223 t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] +
224 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] +
228 if (cpu_load[i].cpu_ticks[CPU_STATE_USER] >=
229 prev_cpu_load[i].cpu_ticks[CPU_STATE_USER])
231 t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] -
232 prev_cpu_load[i].cpu_ticks[CPU_STATE_USER];
236 t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] +
237 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_USER] +
241 if (cpu_load[i].cpu_ticks[CPU_STATE_NICE] >=
242 prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE])
244 t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] -
245 prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE];
249 t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
250 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
254 if (cpu_load[i].cpu_ticks[CPU_STATE_IDLE] >=
255 prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE])
257 t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] -
258 prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE];
262 t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
263 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
266 t_total = t_sys + t_user + t_nice + t_idle;
267 t_idle_all += t_idle;
268 t_total_all += t_total;
270 for (i = 0; i < cpu_count; i++)
272 for (j = 0; j < CPU_STATE_MAX; j++)
274 prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
278 currentCPULoad = 100 - (100 * t_idle_all) / t_total_all;
281 vm_deallocate (mach_task_self (),
282 (vm_address_t) cpu_load,
283 (vm_size_t) (cpu_msg_count * sizeof (*cpu_load)));
284 currentIOLoad = -1; /* FIXME-OSX! */
290 GNUNET_GE_ERROR | GNUNET_GE_USER | GNUNET_GE_ADMIN |
291 GNUNET_GE_BULK, "host_processor_info failed.");
292 return GNUNET_SYSERR;
296 /* try kstat (Solaris only) */
297 #if SOLARIS && HAVE_KSTAT_H && HAVE_SYS_SYSINFO_H
299 static long long last_idlecount;
300 static long long last_totalcount;
301 static int kstat_once; /* if open fails, don't keep
306 long long totalcount;
308 long long deltatotal;
315 GNUNET_GE_LOG_STRERROR (NULL,
316 GNUNET_GE_ERROR | GNUNET_GE_USER |
317 GNUNET_GE_ADMIN | GNUNET_GE_BULK,
324 for (khelper = kc->kc_chain; khelper != NULL; khelper = khelper->ks_next)
328 if (0 != strncmp (khelper->ks_name, "cpu_stat", strlen ("cpu_stat")))
330 if (khelper->ks_data_size > sizeof (cpu_stat_t))
331 continue; /* better save then sorry! */
332 if (-1 != kstat_read (kc, khelper, &stats))
334 idlecount += stats.cpu_sysinfo.cpu[CPU_IDLE];
336 += stats.cpu_sysinfo.cpu[CPU_IDLE] +
337 stats.cpu_sysinfo.cpu[CPU_USER] +
338 stats.cpu_sysinfo.cpu[CPU_KERNEL] +
339 stats.cpu_sysinfo.cpu[CPU_WAIT];
342 if (0 != kstat_close (kc))
343 GNUNET_GE_LOG_STRERROR (NULL,
344 GNUNET_GE_ERROR | GNUNET_GE_ADMIN |
345 GNUNET_GE_USER | GNUNET_GE_BULK, "kstat_close");
346 if ((idlecount == 0) && (totalcount == 0))
347 goto ABORT_KSTAT; /* no stats found => abort */
348 deltaidle = idlecount - last_idlecount;
349 deltatotal = totalcount - last_totalcount;
350 if ((deltatotal > 0) && (last_totalcount > 0))
352 currentCPULoad = (unsigned int) (100.0 * deltaidle / deltatotal);
353 if (currentCPULoad > 100)
354 currentCPULoad = 100; /* odd */
355 if (currentCPULoad < 0)
356 currentCPULoad = 0; /* odd */
357 currentCPULoad = 100 - currentCPULoad; /* computed idle-load before! */
361 currentIOLoad = -1; /* FIXME-SOLARIS! */
362 last_idlecount = idlecount;
363 last_totalcount = totalcount;
366 kstat_once = 1; /* failed, don't try again */
367 return GNUNET_SYSERR;
371 /* insert methods better than getloadavg for
372 other platforms HERE! */
374 /* ok, maybe we have getloadavg on this platform */
377 static int warnOnce = 0;
379 if (1 != getloadavg (&loadavg, 1))
381 /* only warn once, if there is a problem with
382 getloadavg, we're going to hit it frequently... */
386 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "getloadavg");
388 return GNUNET_SYSERR;
392 /* success with getloadavg */
393 currentCPULoad = (int) (100 * loadavg);
394 currentIOLoad = -1; /* FIXME */
402 if (GNNtQuerySystemInformation)
404 static double dLastKernel;
405 static double dLastIdle;
406 static double dLastUser;
413 SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION theInfo;
415 if (GNNtQuerySystemInformation (SystemProcessorPerformanceInformation,
417 sizeof (theInfo), NULL) == NO_ERROR)
419 /* PORT-ME MINGW: Multi-processor? */
420 dKernel = Li2Double (theInfo.KernelTime);
421 dIdle = Li2Double (theInfo.IdleTime);
422 dUser = Li2Double (theInfo.UserTime);
423 dDiffKernel = dKernel - dLastKernel;
424 dDiffIdle = dIdle - dLastIdle;
425 dDiffUser = dUser - dLastUser;
427 if (((dDiffKernel + dDiffUser) > 0) &&
428 (dLastIdle + dLastKernel + dLastUser > 0))
430 100.0 - (dDiffIdle / (dDiffKernel + dDiffUser)) * 100.0;
432 currentCPULoad = -1; /* don't know (yet) */
434 dLastKernel = dKernel;
438 currentIOLoad = -1; /* FIXME-MINGW */
443 /* only warn once, if there is a problem with
444 NtQuery..., we're going to hit it frequently... */
450 GNUNET_GE_ERROR | GNUNET_GE_USER |
451 GNUNET_GE_ADMIN | GNUNET_GE_BULK,
452 _("Cannot query the CPU usage (Windows NT).\n"));
454 return GNUNET_SYSERR;
460 DWORD dwDataSize, dwType, dwDummy;
463 if (RegOpenKeyEx (HKEY_DYN_DATA,
464 "PerfStats\\StartSrv",
465 0, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
473 GNUNET_GE_USER | GNUNET_GE_ADMIN |
474 GNUNET_GE_ERROR | GNUNET_GE_BULK,
475 _("Cannot query the CPU usage (Win 9x)\n"));
479 RegOpenKeyEx (HKEY_DYN_DATA,
480 "PerfStats\\StartStat", 0, KEY_ALL_ACCESS, &hKey);
481 dwDataSize = sizeof (dwDummy);
482 RegQueryValueEx (hKey,
484 NULL, &dwType, (LPBYTE) & dwDummy, &dwDataSize);
488 RegOpenKeyEx (HKEY_DYN_DATA,
489 "PerfStats\\StatData", 0, KEY_ALL_ACCESS, &hKey);
490 dwDataSize = sizeof (currentCPULoad);
491 RegQueryValueEx (hKey,
493 NULL, &dwType, (LPBYTE) & currentCPULoad, &dwDataSize);
495 currentIOLoad = -1; /* FIXME-MINGW! */
498 RegOpenKeyEx (HKEY_DYN_DATA,
499 "PerfStats\\StopStat", 0, KEY_ALL_ACCESS, &hKey);
500 RegOpenKeyEx (HKEY_DYN_DATA,
501 "PerfStats\\StopSrv", 0, KEY_ALL_ACCESS, &hKey);
502 dwDataSize = sizeof (dwDummy);
503 RegQueryValueEx (hKey,
505 NULL, &dwType, (LPBYTE) & dwDummy, &dwDataSize);
512 /* loadaverage not defined and no platform
513 specific alternative defined
516 return GNUNET_SYSERR;
521 * Update load values (if enough time has expired),
522 * including computation of averages. Code assumes
523 * that lock has already been obtained.
528 static struct GNUNET_TIME_Absolute lastCall;
529 struct GNUNET_TIME_Relative age;
531 age = GNUNET_TIME_absolute_get_duration (lastCall);
532 if ( (agedCPULoad == -1)
533 || (age.rel_value > 500) )
535 /* use smoothing, but do NOT update lastRet at frequencies higher
536 than 500ms; this makes the smoothing (mostly) independent from
537 the frequency at which getCPULoad is called (and we don't spend
538 more time measuring CPU than actually computing something). */
539 lastCall = GNUNET_TIME_absolute_get ();
541 if (currentCPULoad == -1)
547 if (agedCPULoad == -1)
549 agedCPULoad = currentCPULoad;
553 /* for CPU, we don't do the 'fast increase' since CPU is much
554 more jitterish to begin with */
555 agedCPULoad = (agedCPULoad * 31 + currentCPULoad) / 32;
558 if (currentIOLoad == -1)
564 if (agedIOLoad == -1)
566 agedIOLoad = currentIOLoad;
570 /* for IO, we don't do the 'fast increase' since IO is much
571 more jitterish to begin with */
572 agedIOLoad = (agedIOLoad * 31 + currentIOLoad) / 32;
579 * Get the load of the CPU relative to what is allowed.
580 * @return the CPU load as a percentage of allowed
581 * (100 is equivalent to full load)
587 return (int) agedCPULoad;
592 * Get the load of the CPU relative to what is allowed.
593 * @return the CPU load as a percentage of allowed
594 * (100 is equivalent to full load)
600 return (int) agedIOLoad;
604 * The following method is called in order to initialize the status calls
605 * routines. After that it is safe to call each of the status calls separately
606 * @return GNUNET_OK on success and GNUNET_SYSERR on error (or calls errexit).
612 proc_stat = fopen ("/proc/stat", "r");
613 if (NULL == proc_stat)
614 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
615 "fopen", "/proc/stat");
621 updateUsage (); /* initialize */
625 * Shutdown the status calls module.
631 if (proc_stat != NULL)
637 GNUNET_free_non_null (prev_cpu_load);
645 /* end of cpustatus.c */