getloadavg: omit unused var
[gnulib.git] / lib / getloadavg.c
1 /* Get the system load averages.
2
3    Copyright (C) 1985-1989, 1991-1995, 1997, 1999-2000, 2003-2011 Free Software
4    Foundation, Inc.
5
6    NOTE: The canonical source of this file is maintained with gnulib.
7    Bugs can be reported to bug-gnulib@gnu.org.
8
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.
13
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.
18
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/>.  */
21
22 /* Compile-time symbols that this file uses:
23
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.
52
53    Specific system predefines this file uses, aside from setting
54    default values if not emacs:
55
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.
76
77    In addition, to avoid nesting many #ifdefs, we internally set
78    LDAV_DONE to indicate that the load average has been computed.
79
80    We also #define LDAV_PRIVILEGED if a program will require
81    special installation to be able to call getloadavg.  */
82
83 /* "configure" defines CONFIGURING_GETLOADAVG to sidestep problems
84    with partially-configured source directories.  */
85
86 #ifndef CONFIGURING_GETLOADAVG
87 # include <config.h>
88 # include <stdbool.h>
89 #endif
90
91 /* Specification.  */
92 #include <stdlib.h>
93
94 #include <errno.h>
95 #include <stdio.h>
96
97 /* Exclude all the code except the test program at the end
98    if the system has its own `getloadavg' function.  */
99
100 #ifndef HAVE_GETLOADAVG
101
102 # include <sys/types.h>
103
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
110
111 # include "intprops.h"
112
113 /* The existing Emacs configuration files define a macro called
114    LOAD_AVE_CVT, which accepts a value of type LOAD_AVE_TYPE, and
115    returns the load average multiplied by 100.  What we actually want
116    is a macro called LDAV_CVT, which returns the load average as an
117    unmultiplied double.
118
119    For backwards compatibility, we'll define LDAV_CVT in terms of
120    LOAD_AVE_CVT, but future machine config files should just define
121    LDAV_CVT directly.  */
122
123 # if !defined (LDAV_CVT) && defined (LOAD_AVE_CVT)
124 #  define LDAV_CVT(n) (LOAD_AVE_CVT (n) / 100.0)
125 # endif
126
127 # if !defined (BSD) && defined (ultrix)
128 /* Ultrix behaves like BSD on Vaxen.  */
129 #  define BSD
130 # endif
131
132 # ifdef NeXT
133 /* NeXT in the 2.{0,1,2} releases defines BSD in <sys/param.h>, which
134    conflicts with the definition understood in this file, that this
135    really is BSD. */
136 #  undef BSD
137
138 /* NeXT defines FSCALE in <sys/param.h>.  However, we take FSCALE being
139    defined to mean that the nlist method should be used, which is not true.  */
140 #  undef FSCALE
141 # endif
142
143 /* Same issues as for NeXT apply to the HURD-based GNU system.  */
144 # ifdef __GNU__
145 #  undef BSD
146 #  undef FSCALE
147 # endif /* __GNU__ */
148
149 /* Set values that are different from the defaults, which are
150    set a little farther down with #ifndef.  */
151
152
153 /* Some shorthands.  */
154
155 # if defined (HPUX) && !defined (hpux)
156 #  define hpux
157 # endif
158
159 # if defined (__hpux) && !defined (hpux)
160 #  define hpux
161 # endif
162
163 # if defined (__sun) && !defined (sun)
164 #  define sun
165 # endif
166
167 # if defined (hp300) && !defined (hpux)
168 #  define MORE_BSD
169 # endif
170
171 # if defined (ultrix) && defined (mips)
172 #  define decstation
173 # endif
174
175 # if defined (__SVR4) && !defined (SVR4)
176 #  define SVR4
177 # endif
178
179 # if (defined (sun) && defined (SVR4)) || defined (SOLARIS2)
180 #  define SUNOS_5
181 # endif
182
183 # if defined (__osf__) && (defined (__alpha) || defined (__alpha__))
184 #  define OSF_ALPHA
185 #  include <sys/mbuf.h>
186 #  include <sys/socket.h>
187 #  include <net/route.h>
188 #  include <sys/table.h>
189 /* Tru64 4.0D's table.h redefines sys */
190 #  undef sys
191 # endif
192
193 # if defined (__osf__) && (defined (mips) || defined (__mips__))
194 #  define OSF_MIPS
195 #  include <sys/table.h>
196 # endif
197
198 /* UTek's /bin/cc on the 4300 has no architecture specific cpp define by
199    default, but _MACH_IND_SYS_TYPES is defined in <sys/types.h>.  Combine
200    that with a couple of other things and we'll have a unique match.  */
201 # if !defined (tek4300) && defined (unix) && defined (m68k) && defined (mc68000) && defined (mc68020) && defined (_MACH_IND_SYS_TYPES)
202 #  define tek4300                       /* Define by emacs, but not by other users.  */
203 # endif
204
205
206 /* VAX C can't handle multi-line #ifs, or lines longer than 256 chars.  */
207 # ifndef LOAD_AVE_TYPE
208
209 #  ifdef MORE_BSD
210 #   define LOAD_AVE_TYPE long
211 #  endif
212
213 #  ifdef sun
214 #   define LOAD_AVE_TYPE long
215 #  endif
216
217 #  ifdef decstation
218 #   define LOAD_AVE_TYPE long
219 #  endif
220
221 #  ifdef _SEQUENT_
222 #   define LOAD_AVE_TYPE long
223 #  endif
224
225 #  ifdef sgi
226 #   define LOAD_AVE_TYPE long
227 #  endif
228
229 #  ifdef SVR4
230 #   define LOAD_AVE_TYPE long
231 #  endif
232
233 #  ifdef sony_news
234 #   define LOAD_AVE_TYPE long
235 #  endif
236
237 #  ifdef sequent
238 #   define LOAD_AVE_TYPE long
239 #  endif
240
241 #  ifdef OSF_ALPHA
242 #   define LOAD_AVE_TYPE long
243 #  endif
244
245 #  if defined (ardent) && defined (titan)
246 #   define LOAD_AVE_TYPE long
247 #  endif
248
249 #  ifdef tek4300
250 #   define LOAD_AVE_TYPE long
251 #  endif
252
253 #  if defined (alliant) && defined (i860) /* Alliant FX/2800 */
254 #   define LOAD_AVE_TYPE long
255 #  endif
256
257 #  if defined _AIX && ! defined HAVE_LIBPERFSTAT
258 #   define LOAD_AVE_TYPE long
259 #  endif
260
261 #  ifdef convex
262 #   define LOAD_AVE_TYPE double
263 #   ifndef LDAV_CVT
264 #    define LDAV_CVT(n) (n)
265 #   endif
266 #  endif
267
268 # endif /* No LOAD_AVE_TYPE.  */
269
270 # ifdef OSF_ALPHA
271 /* <sys/param.h> defines an incorrect value for FSCALE on Alpha OSF/1,
272    according to ghazi@noc.rutgers.edu.  */
273 #  undef FSCALE
274 #  define FSCALE 1024.0
275 # endif
276
277 # if defined (alliant) && defined (i860) /* Alliant FX/2800 */
278 /* <sys/param.h> defines an incorrect value for FSCALE on an
279    Alliant FX/2800 Concentrix 2.2, according to ghazi@noc.rutgers.edu.  */
280 #  undef FSCALE
281 #  define FSCALE 100.0
282 # endif
283
284
285 # ifndef FSCALE
286
287 /* SunOS and some others define FSCALE in sys/param.h.  */
288
289 #  ifdef MORE_BSD
290 #   define FSCALE 2048.0
291 #  endif
292
293 #  if defined (MIPS) || defined (SVR4) || defined (decstation)
294 #   define FSCALE 256
295 #  endif
296
297 #  if defined (sgi) || defined (sequent)
298 /* Sometimes both MIPS and sgi are defined, so FSCALE was just defined
299    above under #ifdef MIPS.  But we want the sgi value.  */
300 #   undef FSCALE
301 #   define FSCALE 1000.0
302 #  endif
303
304 #  if defined (ardent) && defined (titan)
305 #   define FSCALE 65536.0
306 #  endif
307
308 #  ifdef tek4300
309 #   define FSCALE 100.0
310 #  endif
311
312 #  if defined _AIX && !defined HAVE_LIBPERFSTAT
313 #   define FSCALE 65536.0
314 #  endif
315
316 # endif /* Not FSCALE.  */
317
318 # if !defined (LDAV_CVT) && defined (FSCALE)
319 #  define LDAV_CVT(n) (((double) (n)) / FSCALE)
320 # endif
321
322 # ifndef NLIST_STRUCT
323 #  if HAVE_NLIST_H
324 #   define NLIST_STRUCT
325 #  endif
326 # endif
327
328 # if defined (sgi) || (defined (mips) && !defined (BSD))
329 #  define FIXUP_KERNEL_SYMBOL_ADDR(nl) ((nl)[0].n_value &= ~(1 << 31))
330 # endif
331
332
333 # if !defined (KERNEL_FILE) && defined (sequent)
334 #  define KERNEL_FILE "/dynix"
335 # endif
336
337 # if !defined (KERNEL_FILE) && defined (hpux)
338 #  define KERNEL_FILE "/hp-ux"
339 # endif
340
341 # if !defined (KERNEL_FILE) && (defined (_SEQUENT_) || defined (MIPS) || defined (SVR4) || defined (ISC) || defined (sgi) || (defined (ardent) && defined (titan)))
342 #  define KERNEL_FILE "/unix"
343 # endif
344
345
346 # if !defined (LDAV_SYMBOL) && defined (alliant)
347 #  define LDAV_SYMBOL "_Loadavg"
348 # endif
349
350 # 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)))
351 #  define LDAV_SYMBOL "avenrun"
352 # endif
353
354 # include <unistd.h>
355
356 /* LOAD_AVE_TYPE should only get defined if we're going to use the
357    nlist method.  */
358 # if !defined (LOAD_AVE_TYPE) && (defined (BSD) || defined (LDAV_CVT) || defined (KERNEL_FILE) || defined (LDAV_SYMBOL))
359 #  define LOAD_AVE_TYPE double
360 # endif
361
362 # ifdef LOAD_AVE_TYPE
363
364 #  ifndef __VMS
365 #   ifndef __linux__
366 #    ifndef NLIST_STRUCT
367 #     include <a.out.h>
368 #    else /* NLIST_STRUCT */
369 #     include <nlist.h>
370 #    endif /* NLIST_STRUCT */
371
372 #    ifdef SUNOS_5
373 #     include <kvm.h>
374 #     include <kstat.h>
375 #    endif
376
377 #    if defined (hpux) && defined (HAVE_PSTAT_GETDYNAMIC)
378 #     include <sys/pstat.h>
379 #    endif
380
381 #    ifndef KERNEL_FILE
382 #     define KERNEL_FILE "/vmunix"
383 #    endif /* KERNEL_FILE */
384
385 #    ifndef LDAV_SYMBOL
386 #     define LDAV_SYMBOL "_avenrun"
387 #    endif /* LDAV_SYMBOL */
388 #   endif /* __linux__ */
389
390 #  else /* __VMS */
391
392 #   ifndef eunice
393 #    include <iodef.h>
394 #    include <descrip.h>
395 #   else /* eunice */
396 #    include <vms/iodef.h>
397 #   endif /* eunice */
398 #  endif /* __VMS */
399
400 #  ifndef LDAV_CVT
401 #   define LDAV_CVT(n) ((double) (n))
402 #  endif /* !LDAV_CVT */
403
404 # endif /* LOAD_AVE_TYPE */
405
406 # if defined HAVE_LIBPERFSTAT
407 #  include <sys/protosw.h>
408 #  include <libperfstat.h>
409 #  include <sys/proc.h>
410 #  ifndef SBITS
411 #   define SBITS 16
412 #  endif
413 # endif
414
415 # if defined (__GNU__) && !defined (NeXT)
416 /* Note that NeXT Openstep defines __GNU__ even though it should not.  */
417 /* GNU system acts much like NeXT, for load average purposes,
418    but not exactly.  */
419 #  define NeXT
420 #  define host_self mach_host_self
421 # endif
422
423 # ifdef NeXT
424 #  ifdef HAVE_MACH_MACH_H
425 #   include <mach/mach.h>
426 #  else
427 #   include <mach.h>
428 #  endif
429 # endif /* NeXT */
430
431 # ifdef sgi
432 #  include <sys/sysmp.h>
433 # endif /* sgi */
434
435 # ifdef UMAX
436 #  include <signal.h>
437 #  include <sys/time.h>
438 #  include <sys/wait.h>
439 #  include <sys/syscall.h>
440
441 #  ifdef UMAX_43
442 #   include <machine/cpu.h>
443 #   include <inq_stats/statistics.h>
444 #   include <inq_stats/sysstats.h>
445 #   include <inq_stats/cpustats.h>
446 #   include <inq_stats/procstats.h>
447 #  else /* Not UMAX_43.  */
448 #   include <sys/sysdefs.h>
449 #   include <sys/statistics.h>
450 #   include <sys/sysstats.h>
451 #   include <sys/cpudefs.h>
452 #   include <sys/cpustats.h>
453 #   include <sys/procstats.h>
454 #  endif /* Not UMAX_43.  */
455 # endif /* UMAX */
456
457 # ifdef DGUX
458 #  include <sys/dg_sys_info.h>
459 # endif
460
461 # if (defined __linux__ || defined __CYGWIN__ || defined SUNOS_5        \
462       || (defined LOAD_AVE_TYPE && ! defined __VMS))
463 #  include <fcntl.h>
464 # endif
465 \f
466 /* Avoid static vars inside a function since in HPUX they dump as pure.  */
467
468 # ifdef NeXT
469 static processor_set_t default_set;
470 static bool getloadavg_initialized;
471 # endif /* NeXT */
472
473 # ifdef UMAX
474 static unsigned int cpus = 0;
475 static unsigned int samples;
476 # endif /* UMAX */
477
478 # ifdef DGUX
479 static struct dg_sys_info_load_info load_info;  /* what-a-mouthful! */
480 # endif /* DGUX */
481
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 if 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;
489
490 #  if ! defined __VMS && ! defined sgi && ! defined __linux__
491 static struct nlist name_list[2];
492 #  endif
493
494 #  ifdef SUNOS_5
495 static kvm_t *kd;
496 #  endif /* SUNOS_5 */
497
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.  */
504
505 int
506 getloadavg (double loadavg[], int nelem)
507 {
508   int elem = 0;                 /* Return value.  */
509
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
517
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;
524
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;
533
534
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     }
542
543   if (nelem >= 1)
544     loadavg[elem++] = (double) kn->value.ul / FSCALE;
545
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;
552
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     }
561
562   kstat_close (kc);
563 # endif /* HAVE_LIBKSTAT */
564
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
569
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;
579
580 # endif /* hpux && HAVE_PSTAT_GETDYNAMIC */
581
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
597
598 # if !defined (LDAV_DONE) && (defined (__linux__) || defined (__CYGWIN__))
599 #  define LDAV_DONE
600 #  undef LOAD_AVE_TYPE
601
602 #  ifndef LINUX_LDAV_FILE
603 #   define LINUX_LDAV_FILE "/proc/loadavg"
604 #  endif
605
606   char ldavgbuf[3 * (INT_STRLEN_BOUND (int) + sizeof ".00 ")];
607   char const *ptr = ldavgbuf;
608   int fd, count;
609
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';
618
619   for (elem = 0; elem < nelem; elem++)
620     {
621       double numerator = 0;
622       double denominator = 1;
623
624       while (*ptr == ' ')
625         ptr++;
626
627       /* Finish if this number is missing, and report an error if all
628          were missing.  */
629       if (! ('0' <= *ptr && *ptr <= '9'))
630         {
631           if (elem == 0)
632             return -1;
633           break;
634         }
635
636       while ('0' <= *ptr && *ptr <= '9')
637         numerator = 10 * numerator + (*ptr++ - '0');
638
639       if (*ptr == '.')
640         for (ptr++; '0' <= *ptr && *ptr <= '9'; ptr++)
641           numerator = 10 * numerator + (*ptr - '0'), denominator *= 10;
642
643       loadavg[elem++] = numerator / denominator;
644     }
645
646   return elem;
647
648 # endif /* __linux__ || __CYGWIN__ */
649
650 # if !defined (LDAV_DONE) && defined (__NetBSD__)
651 #  define LDAV_DONE
652 #  undef LOAD_AVE_TYPE
653
654 #  ifndef NETBSD_LDAV_FILE
655 #   define NETBSD_LDAV_FILE "/kern/loadavg"
656 #  endif
657
658   unsigned long int load_ave[3], scale;
659   int count;
660   FILE *fp;
661
662   fp = fopen (NETBSD_LDAV_FILE, "r");
663   if (fp == NULL)
664     return -1;
665   count = fscanf (fp, "%lu %lu %lu %lu\n",
666                   &load_ave[0], &load_ave[1], &load_ave[2],
667                   &scale);
668   (void) fclose (fp);
669   if (count != 4)
670     return -1;
671
672   for (elem = 0; elem < nelem; elem++)
673     loadavg[elem] = (double) load_ave[elem] / (double) scale;
674
675   return elem;
676
677 # endif /* __NetBSD__ */
678
679 # if !defined (LDAV_DONE) && defined (NeXT)
680 #  define LDAV_DONE
681   /* The NeXT code was adapted from iscreen 3.2.  */
682
683   host_t host;
684   struct processor_set_basic_info info;
685   unsigned int info_count;
686
687   /* We only know how to get the 1-minute average for this system,
688      so even if the caller asks for more than 1, we only return 1.  */
689
690   if (!getloadavg_initialized)
691     {
692       if (processor_set_default (host_self (), &default_set) == KERN_SUCCESS)
693         getloadavg_initialized = true;
694     }
695
696   if (getloadavg_initialized)
697     {
698       info_count = PROCESSOR_SET_BASIC_INFO_COUNT;
699       if (processor_set_info (default_set, PROCESSOR_SET_BASIC_INFO, &host,
700                               (processor_set_info_t) &info, &info_count)
701           != KERN_SUCCESS)
702         getloadavg_initialized = false;
703       else
704         {
705           if (nelem > 0)
706             loadavg[elem++] = (double) info.load_average / LOAD_SCALE;
707         }
708     }
709
710   if (!getloadavg_initialized)
711     return -1;
712 # endif /* NeXT */
713
714 # if !defined (LDAV_DONE) && defined (UMAX)
715 #  define LDAV_DONE
716 /* UMAX 4.2, which runs on the Encore Multimax multiprocessor, does not
717    have a /dev/kmem.  Information about the workings of the running kernel
718    can be gathered with inq_stats system calls.
719    We only know how to get the 1-minute average for this system.  */
720
721   struct proc_summary proc_sum_data;
722   struct stat_descr proc_info;
723   double load;
724   register unsigned int i, j;
725
726   if (cpus == 0)
727     {
728       register unsigned int c, i;
729       struct cpu_config conf;
730       struct stat_descr desc;
731
732       desc.sd_next = 0;
733       desc.sd_subsys = SUBSYS_CPU;
734       desc.sd_type = CPUTYPE_CONFIG;
735       desc.sd_addr = (char *) &conf;
736       desc.sd_size = sizeof conf;
737
738       if (inq_stats (1, &desc))
739         return -1;
740
741       c = 0;
742       for (i = 0; i < conf.config_maxclass; ++i)
743         {
744           struct class_stats stats;
745           memset (&stats, 0, sizeof stats);
746
747           desc.sd_type = CPUTYPE_CLASS;
748           desc.sd_objid = i;
749           desc.sd_addr = (char *) &stats;
750           desc.sd_size = sizeof stats;
751
752           if (inq_stats (1, &desc))
753             return -1;
754
755           c += stats.class_numcpus;
756         }
757       cpus = c;
758       samples = cpus < 2 ? 3 : (2 * cpus / 3);
759     }
760
761   proc_info.sd_next = 0;
762   proc_info.sd_subsys = SUBSYS_PROC;
763   proc_info.sd_type = PROCTYPE_SUMMARY;
764   proc_info.sd_addr = (char *) &proc_sum_data;
765   proc_info.sd_size = sizeof (struct proc_summary);
766   proc_info.sd_sizeused = 0;
767
768   if (inq_stats (1, &proc_info) != 0)
769     return -1;
770
771   load = proc_sum_data.ps_nrunnable;
772   j = 0;
773   for (i = samples - 1; i > 0; --i)
774     {
775       load += proc_sum_data.ps_nrun[j];
776       if (j++ == PS_NRUNSIZE)
777         j = 0;
778     }
779
780   if (nelem > 0)
781     loadavg[elem++] = load / samples / cpus;
782 # endif /* UMAX */
783
784 # if !defined (LDAV_DONE) && defined (DGUX)
785 #  define LDAV_DONE
786   /* This call can return -1 for an error, but with good args
787      it's not supposed to fail.  The first argument is for no
788      apparent reason of type `long int *'.  */
789   dg_sys_info ((long int *) &load_info,
790                DG_SYS_INFO_LOAD_INFO_TYPE,
791                DG_SYS_INFO_LOAD_VERSION_0);
792
793   if (nelem > 0)
794     loadavg[elem++] = load_info.one_minute;
795   if (nelem > 1)
796     loadavg[elem++] = load_info.five_minute;
797   if (nelem > 2)
798     loadavg[elem++] = load_info.fifteen_minute;
799 # endif /* DGUX */
800
801 # if !defined (LDAV_DONE) && defined (apollo)
802 #  define LDAV_DONE
803 /* Apollo code from lisch@mentorg.com (Ray Lischner).
804
805    This system call is not documented.  The load average is obtained as
806    three long integers, for the load average over the past minute,
807    five minutes, and fifteen minutes.  Each value is a scaled integer,
808    with 16 bits of integer part and 16 bits of fraction part.
809
810    I'm not sure which operating system first supported this system call,
811    but I know that SR10.2 supports it.  */
812
813   extern void proc1_$get_loadav ();
814   unsigned long load_ave[3];
815
816   proc1_$get_loadav (load_ave);
817
818   if (nelem > 0)
819     loadavg[elem++] = load_ave[0] / 65536.0;
820   if (nelem > 1)
821     loadavg[elem++] = load_ave[1] / 65536.0;
822   if (nelem > 2)
823     loadavg[elem++] = load_ave[2] / 65536.0;
824 # endif /* apollo */
825
826 # if !defined (LDAV_DONE) && defined (OSF_MIPS)
827 #  define LDAV_DONE
828
829   struct tbl_loadavg load_ave;
830   table (TBL_LOADAVG, 0, &load_ave, 1, sizeof (load_ave));
831   loadavg[elem++]
832     = (load_ave.tl_lscale == 0
833        ? load_ave.tl_avenrun.d[0]
834        : (load_ave.tl_avenrun.l[0] / (double) load_ave.tl_lscale));
835 # endif /* OSF_MIPS */
836
837 # if !defined (LDAV_DONE) && (defined (__MSDOS__) || defined (WINDOWS32))
838 #  define LDAV_DONE
839
840   /* A faithful emulation is going to have to be saved for a rainy day.  */
841   for ( ; elem < nelem; elem++)
842     {
843       loadavg[elem] = 0.0;
844     }
845 # endif  /* __MSDOS__ || WINDOWS32 */
846
847 # if !defined (LDAV_DONE) && defined (OSF_ALPHA)
848 #  define LDAV_DONE
849
850   struct tbl_loadavg load_ave;
851   table (TBL_LOADAVG, 0, &load_ave, 1, sizeof (load_ave));
852   for (elem = 0; elem < nelem; elem++)
853     loadavg[elem]
854       = (load_ave.tl_lscale == 0
855          ? load_ave.tl_avenrun.d[elem]
856          : (load_ave.tl_avenrun.l[elem] / (double) load_ave.tl_lscale));
857 # endif /* OSF_ALPHA */
858
859 # if ! defined LDAV_DONE && defined __VMS
860   /* VMS specific code -- read from the Load Ave driver.  */
861
862   LOAD_AVE_TYPE load_ave[3];
863   static bool getloadavg_initialized;
864 #  ifdef eunice
865   struct
866   {
867     int dsc$w_length;
868     char *dsc$a_pointer;
869   } descriptor;
870 #  endif
871
872   /* Ensure that there is a channel open to the load ave device.  */
873   if (!getloadavg_initialized)
874     {
875       /* Attempt to open the channel.  */
876 #  ifdef eunice
877       descriptor.dsc$w_length = 18;
878       descriptor.dsc$a_pointer = "$$VMS_LOAD_AVERAGE";
879 #  else
880       $DESCRIPTOR (descriptor, "LAV0:");
881 #  endif
882       if (sys$assign (&descriptor, &channel, 0, 0) & 1)
883         getloadavg_initialized = true;
884     }
885
886   /* Read the load average vector.  */
887   if (getloadavg_initialized
888       && !(sys$qiow (0, channel, IO$_READVBLK, 0, 0, 0,
889                      load_ave, 12, 0, 0, 0, 0) & 1))
890     {
891       sys$dassgn (channel);
892       getloadavg_initialized = false;
893     }
894
895   if (!getloadavg_initialized)
896     return -1;
897 # endif /* ! defined LDAV_DONE && defined __VMS */
898
899 # if ! defined LDAV_DONE && defined LOAD_AVE_TYPE && ! defined __VMS
900
901   /* UNIX-specific code -- read the average from /dev/kmem.  */
902
903 #  define LDAV_PRIVILEGED               /* This code requires special installation.  */
904
905   LOAD_AVE_TYPE load_ave[3];
906
907   /* Get the address of LDAV_SYMBOL.  */
908   if (offset == 0)
909     {
910 #  ifndef sgi
911 #   if ! defined NLIST_STRUCT || ! defined N_NAME_POINTER
912       strcpy (name_list[0].n_name, LDAV_SYMBOL);
913       strcpy (name_list[1].n_name, "");
914 #   else /* NLIST_STRUCT */
915 #    ifdef HAVE_STRUCT_NLIST_N_UN_N_NAME
916       name_list[0].n_un.n_name = LDAV_SYMBOL;
917       name_list[1].n_un.n_name = 0;
918 #    else /* not HAVE_STRUCT_NLIST_N_UN_N_NAME */
919       name_list[0].n_name = LDAV_SYMBOL;
920       name_list[1].n_name = 0;
921 #    endif /* not HAVE_STRUCT_NLIST_N_UN_N_NAME */
922 #   endif /* NLIST_STRUCT */
923
924 #   ifndef SUNOS_5
925       if (
926 #    if !(defined (_AIX) && !defined (ps2))
927           nlist (KERNEL_FILE, name_list)
928 #    else  /* _AIX */
929           knlist (name_list, 1, sizeof (name_list[0]))
930 #    endif
931           >= 0)
932           /* Omit "&& name_list[0].n_type != 0 " -- it breaks on Sun386i.  */
933           {
934 #    ifdef FIXUP_KERNEL_SYMBOL_ADDR
935             FIXUP_KERNEL_SYMBOL_ADDR (name_list);
936 #    endif
937             offset = name_list[0].n_value;
938           }
939 #   endif /* !SUNOS_5 */
940 #  else  /* sgi */
941       int ldav_off;
942
943       ldav_off = sysmp (MP_KERNADDR, MPKA_AVENRUN);
944       if (ldav_off != -1)
945         offset = (long int) ldav_off & 0x7fffffff;
946 #  endif /* sgi */
947     }
948
949   /* Make sure we have /dev/kmem open.  */
950   if (!getloadavg_initialized)
951     {
952 #  ifndef SUNOS_5
953       /* Set the channel to close on exec, so it does not
954          litter any child's descriptor table.  */
955 #   ifndef O_CLOEXEC
956 #    define O_CLOEXEC 0
957 #   endif
958       int fd = open ("/dev/kmem", O_RDONLY | O_CLOEXEC);
959       if (0 <= fd)
960         {
961 #   if F_DUPFD_CLOEXEC
962           if (fd <= STDERR_FILENO)
963             {
964               int fd1 = fcntl (fd, F_DUPFD_CLOEXEC, STDERR_FILENO + 1);
965               close (fd);
966               fd = fd1;
967             }
968 #   endif
969           if (0 <= fd)
970             {
971               channel = fd;
972               getloadavg_initialized = true;
973             }
974         }
975 #  else /* SUNOS_5 */
976       /* We pass 0 for the kernel, corefile, and swapfile names
977          to use the currently running kernel.  */
978       kd = kvm_open (0, 0, 0, O_RDONLY, 0);
979       if (kd != 0)
980         {
981           /* nlist the currently running kernel.  */
982           kvm_nlist (kd, name_list);
983           offset = name_list[0].n_value;
984           getloadavg_initialized = true;
985         }
986 #  endif /* SUNOS_5 */
987     }
988
989   /* If we can, get the load average values.  */
990   if (offset && getloadavg_initialized)
991     {
992       /* Try to read the load.  */
993 #  ifndef SUNOS_5
994       if (lseek (channel, offset, 0) == -1L
995           || read (channel, (char *) load_ave, sizeof (load_ave))
996           != sizeof (load_ave))
997         {
998           close (channel);
999           getloadavg_initialized = false;
1000         }
1001 #  else  /* SUNOS_5 */
1002       if (kvm_read (kd, offset, (char *) load_ave, sizeof (load_ave))
1003           != sizeof (load_ave))
1004         {
1005           kvm_close (kd);
1006           getloadavg_initialized = false;
1007         }
1008 #  endif /* SUNOS_5 */
1009     }
1010
1011   if (offset == 0 || !getloadavg_initialized)
1012     return -1;
1013 # endif /* ! defined LDAV_DONE && defined LOAD_AVE_TYPE && ! defined __VMS */
1014
1015 # if !defined (LDAV_DONE) && defined (LOAD_AVE_TYPE) /* Including VMS.  */
1016   if (nelem > 0)
1017     loadavg[elem++] = LDAV_CVT (load_ave[0]);
1018   if (nelem > 1)
1019     loadavg[elem++] = LDAV_CVT (load_ave[1]);
1020   if (nelem > 2)
1021     loadavg[elem++] = LDAV_CVT (load_ave[2]);
1022
1023 #  define LDAV_DONE
1024 # endif /* !LDAV_DONE && LOAD_AVE_TYPE */
1025
1026 # if !defined LDAV_DONE
1027   /* Set errno to zero to indicate that there was no particular error;
1028      this function just can't work at all on this system.  */
1029   errno = 0;
1030   elem = -1;
1031 # endif
1032   return elem;
1033 }
1034
1035 #endif /* ! HAVE_GETLOADAVG */
1036 \f
1037 #ifdef TEST
1038 int
1039 main (int argc, char **argv)
1040 {
1041   int naptime = 0;
1042
1043   if (argc > 1)
1044     naptime = atoi (argv[1]);
1045
1046   while (1)
1047     {
1048       double avg[3];
1049       int loads;
1050
1051       errno = 0;                /* Don't be misled if it doesn't set errno.  */
1052       loads = getloadavg (avg, 3);
1053       if (loads == -1)
1054         {
1055           perror ("Error getting load average");
1056           return EXIT_FAILURE;
1057         }
1058       if (loads > 0)
1059         printf ("1-minute: %f  ", avg[0]);
1060       if (loads > 1)
1061         printf ("5-minute: %f  ", avg[1]);
1062       if (loads > 2)
1063         printf ("15-minute: %f  ", avg[2]);
1064       if (loads > 0)
1065         putchar ('\n');
1066
1067       if (naptime == 0)
1068         break;
1069       sleep (naptime);
1070     }
1071
1072   return EXIT_SUCCESS;
1073 }
1074 #endif /* TEST */