thermometer.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. // Copyright (C) 2022, Linaro Ltd - Daniel Lezcano <daniel.lezcano@linaro.org>
  3. #define _GNU_SOURCE
  4. #include <dirent.h>
  5. #include <fcntl.h>
  6. #include <getopt.h>
  7. #include <regex.h>
  8. #include <signal.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <sys/stat.h>
  13. #include <sys/signalfd.h>
  14. #include <sys/timerfd.h>
  15. #include <sys/types.h>
  16. #include <sys/wait.h>
  17. #include <time.h>
  18. #include <unistd.h>
  19. #include <linux/thermal.h>
  20. #include <libconfig.h>
  21. #include "thermal-tools.h"
  22. #define CLASS_THERMAL "/sys/class/thermal"
  23. enum {
  24. THERMOMETER_SUCCESS = 0,
  25. THERMOMETER_OPTION_ERROR,
  26. THERMOMETER_LOG_ERROR,
  27. THERMOMETER_CONFIG_ERROR,
  28. THERMOMETER_TIME_ERROR,
  29. THERMOMETER_INIT_ERROR,
  30. THERMOMETER_RUNTIME_ERROR
  31. };
  32. struct options {
  33. int loglvl;
  34. int logopt;
  35. int overwrite;
  36. int duration;
  37. const char *config;
  38. char postfix[PATH_MAX];
  39. char output[PATH_MAX];
  40. };
  41. struct tz_regex {
  42. regex_t regex;
  43. int polling;
  44. };
  45. struct configuration {
  46. struct tz_regex *tz_regex;
  47. int nr_tz_regex;
  48. };
  49. struct tz {
  50. FILE *file_out;
  51. int fd_temp;
  52. int fd_timer;
  53. int polling;
  54. const char *name;
  55. };
  56. struct thermometer {
  57. struct tz *tz;
  58. int nr_tz;
  59. };
  60. static struct tz_regex *configuration_tz_match(const char *expr,
  61. struct configuration *config)
  62. {
  63. int i;
  64. for (i = 0; i < config->nr_tz_regex; i++) {
  65. if (!regexec(&config->tz_regex[i].regex, expr, 0, NULL, 0))
  66. return &config->tz_regex[i];
  67. }
  68. return NULL;
  69. }
  70. static int configuration_default_init(struct configuration *config)
  71. {
  72. config->tz_regex = realloc(config->tz_regex, sizeof(*config->tz_regex) *
  73. (config->nr_tz_regex + 1));
  74. if (regcomp(&config->tz_regex[config->nr_tz_regex].regex, ".*",
  75. REG_NOSUB | REG_EXTENDED)) {
  76. ERROR("Invalid regular expression\n");
  77. return -1;
  78. }
  79. config->tz_regex[config->nr_tz_regex].polling = 250;
  80. config->nr_tz_regex = 1;
  81. return 0;
  82. }
  83. static int configuration_init(const char *path, struct configuration *config)
  84. {
  85. config_t cfg;
  86. config_setting_t *tz;
  87. int i, length;
  88. if (path && access(path, F_OK)) {
  89. ERROR("'%s' is not accessible\n", path);
  90. return -1;
  91. }
  92. if (!path && !config->nr_tz_regex) {
  93. INFO("No thermal zones configured, using wildcard for all of them\n");
  94. return configuration_default_init(config);
  95. }
  96. config_init(&cfg);
  97. if (!config_read_file(&cfg, path)) {
  98. ERROR("Failed to parse %s:%d - %s\n", config_error_file(&cfg),
  99. config_error_line(&cfg), config_error_text(&cfg));
  100. return -1;
  101. }
  102. tz = config_lookup(&cfg, "thermal-zones");
  103. if (!tz) {
  104. ERROR("No thermal zone configured to be monitored\n");
  105. return -1;
  106. }
  107. length = config_setting_length(tz);
  108. INFO("Found %d thermal zone(s) regular expression\n", length);
  109. for (i = 0; i < length; i++) {
  110. config_setting_t *node;
  111. const char *name;
  112. int polling;
  113. node = config_setting_get_elem(tz, i);
  114. if (!node) {
  115. ERROR("Missing node name '%d'\n", i);
  116. return -1;
  117. }
  118. if (!config_setting_lookup_string(node, "name", &name)) {
  119. ERROR("Thermal zone name not found\n");
  120. return -1;
  121. }
  122. if (!config_setting_lookup_int(node, "polling", &polling)) {
  123. ERROR("Polling value not found");
  124. return -1;
  125. }
  126. config->tz_regex = realloc(config->tz_regex, sizeof(*config->tz_regex) *
  127. (config->nr_tz_regex + 1));
  128. if (regcomp(&config->tz_regex[config->nr_tz_regex].regex, name,
  129. REG_NOSUB | REG_EXTENDED)) {
  130. ERROR("Invalid regular expression '%s'\n", name);
  131. continue;
  132. }
  133. config->tz_regex[config->nr_tz_regex].polling = polling;
  134. config->nr_tz_regex++;
  135. INFO("Thermal zone regular expression '%s' with polling %d\n",
  136. name, polling);
  137. }
  138. return 0;
  139. }
  140. static void usage(const char *cmd)
  141. {
  142. printf("%s Version: %s\n", cmd, VERSION);
  143. printf("Usage: %s [options]\n", cmd);
  144. printf("\t-h, --help\t\tthis help\n");
  145. printf("\t-o, --output <dir>\toutput directory for temperature capture\n");
  146. printf("\t-c, --config <file>\tconfiguration file\n");
  147. printf("\t-d, --duration <seconds>\tcapture duration\n");
  148. printf("\t-l, --loglevel <level>\tlog level: ");
  149. printf("DEBUG, INFO, NOTICE, WARN, ERROR\n");
  150. printf("\t-p, --postfix <string>\tpostfix to be happened at the end of the files\n");
  151. printf("\t-s, --syslog\t\toutput to syslog\n");
  152. printf("\t-w, --overwrite\t\toverwrite the temperature capture files if they exist\n");
  153. printf("\n");
  154. exit(0);
  155. }
  156. static int options_init(int argc, char *argv[], struct options *options)
  157. {
  158. int opt;
  159. time_t now = time(NULL);
  160. struct option long_options[] = {
  161. { "help", no_argument, NULL, 'h' },
  162. { "config", required_argument, NULL, 'c' },
  163. { "duration", required_argument, NULL, 'd' },
  164. { "loglevel", required_argument, NULL, 'l' },
  165. { "postfix", required_argument, NULL, 'p' },
  166. { "output", required_argument, NULL, 'o' },
  167. { "syslog", required_argument, NULL, 's' },
  168. { "overwrite", no_argument, NULL, 'w' },
  169. { 0, 0, 0, 0 }
  170. };
  171. strftime(options->postfix, sizeof(options->postfix),
  172. "-%Y-%m-%d_%H:%M:%S", gmtime(&now));
  173. while (1) {
  174. int optindex = 0;
  175. opt = getopt_long(argc, argv, "ho:c:d:l:p:sw", long_options, &optindex);
  176. if (opt == -1)
  177. break;
  178. switch (opt) {
  179. case 'c':
  180. options->config = optarg;
  181. break;
  182. case 'd':
  183. options->duration = atoi(optarg) * 1000;
  184. break;
  185. case 'l':
  186. options->loglvl = log_str2level(optarg);
  187. break;
  188. case 'h':
  189. usage(basename(argv[0]));
  190. break;
  191. case 'p':
  192. strcpy(options->postfix, optarg);
  193. break;
  194. case 'o':
  195. strcpy(options->output, optarg);
  196. break;
  197. case 's':
  198. options->logopt = TO_SYSLOG;
  199. break;
  200. case 'w':
  201. options->overwrite = 1;
  202. break;
  203. default: /* '?' */
  204. ERROR("Usage: %s --help\n", argv[0]);
  205. return -1;
  206. }
  207. }
  208. return 0;
  209. }
  210. static int thermometer_add_tz(const char *path, const char *name, int polling,
  211. struct thermometer *thermometer)
  212. {
  213. int fd;
  214. char tz_path[PATH_MAX];
  215. sprintf(tz_path, CLASS_THERMAL"/%s/temp", path);
  216. fd = open(tz_path, O_RDONLY);
  217. if (fd < 0) {
  218. ERROR("Failed to open '%s': %m\n", tz_path);
  219. return -1;
  220. }
  221. thermometer->tz = realloc(thermometer->tz,
  222. sizeof(*thermometer->tz) * (thermometer->nr_tz + 1));
  223. if (!thermometer->tz) {
  224. ERROR("Failed to allocate thermometer->tz\n");
  225. return -1;
  226. }
  227. thermometer->tz[thermometer->nr_tz].fd_temp = fd;
  228. thermometer->tz[thermometer->nr_tz].name = strdup(name);
  229. thermometer->tz[thermometer->nr_tz].polling = polling;
  230. thermometer->nr_tz++;
  231. INFO("Added thermal zone '%s->%s (polling:%d)'\n", path, name, polling);
  232. return 0;
  233. }
  234. static int thermometer_init(struct configuration *config,
  235. struct thermometer *thermometer)
  236. {
  237. DIR *dir;
  238. struct dirent *dirent;
  239. struct tz_regex *tz_regex;
  240. const char *tz_dirname = "thermal_zone";
  241. if (mainloop_init()) {
  242. ERROR("Failed to start mainloop\n");
  243. return -1;
  244. }
  245. dir = opendir(CLASS_THERMAL);
  246. if (!dir) {
  247. ERROR("failed to open '%s'\n", CLASS_THERMAL);
  248. return -1;
  249. }
  250. while ((dirent = readdir(dir))) {
  251. char tz_type[THERMAL_NAME_LENGTH];
  252. char tz_path[PATH_MAX];
  253. FILE *tz_file;
  254. if (strncmp(dirent->d_name, tz_dirname, strlen(tz_dirname)))
  255. continue;
  256. sprintf(tz_path, CLASS_THERMAL"/%s/type", dirent->d_name);
  257. tz_file = fopen(tz_path, "r");
  258. if (!tz_file) {
  259. ERROR("Failed to open '%s': %m", tz_path);
  260. continue;
  261. }
  262. fscanf(tz_file, "%s", tz_type);
  263. fclose(tz_file);
  264. tz_regex = configuration_tz_match(tz_type, config);
  265. if (!tz_regex)
  266. continue;
  267. if (thermometer_add_tz(dirent->d_name, tz_type,
  268. tz_regex->polling, thermometer))
  269. continue;
  270. }
  271. closedir(dir);
  272. return 0;
  273. }
  274. static int timer_temperature_callback(int fd, void *arg)
  275. {
  276. struct tz *tz = arg;
  277. char buf[16] = { 0 };
  278. pread(tz->fd_temp, buf, sizeof(buf), 0);
  279. fprintf(tz->file_out, "%ld %s", getuptimeofday_ms(), buf);
  280. read(fd, buf, sizeof(buf));
  281. return 0;
  282. }
  283. static int thermometer_start(struct thermometer *thermometer,
  284. struct options *options)
  285. {
  286. struct itimerspec timer_it = { 0 };
  287. char *path;
  288. FILE *f;
  289. int i;
  290. INFO("Capturing %d thermal zone(s) temperature...\n", thermometer->nr_tz);
  291. if (access(options->output, F_OK) && mkdir(options->output, 0700)) {
  292. ERROR("Failed to create directory '%s'\n", options->output);
  293. return -1;
  294. }
  295. for (i = 0; i < thermometer->nr_tz; i++) {
  296. asprintf(&path, "%s/%s%s", options->output,
  297. thermometer->tz[i].name, options->postfix);
  298. if (!options->overwrite && !access(path, F_OK)) {
  299. ERROR("'%s' already exists\n", path);
  300. return -1;
  301. }
  302. f = fopen(path, "w");
  303. if (!f) {
  304. ERROR("Failed to create '%s':%m\n", path);
  305. return -1;
  306. }
  307. fprintf(f, "timestamp(ms) %s(°mC)\n", thermometer->tz[i].name);
  308. thermometer->tz[i].file_out = f;
  309. DEBUG("Created '%s' file for thermal zone '%s'\n", path, thermometer->tz[i].name);
  310. /*
  311. * Create polling timer
  312. */
  313. thermometer->tz[i].fd_timer = timerfd_create(CLOCK_MONOTONIC, 0);
  314. if (thermometer->tz[i].fd_timer < 0) {
  315. ERROR("Failed to create timer for '%s': %m\n",
  316. thermometer->tz[i].name);
  317. return -1;
  318. }
  319. DEBUG("Watching '%s' every %d ms\n",
  320. thermometer->tz[i].name, thermometer->tz[i].polling);
  321. timer_it.it_interval = timer_it.it_value =
  322. msec_to_timespec(thermometer->tz[i].polling);
  323. if (timerfd_settime(thermometer->tz[i].fd_timer, 0,
  324. &timer_it, NULL) < 0)
  325. return -1;
  326. if (mainloop_add(thermometer->tz[i].fd_timer,
  327. timer_temperature_callback,
  328. &thermometer->tz[i]))
  329. return -1;
  330. }
  331. return 0;
  332. }
  333. static int thermometer_execute(int argc, char *argv[], char *const envp[], pid_t *pid)
  334. {
  335. if (!argc)
  336. return 0;
  337. *pid = fork();
  338. if (*pid < 0) {
  339. ERROR("Failed to fork process: %m");
  340. return -1;
  341. }
  342. if (!(*pid)) {
  343. execvpe(argv[0], argv, envp);
  344. exit(1);
  345. }
  346. return 0;
  347. }
  348. static int kill_process(__maybe_unused int fd, void *arg)
  349. {
  350. pid_t pid = *(pid_t *)arg;
  351. if (kill(pid, SIGTERM))
  352. ERROR("Failed to send SIGTERM signal to '%d': %p\n", pid);
  353. else if (waitpid(pid, NULL, 0))
  354. ERROR("Failed to wait pid '%d': %p\n", pid);
  355. mainloop_exit();
  356. return 0;
  357. }
  358. static int exit_mainloop(__maybe_unused int fd, __maybe_unused void *arg)
  359. {
  360. mainloop_exit();
  361. return 0;
  362. }
  363. static int thermometer_wait(struct options *options, pid_t pid)
  364. {
  365. int fd;
  366. sigset_t mask;
  367. /*
  368. * If there is a duration specified, we will exit the mainloop
  369. * and gracefully close all the files which will flush the
  370. * file system cache
  371. */
  372. if (options->duration) {
  373. struct itimerspec timer_it = { 0 };
  374. timer_it.it_value = msec_to_timespec(options->duration);
  375. fd = timerfd_create(CLOCK_MONOTONIC, 0);
  376. if (fd < 0) {
  377. ERROR("Failed to create duration timer: %m\n");
  378. return -1;
  379. }
  380. if (timerfd_settime(fd, 0, &timer_it, NULL)) {
  381. ERROR("Failed to set timer time: %m\n");
  382. return -1;
  383. }
  384. if (mainloop_add(fd, pid < 0 ? exit_mainloop : kill_process, &pid)) {
  385. ERROR("Failed to set timer exit mainloop callback\n");
  386. return -1;
  387. }
  388. }
  389. /*
  390. * We want to catch any keyboard interrupt, as well as child
  391. * signals if any in order to exit properly
  392. */
  393. sigemptyset(&mask);
  394. sigaddset(&mask, SIGINT);
  395. sigaddset(&mask, SIGQUIT);
  396. sigaddset(&mask, SIGCHLD);
  397. if (sigprocmask(SIG_BLOCK, &mask, NULL)) {
  398. ERROR("Failed to set sigprocmask: %m\n");
  399. return -1;
  400. }
  401. fd = signalfd(-1, &mask, 0);
  402. if (fd < 0) {
  403. ERROR("Failed to set the signalfd: %m\n");
  404. return -1;
  405. }
  406. if (mainloop_add(fd, exit_mainloop, NULL)) {
  407. ERROR("Failed to set timer exit mainloop callback\n");
  408. return -1;
  409. }
  410. return mainloop(-1);
  411. }
  412. static int thermometer_stop(struct thermometer *thermometer)
  413. {
  414. int i;
  415. INFO("Closing/flushing output files\n");
  416. for (i = 0; i < thermometer->nr_tz; i++)
  417. fclose(thermometer->tz[i].file_out);
  418. return 0;
  419. }
  420. int main(int argc, char *argv[], char *const envp[])
  421. {
  422. struct options options = {
  423. .loglvl = LOG_DEBUG,
  424. .logopt = TO_STDOUT,
  425. .output = ".",
  426. };
  427. struct configuration config = { 0 };
  428. struct thermometer thermometer = { 0 };
  429. pid_t pid = -1;
  430. if (options_init(argc, argv, &options))
  431. return THERMOMETER_OPTION_ERROR;
  432. if (log_init(options.loglvl, argv[0], options.logopt))
  433. return THERMOMETER_LOG_ERROR;
  434. if (configuration_init(options.config, &config))
  435. return THERMOMETER_CONFIG_ERROR;
  436. if (uptimeofday_init())
  437. return THERMOMETER_TIME_ERROR;
  438. if (thermometer_init(&config, &thermometer))
  439. return THERMOMETER_INIT_ERROR;
  440. if (thermometer_start(&thermometer, &options))
  441. return THERMOMETER_RUNTIME_ERROR;
  442. if (thermometer_execute(argc - optind, &argv[optind], envp, &pid))
  443. return THERMOMETER_RUNTIME_ERROR;
  444. if (thermometer_wait(&options, pid))
  445. return THERMOMETER_RUNTIME_ERROR;
  446. if (thermometer_stop(&thermometer))
  447. return THERMOMETER_RUNTIME_ERROR;
  448. return THERMOMETER_SUCCESS;
  449. }