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