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