Skip to content

Commit

Permalink
Implement ReadMemInfo on FreeBSD
Browse files Browse the repository at this point in the history
Signed-off-by: Doug Rabson <[email protected]>
  • Loading branch information
dfr committed May 12, 2022
1 parent cacc332 commit 68e18dc
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 1 deletion.
75 changes: 75 additions & 0 deletions pkg/system/meminfo_freebsd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//go:build freebsd && cgo
// +build freebsd,cgo

package system

import (
"fmt"
"unsafe"

"golang.org/x/sys/unix"
)

// #include <unistd.h>
// #include <sys/vmmeter.h>
// #include <sys/sysctl.h>
// #include <vm/vm_param.h>
import "C"

func getMemInfo() (int64, int64, error) {
data, err := unix.SysctlRaw("vm.vmtotal")
if err != nil {
return -1, -1, fmt.Errorf("Can't get kernel info: %v", err)
}
if len(data) != C.sizeof_struct_vmtotal {
return -1, -1, fmt.Errorf("unexpected vmtotal size %d", len(data))
}

total := (*C.struct_vmtotal)(unsafe.Pointer(&data[0]))

pagesize := int64(C.sysconf(C._SC_PAGESIZE))
npages := int64(C.sysconf(C._SC_PHYS_PAGES))
return pagesize * npages, pagesize * int64(total.t_free), nil
}

func getSwapInfo() (int64, int64, error) {
var (
total int64 = 0
used int64 = 0
)
for i := 0; ; i++ {
data, err := unix.SysctlRaw("vm.swap_info", i)
if err != nil {
break
}
if len(data) != C.sizeof_struct_xswdev {
return -1, -1, fmt.Errorf("unexpected swap_info size %d", len(data))
}
xsw := (*C.struct_xswdev)(unsafe.Pointer(&data[0]))
total += int64(xsw.xsw_nblks)
used += int64(xsw.xsw_used)
}
pagesize := int64(C.sysconf(C._SC_PAGESIZE))
return pagesize * total, pagesize * used, nil
}

// ReadMemInfo retrieves memory statistics of the host system and returns a
// MemInfo type.
func ReadMemInfo() (*MemInfo, error) {
MemTotal, MemFree, err := getMemInfo()
SwapTotal, SwapFree, err := getSwapInfo()

if MemTotal < 0 || MemFree < 0 || SwapTotal < 0 ||
SwapFree < 0 {
return nil, fmt.Errorf("error getting system memory info %v\n", err)
}

meminfo := &MemInfo{}
// Total memory is total physical memory less than memory locked by kernel
meminfo.MemTotal = MemTotal
meminfo.MemFree = MemFree
meminfo.SwapTotal = SwapTotal
meminfo.SwapFree = SwapFree

return meminfo, nil
}
3 changes: 2 additions & 1 deletion pkg/system/meminfo_unsupported.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// +build !linux,!windows,!solaris
//go:build !linux && !windows && !solaris && !freebsd
// +build !linux,!windows,!solaris,!freebsd

package system

Expand Down

0 comments on commit 68e18dc

Please sign in to comment.