123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148 |
- #define _GNU_SOURCE
- #include "governors-query.h"
- #include "logging.h"
- #include <assert.h>
- #include <glob.h>
- #include <stdio.h>
- #include <string.h>
- int fetch_governors(char governors[MAX_GOVERNORS][MAX_GOVERNOR_LENGTH])
- {
- glob_t glo = { 0 };
- static const char *path = "/sys/devices/system/cpu/cpu*/cpufreq/scaling_governor";
-
- if (glob(path, GLOB_NOSORT, NULL, &glo) != 0) {
- LOG_ERROR("glob failed for cpu governors: (%s)\n", strerror(errno));
- return 0;
- }
- if (glo.gl_pathc < 1) {
- globfree(&glo);
- LOG_ERROR("no cpu governors found\n");
- return 0;
- }
- int num_governors = 0;
-
- for (size_t i = 0; i < glo.gl_pathc; i++) {
- if (i >= MAX_GOVERNORS) {
- break;
- }
-
- char fullpath[PATH_MAX] = { 0 };
- const char *ptr = realpath(glo.gl_pathv[i], fullpath);
- if (fullpath != ptr) {
- continue;
- }
-
- for (int j = 0; j < num_governors; j++) {
- if (strncmp(fullpath, governors[i], PATH_MAX) == 0) {
- continue;
- }
- }
-
- static_assert(MAX_GOVERNOR_LENGTH > PATH_MAX, "possible string truncation");
- strncpy(governors[num_governors], fullpath, MAX_GOVERNOR_LENGTH);
- num_governors++;
- }
- globfree(&glo);
- return num_governors;
- }
- const char *get_gov_state(void)
- {
-
- static char governor[64] = { 0 };
- memset(governor, 0, sizeof(governor));
-
- char governors[MAX_GOVERNORS][MAX_GOVERNOR_LENGTH] = { { 0 } };
- int num = fetch_governors(governors);
-
- for (int i = 0; i < num; i++) {
- const char *gov = governors[i];
- FILE *f = fopen(gov, "r");
- if (!f) {
- LOG_ERROR("Failed to open file for read %s\n", gov);
- continue;
- }
-
- fseek(f, 0, SEEK_END);
- long length = ftell(f);
- fseek(f, 0, SEEK_SET);
- char contents[length];
- if (fread(contents, 1, (size_t)length, f) > 0) {
-
- strtok(contents, "\n");
- if (strlen(governor) > 0 && strncmp(governor, contents, 64) != 0) {
-
- LOG_ERROR("Governors malformed: got \"%s\", expected \"%s\"", contents, governor);
- return "malformed";
- }
- strncpy(governor, contents, sizeof(governor) - 1);
- } else {
- LOG_ERROR("Failed to read contents of %s\n", gov);
- }
- fclose(f);
- }
- return governor;
- }
|