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