Skip to content

Commit

Permalink
Use sysctl(3) on BSD (#733)
Browse files Browse the repository at this point in the history
* Use sysctl(3) on BSD

sysctlbyname(3) is a convenience wrapper for sysctl(3) that is
implemented on FreeBSD and MacOS, but not on OpenBSD.

Include sys/param.h to ensure that BSD is defined.

Tests on OpenBSD:
- make check
- initialize a monitor node and 2 nodes
- perform failover

Tests on MacOS:
- make check

* Use 64-bit sysctl flags to detect total RAM

Tested on

- MacOS 11.4
- FreeBSD 11.4
- OpenBSD 6.9

PG_AUTOCTL_DEBUG=1 pg_autoctl do pgsetup tune --pgdata /tmp -vv

Co-authored-by: Dimitri Fontaine <dimitri@citusdata.com>
  • Loading branch information
eradman and DimCitus committed Jun 28, 2021
1 parent 7a878a4 commit 2eb2197
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/bin/pg_autoctl/system_utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#else
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/param.h>
#endif

#include <math.h>
Expand Down Expand Up @@ -73,26 +74,34 @@ get_system_info_linux(SystemInfo *sysInfo)


/*
* FreeBSD, OpenBSD, and darwin use the sysctlbyname(3) API.
* FreeBSD, OpenBSD, and darwin use the sysctl(3) API.
*/
#if defined(__APPLE__) || defined(BSD)
static bool
get_system_info_bsd(SystemInfo *sysInfo)
{
unsigned int ncpu = 0; /* the API requires an integer here */
int ncpuMIB[2] = { CTL_HW, HW_NCPU };
#if defined(HW_MEMSIZE)
int ramMIB[2] = { CTL_HW, HW_MEMSIZE }; /* MacOS */
#elif defined(HW_PHYSMEM64)
int ramMIB[2] = { CTL_HW, HW_PHYSMEM64 }; /* OpenBSD */
#else
int ramMIB[2] = { CTL_HW, HW_PHYSMEM }; /* FreeBSD */
#endif

size_t cpuSize = sizeof(ncpu);
size_t memSize = sizeof(sysInfo->totalram);

if (sysctlbyname("hw.ncpu", &ncpu, &cpuSize, NULL, 0) != 0)
if (sysctl(ncpuMIB, 2, &ncpu, &cpuSize, NULL, 0) == -1)
{
log_error("Failed to probe number of CPUs: %m");
return false;
}

sysInfo->ncpu = (unsigned short) ncpu;

if (sysctlbyname("hw.memsize", &(sysInfo->totalram), &memSize, NULL, 0) != 0)
if (sysctl(ramMIB, 2, &(sysInfo->totalram), &memSize, NULL, 0) == -1)
{
log_error("Failed to probe Physical Memory: %m");
return false;
Expand Down

0 comments on commit 2eb2197

Please sign in to comment.