Change copyright notice from GPLv2+ to GPLv3+.
[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, 2005, 2006 Free Software
5    Foundation, Inc.
6
7    NOTE: The canonical source of this file is maintained with gnulib.
8    Bugs can be reported to bug-gnulib@gnu.org.
9
10    This program is free software: you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 /* Compile-time symbols that this file uses:
24
25    HAVE_PSTAT_GETDYNAMIC        Define this if your system has the
26                                 pstat_getdynamic function.  I think it
27                                 is unique to HPUX9.  The best way to get the
28                                 definition is through the AC_FUNC_GETLOADAVG
29                                 macro that comes with autoconf 2.13 or newer.
30                                 If that isn't an option, then just put
31                                 AC_CHECK_FUNCS(pstat_getdynamic) in your
32                                 configure.in file.
33    FIXUP_KERNEL_SYMBOL_ADDR()   Adjust address in returned struct nlist.
34    KERNEL_FILE                  Name of the kernel file to nlist.
35    LDAV_CVT()                   Scale the load average from the kernel.
36                                 Returns a double.
37    LDAV_SYMBOL                  Name of kernel symbol giving load average.
38    LOAD_AVE_TYPE                Type of the load average array in the kernel.
39                                 Must be defined unless one of
40                                 apollo, DGUX, NeXT, or UMAX is defined;
41                                 or we have libkstat;
42                                 otherwise, no load average is available.
43    HAVE_NLIST_H                 nlist.h is available.  NLIST_STRUCT defaults
44                                 to this.
45    NLIST_STRUCT                 Include nlist.h, not a.out.h, and
46                                 the nlist n_name element is a pointer,
47                                 not an array.
48    HAVE_STRUCT_NLIST_N_UN_N_NAME `n_un.n_name' is member of `struct nlist'.
49    LINUX_LDAV_FILE              [__linux__, __CYGWIN__]: File containing
50                                 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    __CYGWIN__                   Cygwin emulates linux /proc/loadavg.
74    __NetBSD__                   NetBSD: assumes /kern file system mounted.
75
76    In addition, to avoid nesting many #ifdefs, we internally set
77    LDAV_DONE to indicate that the load average has been computed.
78
79    We also #define LDAV_PRIVILEGED if a program will require
80    special installation to be able to call getloadavg.  */
81
82 /* "configure" defines CONFIGURING_GETLOADAVG to sidestep problems
83    with partially-configured source directories.  */
84
85 #ifndef CONFIGURING_GETLOADAVG
86 # include <config.h>
87 # include <stdbool.h>
88 #endif
89
90 #include <errno.h>
91 #include <stdio.h>
92 #include <stdlib.h>
93
94 /* Exclude all the code except the test program at the end
95    if the system has its own `getloadavg' function.  */
96
97 #ifndef HAVE_GETLOADAVG
98
99 # include <sys/types.h>
100
101 /* Both the Emacs and non-Emacs sections want this.  Some
102    configuration files' definitions for the LOAD_AVE_CVT macro (like
103    sparc.h's) use macros like FSCALE, defined here.  */
104 # if defined (unix) || defined (__unix)
105 #  include <sys/param.h>
106 # endif
107
108 # include "c-strtod.h"
109 # include "cloexec.h"
110 # include "intprops.h"
111 # include "xalloc.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 # endif
190
191 # if defined (__osf__) && (defined (mips) || defined (__mips__))
192 #  define OSF_MIPS
193 #  include <sys/table.h>
194 # endif
195
196 /* UTek's /bin/cc on the 4300 has no architecture specific cpp define by
197    default, but _MACH_IND_SYS_TYPES is defined in <sys/types.h>.  Combine
198    that with a couple of other things and we'll have a unique match.  */
199 # if !defined (tek4300) && defined (unix) && defined (m68k) && defined (mc68000) && defined (mc68020) && defined (_MACH_IND_SYS_TYPES)
200 #  define tek4300                       /* Define by emacs, but not by other users.  */
201 # endif
202
203
204 /* VAX C can't handle multi-line #ifs, or lines longer than 256 chars.  */
205 # ifndef LOAD_AVE_TYPE
206
207 #  ifdef MORE_BSD
208 #   define LOAD_AVE_TYPE long
209 #  endif
210
211 #  ifdef sun
212 #   define LOAD_AVE_TYPE long
213 #  endif
214
215 #  ifdef decstation
216 #   define LOAD_AVE_TYPE long
217 #  endif
218
219 #  ifdef _SEQUENT_
220 #   define LOAD_AVE_TYPE long
221 #  endif
222
223 #  ifdef sgi
224 #   define LOAD_AVE_TYPE long
225 #  endif
226
227 #  ifdef SVR4
228 #   define LOAD_AVE_TYPE long
229 #  endif
230
231 #  ifdef sony_news
232 #   define LOAD_AVE_TYPE long
233 #  endif
234
235 #  ifdef sequent
236 #   define LOAD_AVE_TYPE long
237 #  endif
238
239 #  ifdef OSF_ALPHA
240 #   define LOAD_AVE_TYPE long
241 #  endif
242
243 #  if defined (ardent) && defined (titan)
244 #   define LOAD_AVE_TYPE long
245 #  endif
246
247 #  ifdef tek4300
248 #   define LOAD_AVE_TYPE long
249 #  endif
250
251 #  if defined (alliant) && defined (i860) /* Alliant FX/2800 */
252 #   define LOAD_AVE_TYPE long
253 #  endif
254
255 #  ifdef _AIX
256 #   define LOAD_AVE_TYPE long
257 #  endif
258
259 #  ifdef convex
260 #   define LOAD_AVE_TYPE double
261 #   ifndef LDAV_CVT
262 #    define LDAV_CVT(n) (n)
263 #   endif
264 #  endif
265
266 # endif /* No LOAD_AVE_TYPE.  */
267
268 # ifdef OSF_ALPHA
269 /* <sys/param.h> defines an incorrect value for FSCALE on Alpha OSF/1,
270    according to ghazi@noc.rutgers.edu.  */
271 #  undef FSCALE
272 #  define FSCALE 1024.0
273 # endif
274
275 # if defined (alliant) && defined (i860) /* Alliant FX/2800 */
276 /* <sys/param.h> defines an incorrect value for FSCALE on an
277    Alliant FX/2800 Concentrix 2.2, according to ghazi@noc.rutgers.edu.  */
278 #  undef FSCALE
279 #  define FSCALE 100.0
280 # endif
281
282
283 # ifndef FSCALE
284
285 /* SunOS and some others define FSCALE in sys/param.h.  */
286
287 #  ifdef MORE_BSD
288 #   define FSCALE 2048.0
289 #  endif
290
291 #  if defined (MIPS) || defined (SVR4) || defined (decstation)
292 #   define FSCALE 256
293 #  endif
294
295 #  if defined (sgi) || defined (sequent)
296 /* Sometimes both MIPS and sgi are defined, so FSCALE was just defined
297    above under #ifdef MIPS.  But we want the sgi value.  */
298 #   undef FSCALE
299 #   define FSCALE 1000.0
300 #  endif
301
302 #  if defined (ardent) && defined (titan)
303 #   define FSCALE 65536.0
304 #  endif
305
306 #  ifdef tek4300
307 #   define FSCALE 100.0
308 #  endif
309
310 #  ifdef _AIX
311 #   define FSCALE 65536.0
312 #  endif
313
314 # endif /* Not FSCALE.  */
315
316 # if !defined (LDAV_CVT) && defined (FSCALE)
317 #  define LDAV_CVT(n) (((double) (n)) / FSCALE)
318 # endif
319
320 # ifndef NLIST_STRUCT
321 #  if HAVE_NLIST_H
322 #   define NLIST_STRUCT
323 #  endif
324 # endif
325
326 # if defined (sgi) || (defined (mips) && !defined (BSD))
327 #  define FIXUP_KERNEL_SYMBOL_ADDR(nl) ((nl)[0].n_value &= ~(1 << 31))
328 # endif
329
330
331 # if !defined (KERNEL_FILE) && defined (sequent)
332 #  define KERNEL_FILE "/dynix"
333 # endif
334
335 # if !defined (KERNEL_FILE) && defined (hpux)
336 #  define KERNEL_FILE "/hp-ux"
337 # endif
338
339 # if !defined (KERNEL_FILE) && (defined (_SEQUENT_) || defined (MIPS) || defined (SVR4) || defined (ISC) || defined (sgi) || (defined (ardent) && defined (titan)))
340 #  define KERNEL_FILE "/unix"
341 # endif
342
343
344 # if !defined (LDAV_SYMBOL) && defined (alliant)
345 #  define LDAV_SYMBOL "_Loadavg"
346 # endif
347
348 # if !defined (LDAV_SYMBOL) && ((defined (hpux) && !defined (hp9000s300)) || defined (_SEQUENT_) || defined (SVR4) || defined (ISC) || defined (sgi) || (defined (ardent) && defined (titan)) || defined (_AIX))
349 #  define LDAV_SYMBOL "avenrun"
350 # endif
351
352 # include <unistd.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 # include "fcntl--.h"
452 \f
453 /* Avoid static vars inside a function since in HPUX they dump as pure.  */
454
455 # ifdef NeXT
456 static processor_set_t default_set;
457 static bool getloadavg_initialized;
458 # endif /* NeXT */
459
460 # ifdef UMAX
461 static unsigned int cpus = 0;
462 static unsigned int samples;
463 # endif /* UMAX */
464
465 # ifdef DGUX
466 static struct dg_sys_info_load_info load_info;  /* what-a-mouthful! */
467 # endif /* DGUX */
468
469 # if !defined (HAVE_LIBKSTAT) && defined (LOAD_AVE_TYPE)
470 /* File descriptor open to /dev/kmem or VMS load ave driver.  */
471 static int channel;
472 /* True iff channel is valid.  */
473 static bool getloadavg_initialized;
474 /* Offset in kmem to seek to read load average, or 0 means invalid.  */
475 static long offset;
476
477 #  if ! defined __VMS && ! defined sgi && ! defined __linux__
478 static struct nlist nl[2];
479 #  endif
480
481 #  ifdef SUNOS_5
482 static kvm_t *kd;
483 #  endif /* SUNOS_5 */
484
485 # endif /* LOAD_AVE_TYPE && !HAVE_LIBKSTAT */
486 \f
487 /* Put the 1 minute, 5 minute and 15 minute load averages
488    into the first NELEM elements of LOADAVG.
489    Return the number written (never more than 3, but may be less than NELEM),
490    or -1 if an error occurred.  */
491
492 int
493 getloadavg (double loadavg[], int nelem)
494 {
495   int elem = 0;                 /* Return value.  */
496
497 # ifdef NO_GET_LOAD_AVG
498 #  define LDAV_DONE
499   /* Set errno to zero to indicate that there was no particular error;
500      this function just can't work at all on this system.  */
501   errno = 0;
502   elem = -1;
503 # endif
504
505 # if !defined (LDAV_DONE) && defined (HAVE_LIBKSTAT)
506 /* Use libkstat because we don't have to be root.  */
507 #  define LDAV_DONE
508   kstat_ctl_t *kc;
509   kstat_t *ksp;
510   kstat_named_t *kn;
511
512   kc = kstat_open ();
513   if (kc == 0)
514     return -1;
515   ksp = kstat_lookup (kc, "unix", 0, "system_misc");
516   if (ksp == 0)
517     return -1;
518   if (kstat_read (kc, ksp, 0) == -1)
519     return -1;
520
521
522   kn = kstat_data_lookup (ksp, "avenrun_1min");
523   if (kn == 0)
524     {
525       /* Return -1 if no load average information is available.  */
526       nelem = 0;
527       elem = -1;
528     }
529
530   if (nelem >= 1)
531     loadavg[elem++] = (double) kn->value.ul / FSCALE;
532
533   if (nelem >= 2)
534     {
535       kn = kstat_data_lookup (ksp, "avenrun_5min");
536       if (kn != 0)
537         {
538           loadavg[elem++] = (double) kn->value.ul / FSCALE;
539
540           if (nelem >= 3)
541             {
542               kn = kstat_data_lookup (ksp, "avenrun_15min");
543               if (kn != 0)
544                 loadavg[elem++] = (double) kn->value.ul / FSCALE;
545             }
546         }
547     }
548
549   kstat_close (kc);
550 # endif /* HAVE_LIBKSTAT */
551
552 # if !defined (LDAV_DONE) && defined (hpux) && defined (HAVE_PSTAT_GETDYNAMIC)
553 /* Use pstat_getdynamic() because we don't have to be root.  */
554 #  define LDAV_DONE
555 #  undef LOAD_AVE_TYPE
556
557   struct pst_dynamic dyn_info;
558   if (pstat_getdynamic (&dyn_info, sizeof (dyn_info), 0, 0) < 0)
559     return -1;
560   if (nelem > 0)
561     loadavg[elem++] = dyn_info.psd_avg_1_min;
562   if (nelem > 1)
563     loadavg[elem++] = dyn_info.psd_avg_5_min;
564   if (nelem > 2)
565     loadavg[elem++] = dyn_info.psd_avg_15_min;
566
567 # endif /* hpux && HAVE_PSTAT_GETDYNAMIC */
568
569 # if !defined (LDAV_DONE) && (defined (__linux__) || defined (__CYGWIN__))
570 #  define LDAV_DONE
571 #  undef LOAD_AVE_TYPE
572
573 #  ifndef LINUX_LDAV_FILE
574 #   define LINUX_LDAV_FILE "/proc/loadavg"
575 #  endif
576
577   char ldavgbuf[3 * (INT_STRLEN_BOUND (int) + sizeof ".00 ")];
578   char const *ptr = ldavgbuf;
579   int fd, count;
580
581   fd = open (LINUX_LDAV_FILE, O_RDONLY);
582   if (fd == -1)
583     return -1;
584   count = read (fd, ldavgbuf, sizeof ldavgbuf - 1);
585   (void) close (fd);
586   if (count <= 0)
587     return -1;
588   ldavgbuf[count] = '\0';
589
590   for (elem = 0; elem < nelem; elem++)
591     {
592       char *endptr;
593       double d = c_strtod (ptr, &endptr);
594       if (ptr == endptr)
595         {
596           if (elem == 0)
597             return -1;
598           break;
599         }
600       loadavg[elem] = d;
601       ptr = endptr;
602     }
603
604   return elem;
605
606 # endif /* __linux__ || __CYGWIN__ */
607
608 # if !defined (LDAV_DONE) && defined (__NetBSD__)
609 #  define LDAV_DONE
610 #  undef LOAD_AVE_TYPE
611
612 #  ifndef NETBSD_LDAV_FILE
613 #   define NETBSD_LDAV_FILE "/kern/loadavg"
614 #  endif
615
616   unsigned long int load_ave[3], scale;
617   int count;
618   FILE *fp;
619
620   fp = fopen (NETBSD_LDAV_FILE, "r");
621   if (fp == NULL)
622     return -1;
623   count = fscanf (fp, "%lu %lu %lu %lu\n",
624                   &load_ave[0], &load_ave[1], &load_ave[2],
625                   &scale);
626   (void) fclose (fp);
627   if (count != 4)
628     return -1;
629
630   for (elem = 0; elem < nelem; elem++)
631     loadavg[elem] = (double) load_ave[elem] / (double) scale;
632
633   return elem;
634
635 # endif /* __NetBSD__ */
636
637 # if !defined (LDAV_DONE) && defined (NeXT)
638 #  define LDAV_DONE
639   /* The NeXT code was adapted from iscreen 3.2.  */
640
641   host_t host;
642   struct processor_set_basic_info info;
643   unsigned int info_count;
644
645   /* We only know how to get the 1-minute average for this system,
646      so even if the caller asks for more than 1, we only return 1.  */
647
648   if (!getloadavg_initialized)
649     {
650       if (processor_set_default (host_self (), &default_set) == KERN_SUCCESS)
651         getloadavg_initialized = true;
652     }
653
654   if (getloadavg_initialized)
655     {
656       info_count = PROCESSOR_SET_BASIC_INFO_COUNT;
657       if (processor_set_info (default_set, PROCESSOR_SET_BASIC_INFO, &host,
658                               (processor_set_info_t) &info, &info_count)
659           != KERN_SUCCESS)
660         getloadavg_initialized = false;
661       else
662         {
663           if (nelem > 0)
664             loadavg[elem++] = (double) info.load_average / LOAD_SCALE;
665         }
666     }
667
668   if (!getloadavg_initialized)
669     return -1;
670 # endif /* NeXT */
671
672 # if !defined (LDAV_DONE) && defined (UMAX)
673 #  define LDAV_DONE
674 /* UMAX 4.2, which runs on the Encore Multimax multiprocessor, does not
675    have a /dev/kmem.  Information about the workings of the running kernel
676    can be gathered with inq_stats system calls.
677    We only know how to get the 1-minute average for this system.  */
678
679   struct proc_summary proc_sum_data;
680   struct stat_descr proc_info;
681   double load;
682   register unsigned int i, j;
683
684   if (cpus == 0)
685     {
686       register unsigned int c, i;
687       struct cpu_config conf;
688       struct stat_descr desc;
689
690       desc.sd_next = 0;
691       desc.sd_subsys = SUBSYS_CPU;
692       desc.sd_type = CPUTYPE_CONFIG;
693       desc.sd_addr = (char *) &conf;
694       desc.sd_size = sizeof conf;
695
696       if (inq_stats (1, &desc))
697         return -1;
698
699       c = 0;
700       for (i = 0; i < conf.config_maxclass; ++i)
701         {
702           struct class_stats stats;
703           bzero ((char *) &stats, sizeof stats);
704
705           desc.sd_type = CPUTYPE_CLASS;
706           desc.sd_objid = i;
707           desc.sd_addr = (char *) &stats;
708           desc.sd_size = sizeof stats;
709
710           if (inq_stats (1, &desc))
711             return -1;
712
713           c += stats.class_numcpus;
714         }
715       cpus = c;
716       samples = cpus < 2 ? 3 : (2 * cpus / 3);
717     }
718
719   proc_info.sd_next = 0;
720   proc_info.sd_subsys = SUBSYS_PROC;
721   proc_info.sd_type = PROCTYPE_SUMMARY;
722   proc_info.sd_addr = (char *) &proc_sum_data;
723   proc_info.sd_size = sizeof (struct proc_summary);
724   proc_info.sd_sizeused = 0;
725
726   if (inq_stats (1, &proc_info) != 0)
727     return -1;
728
729   load = proc_sum_data.ps_nrunnable;
730   j = 0;
731   for (i = samples - 1; i > 0; --i)
732     {
733       load += proc_sum_data.ps_nrun[j];
734       if (j++ == PS_NRUNSIZE)
735         j = 0;
736     }
737
738   if (nelem > 0)
739     loadavg[elem++] = load / samples / cpus;
740 # endif /* UMAX */
741
742 # if !defined (LDAV_DONE) && defined (DGUX)
743 #  define LDAV_DONE
744   /* This call can return -1 for an error, but with good args
745      it's not supposed to fail.  The first argument is for no
746      apparent reason of type `long int *'.  */
747   dg_sys_info ((long int *) &load_info,
748                DG_SYS_INFO_LOAD_INFO_TYPE,
749                DG_SYS_INFO_LOAD_VERSION_0);
750
751   if (nelem > 0)
752     loadavg[elem++] = load_info.one_minute;
753   if (nelem > 1)
754     loadavg[elem++] = load_info.five_minute;
755   if (nelem > 2)
756     loadavg[elem++] = load_info.fifteen_minute;
757 # endif /* DGUX */
758
759 # if !defined (LDAV_DONE) && defined (apollo)
760 #  define LDAV_DONE
761 /* Apollo code from lisch@mentorg.com (Ray Lischner).
762
763    This system call is not documented.  The load average is obtained as
764    three long integers, for the load average over the past minute,
765    five minutes, and fifteen minutes.  Each value is a scaled integer,
766    with 16 bits of integer part and 16 bits of fraction part.
767
768    I'm not sure which operating system first supported this system call,
769    but I know that SR10.2 supports it.  */
770
771   extern void proc1_$get_loadav ();
772   unsigned long load_ave[3];
773
774   proc1_$get_loadav (load_ave);
775
776   if (nelem > 0)
777     loadavg[elem++] = load_ave[0] / 65536.0;
778   if (nelem > 1)
779     loadavg[elem++] = load_ave[1] / 65536.0;
780   if (nelem > 2)
781     loadavg[elem++] = load_ave[2] / 65536.0;
782 # endif /* apollo */
783
784 # if !defined (LDAV_DONE) && defined (OSF_MIPS)
785 #  define LDAV_DONE
786
787   struct tbl_loadavg load_ave;
788   table (TBL_LOADAVG, 0, &load_ave, 1, sizeof (load_ave));
789   loadavg[elem++]
790     = (load_ave.tl_lscale == 0
791        ? load_ave.tl_avenrun.d[0]
792        : (load_ave.tl_avenrun.l[0] / (double) load_ave.tl_lscale));
793 # endif /* OSF_MIPS */
794
795 # if !defined (LDAV_DONE) && (defined (__MSDOS__) || defined (WINDOWS32))
796 #  define LDAV_DONE
797
798   /* A faithful emulation is going to have to be saved for a rainy day.  */
799   for ( ; elem < nelem; elem++)
800     {
801       loadavg[elem] = 0.0;
802     }
803 # endif  /* __MSDOS__ || WINDOWS32 */
804
805 # if !defined (LDAV_DONE) && defined (OSF_ALPHA)
806 #  define LDAV_DONE
807
808   struct tbl_loadavg load_ave;
809   table (TBL_LOADAVG, 0, &load_ave, 1, sizeof (load_ave));
810   for (elem = 0; elem < nelem; elem++)
811     loadavg[elem]
812       = (load_ave.tl_lscale == 0
813          ? load_ave.tl_avenrun.d[elem]
814          : (load_ave.tl_avenrun.l[elem] / (double) load_ave.tl_lscale));
815 # endif /* OSF_ALPHA */
816
817 # if ! defined LDAV_DONE && defined __VMS
818   /* VMS specific code -- read from the Load Ave driver.  */
819
820   LOAD_AVE_TYPE load_ave[3];
821   static bool getloadavg_initialized;
822 #  ifdef eunice
823   struct
824   {
825     int dsc$w_length;
826     char *dsc$a_pointer;
827   } descriptor;
828 #  endif
829
830   /* Ensure that there is a channel open to the load ave device.  */
831   if (!getloadavg_initialized)
832     {
833       /* Attempt to open the channel.  */
834 #  ifdef eunice
835       descriptor.dsc$w_length = 18;
836       descriptor.dsc$a_pointer = "$$VMS_LOAD_AVERAGE";
837 #  else
838       $DESCRIPTOR (descriptor, "LAV0:");
839 #  endif
840       if (sys$assign (&descriptor, &channel, 0, 0) & 1)
841         getloadavg_initialized = true;
842     }
843
844   /* Read the load average vector.  */
845   if (getloadavg_initialized
846       && !(sys$qiow (0, channel, IO$_READVBLK, 0, 0, 0,
847                      load_ave, 12, 0, 0, 0, 0) & 1))
848     {
849       sys$dassgn (channel);
850       getloadavg_initialized = false;
851     }
852
853   if (!getloadavg_initialized)
854     return -1;
855 # endif /* ! defined LDAV_DONE && defined __VMS */
856
857 # if ! defined LDAV_DONE && defined LOAD_AVE_TYPE && ! defined __VMS
858
859   /* UNIX-specific code -- read the average from /dev/kmem.  */
860
861 #  define LDAV_PRIVILEGED               /* This code requires special installation.  */
862
863   LOAD_AVE_TYPE load_ave[3];
864
865   /* Get the address of LDAV_SYMBOL.  */
866   if (offset == 0)
867     {
868 #  ifndef sgi
869 #   ifndef NLIST_STRUCT
870       strcpy (nl[0].n_name, LDAV_SYMBOL);
871       strcpy (nl[1].n_name, "");
872 #   else /* NLIST_STRUCT */
873 #    ifdef HAVE_STRUCT_NLIST_N_UN_N_NAME
874       nl[0].n_un.n_name = LDAV_SYMBOL;
875       nl[1].n_un.n_name = 0;
876 #    else /* not HAVE_STRUCT_NLIST_N_UN_N_NAME */
877       nl[0].n_name = LDAV_SYMBOL;
878       nl[1].n_name = 0;
879 #    endif /* not HAVE_STRUCT_NLIST_N_UN_N_NAME */
880 #   endif /* NLIST_STRUCT */
881
882 #   ifndef SUNOS_5
883       if (
884 #    if !(defined (_AIX) && !defined (ps2))
885           nlist (KERNEL_FILE, nl)
886 #    else  /* _AIX */
887           knlist (nl, 1, sizeof (nl[0]))
888 #    endif
889           >= 0)
890           /* Omit "&& nl[0].n_type != 0 " -- it breaks on Sun386i.  */
891           {
892 #    ifdef FIXUP_KERNEL_SYMBOL_ADDR
893             FIXUP_KERNEL_SYMBOL_ADDR (nl);
894 #    endif
895             offset = nl[0].n_value;
896           }
897 #   endif /* !SUNOS_5 */
898 #  else  /* sgi */
899       int ldav_off;
900
901       ldav_off = sysmp (MP_KERNADDR, MPKA_AVENRUN);
902       if (ldav_off != -1)
903         offset = (long int) ldav_off & 0x7fffffff;
904 #  endif /* sgi */
905     }
906
907   /* Make sure we have /dev/kmem open.  */
908   if (!getloadavg_initialized)
909     {
910 #  ifndef SUNOS_5
911       channel = open ("/dev/kmem", O_RDONLY);
912       if (channel >= 0)
913         {
914           /* Set the channel to close on exec, so it does not
915              litter any child's descriptor table.  */
916           set_cloexec_flag (channel, true);
917           getloadavg_initialized = true;
918         }
919 #  else /* SUNOS_5 */
920       /* We pass 0 for the kernel, corefile, and swapfile names
921          to use the currently running kernel.  */
922       kd = kvm_open (0, 0, 0, O_RDONLY, 0);
923       if (kd != 0)
924         {
925           /* nlist the currently running kernel.  */
926           kvm_nlist (kd, nl);
927           offset = nl[0].n_value;
928           getloadavg_initialized = true;
929         }
930 #  endif /* SUNOS_5 */
931     }
932
933   /* If we can, get the load average values.  */
934   if (offset && getloadavg_initialized)
935     {
936       /* Try to read the load.  */
937 #  ifndef SUNOS_5
938       if (lseek (channel, offset, 0) == -1L
939           || read (channel, (char *) load_ave, sizeof (load_ave))
940           != sizeof (load_ave))
941         {
942           close (channel);
943           getloadavg_initialized = false;
944         }
945 #  else  /* SUNOS_5 */
946       if (kvm_read (kd, offset, (char *) load_ave, sizeof (load_ave))
947           != sizeof (load_ave))
948         {
949           kvm_close (kd);
950           getloadavg_initialized = false;
951         }
952 #  endif /* SUNOS_5 */
953     }
954
955   if (offset == 0 || !getloadavg_initialized)
956     return -1;
957 # endif /* ! defined LDAV_DONE && defined LOAD_AVE_TYPE && ! defined __VMS */
958
959 # if !defined (LDAV_DONE) && defined (LOAD_AVE_TYPE) /* Including VMS.  */
960   if (nelem > 0)
961     loadavg[elem++] = LDAV_CVT (load_ave[0]);
962   if (nelem > 1)
963     loadavg[elem++] = LDAV_CVT (load_ave[1]);
964   if (nelem > 2)
965     loadavg[elem++] = LDAV_CVT (load_ave[2]);
966
967 #  define LDAV_DONE
968 # endif /* !LDAV_DONE && LOAD_AVE_TYPE */
969
970 # if !defined LDAV_DONE
971   /* Set errno to zero to indicate that there was no particular error;
972      this function just can't work at all on this system.  */
973   errno = 0;
974   elem = -1;
975 # endif
976   return elem;
977 }
978
979 #endif /* ! HAVE_GETLOADAVG */
980 \f
981 #ifdef TEST
982 int
983 main (int argc, char **argv)
984 {
985   int naptime = 0;
986
987   if (argc > 1)
988     naptime = atoi (argv[1]);
989
990   while (1)
991     {
992       double avg[3];
993       int loads;
994
995       errno = 0;                /* Don't be misled if it doesn't set errno.  */
996       loads = getloadavg (avg, 3);
997       if (loads == -1)
998         {
999           perror ("Error getting load average");
1000           return EXIT_FAILURE;
1001         }
1002       if (loads > 0)
1003         printf ("1-minute: %f  ", avg[0]);
1004       if (loads > 1)
1005         printf ("5-minute: %f  ", avg[1]);
1006       if (loads > 2)
1007         printf ("15-minute: %f  ", avg[2]);
1008       if (loads > 0)
1009         putchar ('\n');
1010
1011       if (naptime == 0)
1012         break;
1013       sleep (naptime);
1014     }
1015
1016   return EXIT_SUCCESS;
1017 }
1018 #endif /* TEST */