master ohmu/fastfetch-openbsd / src / detection / cpu / cpu_obsd.c
ohmu  ·  2026-10-15
 1#include "cpu.h"
 2#include "common/debug.h"
 3#include "common/sysctl.h"
 4#include "common/strutil.h"
 5
 6#include <string.h>
 7#include <errno.h>
 8#include <sys/time.h>
 9#include <sys/sensors.h>
10
11static const char* detectCPUTemp(const FFCPUOptions* options, FFCPUResult* cpu) {
12    int mib[5] = { CTL_HW, HW_SENSORS, 0, SENSOR_TEMP, 0 };
13
14    for (mib[2] = 0; mib[2] < 1024; mib[2]++) {
15        struct sensordev sensordev;
16        size_t sdlen = sizeof(struct sensordev);
17        if (sysctl(mib, 3, &sensordev, &sdlen, nullptr, 0) < 0) {
18            if (errno == ENOENT) {
19                break;
20            }
21            if (errno == ENXIO) {
22                continue;
23            }
24            FF_DEBUG("sysctl(sensordev) failed: %s", strerror(errno));
25            return "sysctl(sensordev) failed";
26        }
27
28        if (options->tempSensor.length > 0) {
29            if (!ffStrbufEqualS(&options->tempSensor, sensordev.xname)) {
30                continue;
31            }
32        } else {
33            if (!ffStrStartsWith(sensordev.xname, "cpu")) {
34                continue;
35            }
36        }
37
38        for (mib[4] = 0; mib[4] < sensordev.maxnumt[SENSOR_TEMP]; mib[4]++) {
39            struct sensor sensor;
40            size_t slen = sizeof(struct sensor);
41            if (sysctl(mib, 5, &sensor, &slen, nullptr, 0) < 0) {
42                if (errno != ENOENT) {
43                    FF_DEBUG("sysctl(sensor) failed: %s", strerror(errno));
44                    return "sysctl(sensor) failed";
45                }
46                continue;
47            }
48            if (sensor.flags & SENSOR_FINVALID) {
49                continue;
50            }
51
52            cpu->temperature = (double) (sensor.value - 273150000) / 1E6;
53            return nullptr;
54        }
55    }
56
57    FF_DEBUG("No sensor for CPU temp found");
58    return "No sensor for CPU temp found";
59}
60
61const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) {
62    const char* error = ffSysctlGetString(CTL_HW, HW_MODEL, &cpu->name);
63    if (error) {
64        FF_DEBUG("sysctl(hw.model) failed: %s", error);
65        return "sysctl(hw.model) failed";
66    }
67
68    cpu->coresPhysical = (uint16_t) ffSysctlGetInt(CTL_HW, HW_NCPU, 1);
69    cpu->coresLogical = cpu->coresPhysical;
70    cpu->coresOnline = (uint16_t) ffSysctlGetInt(CTL_HW, HW_NCPUONLINE, cpu->coresLogical);
71
72    ffCPUDetectByCpuid(cpu);
73
74    uint32_t cpuspeed = (uint32_t) ffSysctlGetInt(CTL_HW, HW_CPUSPEED, 0);
75    if (cpuspeed > cpu->frequencyBase) {
76        cpu->frequencyBase = cpuspeed;
77    }
78
79    cpu->temperature = FF_CPU_TEMP_UNSET;
80    if (options->temp) {
81        detectCPUTemp(options, cpu);
82    }
83
84    return nullptr;
85}