]> icculus.org git repositories - icculus/xz.git/blob - src/common/physmem.h
Imported to git.
[icculus/xz.git] / src / common / physmem.h
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 /// \file       physmem.h
4 /// \brief      Get the amount of physical memory
5 //
6 //  This code has been put into the public domain.
7 //
8 //  This library is distributed in the hope that it will be useful,
9 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
10 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 //
12 ///////////////////////////////////////////////////////////////////////////////
13
14 #ifndef PHYSMEM_H
15 #define PHYSMEM_H
16
17 #ifdef HAVE_CONFIG_H
18 #       include <config.h>
19 #endif
20
21 #include <sys/types.h>
22 #include <inttypes.h>
23
24 #ifdef HAVE_LIMITS_H
25 #       include <limits.h>
26 #endif
27
28 #if defined(HAVE_PHYSMEM_SYSCTL) || defined(HAVE_NCPU_SYSCTL)
29 #       ifdef HAVE_SYS_PARAM_H
30 #               include <sys/param.h>
31 #       endif
32 #       ifdef HAVE_SYS_SYSCTL_H
33 #               include <sys/sysctl.h>
34 #       endif
35 #endif
36
37
38 /// \brief      Get the amount of physical memory in bytes
39 ///
40 /// \return     Amount of physical memory in bytes. On error, zero is
41 ///             returned.
42 static inline uint64_t
43 physmem(void)
44 {
45         uint64_t ret = 0;
46
47 #if defined(HAVE_PHYSMEM_SYSCONF)
48         const long pagesize = sysconf(_SC_PAGESIZE);
49         const long pages = sysconf(_SC_PHYS_PAGES);
50         if (pagesize != -1 || pages != -1)
51                 // According to docs, pagesize * pages can overflow.
52                 // Simple case is 32-bit box with 4 GiB or more RAM,
53                 // which may report exactly 4 GiB of RAM, and "long"
54                 // being 32-bit will overflow. Casting to uint64_t
55                 // hopefully avoids overflows in the near future.
56                 ret = (uint64_t)(pagesize) * (uint64_t)(pages);
57
58 #elif defined(HAVE_PHYSMEM_SYSCTL)
59         int name[2] = { CTL_HW, HW_PHYSMEM };
60         unsigned long mem;
61         size_t mem_ptr_size = sizeof(mem);
62         if (!sysctl(name, 2, &mem, &mem_ptr_size, NULL, NULL)) {
63                 // Some systems use unsigned int as the "return value".
64                 // This makes a difference on 64-bit boxes.
65                 if (mem_ptr_size != sizeof(mem)) {
66                         if (mem_ptr_size == sizeof(unsigned int))
67                                 ret = *(unsigned int *)(&mem);
68                 } else {
69                         ret = mem;
70                 }
71         }
72 #endif
73
74         return ret;
75 }
76
77 #endif