]> icculus.org git repositories - icculus/xz.git/blob - src/common/physmem.h
597227ac2fbdca5bc4128a7ce24633ca39d08f61
[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 #if defined(HAVE_PHYSMEM_SYSCTL) || defined(HAVE_NCPU_SYSCTL)
18 #       ifdef HAVE_SYS_PARAM_H
19 #               include <sys/param.h>
20 #       endif
21 #       ifdef HAVE_SYS_SYSCTL_H
22 #               include <sys/sysctl.h>
23 #       endif
24 #endif
25
26
27 /// \brief      Get the amount of physical memory in bytes
28 ///
29 /// \return     Amount of physical memory in bytes. On error, zero is
30 ///             returned.
31 static inline uint64_t
32 physmem(void)
33 {
34         uint64_t ret = 0;
35
36 #if defined(HAVE_PHYSMEM_SYSCONF)
37         const long pagesize = sysconf(_SC_PAGESIZE);
38         const long pages = sysconf(_SC_PHYS_PAGES);
39         if (pagesize != -1 || pages != -1)
40                 // According to docs, pagesize * pages can overflow.
41                 // Simple case is 32-bit box with 4 GiB or more RAM,
42                 // which may report exactly 4 GiB of RAM, and "long"
43                 // being 32-bit will overflow. Casting to uint64_t
44                 // hopefully avoids overflows in the near future.
45                 ret = (uint64_t)(pagesize) * (uint64_t)(pages);
46
47 #elif defined(HAVE_PHYSMEM_SYSCTL)
48         int name[2] = { CTL_HW, HW_PHYSMEM };
49         unsigned long mem;
50         size_t mem_ptr_size = sizeof(mem);
51         if (!sysctl(name, 2, &mem, &mem_ptr_size, NULL, NULL)) {
52                 // Some systems use unsigned int as the "return value".
53                 // This makes a difference on 64-bit boxes.
54                 if (mem_ptr_size != sizeof(mem)) {
55                         if (mem_ptr_size == sizeof(unsigned int))
56                                 ret = *(unsigned int *)(&mem);
57                 } else {
58                         ret = mem;
59                 }
60         }
61 #endif
62
63         return ret;
64 }
65
66 #endif