File Index
Files and directories
Sign in
FILE

thermometer.c

File preview with syntax highlighting.

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