Path: blob/main/databases/clickhouse/files/patch-src_Common_MemoryStatisticsOS.cpp
16460 views
--- src/Common/MemoryStatisticsOS.cpp.orig 2021-12-26 09:29:33 UTC1+++ src/Common/MemoryStatisticsOS.cpp2@@ -1,4 +1,4 @@3-#if defined(OS_LINUX)4+#if defined(OS_LINUX) || defined(OS_FREEBSD)56#include <sys/types.h>7#include <sys/stat.h>8@@ -6,6 +6,13 @@9#include <unistd.h>10#include <cassert>1112+#ifdef OS_FREEBSD13+#include <sys/param.h>14+#include <sys/sysctl.h>15+#include <sys/user.h>16+#include <libprocstat.h>17+#endif18+19#include "MemoryStatisticsOS.h"2021#include <base/logger_useful.h>22@@ -24,20 +31,40 @@ namespace ErrorCodes23extern const int CANNOT_OPEN_FILE;24extern const int CANNOT_READ_FROM_FILE_DESCRIPTOR;25extern const int CANNOT_CLOSE_FILE;26+#ifdef OS_FREEBSD27+ extern const int CANNOT_ALLOCATE_MEMORY;28+#endif29}3031-static constexpr auto filename = "/proc/self/statm";32+#ifndef OS_FREEBSD33+ static constexpr auto filename = "/proc/self/statm";34+ static constexpr size_t PAGE_SIZE = 4096;35+#endif3637MemoryStatisticsOS::MemoryStatisticsOS()38{39+#ifdef OS_FREEBSD40+ pstat = ::procstat_open_sysctl();41+ if (NULL == pstat)42+ {43+ throwFromErrno("Cannot open sysctl", ErrorCodes::CANNOT_ALLOCATE_MEMORY);44+ }45+#else46fd = ::open(filename, O_RDONLY | O_CLOEXEC);4748if (-1 == fd)49throwFromErrno("Cannot open file " + std::string(filename), errno == ENOENT ? ErrorCodes::FILE_DOESNT_EXIST : ErrorCodes::CANNOT_OPEN_FILE);50+#endif51}5253MemoryStatisticsOS::~MemoryStatisticsOS()54{55+#ifdef OS_FREEBSD56+ if (NULL != pstat)57+ {58+ ::procstat_close(pstat);59+ }60+#else61if (0 != ::close(fd))62{63try64@@ -51,12 +78,42 @@ MemoryStatisticsOS::~MemoryStatisticsOS()65DB::tryLogCurrentException(__PRETTY_FUNCTION__);66}67}68+#endif69}7071MemoryStatisticsOS::Data MemoryStatisticsOS::get() const72{73Data data;7475+#ifdef OS_FREEBSD76+ size_t pagesize = ::getpagesize();77+ unsigned int count = 0;78+79+ struct kinfo_proc *kp;80+ struct kinfo_vmentry *kve;81+82+ kp = ::procstat_getprocs(pstat, KERN_PROC_PID, ::getpid(), &count);83+ if (NULL == kp)84+ {85+ throwFromErrno("Cannot get proc info", ErrorCodes::CANNOT_ALLOCATE_MEMORY);86+ }87+88+ kve = ::procstat_getvmmap(pstat, kp, &count);89+ if (NULL == kve)90+ {91+ ::procstat_freeprocs(pstat, kp);92+ throwFromErrno("Cannot get vmmap info", ErrorCodes::CANNOT_ALLOCATE_MEMORY);93+ }94+95+ data.virt = kp->ki_size;96+ data.resident = kp->ki_rssize * pagesize;97+ data.shared = (kp->ki_rssize - kve->kve_private_resident) * pagesize;98+ data.code = kp->ki_tsize * pagesize;99+ data.data_and_stack = (kp->ki_dsize + kp->ki_ssize) * pagesize;100+101+ ::procstat_freevmmap(pstat, kve);102+ ::procstat_freeprocs(pstat, kp);103+#else104constexpr size_t buf_size = 1024;105char buf[buf_size];106107@@ -99,7 +156,7 @@ MemoryStatisticsOS::Data MemoryStatisticsOS::get() con108data.shared *= page_size;109data.code *= page_size;110data.data_and_stack *= page_size;111-112+#endif113return data;114}115116117118