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.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
62 * File descriptor for reading /proc/stat (or NULL)
64 static FILE *proc_stat;
67 * Is this the first time we're trying to open /proc/stat? If
68 * not, we don't try again if we failed...
70 static int first_time;
74 * Current CPU load, as percentage of CPU cycles not idle or
77 static int currentCPULoad;
79 static double agedCPULoad = -1;
82 * Current IO load, as percentage of CPU cycles blocked on IO.
84 static int currentIOLoad;
86 static double agedIOLoad = -1;
92 unsigned int cpu_count;
93 processor_cpu_load_info_t cpu_load;
94 mach_msg_type_number_t cpu_msg_count;
98 kret = host_processor_info (mach_host_self (),
99 PROCESSOR_CPU_LOAD_INFO,
101 (processor_info_array_t *) & cpu_load,
103 if (kret != KERN_SUCCESS)
105 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
106 "host_processor_info failed.");
107 return GNUNET_SYSERR;
109 prev_cpu_load = GNUNET_malloc (cpu_count * sizeof (*prev_cpu_load));
110 for (i = 0; i < cpu_count; i++)
112 for (j = 0; j < CPU_STATE_MAX; j++)
114 prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
117 vm_deallocate (mach_task_self (),
118 (vm_address_t) cpu_load,
119 (vm_size_t) (cpu_msg_count * sizeof (*cpu_load)));
126 * Update the currentCPU and currentIO load values.
128 * Before its first invocation the method initStatusCalls() must be called.
129 * If there is an error the method returns -1.
137 /* under linux, first try %idle/usage using /proc/stat;
138 if that does not work, disable /proc/stat for the future
139 by closing the file and use the next-best method. */
143 proc_stat = fopen ("/proc/stat", "r");
144 if (NULL == proc_stat)
145 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "fopen", "/proc/stat");
147 if (proc_stat != NULL)
149 static unsigned long long last_cpu_results[5] = { 0, 0, 0, 0, 0 };
150 static int have_last_cpu = GNUNET_NO;
153 unsigned long long user_read, system_read, nice_read, idle_read,
155 unsigned long long user, system, nice, idle, iowait;
156 unsigned long long usage_time = 0, total_time = 1;
158 /* Get the first line with the data */
161 if (NULL == fgets (line, 256, proc_stat))
163 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR |
164 GNUNET_ERROR_TYPE_BULK,
165 "fgets", "/proc/stat");
167 proc_stat = NULL; /* don't try again */
172 ret = sscanf (line, "%*s %llu %llu %llu %llu %llu",
174 &system_read, &nice_read, &idle_read, &iowait_read);
177 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR |
178 GNUNET_ERROR_TYPE_BULK,
179 "fgets-sscanf", "/proc/stat");
181 proc_stat = NULL; /* don't try again */
182 have_last_cpu = GNUNET_NO;
186 /* Store the current usage */
187 user = user_read - last_cpu_results[0];
188 system = system_read - last_cpu_results[1];
189 nice = nice_read - last_cpu_results[2];
190 idle = idle_read - last_cpu_results[3];
191 iowait = iowait_read - last_cpu_results[4];
192 /* Calculate the % usage */
193 usage_time = user + system + nice;
194 total_time = usage_time + idle + iowait;
195 if ((total_time > 0) && (have_last_cpu == GNUNET_YES))
197 currentCPULoad = (int) (100L * usage_time / total_time);
199 currentIOLoad = (int) (100L * iowait / total_time);
201 currentIOLoad = -1; /* 2.4 kernel */
203 /* Store the values for the next calculation */
204 last_cpu_results[0] = user_read;
205 last_cpu_results[1] = system_read;
206 last_cpu_results[2] = nice_read;
207 last_cpu_results[3] = idle_read;
208 last_cpu_results[4] = iowait_read;
209 have_last_cpu = GNUNET_YES;
218 unsigned int cpu_count;
219 processor_cpu_load_info_t cpu_load;
220 mach_msg_type_number_t cpu_msg_count;
221 unsigned long long t_sys, t_user, t_nice, t_idle, t_total;
222 unsigned long long t_idle_all, t_total_all;
226 t_idle_all = t_total_all = 0;
227 kret = host_processor_info (mach_host_self (), PROCESSOR_CPU_LOAD_INFO,
229 (processor_info_array_t *) & cpu_load,
231 if (kret == KERN_SUCCESS)
233 for (i = 0; i < cpu_count; i++)
235 if (cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] >=
236 prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM])
238 t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] -
239 prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM];
243 t_sys = cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] +
244 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM] +
248 if (cpu_load[i].cpu_ticks[CPU_STATE_USER] >=
249 prev_cpu_load[i].cpu_ticks[CPU_STATE_USER])
251 t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] -
252 prev_cpu_load[i].cpu_ticks[CPU_STATE_USER];
256 t_user = cpu_load[i].cpu_ticks[CPU_STATE_USER] +
257 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_USER] +
261 if (cpu_load[i].cpu_ticks[CPU_STATE_NICE] >=
262 prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE])
264 t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] -
265 prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE];
269 t_nice = cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
270 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_NICE] +
274 if (cpu_load[i].cpu_ticks[CPU_STATE_IDLE] >=
275 prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE])
277 t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] -
278 prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE];
282 t_idle = cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
283 (ULONG_MAX - prev_cpu_load[i].cpu_ticks[CPU_STATE_IDLE] +
286 t_total = t_sys + t_user + t_nice + t_idle;
287 t_idle_all += t_idle;
288 t_total_all += t_total;
290 for (i = 0; i < cpu_count; i++)
292 for (j = 0; j < CPU_STATE_MAX; j++)
294 prev_cpu_load[i].cpu_ticks[j] = cpu_load[i].cpu_ticks[j];
298 currentCPULoad = 100 - (100 * t_idle_all) / t_total_all;
301 vm_deallocate (mach_task_self (),
302 (vm_address_t) cpu_load,
303 (vm_size_t) (cpu_msg_count * sizeof (*cpu_load)));
304 currentIOLoad = -1; /* There's no IO load meter on darwin */
309 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
310 "host_processor_info failed.");
311 return GNUNET_SYSERR;
315 /* try kstat (Solaris only) */
316 #if SOLARIS && HAVE_KSTAT_H && HAVE_SYS_SYSINFO_H
318 static long long last_idlecount;
319 static long long last_totalcount;
320 static int kstat_once; /* if open fails, don't keep
325 long long totalcount;
327 long long deltatotal;
334 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
341 for (khelper = kc->kc_chain; khelper != NULL; khelper = khelper->ks_next)
345 if (0 != strncmp (khelper->ks_name, "cpu_stat", strlen ("cpu_stat")))
347 if (khelper->ks_data_size > sizeof (cpu_stat_t))
348 continue; /* better save then sorry! */
349 if (-1 != kstat_read (kc, khelper, &stats))
351 idlecount += stats.cpu_sysinfo.cpu[CPU_IDLE];
353 += stats.cpu_sysinfo.cpu[CPU_IDLE] +
354 stats.cpu_sysinfo.cpu[CPU_USER] +
355 stats.cpu_sysinfo.cpu[CPU_KERNEL] +
356 stats.cpu_sysinfo.cpu[CPU_WAIT];
359 if (0 != kstat_close (kc))
360 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
362 if ((idlecount == 0) && (totalcount == 0))
363 goto ABORT_KSTAT; /* no stats found => abort */
364 deltaidle = idlecount - last_idlecount;
365 deltatotal = totalcount - last_totalcount;
366 if ((deltatotal > 0) && (last_totalcount > 0))
368 currentCPULoad = (unsigned int) (100.0 * deltaidle / deltatotal);
369 if (currentCPULoad > 100)
370 currentCPULoad = 100; /* odd */
371 if (currentCPULoad < 0)
372 currentCPULoad = 0; /* odd */
373 currentCPULoad = 100 - currentCPULoad; /* computed idle-load before! */
377 currentIOLoad = -1; /* FIXME-SOLARIS! */
378 last_idlecount = idlecount;
379 last_totalcount = totalcount;
382 kstat_once = 1; /* failed, don't try again */
383 return GNUNET_SYSERR;
387 /* insert methods better than getloadavg for
388 other platforms HERE! */
390 /* ok, maybe we have getloadavg on this platform */
393 static int warnOnce = 0;
395 if (1 != getloadavg (&loadavg, 1))
397 /* only warn once, if there is a problem with
398 getloadavg, we're going to hit it frequently... */
402 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "getloadavg");
404 return GNUNET_SYSERR;
408 /* success with getloadavg */
409 currentCPULoad = (int) (100 * loadavg);
410 currentIOLoad = -1; /* FIXME */
418 if (GNNtQuerySystemInformation)
420 static double dLastKernel;
421 static double dLastIdle;
422 static double dLastUser;
429 SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION theInfo;
431 if (GNNtQuerySystemInformation (SystemProcessorPerformanceInformation,
433 sizeof (theInfo), NULL) == NO_ERROR)
435 /* PORT-ME MINGW: Multi-processor? */
436 dKernel = Li2Double (theInfo.KernelTime);
437 dIdle = Li2Double (theInfo.IdleTime);
438 dUser = Li2Double (theInfo.UserTime);
439 dDiffKernel = dKernel - dLastKernel;
440 dDiffIdle = dIdle - dLastIdle;
441 dDiffUser = dUser - dLastUser;
443 if (((dDiffKernel + dDiffUser) > 0) &&
444 (dLastIdle + dLastKernel + dLastUser > 0))
446 100.0 - (dDiffIdle / (dDiffKernel + dDiffUser)) * 100.0;
448 currentCPULoad = -1; /* don't know (yet) */
450 dLastKernel = dKernel;
454 currentIOLoad = -1; /* FIXME-MINGW */
459 /* only warn once, if there is a problem with
460 NtQuery..., we're going to hit it frequently... */
465 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
466 _("Cannot query the CPU usage (Windows NT).\n"));
468 return GNUNET_SYSERR;
474 DWORD dwDataSize, dwType, dwDummy;
477 if (RegOpenKeyEx (HKEY_DYN_DATA,
478 "PerfStats\\StartSrv",
479 0, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
486 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
487 _("Cannot query the CPU usage (Win 9x)\n"));
491 RegOpenKeyEx (HKEY_DYN_DATA,
492 "PerfStats\\StartStat", 0, KEY_ALL_ACCESS, &hKey);
493 dwDataSize = sizeof (dwDummy);
494 RegQueryValueEx (hKey,
496 NULL, &dwType, (LPBYTE) & dwDummy, &dwDataSize);
500 RegOpenKeyEx (HKEY_DYN_DATA,
501 "PerfStats\\StatData", 0, KEY_ALL_ACCESS, &hKey);
502 dwDataSize = sizeof (currentCPULoad);
503 RegQueryValueEx (hKey,
505 NULL, &dwType, (LPBYTE) & currentCPULoad, &dwDataSize);
507 currentIOLoad = -1; /* FIXME-MINGW! */
510 RegOpenKeyEx (HKEY_DYN_DATA,
511 "PerfStats\\StopStat", 0, KEY_ALL_ACCESS, &hKey);
512 RegOpenKeyEx (HKEY_DYN_DATA,
513 "PerfStats\\StopSrv", 0, KEY_ALL_ACCESS, &hKey);
514 dwDataSize = sizeof (dwDummy);
515 RegQueryValueEx (hKey,
517 NULL, &dwType, (LPBYTE) & dwDummy, &dwDataSize);
524 /* loadaverage not defined and no platform
525 specific alternative defined
528 return GNUNET_SYSERR;
532 * Update load values (if enough time has expired),
533 * including computation of averages. Code assumes
534 * that lock has already been obtained.
537 updateAgedLoad (const struct GNUNET_CONFIGURATION_Handle *cfg)
539 static struct GNUNET_TIME_Absolute lastCall;
541 if ((agedCPULoad == -1)
542 || (GNUNET_TIME_absolute_get_duration (lastCall).value > 500))
544 /* use smoothing, but do NOT update lastRet at frequencies higher
545 than 500ms; this makes the smoothing (mostly) independent from
546 the frequency at which getCPULoad is called (and we don't spend
547 more time measuring CPU than actually computing something). */
548 lastCall = GNUNET_TIME_absolute_get ();
550 if (currentCPULoad == -1)
556 if (agedCPULoad == -1)
558 agedCPULoad = currentCPULoad;
562 /* for CPU, we don't do the 'fast increase' since CPU is much
563 more jitterish to begin with */
564 agedCPULoad = (agedCPULoad * 31 + currentCPULoad) / 32;
567 if (currentIOLoad == -1)
573 if (agedIOLoad == -1)
575 agedIOLoad = currentIOLoad;
579 /* for IO, we don't do the 'fast increase' since IO is much
580 more jitterish to begin with */
581 agedIOLoad = (agedIOLoad * 31 + currentIOLoad) / 32;
588 * Get the load of the CPU relative to what is allowed.
589 * @return the CPU load as a percentage of allowed
590 * (100 is equivalent to full load)
593 GNUNET_OS_load_cpu_get (const struct GNUNET_CONFIGURATION_Handle *cfg)
595 unsigned long long maxCPULoad;
598 updateAgedLoad (cfg);
603 GNUNET_CONFIGURATION_get_value_number (cfg, "LOAD", "MAXCPULOAD",
605 return GNUNET_SYSERR;
608 return (100 * ret) / maxCPULoad;
613 * Get the load of the CPU relative to what is allowed.
614 * @return the CPU load as a percentage of allowed
615 * (100 is equivalent to full load)
618 GNUNET_OS_load_disk_get (const struct GNUNET_CONFIGURATION_Handle *cfg)
620 unsigned long long maxIOLoad;
623 updateAgedLoad (cfg);
628 GNUNET_CONFIGURATION_get_value_number (cfg, "LOAD", "MAXIOLOAD",
630 return GNUNET_SYSERR;
633 return (100 * ret) / maxIOLoad;
637 * The following method is called in order to initialize the status calls
638 * routines. After that it is safe to call each of the status calls separately
639 * @return GNUNET_OK on success and GNUNET_SYSERR on error (or calls errexit).
641 void __attribute__ ((constructor)) GNUNET_cpustats_ltdl_init ()
644 updateUsage (); /* initialize */
645 /* Most GNUnet processes don't really need this, so close the FD, but allow
646 re-opening it (unless we failed) */
647 if (proc_stat != NULL)
649 GNUNET_break (0 == fclose (proc_stat));
653 #elif defined(DARWIN)
655 updateUsage (); /* initialize */
658 updateUsage (); /* initialize */
660 updateUsage (); /* initialize */
665 * Shutdown the status calls module.
667 void __attribute__ ((destructor)) GNUNET_cpustats_ltdl_fini ()
670 if (proc_stat != NULL)
675 #elif defined(DARWIN)
676 GNUNET_free_non_null (prev_cpu_load);
683 /* end of os_load.c */