[HAVE_SYS_PSTAT_H]: Include <sys/pstat.h>.
[gnulib.git] / lib / physmem.c
1 /* Calculate the size of physical memory.
2    Copyright 2000, 2001 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by Paul Eggert.  */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include "physmem.h"
25
26 #if HAVE_UNISTD_H
27 # include <unistd.h>
28 #endif
29
30 #if HAVE_SYS_PSTAT_H
31 # include <sys/pstat.h>
32 #endif
33
34 /* Return the total amount of physical memory.  */
35 double
36 physmem_total (void)
37 {
38 #if defined _SC_PHYS_PAGES && defined _SC_PAGESIZE
39   {
40     double pages = sysconf (_SC_PHYS_PAGES);
41     double pagesize = sysconf (_SC_PAGESIZE);
42     if (0 <= pages && 0 <= pagesize)
43       return pages * pagesize;
44   }
45 #endif
46
47 #if HAVE_PSTAT_GETSTATIC
48   {
49     struct pst_static pss;
50     if (0 <= pstat_getstatic (&pss, sizeof pss, 1, 0))
51       {
52         double pages = pss.physical_memory;
53         double pagesize = pss.page_size;
54         if (0 <= pages && 0 <= pagesize)
55           return pages * pagesize;
56       }
57   }
58 #endif
59
60   /* Guess 64 MB.  It's probably an older host, so guess small.  */
61   return 64 * 1024 * 1024;
62 }
63
64 /* Return the amount of physical memory available.  */
65 double
66 physmem_available (void)
67 {
68 #if defined _SC_AVPHYS_PAGES && defined _SC_PAGESIZE
69   {
70     double pages = sysconf (_SC_AVPHYS_PAGES);
71     double pagesize = sysconf (_SC_PAGESIZE);
72     if (0 <= pages && 0 <= pagesize)
73       return pages * pagesize;
74   }
75 #endif
76
77 #if HAVE_PSTAT_GETSTATIC && HAVE_PSTAT_GETDYNAMIC
78   {
79     struct pst_static pss;
80     struct pst_dynamic psd;
81     if (0 <= pstat_getstatic (&pss, sizeof pss, 1, 0)
82         && 0 <= pstat_getdynamic (&psd, sizeof psd, 1, 0))
83       {
84         double pages = psd.psd_free;
85         double pagesize = pss.page_size;
86         if (0 <= pages && 0 <= pagesize)
87           return pages * pagesize;
88       }
89   }
90 #endif
91
92   /* Guess 25% of physical memory.  */
93   return physmem_total () / 4;
94 }