master ohmu/fastfetch-openbsd / src / detection / cpuusage / cpuusage_sunos.c
ohmu  ·  2026-10-15
 1#include "fastfetch.h"
 2#include "common/debug.h"
 3#include "detection/cpuusage/cpuusage.h"
 4
 5#include <kstat.h>
 6#include <sys/sysinfo.h>
 7
 8static inline void kstatFreeWrap(kstat_ctl_t** pkc) {
 9    assert(pkc);
10    if (*pkc) {
11        kstat_close(*pkc);
12    }
13}
14
15const char* ffGetCpuUsageInfo(FFlist* cpuTimes) {
16    [[gnu::cleanup(kstatFreeWrap)]] kstat_ctl_t* kc = kstat_open();
17    if (!kc) {
18        FF_DEBUG("kstat_open() failed");
19        return "kstat_open() failed";
20    }
21
22    for (int i = 0;; ++i) {
23        kstat_t* ks = kstat_lookup(kc, "cpu_stat", i, nullptr);
24
25        cpu_stat_t cs;
26        if (!ks || kstat_read(kc, ks, &cs) < 0) {
27            break;
28        }
29
30        uint64_t inUse = cs.cpu_sysinfo.cpu[CPU_USER] + cs.cpu_sysinfo.cpu[CPU_KERNEL];
31        uint64_t total = inUse + cs.cpu_sysinfo.cpu[CPU_IDLE] + cs.cpu_sysinfo.cpu[CPU_WAIT];
32
33        FFCpuUsageInfo* info = FF_LIST_ADD(FFCpuUsageInfo, *cpuTimes);
34        *info = (FFCpuUsageInfo) {
35            .inUseAll = inUse,
36            .totalAll = total,
37        };
38    }
39    return nullptr;
40}