Code

Sync with the latest Gnulib code (177f525)
[nagiosplug.git] / gl / getloadavg.c
1 /* Get the system load averages.
3    Copyright (C) 1985-1989, 1991-1995, 1997, 1999-2000, 2003-2010 Free Software
4    Foundation, Inc.
6    NOTE: The canonical source of this file is maintained with gnulib.
7    Bugs can be reported to bug-gnulib@gnu.org.
9    This program is free software: you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22 /* Compile-time symbols that this file uses:
24    HAVE_PSTAT_GETDYNAMIC        Define this if your system has the
25                                 pstat_getdynamic function.  I think it
26                                 is unique to HPUX9.  The best way to get the
27                                 definition is through the AC_FUNC_GETLOADAVG
28                                 macro that comes with autoconf 2.13 or newer.
29                                 If that isn't an option, then just put
30                                 AC_CHECK_FUNCS(pstat_getdynamic) in your
31                                 configure.in file.
32    HAVE_LIBPERFSTAT Define this if your system has the
33                                 perfstat_cpu_total function in libperfstat (AIX).
34    FIXUP_KERNEL_SYMBOL_ADDR()   Adjust address in returned struct nlist.
35    KERNEL_FILE                  Name of the kernel file to nlist.
36    LDAV_CVT()                   Scale the load average from the kernel.
37                                 Returns a double.
38    LDAV_SYMBOL                  Name of kernel symbol giving load average.
39    LOAD_AVE_TYPE                Type of the load average array in the kernel.
40                                 Must be defined unless one of
41                                 apollo, DGUX, NeXT, or UMAX is defined;
42                                 or we have libkstat;
43                                 otherwise, no load average is available.
44    HAVE_NLIST_H                 nlist.h is available.  NLIST_STRUCT defaults
45                                 to this.
46    NLIST_STRUCT                 Include nlist.h, not a.out.h.
47    N_NAME_POINTER               The nlist n_name element is a pointer,
48                                 not an array.
49    HAVE_STRUCT_NLIST_N_UN_N_NAME `n_un.n_name' is member of `struct nlist'.
50    LINUX_LDAV_FILE              [__linux__, __CYGWIN__]: File containing
51                                 load averages.
53    Specific system predefines this file uses, aside from setting
54    default values if not emacs:
56    apollo
57    BSD                          Real BSD, not just BSD-like.
58    convex
59    DGUX
60    eunice                       UNIX emulator under VMS.
61    hpux
62    __MSDOS__                    No-op for MSDOS.
63    NeXT
64    sgi
65    sequent                      Sequent Dynix 3.x.x (BSD)
66    _SEQUENT_                    Sequent DYNIX/ptx 1.x.x (SYSV)
67    sony_news                    NEWS-OS (works at least for 4.1C)
68    UMAX
69    UMAX4_3
70    VMS
71    WINDOWS32                    No-op for Windows95/NT.
72    __linux__                    Linux: assumes /proc file system mounted.
73                                 Support from Michael K. Johnson.
74    __CYGWIN__                   Cygwin emulates linux /proc/loadavg.
75    __NetBSD__                   NetBSD: assumes /kern file system mounted.
77    In addition, to avoid nesting many #ifdefs, we internally set
78    LDAV_DONE to indicate that the load average has been computed.
80    We also #define LDAV_PRIVILEGED if a program will require
81    special installation to be able to call getloadavg.  */
83 /* "configure" defines CONFIGURING_GETLOADAVG to sidestep problems
84    with partially-configured source directories.  */
86 #ifndef CONFIGURING_GETLOADAVG
87 # include <config.h>
88 # include <stdbool.h>
89 #endif
91 /* Specification.  */
92 #include <stdlib.h>
94 #include <errno.h>
95 #include <stdio.h>
97 /* Exclude all the code except the test program at the end
98    if the system has its own `getloadavg' function.  */
100 #ifndef HAVE_GETLOADAVG
102 # include <sys/types.h>
104 /* Both the Emacs and non-Emacs sections want this.  Some
105    configuration files' definitions for the LOAD_AVE_CVT macro (like
106    sparc.h's) use macros like FSCALE, defined here.  */
107 # if defined (unix) || defined (__unix)
108 #  include <sys/param.h>
109 # endif
111 # include "c-strtod.h"
112 # include "cloexec.h"
113 # include "intprops.h"
115 /* The existing Emacs configuration files define a macro called
116    LOAD_AVE_CVT, which accepts a value of type LOAD_AVE_TYPE, and
117    returns the load average multiplied by 100.  What we actually want
118    is a macro called LDAV_CVT, which returns the load average as an
119    unmultiplied double.
121    For backwards compatibility, we'll define LDAV_CVT in terms of
122    LOAD_AVE_CVT, but future machine config files should just define
123    LDAV_CVT directly.  */
125 # if !defined (LDAV_CVT) && defined (LOAD_AVE_CVT)
126 #  define LDAV_CVT(n) (LOAD_AVE_CVT (n) / 100.0)
127 # endif
129 # if !defined (BSD) && defined (ultrix)
130 /* Ultrix behaves like BSD on Vaxen.  */
131 #  define BSD
132 # endif
134 # ifdef NeXT
135 /* NeXT in the 2.{0,1,2} releases defines BSD in <sys/param.h>, which
136    conflicts with the definition understood in this file, that this
137    really is BSD. */
138 #  undef BSD
140 /* NeXT defines FSCALE in <sys/param.h>.  However, we take FSCALE being
141    defined to mean that the nlist method should be used, which is not true.  */
142 #  undef FSCALE
143 # endif
145 /* Same issues as for NeXT apply to the HURD-based GNU system.  */
146 # ifdef __GNU__
147 #  undef BSD
148 #  undef FSCALE
149 # endif /* __GNU__ */
151 /* Set values that are different from the defaults, which are
152    set a little farther down with #ifndef.  */
155 /* Some shorthands.  */
157 # if defined (HPUX) && !defined (hpux)
158 #  define hpux
159 # endif
161 # if defined (__hpux) && !defined (hpux)
162 #  define hpux
163 # endif
165 # if defined (__sun) && !defined (sun)
166 #  define sun
167 # endif
169 # if defined (hp300) && !defined (hpux)
170 #  define MORE_BSD
171 # endif
173 # if defined (ultrix) && defined (mips)
174 #  define decstation
175 # endif
177 # if defined (__SVR4) && !defined (SVR4)
178 #  define SVR4
179 # endif
181 # if (defined (sun) && defined (SVR4)) || defined (SOLARIS2)
182 #  define SUNOS_5
183 # endif
185 # if defined (__osf__) && (defined (__alpha) || defined (__alpha__))
186 #  define OSF_ALPHA
187 #  include <sys/mbuf.h>
188 #  include <sys/socket.h>
189 #  include <net/route.h>
190 #  include <sys/table.h>
191 /* Tru64 4.0D's table.h redefines sys */
192 #  undef sys
193 # endif
195 # if defined (__osf__) && (defined (mips) || defined (__mips__))
196 #  define OSF_MIPS
197 #  include <sys/table.h>
198 # endif
200 /* UTek's /bin/cc on the 4300 has no architecture specific cpp define by
201    default, but _MACH_IND_SYS_TYPES is defined in <sys/types.h>.  Combine
202    that with a couple of other things and we'll have a unique match.  */
203 # if !defined (tek4300) && defined (unix) && defined (m68k) && defined (mc68000) && defined (mc68020) && defined (_MACH_IND_SYS_TYPES)
204 #  define tek4300                       /* Define by emacs, but not by other users.  */
205 # endif
208 /* VAX C can't handle multi-line #ifs, or lines longer than 256 chars.  */
209 # ifndef LOAD_AVE_TYPE
211 #  ifdef MORE_BSD
212 #   define LOAD_AVE_TYPE long
213 #  endif
215 #  ifdef sun
216 #   define LOAD_AVE_TYPE long
217 #  endif
219 #  ifdef decstation
220 #   define LOAD_AVE_TYPE long
221 #  endif
223 #  ifdef _SEQUENT_
224 #   define LOAD_AVE_TYPE long
225 #  endif
227 #  ifdef sgi
228 #   define LOAD_AVE_TYPE long
229 #  endif
231 #  ifdef SVR4
232 #   define LOAD_AVE_TYPE long
233 #  endif
235 #  ifdef sony_news
236 #   define LOAD_AVE_TYPE long
237 #  endif
239 #  ifdef sequent
240 #   define LOAD_AVE_TYPE long
241 #  endif
243 #  ifdef OSF_ALPHA
244 #   define LOAD_AVE_TYPE long
245 #  endif
247 #  if defined (ardent) && defined (titan)
248 #   define LOAD_AVE_TYPE long
249 #  endif
251 #  ifdef tek4300
252 #   define LOAD_AVE_TYPE long
253 #  endif
255 #  if defined (alliant) && defined (i860) /* Alliant FX/2800 */
256 #   define LOAD_AVE_TYPE long
257 #  endif
259 #  if defined _AIX && ! defined HAVE_LIBPERFSTAT
260 #   define LOAD_AVE_TYPE long
261 #  endif
263 #  ifdef convex
264 #   define LOAD_AVE_TYPE double
265 #   ifndef LDAV_CVT
266 #    define LDAV_CVT(n) (n)
267 #   endif
268 #  endif
270 # endif /* No LOAD_AVE_TYPE.  */
272 # ifdef OSF_ALPHA
273 /* <sys/param.h> defines an incorrect value for FSCALE on Alpha OSF/1,
274    according to ghazi@noc.rutgers.edu.  */
275 #  undef FSCALE
276 #  define FSCALE 1024.0
277 # endif
279 # if defined (alliant) && defined (i860) /* Alliant FX/2800 */
280 /* <sys/param.h> defines an incorrect value for FSCALE on an
281    Alliant FX/2800 Concentrix 2.2, according to ghazi@noc.rutgers.edu.  */
282 #  undef FSCALE
283 #  define FSCALE 100.0
284 # endif
287 # ifndef FSCALE
289 /* SunOS and some others define FSCALE in sys/param.h.  */
291 #  ifdef MORE_BSD
292 #   define FSCALE 2048.0
293 #  endif
295 #  if defined (MIPS) || defined (SVR4) || defined (decstation)
296 #   define FSCALE 256
297 #  endif
299 #  if defined (sgi) || defined (sequent)
300 /* Sometimes both MIPS and sgi are defined, so FSCALE was just defined
301    above under #ifdef MIPS.  But we want the sgi value.  */
302 #   undef FSCALE
303 #   define FSCALE 1000.0
304 #  endif
306 #  if defined (ardent) && defined (titan)
307 #   define FSCALE 65536.0
308 #  endif
310 #  ifdef tek4300
311 #   define FSCALE 100.0
312 #  endif
314 #  if defined _AIX && !defined HAVE_LIBPERFSTAT
315 #   define FSCALE 65536.0
316 #  endif
318 # endif /* Not FSCALE.  */
320 # if !defined (LDAV_CVT) && defined (FSCALE)
321 #  define LDAV_CVT(n) (((double) (n)) / FSCALE)
322 # endif
324 # ifndef NLIST_STRUCT
325 #  if HAVE_NLIST_H
326 #   define NLIST_STRUCT
327 #  endif
328 # endif
330 # if defined (sgi) || (defined (mips) && !defined (BSD))
331 #  define FIXUP_KERNEL_SYMBOL_ADDR(nl) ((nl)[0].n_value &= ~(1 << 31))
332 # endif
335 # if !defined (KERNEL_FILE) && defined (sequent)
336 #  define KERNEL_FILE "/dynix"
337 # endif
339 # if !defined (KERNEL_FILE) && defined (hpux)
340 #  define KERNEL_FILE "/hp-ux"
341 # endif
343 # if !defined (KERNEL_FILE) && (defined (_SEQUENT_) || defined (MIPS) || defined (SVR4) || defined (ISC) || defined (sgi) || (defined (ardent) && defined (titan)))
344 #  define KERNEL_FILE "/unix"
345 # endif
348 # if !defined (LDAV_SYMBOL) && defined (alliant)
349 #  define LDAV_SYMBOL "_Loadavg"
350 # endif
352 # if !defined (LDAV_SYMBOL) && ((defined (hpux) && !defined (hp9000s300)) || defined (_SEQUENT_) || defined (SVR4) || defined (ISC) || defined (sgi) || (defined (ardent) && defined (titan)) || (defined (_AIX) && !defined(HAVE_LIBPERFSTAT)))
353 #  define LDAV_SYMBOL "avenrun"
354 # endif
356 # include <unistd.h>
358 /* LOAD_AVE_TYPE should only get defined if we're going to use the
359    nlist method.  */
360 # if !defined (LOAD_AVE_TYPE) && (defined (BSD) || defined (LDAV_CVT) || defined (KERNEL_FILE) || defined (LDAV_SYMBOL))
361 #  define LOAD_AVE_TYPE double
362 # endif
364 # ifdef LOAD_AVE_TYPE
366 #  ifndef __VMS
367 #   ifndef __linux__
368 #    ifndef NLIST_STRUCT
369 #     include <a.out.h>
370 #    else /* NLIST_STRUCT */
371 #     include <nlist.h>
372 #    endif /* NLIST_STRUCT */
374 #    ifdef SUNOS_5
375 #     include <fcntl.h>
376 #     include <kvm.h>
377 #     include <kstat.h>
378 #    endif
380 #    if defined (hpux) && defined (HAVE_PSTAT_GETDYNAMIC)
381 #     include <sys/pstat.h>
382 #    endif
384 #    ifndef KERNEL_FILE
385 #     define KERNEL_FILE "/vmunix"
386 #    endif /* KERNEL_FILE */
388 #    ifndef LDAV_SYMBOL
389 #     define LDAV_SYMBOL "_avenrun"
390 #    endif /* LDAV_SYMBOL */
391 #   endif /* __linux__ */
393 #  else /* __VMS */
395 #   ifndef eunice
396 #    include <iodef.h>
397 #    include <descrip.h>
398 #   else /* eunice */
399 #    include <vms/iodef.h>
400 #   endif /* eunice */
401 #  endif /* __VMS */
403 #  ifndef LDAV_CVT
404 #   define LDAV_CVT(n) ((double) (n))
405 #  endif /* !LDAV_CVT */
407 # endif /* LOAD_AVE_TYPE */
409 # if defined HAVE_LIBPERFSTAT
410 #  include <sys/protosw.h>
411 #  include <libperfstat.h>
412 #  include <sys/proc.h>
413 #  ifndef SBITS
414 #   define SBITS 16
415 #  endif
416 # endif
418 # if defined (__GNU__) && !defined (NeXT)
419 /* Note that NeXT Openstep defines __GNU__ even though it should not.  */
420 /* GNU system acts much like NeXT, for load average purposes,
421    but not exactly.  */
422 #  define NeXT
423 #  define host_self mach_host_self
424 # endif
426 # ifdef NeXT
427 #  ifdef HAVE_MACH_MACH_H
428 #   include <mach/mach.h>
429 #  else
430 #   include <mach.h>
431 #  endif
432 # endif /* NeXT */
434 # ifdef sgi
435 #  include <sys/sysmp.h>
436 # endif /* sgi */
438 # ifdef UMAX
439 #  include <signal.h>
440 #  include <sys/time.h>
441 #  include <sys/wait.h>
442 #  include <sys/syscall.h>
444 #  ifdef UMAX_43
445 #   include <machine/cpu.h>
446 #   include <inq_stats/statistics.h>
447 #   include <inq_stats/sysstats.h>
448 #   include <inq_stats/cpustats.h>
449 #   include <inq_stats/procstats.h>
450 #  else /* Not UMAX_43.  */
451 #   include <sys/sysdefs.h>
452 #   include <sys/statistics.h>
453 #   include <sys/sysstats.h>
454 #   include <sys/cpudefs.h>
455 #   include <sys/cpustats.h>
456 #   include <sys/procstats.h>
457 #  endif /* Not UMAX_43.  */
458 # endif /* UMAX */
460 # ifdef DGUX
461 #  include <sys/dg_sys_info.h>
462 # endif
464 # include "fcntl--.h"
465 \f
466 /* Avoid static vars inside a function since in HPUX they dump as pure.  */
468 # ifdef NeXT
469 static processor_set_t default_set;
470 static bool getloadavg_initialized;
471 # endif /* NeXT */
473 # ifdef UMAX
474 static unsigned int cpus = 0;
475 static unsigned int samples;
476 # endif /* UMAX */
478 # ifdef DGUX
479 static struct dg_sys_info_load_info load_info;  /* what-a-mouthful! */
480 # endif /* DGUX */
482 # if !defined (HAVE_LIBKSTAT) && defined (LOAD_AVE_TYPE)
483 /* File descriptor open to /dev/kmem or VMS load ave driver.  */
484 static int channel;
485 /* True iff channel is valid.  */
486 static bool getloadavg_initialized;
487 /* Offset in kmem to seek to read load average, or 0 means invalid.  */
488 static long offset;
490 #  if ! defined __VMS && ! defined sgi && ! defined __linux__
491 static struct nlist nl[2];
492 #  endif
494 #  ifdef SUNOS_5
495 static kvm_t *kd;
496 #  endif /* SUNOS_5 */
498 # endif /* LOAD_AVE_TYPE && !HAVE_LIBKSTAT */
499 \f
500 /* Put the 1 minute, 5 minute and 15 minute load averages
501    into the first NELEM elements of LOADAVG.
502    Return the number written (never more than 3, but may be less than NELEM),
503    or -1 if an error occurred.  */
505 int
506 getloadavg (double loadavg[], int nelem)
508   int elem = 0;                 /* Return value.  */
510 # ifdef NO_GET_LOAD_AVG
511 #  define LDAV_DONE
512   /* Set errno to zero to indicate that there was no particular error;
513      this function just can't work at all on this system.  */
514   errno = 0;
515   elem = -1;
516 # endif
518 # if !defined (LDAV_DONE) && defined (HAVE_LIBKSTAT)
519 /* Use libkstat because we don't have to be root.  */
520 #  define LDAV_DONE
521   kstat_ctl_t *kc;
522   kstat_t *ksp;
523   kstat_named_t *kn;
525   kc = kstat_open ();
526   if (kc == 0)
527     return -1;
528   ksp = kstat_lookup (kc, "unix", 0, "system_misc");
529   if (ksp == 0)
530     return -1;
531   if (kstat_read (kc, ksp, 0) == -1)
532     return -1;
535   kn = kstat_data_lookup (ksp, "avenrun_1min");
536   if (kn == 0)
537     {
538       /* Return -1 if no load average information is available.  */
539       nelem = 0;
540       elem = -1;
541     }
543   if (nelem >= 1)
544     loadavg[elem++] = (double) kn->value.ul / FSCALE;
546   if (nelem >= 2)
547     {
548       kn = kstat_data_lookup (ksp, "avenrun_5min");
549       if (kn != 0)
550         {
551           loadavg[elem++] = (double) kn->value.ul / FSCALE;
553           if (nelem >= 3)
554             {
555               kn = kstat_data_lookup (ksp, "avenrun_15min");
556               if (kn != 0)
557                 loadavg[elem++] = (double) kn->value.ul / FSCALE;
558             }
559         }
560     }
562   kstat_close (kc);
563 # endif /* HAVE_LIBKSTAT */
565 # if !defined (LDAV_DONE) && defined (hpux) && defined (HAVE_PSTAT_GETDYNAMIC)
566 /* Use pstat_getdynamic() because we don't have to be root.  */
567 #  define LDAV_DONE
568 #  undef LOAD_AVE_TYPE
570   struct pst_dynamic dyn_info;
571   if (pstat_getdynamic (&dyn_info, sizeof (dyn_info), 0, 0) < 0)
572     return -1;
573   if (nelem > 0)
574     loadavg[elem++] = dyn_info.psd_avg_1_min;
575   if (nelem > 1)
576     loadavg[elem++] = dyn_info.psd_avg_5_min;
577   if (nelem > 2)
578     loadavg[elem++] = dyn_info.psd_avg_15_min;
580 # endif /* hpux && HAVE_PSTAT_GETDYNAMIC */
582 # if ! defined LDAV_DONE && defined HAVE_LIBPERFSTAT
583 #  define LDAV_DONE
584 #  undef LOAD_AVE_TYPE
585 /* Use perfstat_cpu_total because we don't have to be root. */
586   {
587     perfstat_cpu_total_t cpu_stats;
588     int result = perfstat_cpu_total (NULL, &cpu_stats, sizeof cpu_stats, 1);
589     if (result == -1)
590       return result;
591     loadavg[0] = cpu_stats.loadavg[0] / (double)(1 << SBITS);
592     loadavg[1] = cpu_stats.loadavg[1] / (double)(1 << SBITS);
593     loadavg[2] = cpu_stats.loadavg[2] / (double)(1 << SBITS);
594     elem = 3;
595   }
596 # endif
598 # if !defined (LDAV_DONE) && (defined (__linux__) || defined (__CYGWIN__))
599 #  define LDAV_DONE
600 #  undef LOAD_AVE_TYPE
602 #  ifndef LINUX_LDAV_FILE
603 #   define LINUX_LDAV_FILE "/proc/loadavg"
604 #  endif
606   char ldavgbuf[3 * (INT_STRLEN_BOUND (int) + sizeof ".00 ")];
607   char const *ptr = ldavgbuf;
608   int fd, count;
610   fd = open (LINUX_LDAV_FILE, O_RDONLY);
611   if (fd == -1)
612     return -1;
613   count = read (fd, ldavgbuf, sizeof ldavgbuf - 1);
614   (void) close (fd);
615   if (count <= 0)
616     return -1;
617   ldavgbuf[count] = '\0';
619   for (elem = 0; elem < nelem; elem++)
620     {
621       char *endptr;
622       double d;
624       errno = 0;
625       d = c_strtod (ptr, &endptr);
626       if (ptr == endptr || (d == 0 && errno != 0))
627         {
628           if (elem == 0)
629             return -1;
630           break;
631         }
632       loadavg[elem] = d;
633       ptr = endptr;
634     }
636   return elem;
638 # endif /* __linux__ || __CYGWIN__ */
640 # if !defined (LDAV_DONE) && defined (__NetBSD__)
641 #  define LDAV_DONE
642 #  undef LOAD_AVE_TYPE
644 #  ifndef NETBSD_LDAV_FILE
645 #   define NETBSD_LDAV_FILE "/kern/loadavg"
646 #  endif
648   unsigned long int load_ave[3], scale;
649   int count;
650   FILE *fp;
652   fp = fopen (NETBSD_LDAV_FILE, "r");
653   if (fp == NULL)
654     return -1;
655   count = fscanf (fp, "%lu %lu %lu %lu\n",
656                   &load_ave[0], &load_ave[1], &load_ave[2],
657                   &scale);
658   (void) fclose (fp);
659   if (count != 4)
660     return -1;
662   for (elem = 0; elem < nelem; elem++)
663     loadavg[elem] = (double) load_ave[elem] / (double) scale;
665   return elem;
667 # endif /* __NetBSD__ */
669 # if !defined (LDAV_DONE) && defined (NeXT)
670 #  define LDAV_DONE
671   /* The NeXT code was adapted from iscreen 3.2.  */
673   host_t host;
674   struct processor_set_basic_info info;
675   unsigned int info_count;
677   /* We only know how to get the 1-minute average for this system,
678      so even if the caller asks for more than 1, we only return 1.  */
680   if (!getloadavg_initialized)
681     {
682       if (processor_set_default (host_self (), &default_set) == KERN_SUCCESS)
683         getloadavg_initialized = true;
684     }
686   if (getloadavg_initialized)
687     {
688       info_count = PROCESSOR_SET_BASIC_INFO_COUNT;
689       if (processor_set_info (default_set, PROCESSOR_SET_BASIC_INFO, &host,
690                               (processor_set_info_t) &info, &info_count)
691           != KERN_SUCCESS)
692         getloadavg_initialized = false;
693       else
694         {
695           if (nelem > 0)
696             loadavg[elem++] = (double) info.load_average / LOAD_SCALE;
697         }
698     }
700   if (!getloadavg_initialized)
701     return -1;
702 # endif /* NeXT */
704 # if !defined (LDAV_DONE) && defined (UMAX)
705 #  define LDAV_DONE
706 /* UMAX 4.2, which runs on the Encore Multimax multiprocessor, does not
707    have a /dev/kmem.  Information about the workings of the running kernel
708    can be gathered with inq_stats system calls.
709    We only know how to get the 1-minute average for this system.  */
711   struct proc_summary proc_sum_data;
712   struct stat_descr proc_info;
713   double load;
714   register unsigned int i, j;
716   if (cpus == 0)
717     {
718       register unsigned int c, i;
719       struct cpu_config conf;
720       struct stat_descr desc;
722       desc.sd_next = 0;
723       desc.sd_subsys = SUBSYS_CPU;
724       desc.sd_type = CPUTYPE_CONFIG;
725       desc.sd_addr = (char *) &conf;
726       desc.sd_size = sizeof conf;
728       if (inq_stats (1, &desc))
729         return -1;
731       c = 0;
732       for (i = 0; i < conf.config_maxclass; ++i)
733         {
734           struct class_stats stats;
735           bzero ((char *) &stats, sizeof stats);
737           desc.sd_type = CPUTYPE_CLASS;
738           desc.sd_objid = i;
739           desc.sd_addr = (char *) &stats;
740           desc.sd_size = sizeof stats;
742           if (inq_stats (1, &desc))
743             return -1;
745           c += stats.class_numcpus;
746         }
747       cpus = c;
748       samples = cpus < 2 ? 3 : (2 * cpus / 3);
749     }
751   proc_info.sd_next = 0;
752   proc_info.sd_subsys = SUBSYS_PROC;
753   proc_info.sd_type = PROCTYPE_SUMMARY;
754   proc_info.sd_addr = (char *) &proc_sum_data;
755   proc_info.sd_size = sizeof (struct proc_summary);
756   proc_info.sd_sizeused = 0;
758   if (inq_stats (1, &proc_info) != 0)
759     return -1;
761   load = proc_sum_data.ps_nrunnable;
762   j = 0;
763   for (i = samples - 1; i > 0; --i)
764     {
765       load += proc_sum_data.ps_nrun[j];
766       if (j++ == PS_NRUNSIZE)
767         j = 0;
768     }
770   if (nelem > 0)
771     loadavg[elem++] = load / samples / cpus;
772 # endif /* UMAX */
774 # if !defined (LDAV_DONE) && defined (DGUX)
775 #  define LDAV_DONE
776   /* This call can return -1 for an error, but with good args
777      it's not supposed to fail.  The first argument is for no
778      apparent reason of type `long int *'.  */
779   dg_sys_info ((long int *) &load_info,
780                DG_SYS_INFO_LOAD_INFO_TYPE,
781                DG_SYS_INFO_LOAD_VERSION_0);
783   if (nelem > 0)
784     loadavg[elem++] = load_info.one_minute;
785   if (nelem > 1)
786     loadavg[elem++] = load_info.five_minute;
787   if (nelem > 2)
788     loadavg[elem++] = load_info.fifteen_minute;
789 # endif /* DGUX */
791 # if !defined (LDAV_DONE) && defined (apollo)
792 #  define LDAV_DONE
793 /* Apollo code from lisch@mentorg.com (Ray Lischner).
795    This system call is not documented.  The load average is obtained as
796    three long integers, for the load average over the past minute,
797    five minutes, and fifteen minutes.  Each value is a scaled integer,
798    with 16 bits of integer part and 16 bits of fraction part.
800    I'm not sure which operating system first supported this system call,
801    but I know that SR10.2 supports it.  */
803   extern void proc1_$get_loadav ();
804   unsigned long load_ave[3];
806   proc1_$get_loadav (load_ave);
808   if (nelem > 0)
809     loadavg[elem++] = load_ave[0] / 65536.0;
810   if (nelem > 1)
811     loadavg[elem++] = load_ave[1] / 65536.0;
812   if (nelem > 2)
813     loadavg[elem++] = load_ave[2] / 65536.0;
814 # endif /* apollo */
816 # if !defined (LDAV_DONE) && defined (OSF_MIPS)
817 #  define LDAV_DONE
819   struct tbl_loadavg load_ave;
820   table (TBL_LOADAVG, 0, &load_ave, 1, sizeof (load_ave));
821   loadavg[elem++]
822     = (load_ave.tl_lscale == 0
823        ? load_ave.tl_avenrun.d[0]
824        : (load_ave.tl_avenrun.l[0] / (double) load_ave.tl_lscale));
825 # endif /* OSF_MIPS */
827 # if !defined (LDAV_DONE) && (defined (__MSDOS__) || defined (WINDOWS32))
828 #  define LDAV_DONE
830   /* A faithful emulation is going to have to be saved for a rainy day.  */
831   for ( ; elem < nelem; elem++)
832     {
833       loadavg[elem] = 0.0;
834     }
835 # endif  /* __MSDOS__ || WINDOWS32 */
837 # if !defined (LDAV_DONE) && defined (OSF_ALPHA)
838 #  define LDAV_DONE
840   struct tbl_loadavg load_ave;
841   table (TBL_LOADAVG, 0, &load_ave, 1, sizeof (load_ave));
842   for (elem = 0; elem < nelem; elem++)
843     loadavg[elem]
844       = (load_ave.tl_lscale == 0
845          ? load_ave.tl_avenrun.d[elem]
846          : (load_ave.tl_avenrun.l[elem] / (double) load_ave.tl_lscale));
847 # endif /* OSF_ALPHA */
849 # if ! defined LDAV_DONE && defined __VMS
850   /* VMS specific code -- read from the Load Ave driver.  */
852   LOAD_AVE_TYPE load_ave[3];
853   static bool getloadavg_initialized;
854 #  ifdef eunice
855   struct
856   {
857     int dsc$w_length;
858     char *dsc$a_pointer;
859   } descriptor;
860 #  endif
862   /* Ensure that there is a channel open to the load ave device.  */
863   if (!getloadavg_initialized)
864     {
865       /* Attempt to open the channel.  */
866 #  ifdef eunice
867       descriptor.dsc$w_length = 18;
868       descriptor.dsc$a_pointer = "$$VMS_LOAD_AVERAGE";
869 #  else
870       $DESCRIPTOR (descriptor, "LAV0:");
871 #  endif
872       if (sys$assign (&descriptor, &channel, 0, 0) & 1)
873         getloadavg_initialized = true;
874     }
876   /* Read the load average vector.  */
877   if (getloadavg_initialized
878       && !(sys$qiow (0, channel, IO$_READVBLK, 0, 0, 0,
879                      load_ave, 12, 0, 0, 0, 0) & 1))
880     {
881       sys$dassgn (channel);
882       getloadavg_initialized = false;
883     }
885   if (!getloadavg_initialized)
886     return -1;
887 # endif /* ! defined LDAV_DONE && defined __VMS */
889 # if ! defined LDAV_DONE && defined LOAD_AVE_TYPE && ! defined __VMS
891   /* UNIX-specific code -- read the average from /dev/kmem.  */
893 #  define LDAV_PRIVILEGED               /* This code requires special installation.  */
895   LOAD_AVE_TYPE load_ave[3];
897   /* Get the address of LDAV_SYMBOL.  */
898   if (offset == 0)
899     {
900 #  ifndef sgi
901 #   if ! defined NLIST_STRUCT || ! defined N_NAME_POINTER
902       strcpy (nl[0].n_name, LDAV_SYMBOL);
903       strcpy (nl[1].n_name, "");
904 #   else /* NLIST_STRUCT */
905 #    ifdef HAVE_STRUCT_NLIST_N_UN_N_NAME
906       nl[0].n_un.n_name = LDAV_SYMBOL;
907       nl[1].n_un.n_name = 0;
908 #    else /* not HAVE_STRUCT_NLIST_N_UN_N_NAME */
909       nl[0].n_name = LDAV_SYMBOL;
910       nl[1].n_name = 0;
911 #    endif /* not HAVE_STRUCT_NLIST_N_UN_N_NAME */
912 #   endif /* NLIST_STRUCT */
914 #   ifndef SUNOS_5
915       if (
916 #    if !(defined (_AIX) && !defined (ps2))
917           nlist (KERNEL_FILE, nl)
918 #    else  /* _AIX */
919           knlist (nl, 1, sizeof (nl[0]))
920 #    endif
921           >= 0)
922           /* Omit "&& nl[0].n_type != 0 " -- it breaks on Sun386i.  */
923           {
924 #    ifdef FIXUP_KERNEL_SYMBOL_ADDR
925             FIXUP_KERNEL_SYMBOL_ADDR (nl);
926 #    endif
927             offset = nl[0].n_value;
928           }
929 #   endif /* !SUNOS_5 */
930 #  else  /* sgi */
931       int ldav_off;
933       ldav_off = sysmp (MP_KERNADDR, MPKA_AVENRUN);
934       if (ldav_off != -1)
935         offset = (long int) ldav_off & 0x7fffffff;
936 #  endif /* sgi */
937     }
939   /* Make sure we have /dev/kmem open.  */
940   if (!getloadavg_initialized)
941     {
942 #  ifndef SUNOS_5
943       channel = open ("/dev/kmem", O_RDONLY);
944       if (channel >= 0)
945         {
946           /* Set the channel to close on exec, so it does not
947              litter any child's descriptor table.  */
948           set_cloexec_flag (channel, true);
949           getloadavg_initialized = true;
950         }
951 #  else /* SUNOS_5 */
952       /* We pass 0 for the kernel, corefile, and swapfile names
953          to use the currently running kernel.  */
954       kd = kvm_open (0, 0, 0, O_RDONLY, 0);
955       if (kd != 0)
956         {
957           /* nlist the currently running kernel.  */
958           kvm_nlist (kd, nl);
959           offset = nl[0].n_value;
960           getloadavg_initialized = true;
961         }
962 #  endif /* SUNOS_5 */
963     }
965   /* If we can, get the load average values.  */
966   if (offset && getloadavg_initialized)
967     {
968       /* Try to read the load.  */
969 #  ifndef SUNOS_5
970       if (lseek (channel, offset, 0) == -1L
971           || read (channel, (char *) load_ave, sizeof (load_ave))
972           != sizeof (load_ave))
973         {
974           close (channel);
975           getloadavg_initialized = false;
976         }
977 #  else  /* SUNOS_5 */
978       if (kvm_read (kd, offset, (char *) load_ave, sizeof (load_ave))
979           != sizeof (load_ave))
980         {
981           kvm_close (kd);
982           getloadavg_initialized = false;
983         }
984 #  endif /* SUNOS_5 */
985     }
987   if (offset == 0 || !getloadavg_initialized)
988     return -1;
989 # endif /* ! defined LDAV_DONE && defined LOAD_AVE_TYPE && ! defined __VMS */
991 # if !defined (LDAV_DONE) && defined (LOAD_AVE_TYPE) /* Including VMS.  */
992   if (nelem > 0)
993     loadavg[elem++] = LDAV_CVT (load_ave[0]);
994   if (nelem > 1)
995     loadavg[elem++] = LDAV_CVT (load_ave[1]);
996   if (nelem > 2)
997     loadavg[elem++] = LDAV_CVT (load_ave[2]);
999 #  define LDAV_DONE
1000 # endif /* !LDAV_DONE && LOAD_AVE_TYPE */
1002 # if !defined LDAV_DONE
1003   /* Set errno to zero to indicate that there was no particular error;
1004      this function just can't work at all on this system.  */
1005   errno = 0;
1006   elem = -1;
1007 # endif
1008   return elem;
1011 #endif /* ! HAVE_GETLOADAVG */
1012 \f
1013 #ifdef TEST
1014 int
1015 main (int argc, char **argv)
1017   int naptime = 0;
1019   if (argc > 1)
1020     naptime = atoi (argv[1]);
1022   while (1)
1023     {
1024       double avg[3];
1025       int loads;
1027       errno = 0;                /* Don't be misled if it doesn't set errno.  */
1028       loads = getloadavg (avg, 3);
1029       if (loads == -1)
1030         {
1031           perror ("Error getting load average");
1032           return EXIT_FAILURE;
1033         }
1034       if (loads > 0)
1035         printf ("1-minute: %f  ", avg[0]);
1036       if (loads > 1)
1037         printf ("5-minute: %f  ", avg[1]);
1038       if (loads > 2)
1039         printf ("15-minute: %f  ", avg[2]);
1040       if (loads > 0)
1041         putchar ('\n');
1043       if (naptime == 0)
1044         break;
1045       sleep (naptime);
1046     }
1048   return EXIT_SUCCESS;
1050 #endif /* TEST */