From 6b008ed93b57f23d5157f16ed96f7b40423defdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=80=9A=E6=B4=B2?= Date: Tue, 10 Oct 2023 13:40:00 +0800 Subject: [PATCH] CPUUsage (FreeBSD): count cpu cores separately --- src/detection/cpuusage/cpuusage_bsd.c | 29 +++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/detection/cpuusage/cpuusage_bsd.c b/src/detection/cpuusage/cpuusage_bsd.c index fa1945aaa..8f888491b 100644 --- a/src/detection/cpuusage/cpuusage_bsd.c +++ b/src/detection/cpuusage/cpuusage_bsd.c @@ -1,19 +1,32 @@ #include "detection/cpuusage/cpuusage.h" +#include "util/mallocHelper.h" #include -#include #include +#include +#include const char* ffGetCpuUsageInfo(uint64_t* inUseAll, uint64_t* totalAll) { - // interrupt processing, user processes, system processing, lock spinning, and idling - uint64_t cpTime[5]; - size_t neededLength = sizeof(cpTime); - if(sysctlbyname("kern.cp_time", cpTime, &neededLength, NULL, 0) != 0) - return "sysctlbyname(kern.cp_time) failed"; + size_t neededLength = 0; + if(sysctlbyname("kern.cp_times", NULL, &neededLength, NULL, 0) != 0) + return "sysctlbyname(kern.cp_times, NULL) failed"; - *inUseAll = cpTime[0] + cpTime[1] + cpTime[2] + cpTime[3]; - *totalAll = *inUseAll + cpTime[4]; + uint32_t coreCount = neededLength / (CPUSTATES * sizeof(uint64_t)); + assert(coreCount > 0); + + FF_AUTO_FREE uint64_t (*cpTimes)[CPUSTATES] = malloc(neededLength); + if(sysctlbyname("kern.cp_times", cpTimes, &neededLength, NULL, 0) != 0) + return "sysctlbyname(kern.cp_times, cpTime) failed"; + + for (uint32_t i = 0; i < coreCount; ++i) + { + uint64_t* cpTime = cpTimes[i]; + uint64_t inUse = cpTime[CP_USER] + cpTime[CP_NICE] + cpTime[CP_SYS]; + uint64_t total = cpTime[CP_INTR] + cpTime[CP_IDLE]; + *inUseAll += inUse; + *totalAll += total; + } return NULL; }