2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2005, 2006 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 util/os_load_cpu.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)
31 #include "gnunet_common.h"
32 #include "gnunet_os_lib.h"
33 #include "gnunet_strings_lib.h"
39 #if HAVE_SYS_SYSINFO_H
40 #include <sys/sysinfo.h>
53 #include <mach/mach.h>
55 static processor_cpu_load_info_t prev_cpu_load;
58 #define DEBUG_STATUSCALLS GNUNET_NO
61 static FILE *proc_stat;
65 * Current CPU load, as percentage of CPU cycles not idle or
68 static int currentCPULoad;
70 static double agedCPULoad = -1;
73 * Current IO load, as percentage of CPU cycles blocked on IO.
75 static int currentIOLoad;
77 static double agedIOLoad = -1;
83 unsigned int cpu_count;
84 processor_cpu_load_info_t cpu_load;
85 mach_msg_type_number_t cpu_msg_count;
89 kret = host_processor_info (mach_host_self (),
90 PROCESSOR_CPU_LOAD_INFO,
92 (processor_info_array_t *) & cpu_load,
94 if (kret != KERN_SUCCESS)
96 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
97 "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_ERROR |
147 GNUNET_ERROR_TYPE_BULK,
148 "fgets", "/proc/stat");
150 proc_stat = NULL; /* don't try again */
155 ret = sscanf (line, "%*s %llu %llu %llu %llu %llu",
157 &system_read, &nice_read, &idle_read, &iowait_read);
160 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR |
161 GNUNET_ERROR_TYPE_BULK,
162 "fgets-sscanf", "/proc/stat");
164 proc_stat = NULL; /* don't try again */
165 have_last_cpu = GNUNET_NO;
169 /* Store the current usage */
170 user = user_read - last_cpu_results[0];
171 system = system_read - last_cpu_results[1];
172 nice = nice_read - last_cpu_results[2];
173 idle = idle_read - last_cpu_results[3];
174 iowait = iowait_read - last_cpu_results[4];
175 /* Calculate the % usage */
176 usage_time = user + system + nice;
177 total_time = usage_time + idle + iowait;
178 if ((total_time > 0) && (have_last_cpu == GNUNET_YES))
180 currentCPULoad = (int) (100L * usage_time / total_time);
182 currentIOLoad = (int) (100L * iowait / total_time);
184 currentIOLoad = -1; /* 2.4 kernel */
186 /* Store the values for the next calculation */
187 last_cpu_results[0] = user_read;
188 last_cpu_results[1] = system_read;
189 last_cpu_results[2] = nice_read;
190 last_cpu_results[3] = idle_read;
191 last_cpu_results[4] = iowait_read;
192 have_last_cpu = GNUNET_YES;
201 unsigned int cpu_count;
202 processor_cpu_load_info_t cpu_load;
203 mach_msg_type_number_t cpu_msg_count;
204 unsigned long long t_sys, t_user, t_nice, t_idle, t_total;
205 unsigned long long t_idle_all, t_total_all;
209 t_idle_all = t_total_all = 0;
210 kret = host_processor_info (mach_host_self (), PROCESSOR_CPU_LOAD_INFO,
212 (processor_info_array_t *) & cpu_load,
214 if (kret == KERN_SUCCESS)
216 for (i = 0; i < cpu_count; i++)
218 if (cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] >=
219 prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM])
221 t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] -
222 prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM];
226 t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] +
227 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] +
231 if (cpu_load[i].cpu_ticks[CPU_STATE_USER] >=
232 prev_cpu_load[i].cpu_ticks[CPU_STATE_USER])
234 t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] -
235 prev_cpu_load[i].cpu_ticks[CPU_STATE_USER];
239 t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] +
240 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_USER] +
244 if (cpu_load[i].cpu_ticks[CPU_STATE_NICE] >=
245 prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE])
247 t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] -
248 prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE];
252 t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
253 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
257 if (cpu_load[i].cpu_ticks[CPU_STATE_IDLE] >=
258 prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE])
260 t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] -
261 prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE];
265 t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
266 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
269 t_total = t_sys + t_user + t_nice + t_idle;
270 t_idle_all += t_idle;
271 t_total_all += t_total;
273 for (i = 0; i < cpu_count; i++)
275 for (j = 0; j < CPU_STATE_MAX; j++)
277 prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
281 currentCPULoad = 100 - (100 * t_idle_all) / t_total_all;
284 vm_deallocate (mach_task_self (),
285 (vm_address_t) cpu_load,
286 (vm_size_t) (cpu_msg_count * sizeof (*cpu_load)));
287 currentIOLoad = -1; /* FIXME-OSX! */
292 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
293 "host_processor_info failed.");
294 return GNUNET_SYSERR;
298 /* try kstat (Solaris only) */
299 #if SOLARIS && HAVE_KSTAT_H && HAVE_SYS_SYSINFO_H
301 static long long last_idlecount;
302 static long long last_totalcount;
303 static int kstat_once; /* if open fails, don't keep
308 long long totalcount;
310 long long deltatotal;
317 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_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_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
345 if ((idlecount == 0) && (totalcount == 0))
346 goto ABORT_KSTAT; /* no stats found => abort */
347 deltaidle = idlecount - last_idlecount;
348 deltatotal = totalcount - last_totalcount;
349 if ((deltatotal > 0) && (last_totalcount > 0))
351 currentCPULoad = (unsigned int) (100.0 * deltaidle / deltatotal);
352 if (currentCPULoad > 100)
353 currentCPULoad = 100; /* odd */
354 if (currentCPULoad < 0)
355 currentCPULoad = 0; /* odd */
356 currentCPULoad = 100 - currentCPULoad; /* computed idle-load before! */
360 currentIOLoad = -1; /* FIXME-SOLARIS! */
361 last_idlecount = idlecount;
362 last_totalcount = totalcount;
365 kstat_once = 1; /* failed, don't try again */
366 return GNUNET_SYSERR;
370 /* insert methods better than getloadavg for
371 other platforms HERE! */
373 /* ok, maybe we have getloadavg on this platform */
376 static int warnOnce = 0;
378 if (1 != getloadavg (&loadavg, 1))
380 /* only warn once, if there is a problem with
381 getloadavg, we're going to hit it frequently... */
385 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "getloadavg");
387 return GNUNET_SYSERR;
391 /* success with getloadavg */
392 currentCPULoad = (int) (100 * loadavg);
393 currentIOLoad = -1; /* FIXME */
401 if (GNNtQuerySystemInformation)
403 static double dLastKernel;
404 static double dLastIdle;
405 static double dLastUser;
412 SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION theInfo;
414 if (GNNtQuerySystemInformation (SystemProcessorPerformanceInformation,
416 sizeof (theInfo), NULL) == NO_ERROR)
418 /* PORT-ME MINGW: Multi-processor? */
419 dKernel = Li2Double (theInfo.KernelTime);
420 dIdle = Li2Double (theInfo.IdleTime);
421 dUser = Li2Double (theInfo.UserTime);
422 dDiffKernel = dKernel - dLastKernel;
423 dDiffIdle = dIdle - dLastIdle;
424 dDiffUser = dUser - dLastUser;
426 if (((dDiffKernel + dDiffUser) > 0) &&
427 (dLastIdle + dLastKernel + dLastUser > 0))
429 100.0 - (dDiffIdle / (dDiffKernel + dDiffUser)) * 100.0;
431 currentCPULoad = -1; /* don't know (yet) */
433 dLastKernel = dKernel;
437 currentIOLoad = -1; /* FIXME-MINGW */
442 /* only warn once, if there is a problem with
443 NtQuery..., we're going to hit it frequently... */
448 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
449 _("Cannot query the CPU usage (Windows NT).\n"));
451 return GNUNET_SYSERR;
457 DWORD dwDataSize, dwType, dwDummy;
460 if (RegOpenKeyEx (HKEY_DYN_DATA,
461 "PerfStats\\StartSrv",
462 0, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
469 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
470 _("Cannot query the CPU usage (Win 9x)\n"));
474 RegOpenKeyEx (HKEY_DYN_DATA,
475 "PerfStats\\StartStat", 0, KEY_ALL_ACCESS, &hKey);
476 dwDataSize = sizeof (dwDummy);
477 RegQueryValueEx (hKey,
479 NULL, &dwType, (LPBYTE) & dwDummy, &dwDataSize);
483 RegOpenKeyEx (HKEY_DYN_DATA,
484 "PerfStats\\StatData", 0, KEY_ALL_ACCESS, &hKey);
485 dwDataSize = sizeof (currentCPULoad);
486 RegQueryValueEx (hKey,
488 NULL, &dwType, (LPBYTE) & currentCPULoad, &dwDataSize);
490 currentIOLoad = -1; /* FIXME-MINGW! */
493 RegOpenKeyEx (HKEY_DYN_DATA,
494 "PerfStats\\StopStat", 0, KEY_ALL_ACCESS, &hKey);
495 RegOpenKeyEx (HKEY_DYN_DATA,
496 "PerfStats\\StopSrv", 0, KEY_ALL_ACCESS, &hKey);
497 dwDataSize = sizeof (dwDummy);
498 RegQueryValueEx (hKey,
500 NULL, &dwType, (LPBYTE) & dwDummy, &dwDataSize);
507 /* loadaverage not defined and no platform
508 specific alternative defined
511 return GNUNET_SYSERR;
515 * Update load values (if enough time has expired),
516 * including computation of averages. Code assumes
517 * that lock has already been obtained.
520 updateAgedLoad (const struct GNUNET_CONFIGURATION_Handle *cfg)
522 static struct GNUNET_TIME_Absolute lastCall;
524 if ((agedCPULoad == -1)
525 || (GNUNET_TIME_absolute_get_duration (lastCall).value > 500))
527 /* use smoothing, but do NOT update lastRet at frequencies higher
528 than 500ms; this makes the smoothing (mostly) independent from
529 the frequency at which getCPULoad is called (and we don't spend
530 more time measuring CPU than actually computing something). */
531 lastCall = GNUNET_TIME_absolute_get ();
533 if (currentCPULoad == -1)
539 if (agedCPULoad == -1)
541 agedCPULoad = currentCPULoad;
545 /* for CPU, we don't do the 'fast increase' since CPU is much
546 more jitterish to begin with */
547 agedCPULoad = (agedCPULoad * 31 + currentCPULoad) / 32;
550 if (currentIOLoad == -1)
556 if (agedIOLoad == -1)
558 agedIOLoad = currentIOLoad;
562 /* for IO, we don't do the 'fast increase' since IO is much
563 more jitterish to begin with */
564 agedIOLoad = (agedIOLoad * 31 + currentIOLoad) / 32;
571 * Get the load of the CPU relative to what is allowed.
572 * @return the CPU load as a percentage of allowed
573 * (100 is equivalent to full load)
576 GNUNET_OS_load_cpu_get (const struct GNUNET_CONFIGURATION_Handle *cfg)
578 unsigned long long maxCPULoad;
581 updateAgedLoad (cfg);
586 GNUNET_CONFIGURATION_get_value_number (cfg, "LOAD", "MAXCPULOAD",
588 return GNUNET_SYSERR;
589 return (100 * ret) / maxCPULoad;
594 * Get the load of the CPU relative to what is allowed.
595 * @return the CPU load as a percentage of allowed
596 * (100 is equivalent to full load)
599 GNUNET_OS_load_disk_get (const struct GNUNET_CONFIGURATION_Handle *cfg)
601 unsigned long long maxIOLoad;
604 updateAgedLoad (cfg);
609 GNUNET_CONFIGURATION_get_value_number (cfg, "LOAD", "MAXIOLOAD",
611 return GNUNET_SYSERR;
612 return (100 * ret) / maxIOLoad;
616 * The following method is called in order to initialize the status calls
617 * routines. After that it is safe to call each of the status calls separately
618 * @return GNUNET_OK on success and GNUNET_SYSERR on error (or calls errexit).
620 void __attribute__ ((constructor)) GNUNET_cpustats_ltdl_init ()
623 proc_stat = fopen ("/proc/stat", "r");
624 if (NULL == proc_stat)
625 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", "/proc/stat");
631 updateUsage (); /* initialize */
635 * Shutdown the status calls module.
637 void __attribute__ ((destructor)) GNUNET_cpustats_ltdl_fini ()
640 if (proc_stat != NULL)
646 GNUNET_free_non_null (prev_cpu_load);
653 /* end of os_load_cpu.c */