xref: /linux/tools/power/cpupower/utils/idle_monitor/cpupower-monitor.c (revision 53edfecef66bfa65882ae065ed1a52f466c88979)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  (C) 2010,2011       Thomas Renninger <trenn@suse.de>, Novell Inc.
4  *
5  *  Output format inspired by Len Brown's <lenb@kernel.org> turbostat tool.
6  */
7 
8 
9 #include <errno.h>
10 #include <stdio.h>
11 #include <unistd.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <time.h>
15 #include <signal.h>
16 #include <sys/types.h>
17 #include <sys/wait.h>
18 #include <libgen.h>
19 
20 #include "idle_monitor/cpupower-monitor.h"
21 #include "idle_monitor/idle_monitors.h"
22 #include "helpers/helpers.h"
23 
24 /* Define pointers to all monitors.  */
25 #define DEF(x) & x ## _monitor ,
26 struct cpuidle_monitor *all_monitors[] = {
27 #include "idle_monitors.def"
28 0
29 };
30 
31 int cpu_count;
32 
33 static struct cpuidle_monitor *monitors[MONITORS_MAX];
34 static unsigned int avail_monitors;
35 
36 static char *progname;
37 
38 enum operation_mode_e { list = 1, show, show_all };
39 static enum operation_mode_e mode;
40 static int interval = 1;
41 static char *show_monitors_param;
42 static struct cpupower_topology cpu_top;
43 static unsigned int wake_cpus;
44 
45 /* ToDo: Document this in the manpage */
46 static char range_abbr[RANGE_MAX] = { 'T', 'C', 'P', 'M', };
47 
print_wrong_arg_exit(void)48 static void print_wrong_arg_exit(void)
49 {
50 	printf(_("invalid or unknown argument\n"));
51 	exit(EXIT_FAILURE);
52 }
53 
timespec_diff_us(struct timespec start,struct timespec end)54 long long timespec_diff_us(struct timespec start, struct timespec end)
55 {
56 	struct timespec temp;
57 	if ((end.tv_nsec - start.tv_nsec) < 0) {
58 		temp.tv_sec = end.tv_sec - start.tv_sec - 1;
59 		temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
60 	} else {
61 		temp.tv_sec = end.tv_sec - start.tv_sec;
62 		temp.tv_nsec = end.tv_nsec - start.tv_nsec;
63 	}
64 	return (temp.tv_sec * 1000000) + (temp.tv_nsec / 1000);
65 }
66 
print_n_spaces(int n)67 void print_n_spaces(int n)
68 {
69 	int x;
70 	for (x = 0; x < n; x++)
71 		printf(" ");
72 }
73 
74 /*s is filled with left and right spaces
75  *to make its length atleast n+1
76  */
fill_string_with_spaces(char * s,int n)77 int fill_string_with_spaces(char *s, int n)
78 {
79 	char *temp;
80 	int len = strlen(s);
81 
82 	if (len >= n)
83 		return -1;
84 
85 	temp = malloc(sizeof(char) * (n+1));
86 	for (; len < n; len++)
87 		s[len] = ' ';
88 	s[len] = '\0';
89 	snprintf(temp, n+1, " %s", s);
90 	strcpy(s, temp);
91 	free(temp);
92 	return 0;
93 }
94 
95 #define MAX_COL_WIDTH		6
96 #define TOPOLOGY_DEPTH_PKG	3
97 #define TOPOLOGY_DEPTH_CORE	2
98 #define TOPOLOGY_DEPTH_CPU	1
99 
print_header(int topology_depth)100 void print_header(int topology_depth)
101 {
102 	int unsigned mon;
103 	int state, need_len;
104 	cstate_t s;
105 	char buf[128] = "";
106 
107 	fill_string_with_spaces(buf, topology_depth * 5 - 1);
108 	printf("%s|", buf);
109 
110 	for (mon = 0; mon < avail_monitors; mon++) {
111 		need_len = monitors[mon]->hw_states_num * (MAX_COL_WIDTH + 1)
112 			- 1;
113 		if (mon != 0)
114 			printf("||");
115 		sprintf(buf, "%s", monitors[mon]->name);
116 		fill_string_with_spaces(buf, need_len);
117 		printf("%s", buf);
118 	}
119 	printf("\n");
120 
121 	switch (topology_depth) {
122 	case TOPOLOGY_DEPTH_PKG:
123 		printf(" PKG|");
124 	case TOPOLOGY_DEPTH_CORE:
125 		printf("CORE|");
126 	case	TOPOLOGY_DEPTH_CPU:
127 		printf(" CPU|");
128 		break;
129 	default:
130 		return;
131 	}
132 
133 	for (mon = 0; mon < avail_monitors; mon++) {
134 		if (mon != 0)
135 			printf("||");
136 		for (state = 0; state < monitors[mon]->hw_states_num; state++) {
137 			if (state != 0)
138 				printf("|");
139 			s = monitors[mon]->hw_states[state];
140 			sprintf(buf, "%s", s.name);
141 			fill_string_with_spaces(buf, MAX_COL_WIDTH);
142 			printf("%s", buf);
143 		}
144 		printf(" ");
145 	}
146 	printf("\n");
147 }
148 
149 
print_results(int topology_depth,int cpu)150 void print_results(int topology_depth, int cpu)
151 {
152 	unsigned int mon;
153 	int state, ret;
154 	double percent;
155 	unsigned long long result;
156 	cstate_t s;
157 
158 	/* Be careful CPUs may got resorted for pkg value do not just use cpu */
159 	if (!bitmask_isbitset(cpus_chosen, cpu_top.core_info[cpu].cpu))
160 		return;
161 	if (!cpu_top.core_info[cpu].is_online &&
162 	    cpu_top.core_info[cpu].pkg == -1)
163 		return;
164 
165 	switch (topology_depth) {
166 	case TOPOLOGY_DEPTH_PKG:
167 		printf("%4d|", cpu_top.core_info[cpu].pkg);
168 	case TOPOLOGY_DEPTH_CORE:
169 		printf("%4d|", cpu_top.core_info[cpu].core);
170 	case TOPOLOGY_DEPTH_CPU:
171 		printf("%4d|", cpu_top.core_info[cpu].cpu);
172 		break;
173 	default:
174 		return;
175 	}
176 
177 	for (mon = 0; mon < avail_monitors; mon++) {
178 		if (mon != 0)
179 			printf("||");
180 
181 		for (state = 0; state < monitors[mon]->hw_states_num; state++) {
182 			if (state != 0)
183 				printf("|");
184 
185 			s = monitors[mon]->hw_states[state];
186 
187 			if (s.get_count_percent) {
188 				ret = s.get_count_percent(s.id, &percent,
189 						  cpu_top.core_info[cpu].cpu);
190 				if (ret)
191 					printf("******");
192 				else if (percent >= 100.0)
193 					printf("%6.1f", percent);
194 				else
195 					printf("%6.2f", percent);
196 			} else if (s.get_count) {
197 				ret = s.get_count(s.id, &result,
198 						  cpu_top.core_info[cpu].cpu);
199 				if (ret)
200 					printf("******");
201 				else
202 					printf("%6llu", result);
203 			} else {
204 				printf(_("Monitor %s, Counter %s has no count "
205 					 "function. Implementation error\n"),
206 				       monitors[mon]->name, s.name);
207 				exit(EXIT_FAILURE);
208 			}
209 		}
210 	}
211 	/*
212 	 * The monitor could still provide useful data, for example
213 	 * AMD HW counters partly sit in PCI config space.
214 	 * It's up to the monitor plug-in to check .is_online, this one
215 	 * is just for additional info.
216 	 */
217 	if (!cpu_top.core_info[cpu].is_online &&
218 	    cpu_top.core_info[cpu].pkg != -1) {
219 		printf(_(" *is offline\n"));
220 		return;
221 	} else
222 		printf("\n");
223 }
224 
225 
226 /* param: string passed by -m param (The list of monitors to show)
227  *
228  * Monitors must have been registered already, matching monitors
229  * are picked out and available monitors array is overridden
230  * with matching ones
231  *
232  * Monitors get sorted in the same order the user passes them
233 */
234 
parse_monitor_param(char * param)235 static void parse_monitor_param(char *param)
236 {
237 	unsigned int num;
238 	int mon, hits = 0;
239 	char *tmp = param, *token;
240 	struct cpuidle_monitor *tmp_mons[MONITORS_MAX];
241 
242 
243 	for (mon = 0; mon < MONITORS_MAX; mon++, tmp = NULL) {
244 		token = strtok(tmp, ",");
245 		if (token == NULL)
246 			break;
247 		if (strlen(token) >= MONITOR_NAME_LEN) {
248 			printf(_("%s: max monitor name length"
249 				 " (%d) exceeded\n"), token, MONITOR_NAME_LEN);
250 			continue;
251 		}
252 
253 		for (num = 0; num < avail_monitors; num++) {
254 			if (!strcmp(monitors[num]->name, token)) {
255 				dprint("Found requested monitor: %s\n", token);
256 				tmp_mons[hits] = monitors[num];
257 				hits++;
258 			}
259 		}
260 	}
261 	if (hits == 0) {
262 		printf(_("No matching monitor found in %s, "
263 			 "try -l option\n"), param);
264 		exit(EXIT_FAILURE);
265 	}
266 	/* Override detected/registerd monitors array with requested one */
267 	memcpy(monitors, tmp_mons,
268 		sizeof(struct cpuidle_monitor *) * MONITORS_MAX);
269 	avail_monitors = hits;
270 }
271 
list_monitors(void)272 void list_monitors(void)
273 {
274 	unsigned int mon;
275 	int state;
276 	cstate_t s;
277 
278 	for (mon = 0; mon < avail_monitors; mon++) {
279 		printf(_("Monitor \"%s\" (%d states) - Might overflow after %u "
280 			 "s\n"),
281 			monitors[mon]->name, monitors[mon]->hw_states_num,
282 			monitors[mon]->overflow_s);
283 
284 		for (state = 0; state < monitors[mon]->hw_states_num; state++) {
285 			s = monitors[mon]->hw_states[state];
286 			/*
287 			 * ToDo show more state capabilities:
288 			 * percent, time (granlarity)
289 			 */
290 			printf("%s\t[%c] -> %s\n", s.name, range_abbr[s.range],
291 			       gettext(s.desc));
292 		}
293 	}
294 }
295 
fork_it(char ** argv)296 int fork_it(char **argv)
297 {
298 	int status;
299 	unsigned int num;
300 	unsigned long long timediff;
301 	pid_t child_pid;
302 	struct timespec start, end;
303 
304 	child_pid = fork();
305 	clock_gettime(CLOCK_REALTIME, &start);
306 
307 	for (num = 0; num < avail_monitors; num++)
308 		monitors[num]->start();
309 
310 	if (!child_pid) {
311 		/* child */
312 		if (execvp(argv[0], argv) == -1) {
313 			printf("Invalid monitor command %s\n", argv[0]);
314 			exit(errno);
315 		}
316 	} else {
317 		/* parent */
318 		if (child_pid == -1) {
319 			perror("fork");
320 			exit(1);
321 		}
322 
323 		signal(SIGINT, SIG_IGN);
324 		signal(SIGQUIT, SIG_IGN);
325 		if (waitpid(child_pid, &status, 0) == -1) {
326 			perror("wait");
327 			exit(1);
328 		}
329 	}
330 	clock_gettime(CLOCK_REALTIME, &end);
331 	for (num = 0; num < avail_monitors; num++)
332 		monitors[num]->stop();
333 
334 	timediff = timespec_diff_us(start, end);
335 	if (WIFEXITED(status))
336 		printf(_("%s took %.5f seconds and exited with status %d\n"),
337 			argv[0], timediff / (1000.0 * 1000),
338 			WEXITSTATUS(status));
339 	return 0;
340 }
341 
do_interval_measure(int i)342 int do_interval_measure(int i)
343 {
344 	unsigned int num;
345 	int cpu;
346 
347 	if (wake_cpus)
348 		for (cpu = 0; cpu < cpu_count; cpu++)
349 			bind_cpu(cpu);
350 
351 	for (num = 0; num < avail_monitors; num++) {
352 		dprint("HW C-state residency monitor: %s - States: %d\n",
353 		       monitors[num]->name, monitors[num]->hw_states_num);
354 		monitors[num]->start();
355 	}
356 
357 	sleep(i);
358 
359 	if (wake_cpus)
360 		for (cpu = 0; cpu < cpu_count; cpu++)
361 			bind_cpu(cpu);
362 
363 	for (num = 0; num < avail_monitors; num++)
364 		monitors[num]->stop();
365 
366 
367 	return 0;
368 }
369 
cmdline(int argc,char * argv[])370 static void cmdline(int argc, char *argv[])
371 {
372 	int opt;
373 	progname = basename(argv[0]);
374 
375 	while ((opt = getopt(argc, argv, "+lci:m:")) != -1) {
376 		switch (opt) {
377 		case 'l':
378 			if (mode)
379 				print_wrong_arg_exit();
380 			mode = list;
381 			break;
382 		case 'i':
383 			/* only allow -i with -m or no option */
384 			if (mode && mode != show)
385 				print_wrong_arg_exit();
386 			interval = atoi(optarg);
387 			break;
388 		case 'm':
389 			if (mode)
390 				print_wrong_arg_exit();
391 			mode = show;
392 			show_monitors_param = optarg;
393 			break;
394 		case 'c':
395 			wake_cpus = 1;
396 			break;
397 		default:
398 			print_wrong_arg_exit();
399 		}
400 	}
401 	if (!mode)
402 		mode = show_all;
403 }
404 
cmd_monitor(int argc,char ** argv)405 int cmd_monitor(int argc, char **argv)
406 {
407 	unsigned int num;
408 	struct cpuidle_monitor *test_mon;
409 	int cpu;
410 
411 	cmdline(argc, argv);
412 	cpu_count = get_cpu_topology(&cpu_top);
413 	if (cpu_count < 0) {
414 		printf(_("Cannot read number of available processors\n"));
415 		return EXIT_FAILURE;
416 	}
417 
418 	if (!cpu_top.core_info[0].is_online)
419 		printf("WARNING: at least one cpu is offline\n");
420 
421 	/* Default is: monitor all CPUs */
422 	if (bitmask_isallclear(cpus_chosen))
423 		bitmask_setall(cpus_chosen);
424 
425 	dprint("System has up to %d CPU cores\n", cpu_count);
426 
427 	for (num = 0; all_monitors[num]; num++) {
428 		dprint("Try to register: %s\n", all_monitors[num]->name);
429 		test_mon = all_monitors[num]->do_register();
430 		if (test_mon) {
431 			if (test_mon->flags.needs_root && !run_as_root) {
432 				fprintf(stderr, _("Available monitor %s needs "
433 					  "root access\n"), test_mon->name);
434 				continue;
435 			}
436 			monitors[avail_monitors] = test_mon;
437 			dprint("%s registered\n", all_monitors[num]->name);
438 			avail_monitors++;
439 		}
440 	}
441 
442 	if (avail_monitors == 0) {
443 		printf(_("No HW Cstate monitors found\n"));
444 		cpu_topology_release(cpu_top);
445 		return 1;
446 	}
447 
448 	if (mode == list) {
449 		list_monitors();
450 		cpu_topology_release(cpu_top);
451 		exit(EXIT_SUCCESS);
452 	}
453 
454 	if (mode == show)
455 		parse_monitor_param(show_monitors_param);
456 
457 	dprint("Packages: %d - Cores: %d - CPUs: %d\n",
458 	       cpu_top.pkgs, cpu_top.cores, cpu_count);
459 
460 	/*
461 	 * if any params left, it must be a command to fork
462 	 */
463 	if (argc - optind)
464 		fork_it(argv + optind);
465 	else
466 		do_interval_measure(interval);
467 
468 	/* ToDo: Topology parsing needs fixing first to do
469 	   this more generically */
470 	if (cpu_top.pkgs > 1)
471 		print_header(TOPOLOGY_DEPTH_PKG);
472 	else
473 		print_header(TOPOLOGY_DEPTH_CPU);
474 
475 	for (cpu = 0; cpu < cpu_count; cpu++) {
476 		if (cpu_top.pkgs > 1)
477 			print_results(TOPOLOGY_DEPTH_PKG, cpu);
478 		else
479 			print_results(TOPOLOGY_DEPTH_CPU, cpu);
480 	}
481 
482 	for (num = 0; num < avail_monitors; num++) {
483 		if (monitors[num]->unregister)
484 			monitors[num]->unregister();
485 	}
486 	cpu_topology_release(cpu_top);
487 	return 0;
488 }
489