xref: /linux/tools/power/x86/x86_energy_perf_policy/x86_energy_perf_policy.c (revision ed9324befbded16f66840327f981e508091eab3e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * x86_energy_perf_policy -- set the energy versus performance
4  * policy preference bias on recent X86 processors.
5  */
6 /*
7  * Copyright (c) 2010 - 2026 Intel Corporation.
8  * Len Brown <len.brown@intel.com>
9  */
10 
11 #define _GNU_SOURCE
12 /*
13  * MSRHEADER macro should be defined by the build system to include the
14  * appropriate MSR definitions header file. Typical usage:
15  * gcc -DMSRHEADER=\"msr-index.h\" or similar platform-specific MSR header
16  */
17 #include MSRHEADER  /* e.g., msr-index.h with MSR_* constant definitions */
18 #include <stdio.h>
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <sched.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
24 #include <sys/resource.h>
25 #include <getopt.h>
26 #include <err.h>
27 #include <fcntl.h>
28 #include <sys/time.h>
29 #include <limits.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <cpuid.h>
33 #include <errno.h>
34 
35 #define	OPTARG_NORMAL			(INT_MAX - 1)
36 #define	OPTARG_POWER			(INT_MAX - 2)
37 #define	OPTARG_BALANCE_POWER		(INT_MAX - 3)
38 #define	OPTARG_BALANCE_PERFORMANCE	(INT_MAX - 4)
39 #define	OPTARG_PERFORMANCE		(INT_MAX - 5)
40 
41 /* Maximum HWP activity window duration in microseconds */
42 #define HWP_WINDOW_MAX_USEC 1270000000U
43 
44 /* Nominal bus clock frequency in MHz - assumed for all HWP systems */
45 #define BCLK_MHZ 100
46 #define KHZ_PER_MHZ 1000
47 
48 struct msr_hwp_cap {
49 	unsigned char highest;
50 	unsigned char guaranteed;
51 	unsigned char efficient;
52 	unsigned char lowest;
53 };
54 
55 struct msr_hwp_request {
56 	unsigned char hwp_min;
57 	unsigned char hwp_max;
58 	unsigned char hwp_desired;
59 	unsigned char hwp_epp;
60 	unsigned int hwp_window;
61 	unsigned char hwp_use_pkg;
62 } req_update;
63 
64 unsigned int debug;
65 unsigned int verbose;
66 unsigned int force;
67 char *progname;
68 int base_cpu;
69 unsigned char update_epb;
70 unsigned long long new_epb;
71 unsigned char turbo_is_enabled;
72 unsigned char update_turbo;
73 unsigned char turbo_update_value;
74 unsigned char update_hwp_epp;
75 unsigned char update_hwp_min;
76 unsigned char update_hwp_max;
77 unsigned char hwp_limits_done_via_sysfs;
78 unsigned char update_hwp_desired;
79 unsigned char update_hwp_window;
80 unsigned char update_hwp_use_pkg;
81 unsigned char update_hwp_enable;
82 #define hwp_update_enabled() (update_hwp_enable | update_hwp_epp | update_hwp_max | update_hwp_min | update_hwp_desired | update_hwp_window | update_hwp_use_pkg)
83 int max_cpu_num;
84 int max_pkg_num;
85 #define MAX_PACKAGES 64
86 unsigned int first_cpu_in_pkg[MAX_PACKAGES];
87 unsigned long long pkg_present_set;
88 unsigned long long pkg_selected_set;
89 cpu_set_t *cpu_present_set;
90 cpu_set_t *cpu_selected_set;
91 int genuine_intel;
92 
93 size_t cpu_setsize;
94 
95 char *proc_stat = "/proc/stat";
96 
97 unsigned int has_epb;		/* MSR_IA32_ENERGY_PERF_BIAS */
98 unsigned int has_hwp;		/* IA32_PM_ENABLE, IA32_HWP_CAPABILITIES */
99 			/* IA32_HWP_REQUEST, IA32_HWP_STATUS */
100 unsigned int has_hwp_notify;	/* IA32_HWP_INTERRUPT */
101 unsigned int has_hwp_activity_window;	/* IA32_HWP_REQUEST[bits 41:32] */
102 unsigned int has_hwp_epp;	/* IA32_HWP_REQUEST[bits 31:24] */
103 unsigned int has_hwp_request_pkg;	/* IA32_HWP_REQUEST_PKG */
104 
105 unsigned int bdx_highest_ratio;
106 
107 unsigned char update_soc_slider_balance;
108 unsigned char update_soc_slider_offset;
109 unsigned char update_platform_profile;
110 int soc_slider_balance;
111 int soc_slider_offset;
112 char platform_profile[64];
113 char msr_path[64];
114 
115 #define PATH_TO_CPU "/sys/devices/system/cpu/"
116 #define SYSFS_PATH_MAX 255
117 #define PATH_SOC_SLIDER_BALANCE "/sys/module/processor_thermal_soc_slider/parameters/slider_balance"
118 #define PATH_SOC_SLIDER_OFFSET "/sys/module/processor_thermal_soc_slider/parameters/slider_offset"
119 #define PATH_PLATFORM_PROFILE "/sys/class/platform-profile/platform-profile-0/profile"
120 #define PATH_PLATFORM_PROFILE_NAME "/sys/class/platform-profile/platform-profile-0/name"
121 #define POWER_SLIDER_NAME "SoC Power Slider"
122 
123 static int use_android_msr_path;
124 
125 static unsigned int read_sysfs(const char *, char *, size_t);
126 static int sysfs_read_string(const char *, char *, size_t);
127 
128 /*
129  * maintain compatibility with original implementation, but don't document it:
130  */
131 void usage(void)
132 {
133 	fprintf(stderr, "%s [options] [scope][field value]\n", progname);
134 	fprintf(stderr, "scope: --cpu cpu-list [--hwp-use-pkg #] | --pkg pkg-list\n");
135 	fprintf(stderr, "field: --all | --epb | --hwp-epp | --hwp-min | --hwp-max | --hwp-desired\n");
136 	fprintf(stderr, "other: --hwp-enable | --turbo-enable (0 | 1) | --help | --force\n");
137 	fprintf(stderr, "soc-slider: --soc-slider-balance # | --soc-slider-offset # | --platform-profile <name>\n");
138 	fprintf(stderr, "value: ( # | \"normal\" | \"performance\" | \"balance-performance\" | \"balance-power\"| \"power\")\n");
139 	fprintf(stderr, "--hwp-window usec\n");
140 
141 	fprintf(stderr, "Specify only Energy Performance BIAS (legacy usage):\n");
142 	fprintf(stderr, "%s: [-c cpu] [-v] (-r | policy-value )\n", progname);
143 
144 	exit(1);
145 }
146 
147 /*
148  * If bdx_highest_ratio is set,
149  * then we must translate between MSR format and simple ratio
150  * used on the cmdline.
151  */
152 int ratio_2_msr_perf(int ratio)
153 {
154 	int msr_perf;
155 	unsigned long long temp;
156 
157 	if (!bdx_highest_ratio)
158 		return ratio;
159 
160 	temp = (unsigned long long)ratio * 255;
161 	msr_perf = temp / bdx_highest_ratio;
162 
163 	if (debug)
164 		fprintf(stderr, "%d = ratio_to_msr_perf(%d)\n", msr_perf, ratio);
165 
166 	return msr_perf;
167 }
168 
169 int msr_perf_2_ratio(int msr_perf)
170 {
171 	int ratio;
172 	double d;
173 
174 	if (!bdx_highest_ratio)
175 		return msr_perf;
176 
177 	d = (double)msr_perf * (double)bdx_highest_ratio / 255.0;
178 	d = d + 0.5;		/* round */
179 	ratio = (int)d;
180 
181 	if (debug)
182 		fprintf(stderr, "%d = msr_perf_ratio(%d) {%f}\n", ratio, msr_perf, d);
183 
184 	return ratio;
185 }
186 
187 int parse_cmdline_epb(int i)
188 {
189 	if (!has_epb)
190 		errx(1, "EPB not enabled on this platform");
191 
192 	update_epb = 1;
193 
194 	switch (i) {
195 	case OPTARG_POWER:
196 		return ENERGY_PERF_BIAS_POWERSAVE;
197 	case OPTARG_BALANCE_POWER:
198 		return ENERGY_PERF_BIAS_BALANCE_POWERSAVE;
199 	case OPTARG_NORMAL:
200 		return ENERGY_PERF_BIAS_NORMAL;
201 	case OPTARG_BALANCE_PERFORMANCE:
202 		return ENERGY_PERF_BIAS_BALANCE_PERFORMANCE;
203 	case OPTARG_PERFORMANCE:
204 		return ENERGY_PERF_BIAS_PERFORMANCE;
205 	}
206 	if (i < 0 || i > ENERGY_PERF_BIAS_POWERSAVE)
207 		errx(1, "--epb must be 0 through 15");
208 	return i;
209 }
210 
211 #define HWP_CAP_LOWEST 0
212 #define HWP_CAP_HIGHEST 255
213 
214 /*
215  * "performance" changes hwp_min to cap.highest
216  * All others leave it at cap.lowest
217  */
218 int parse_cmdline_hwp_min(int i)
219 {
220 	update_hwp_min = 1;
221 
222 	switch (i) {
223 	case OPTARG_POWER:
224 	case OPTARG_BALANCE_POWER:
225 	case OPTARG_NORMAL:
226 	case OPTARG_BALANCE_PERFORMANCE:
227 		return HWP_CAP_LOWEST;
228 	case OPTARG_PERFORMANCE:
229 		return HWP_CAP_HIGHEST;
230 	}
231 	return i;
232 }
233 
234 /*
235  * "power" changes hwp_max to cap.lowest
236  * All others leave it at cap.highest
237  */
238 int parse_cmdline_hwp_max(int i)
239 {
240 	update_hwp_max = 1;
241 
242 	switch (i) {
243 	case OPTARG_POWER:
244 		return HWP_CAP_LOWEST;
245 	case OPTARG_NORMAL:
246 	case OPTARG_BALANCE_POWER:
247 	case OPTARG_BALANCE_PERFORMANCE:
248 	case OPTARG_PERFORMANCE:
249 		return HWP_CAP_HIGHEST;
250 	}
251 	return i;
252 }
253 
254 /*
255  * for --hwp-des, all strings leave it in autonomous mode
256  * If you want to change it, you need to explicitly pick a value
257  */
258 int parse_cmdline_hwp_desired(int i)
259 {
260 	update_hwp_desired = 1;
261 
262 	switch (i) {
263 	case OPTARG_POWER:
264 	case OPTARG_BALANCE_POWER:
265 	case OPTARG_BALANCE_PERFORMANCE:
266 	case OPTARG_NORMAL:
267 	case OPTARG_PERFORMANCE:
268 		return 0;	/* autonomous */
269 	}
270 	return i;
271 }
272 
273 unsigned int parse_cmdline_hwp_window(unsigned int i)
274 {
275 	unsigned int exponent;
276 
277 	update_hwp_window = 1;
278 
279 	switch (i) {
280 	case OPTARG_POWER:
281 	case OPTARG_BALANCE_POWER:
282 	case OPTARG_NORMAL:
283 	case OPTARG_BALANCE_PERFORMANCE:
284 	case OPTARG_PERFORMANCE:
285 		return 0;
286 	}
287 	if (i > HWP_WINDOW_MAX_USEC) {
288 		fprintf(stderr, "--hwp-window: 0 for auto; 1 - %u usec for window duration\n", HWP_WINDOW_MAX_USEC);
289 		usage();
290 	}
291 	for (exponent = 0;; ++exponent) {
292 		if (debug)
293 			printf("%u 10^%d\n", i, exponent);
294 
295 		if (i <= 127)
296 			break;
297 
298 		i = i / 10;
299 	}
300 	if (debug)
301 		fprintf(stderr, "%u*10^%d: 0x%x\n", i, exponent, (exponent << 7) | i);
302 
303 	return (exponent << 7) | i;
304 }
305 
306 int parse_cmdline_hwp_epp(int i)
307 {
308 	update_hwp_epp = 1;
309 
310 	switch (i) {
311 	case OPTARG_POWER:
312 		return HWP_EPP_POWERSAVE;
313 	case OPTARG_BALANCE_POWER:
314 		return HWP_EPP_BALANCE_POWERSAVE;
315 	case OPTARG_NORMAL:
316 	case OPTARG_BALANCE_PERFORMANCE:
317 		return HWP_EPP_BALANCE_PERFORMANCE;
318 	case OPTARG_PERFORMANCE:
319 		return HWP_EPP_PERFORMANCE;
320 	}
321 	if (i < 0 || i > 255) {
322 		fprintf(stderr, "--hwp-epp must be 0 through 255\n");
323 		usage();
324 	}
325 	return i;
326 }
327 
328 int parse_cmdline_turbo(int i)
329 {
330 	update_turbo = 1;
331 
332 	switch (i) {
333 	case OPTARG_POWER:
334 		return 0;
335 	case OPTARG_NORMAL:
336 	case OPTARG_BALANCE_POWER:
337 	case OPTARG_BALANCE_PERFORMANCE:
338 	case OPTARG_PERFORMANCE:
339 		return 1;
340 	}
341 	if (i < 0 || i > 1) {
342 		fprintf(stderr, "--turbo-enable: 1 to enable, 0 to disable\n");
343 		usage();
344 	}
345 	return i;
346 }
347 
348 long parse_optarg_string(const char *s)
349 {
350 	long i;
351 	char *endptr;
352 
353 	if (strcmp(s, "default") == 0)
354 		return OPTARG_NORMAL;
355 
356 	if (strcmp(s, "normal") == 0)
357 		return OPTARG_NORMAL;
358 
359 	if (strcmp(s, "power") == 0)
360 		return OPTARG_POWER;
361 
362 	if (strcmp(s, "balance-power") == 0)
363 		return OPTARG_BALANCE_POWER;
364 
365 	if (strcmp(s, "balance-performance") == 0)
366 		return OPTARG_BALANCE_PERFORMANCE;
367 
368 	if (strcmp(s, "performance") == 0)
369 		return OPTARG_PERFORMANCE;
370 
371 	errno = 0;
372 	i = strtol(s, &endptr, 0);
373 	if (endptr == s || errno == ERANGE || i < 0 || i > 255) {
374 		warnx("bad value \"%s\"", s);
375 		usage();
376 	}
377 
378 	return i;
379 }
380 
381 void parse_cmdline_all(char *s)
382 {
383 	force++;
384 	update_hwp_enable = 1;
385 	req_update.hwp_min = parse_cmdline_hwp_min(parse_optarg_string(s));
386 	req_update.hwp_max = parse_cmdline_hwp_max(parse_optarg_string(s));
387 	req_update.hwp_epp = parse_cmdline_hwp_epp(parse_optarg_string(s));
388 	if (has_epb)
389 		new_epb = parse_cmdline_epb(parse_optarg_string(s));
390 	turbo_update_value = parse_cmdline_turbo(parse_optarg_string(s));
391 	req_update.hwp_desired = parse_cmdline_hwp_desired(parse_optarg_string(s));
392 	req_update.hwp_window = parse_cmdline_hwp_window(parse_optarg_string(s));
393 }
394 
395 void validate_cpu_selected_set(void)
396 {
397 	int cpu;
398 
399 	if (CPU_COUNT_S(cpu_setsize, cpu_selected_set) == 0)
400 		errx(0, "no CPUs requested");
401 
402 	for (cpu = 0; cpu <= max_cpu_num; ++cpu) {
403 		if (CPU_ISSET_S(cpu, cpu_setsize, cpu_selected_set))
404 			if (!CPU_ISSET_S(cpu, cpu_setsize, cpu_present_set))
405 				errx(1, "Requested cpu%d is not present", cpu);
406 	}
407 }
408 
409 void parse_cmdline_cpu(char *s)
410 {
411 	char *startp, *endp;
412 	int cpu = 0;
413 
414 	if (pkg_selected_set) {
415 		usage();
416 		errx(1, "--cpu | --pkg");
417 	}
418 	cpu_selected_set = CPU_ALLOC((max_cpu_num + 1));
419 	if (cpu_selected_set == NULL)
420 		err(1, "cpu_selected_set");
421 	CPU_ZERO_S(cpu_setsize, cpu_selected_set);
422 
423 	for (startp = s; startp && *startp;) {
424 
425 		if (*startp == ',') {
426 			startp++;
427 			continue;
428 		}
429 
430 		if (*startp == '-') {
431 			int end_cpu;
432 
433 			startp++;
434 			errno = 0;
435 			end_cpu = strtol(startp, &endp, 10);
436 			if (startp == endp || errno == ERANGE)
437 				errx(1, "Confused by end_cpu '%s'", startp);
438 
439 			while (cpu <= end_cpu) {
440 				if (cpu > max_cpu_num)
441 					errx(1, "Requested cpu%d exceeds max cpu%d", cpu, max_cpu_num);
442 				CPU_SET_S(cpu, cpu_setsize, cpu_selected_set);
443 				cpu++;
444 			}
445 			startp = endp;
446 			continue;
447 		}
448 
449 		if (strncmp(startp, "all", 3) == 0) {
450 			for (cpu = 0; cpu <= max_cpu_num; cpu += 1) {
451 				if (CPU_ISSET_S(cpu, cpu_setsize, cpu_present_set))
452 					CPU_SET_S(cpu, cpu_setsize, cpu_selected_set);
453 			}
454 			startp += 3;
455 			if (*startp == 0)
456 				break;
457 		}
458 		/* "--cpu even" is not documented */
459 		if (strncmp(startp, "even", 4) == 0) {
460 			for (cpu = 0; cpu <= max_cpu_num; cpu += 2) {
461 				if (CPU_ISSET_S(cpu, cpu_setsize, cpu_present_set))
462 					CPU_SET_S(cpu, cpu_setsize, cpu_selected_set);
463 			}
464 			startp += 4;
465 			if (*startp == 0)
466 				break;
467 		}
468 
469 		/* "--cpu odd" is not documented */
470 		if (strncmp(startp, "odd", 3) == 0) {
471 			for (cpu = 1; cpu <= max_cpu_num; cpu += 2) {
472 				if (CPU_ISSET_S(cpu, cpu_setsize, cpu_present_set))
473 					CPU_SET_S(cpu, cpu_setsize, cpu_selected_set);
474 			}
475 			startp += 3;
476 			if (*startp == 0)
477 				break;
478 		}
479 
480 		errno = 0;
481 		cpu = strtol(startp, &endp, 10);
482 		if (startp == endp || errno == ERANGE || cpu < 0 || cpu > max_cpu_num)
483 			errx(1, "--cpu cpu-set: confused by '%s'", startp);
484 
485 		CPU_SET_S(cpu, cpu_setsize, cpu_selected_set);
486 		startp = endp;
487 	}
488 
489 	validate_cpu_selected_set();
490 
491 }
492 
493 void parse_cmdline_pkg(char *s)
494 {
495 	char *startp, *endp;
496 	int pkg = 0;
497 
498 	if (cpu_selected_set) {
499 		usage();
500 		errx(1, "--pkg | --cpu");
501 	}
502 	pkg_selected_set = 0;
503 
504 	for (startp = s; startp && *startp;) {
505 
506 		if (*startp == ',') {
507 			startp++;
508 			continue;
509 		}
510 
511 		if (*startp == '-') {
512 			int end_pkg;
513 
514 			startp++;
515 			errno = 0;
516 			end_pkg = strtol(startp, &endp, 10);
517 			if (startp == endp || errno == ERANGE)
518 				errx(1, "Confused by end_pkg '%s'", startp);
519 
520 			while (pkg <= end_pkg) {
521 				if (pkg > max_pkg_num)
522 					errx(1, "Requested pkg%d exceeds max pkg%d", pkg, max_pkg_num);
523 				pkg_selected_set |= 1ULL << pkg;
524 				pkg++;
525 			}
526 			startp = endp;
527 			continue;
528 		}
529 
530 		if (strncmp(startp, "all", 3) == 0) {
531 			pkg_selected_set = pkg_present_set;
532 			return;
533 		}
534 
535 		errno = 0;
536 		pkg = strtol(startp, &endp, 10);
537 		if (startp == endp || errno == ERANGE || pkg < 0 || pkg > max_pkg_num)
538 			errx(1, "Confused by pkg '%s'", startp);
539 
540 		pkg_selected_set |= 1ULL << pkg;
541 		startp = endp;
542 	}
543 }
544 
545 void for_packages(unsigned long long pkg_set, int (func) (int))
546 {
547 	int pkg_num;
548 
549 	for (pkg_num = 0; pkg_num <= max_pkg_num && pkg_num < MAX_PACKAGES; ++pkg_num) {
550 		if (pkg_set & (1ULL << pkg_num))
551 			func(pkg_num);
552 	}
553 }
554 
555 static int parse_cmdline_int(const char *s, int *out)
556 {
557 	char *endp;
558 	long val;
559 
560 	errno = 0;
561 	val = strtol(s, &endp, 0);
562 	if (endp == s || errno == ERANGE)
563 		return -1;
564 	if (*endp != '\0')
565 		return -1;
566 	if (val < INT_MIN || val > INT_MAX)
567 		return -1;
568 
569 	*out = (int)val;
570 	return 0;
571 }
572 
573 void print_version(void)
574 {
575 	printf("x86_energy_perf_policy 2026.10.31 Len Brown <lenb@kernel.org>\n");
576 }
577 
578 static int platform_profile_access(int mode)
579 {
580 	if (access(PATH_PLATFORM_PROFILE, mode)) {
581 		if (debug)
582 			fprintf(stderr, "Can not access %s\n", PATH_PLATFORM_PROFILE);
583 		return 0;
584 	}
585 
586 	return 1;
587 }
588 
589 static int platform_profile_name_is(const char *name)
590 {
591 	char buf[64];
592 
593 	if (sysfs_read_string(PATH_PLATFORM_PROFILE_NAME, buf, sizeof(buf)) != 0) {
594 		if (debug)
595 			fprintf(stderr, "Can not read %s\n", PATH_PLATFORM_PROFILE_NAME);
596 		return 0;
597 	}
598 
599 	if (strncmp(buf, name, 16)) {
600 		if (debug)
601 			fprintf(stderr, "%s does not match '%s'\n", PATH_PLATFORM_PROFILE_NAME, name);
602 		return 0;
603 	}
604 
605 	return 1;
606 }
607 
608 static int soc_slider_access(int mode)
609 {
610 	if (!platform_profile_access(R_OK))
611 		return 0;
612 
613 	if (!platform_profile_name_is(POWER_SLIDER_NAME))
614 		return 0;
615 
616 	if (access(PATH_SOC_SLIDER_BALANCE, mode)) {
617 		if (debug)
618 			fprintf(stderr, "Can not access %s\n", PATH_SOC_SLIDER_BALANCE);
619 		return 0;
620 	}
621 
622 	if (access(PATH_SOC_SLIDER_OFFSET, mode)) {
623 		if (debug)
624 			fprintf(stderr, "Can not access %s\n", PATH_SOC_SLIDER_OFFSET);
625 		return 0;
626 	}
627 
628 	return 1;
629 }
630 
631 void cmdline(int argc, char **argv)
632 {
633 	int opt;
634 	int option_index = 0;
635 
636 	static struct option long_options[] = {
637 		{ "all", required_argument, 0, 'a' },
638 		{ "cpu", required_argument, 0, 'c' },
639 		{ "pkg", required_argument, 0, 'p' },
640 		{ "debug", no_argument, 0, 'd' },
641 		{ "hwp-desired", required_argument, 0, 'D' },
642 		{ "epb", required_argument, 0, 'B' },
643 		{ "force", no_argument, 0, 'f' },
644 		{ "hwp-enable", no_argument, 0, 'e' },
645 		{ "help", no_argument, 0, 'h' },
646 		{ "hwp-epp", required_argument, 0, 'P' },
647 		{ "hwp-min", required_argument, 0, 'm' },
648 		{ "hwp-max", required_argument, 0, 'M' },
649 		{ "read", no_argument, 0, 'r' },
650 		{ "turbo-enable", required_argument, 0, 't' },
651 		{ "hwp-use-pkg", required_argument, 0, 'u' },
652 		{ "version", no_argument, 0, 'v' },
653 		{ "hwp-window", required_argument, 0, 'w' },
654 		{ "soc-slider-balance", required_argument, 0, 'S' },
655 		{ "soc-slider-offset", required_argument, 0, 'O' },
656 		{ "platform-profile", required_argument, 0, 'F' },
657 		{ 0, 0, 0, 0 }
658 	};
659 
660 	progname = argv[0];
661 
662 	while ((opt = getopt_long_only(argc, argv, "+a:c:dD:E:e:f:m:M:rt:u:vw::S:O:F:", long_options, &option_index)) != -1) {
663 		switch (opt) {
664 		case 'a':
665 			parse_cmdline_all(optarg);
666 			break;
667 		case 'B':
668 			new_epb = parse_cmdline_epb(parse_optarg_string(optarg));
669 			break;
670 		case 'c':
671 			parse_cmdline_cpu(optarg);
672 			break;
673 		case 'e':
674 			update_hwp_enable = 1;
675 			break;
676 		case 'h':
677 			usage();
678 			break;
679 		case 'd':
680 			debug++;
681 			verbose++;
682 			break;
683 		case 'f':
684 			force++;
685 			break;
686 		case 'D':
687 			req_update.hwp_desired = parse_cmdline_hwp_desired(parse_optarg_string(optarg));
688 			break;
689 		case 'F':
690 			if (strlen(optarg) >= sizeof(platform_profile))
691 				errx(1, "--platform-profile: value too long");
692 			if (!platform_profile_access(W_OK))
693 				errx(1, "Can not update platform-profile in '%s'", PATH_PLATFORM_PROFILE);
694 			snprintf(platform_profile, sizeof(platform_profile), "%s", optarg);
695 			update_platform_profile = 1;
696 			break;
697 		case 'm':
698 			req_update.hwp_min = parse_cmdline_hwp_min(parse_optarg_string(optarg));
699 			break;
700 		case 'M':
701 			req_update.hwp_max = parse_cmdline_hwp_max(parse_optarg_string(optarg));
702 			break;
703 		case 'O':
704 			if (parse_cmdline_int(optarg, &soc_slider_offset))
705 				errx(1, "--soc-slider-offset: invalid value");
706 			if (!soc_slider_access(W_OK))
707 				errx(1, "Unable to write SOC Slider Offset");
708 			update_soc_slider_offset = 1;
709 			break;
710 		case 'p':
711 			parse_cmdline_pkg(optarg);
712 			break;
713 		case 'P':
714 			req_update.hwp_epp = parse_cmdline_hwp_epp(parse_optarg_string(optarg));
715 			break;
716 		case 'r':
717 			/* v1 used -r to specify read-only mode, now the default */
718 			break;
719 		case 'S':
720 			if (parse_cmdline_int(optarg, &soc_slider_balance))
721 				errx(1, "--soc-slider-balance: invalid value");
722 			if (!soc_slider_access(W_OK))
723 				errx(1, "Unable to write SOC Slider-Balance in '%s'", PATH_SOC_SLIDER_BALANCE);
724 			update_soc_slider_balance = 1;
725 			break;
726 		case 't':
727 			turbo_update_value = parse_cmdline_turbo(parse_optarg_string(optarg));
728 			break;
729 		case 'u': {
730 				char *endp;
731 				long val;
732 
733 				update_hwp_use_pkg++;
734 
735 				errno = 0;
736 				val = strtol(optarg, &endp, 10);
737 				if (endp == optarg || errno == ERANGE || val < 0 || val > 1)
738 					errx(1, "--hwp-use-pkg: must be 0 or 1");
739 				req_update.hwp_use_pkg = val;
740 				break;
741 			}
742 		case 'v':
743 			print_version();
744 			exit(0);
745 			break;
746 		case 'w':
747 			req_update.hwp_window = parse_cmdline_hwp_window(parse_optarg_string(optarg));
748 			break;
749 		default:
750 			usage();
751 		}
752 	}
753 	/*
754 	 * v1 allowed "performance"|"normal"|"power" with no policy specifier
755 	 * to update BIAS.  Continue to support that, even though no longer documented.
756 	 */
757 	if (argc == optind + 1)
758 		new_epb = parse_cmdline_epb(parse_optarg_string(argv[optind]));
759 
760 	if (argc > optind + 1) {
761 		fprintf(stderr, "stray parameter '%s'\n", argv[optind + 1]);
762 		usage();
763 	}
764 }
765 
766 /*
767  * Open a file, and exit on failure
768  */
769 FILE *fopen_or_die(const char *path, const char *mode)
770 {
771 	FILE *filep = fopen(path, mode);
772 
773 	if (!filep)
774 		err(1, "%s: open failed", path);
775 	return filep;
776 }
777 
778 void err_on_hypervisor(void)
779 {
780 	FILE *cpuinfo;
781 	char *flags, *hypervisor;
782 	char *buffer;
783 
784 	/* On VMs /proc/cpuinfo contains a "flags" entry for hypervisor */
785 	cpuinfo = fopen_or_die("/proc/cpuinfo", "r");
786 
787 	buffer = calloc(4096, 1);
788 	if (!buffer) {
789 		fclose(cpuinfo);
790 		err(-ENOMEM, "buffer calloc fail");
791 	}
792 
793 	if (!fread(buffer, 1024, 1, cpuinfo)) {
794 		fclose(cpuinfo);
795 		free(buffer);
796 		err(1, "Reading /proc/cpuinfo failed");
797 	}
798 
799 	flags = strstr(buffer, "flags");
800 	if (!flags) {
801 		fclose(cpuinfo);
802 		free(buffer);
803 		err(1, "Failed to find 'flags' in /proc/cpuinfo");
804 	}
805 	rewind(cpuinfo);
806 	if (fseek(cpuinfo, flags - buffer, SEEK_SET) != 0) {
807 		fclose(cpuinfo);
808 		free(buffer);
809 		err(1, "Failed to seek in /proc/cpuinfo");
810 	}
811 	if (!fgets(buffer, 4096, cpuinfo)) {
812 		fclose(cpuinfo);
813 		free(buffer);
814 		err(1, "Reading /proc/cpuinfo failed");
815 	}
816 	fclose(cpuinfo);
817 
818 	hypervisor = strstr(buffer, "hypervisor");
819 	if (hypervisor)
820 		err(-1, "not supported on this virtual machine");
821 
822 	free(buffer);
823 }
824 
825 /*
826  * if (use_android_msr_path)
827  *	msr_path = /dev/msr%d	// Android
828  * else
829  *	msr_path = /dev/cpu/%d/msr	// Linux
830  */
831 static void set_msr_path(int cpu)
832 {
833 	if (snprintf(msr_path, sizeof(msr_path), use_android_msr_path ? "/dev/msr%d" : "/dev/cpu/%d/msr", cpu) >= (int)sizeof(msr_path))
834 		err(-1, "MSR path buffer overflow for cpu%d", cpu);
835 }
836 
837 int get_msr(int cpu, int offset, unsigned long long *msr)
838 {
839 	int retval;
840 	int fd;
841 
842 	set_msr_path(cpu);
843 	fd = open(msr_path, O_RDONLY);
844 	if (fd < 0)
845 		err(-1, "%s open failed, try chown or chmod +r, or run as root", msr_path);
846 
847 	retval = pread(fd, msr, sizeof(*msr), offset);
848 	if (retval != sizeof(*msr)) {
849 		err_on_hypervisor();
850 		err(-1, "%s offset 0x%llx read failed", msr_path, (unsigned long long)offset);
851 	}
852 
853 	if (debug > 1)
854 		fprintf(stderr, "get_msr(cpu%d, 0x%X, 0x%llX)\n", cpu, offset, *msr);
855 
856 	close(fd);
857 	return 0;
858 }
859 
860 int put_msr(int cpu, int offset, unsigned long long new_msr)
861 {
862 	int retval;
863 	int fd;
864 
865 	set_msr_path(cpu);
866 	fd = open(msr_path, O_RDWR);
867 	if (fd < 0)
868 		err(-1, "%s open failed, try chown or chmod +w, or run as root", msr_path);
869 
870 	retval = pwrite(fd, &new_msr, sizeof(new_msr), offset);
871 	if (retval != sizeof(new_msr))
872 		err(-2, "pwrite(cpu%d, offset 0x%x, 0x%llx) = %d", cpu, offset, new_msr, retval);
873 
874 	close(fd);
875 
876 	if (debug > 1)
877 		fprintf(stderr, "put_msr(cpu%d, 0x%X, 0x%llX)\n", cpu, offset, new_msr);
878 
879 	return 0;
880 }
881 
882 static unsigned int read_sysfs(const char *path, char *buf, size_t buflen)
883 {
884 	ssize_t numread;
885 	int fd;
886 
887 	fd = open(path, O_RDONLY);
888 	if (fd == -1)
889 		return 0;
890 
891 	numread = read(fd, buf, buflen - 1);
892 	if (numread < 1) {
893 		close(fd);
894 		return 0;
895 	}
896 
897 	buf[numread] = '\0';
898 	close(fd);
899 
900 	return (unsigned int)numread;
901 }
902 
903 static int write_sysfs(const char *path, char *buf, size_t buflen)
904 {
905 	ssize_t numwritten;
906 	int fd;
907 
908 	fd = open(path, O_WRONLY);
909 	if (fd == -1)
910 		return -1;
911 
912 	numwritten = write(fd, buf, buflen - 1);
913 	if (numwritten < 1) {
914 		buf[strcspn(buf, "\n")] = '\0';
915 		warn("Write '%s' to '%s' failed", buf, path);
916 		close(fd);
917 		return -1;
918 	}
919 
920 	close(fd);
921 
922 	return 0;
923 }
924 
925 static int sysfs_read_string(const char *path, char *buf, size_t buflen)
926 {
927 	unsigned int len;
928 	size_t n;
929 
930 	len = read_sysfs(path, buf, buflen);
931 	if (!len)
932 		return -1;
933 
934 	n = strcspn(buf, "\n");
935 	buf[n] = '\0';
936 	return 0;
937 }
938 
939 static int sysfs_write_string(const char *path, const char *buf)
940 {
941 	char tmp[128];
942 	int len;
943 
944 	len = snprintf(tmp, sizeof(tmp), "%s\n", buf);
945 	if (len < 0 || len >= (int)sizeof(tmp))
946 		return -1;
947 	return write_sysfs(path, tmp, (size_t)len + 1);
948 }
949 
950 void print_hwp_cap(int cpu, struct msr_hwp_cap *cap, char *str)
951 {
952 	if (cpu != -1)
953 		printf("cpu%d: ", cpu);
954 
955 	printf("HWP_CAP: low %d eff %d guar %d high %d\n", cap->lowest, cap->efficient, cap->guaranteed, cap->highest);
956 }
957 
958 void read_hwp_cap(int cpu, struct msr_hwp_cap *cap, unsigned int msr_offset)
959 {
960 	unsigned long long msr;
961 
962 	get_msr(cpu, msr_offset, &msr);
963 
964 	cap->highest = msr_perf_2_ratio(HWP_HIGHEST_PERF(msr));
965 	cap->guaranteed = msr_perf_2_ratio(HWP_GUARANTEED_PERF(msr));
966 	cap->efficient = msr_perf_2_ratio(HWP_MOSTEFFICIENT_PERF(msr));
967 	cap->lowest = msr_perf_2_ratio(HWP_LOWEST_PERF(msr));
968 }
969 
970 void print_hwp_request(int cpu, struct msr_hwp_request *h, const char *str)
971 {
972 	if (cpu != -1)
973 		printf("cpu%d: ", cpu);
974 
975 	if (str)
976 		printf("%s", str);
977 
978 	printf("HWP_REQ: min %d max %d des %d epp %d window 0x%x (%d*10^%dus) use_pkg %d\n",
979 	       h->hwp_min, h->hwp_max, h->hwp_desired, h->hwp_epp, h->hwp_window, h->hwp_window & 0x7F, (h->hwp_window >> 7) & 0x7, h->hwp_use_pkg);
980 }
981 
982 void print_hwp_request_pkg(int pkg, struct msr_hwp_request *h, const char *str)
983 {
984 	printf("pkg%d: ", pkg);
985 
986 	if (str)
987 		printf("%s", str);
988 
989 	printf("HWP_REQ_PKG: min %d max %d des %d epp %d window 0x%x (%d*10^%dus)\n",
990 	       h->hwp_min, h->hwp_max, h->hwp_desired, h->hwp_epp, h->hwp_window, h->hwp_window & 0x7F, (h->hwp_window >> 7) & 0x7);
991 }
992 
993 void read_hwp_request_msr(int cpu, struct msr_hwp_request *hwp_req, unsigned int msr_offset)
994 {
995 	unsigned long long msr;
996 
997 	get_msr(cpu, msr_offset, &msr);
998 
999 	hwp_req->hwp_min = msr_perf_2_ratio((((msr) >> 0) & 0xff));
1000 	hwp_req->hwp_max = msr_perf_2_ratio((((msr) >> 8) & 0xff));
1001 	hwp_req->hwp_desired = msr_perf_2_ratio((((msr) >> 16) & 0xff));
1002 	hwp_req->hwp_epp = (((msr) >> 24) & 0xff);
1003 	hwp_req->hwp_window = (((msr) >> 32) & 0x3ff);
1004 	hwp_req->hwp_use_pkg = (((msr) >> 42) & 0x1);
1005 }
1006 
1007 void write_hwp_request_msr(int cpu, struct msr_hwp_request *hwp_req, unsigned int msr_offset)
1008 {
1009 	unsigned long long msr = 0;
1010 
1011 	if (debug > 1)
1012 		printf("cpu%d: requesting min %d max %d des %d epp %d window 0x%0x use_pkg %d\n",
1013 		       cpu, hwp_req->hwp_min, hwp_req->hwp_max, hwp_req->hwp_desired, hwp_req->hwp_epp, hwp_req->hwp_window, hwp_req->hwp_use_pkg);
1014 
1015 	msr |= HWP_MIN_PERF(ratio_2_msr_perf(hwp_req->hwp_min));
1016 	msr |= HWP_MAX_PERF(ratio_2_msr_perf(hwp_req->hwp_max));
1017 	msr |= HWP_DESIRED_PERF(ratio_2_msr_perf(hwp_req->hwp_desired));
1018 	msr |= HWP_ENERGY_PERF_PREFERENCE(hwp_req->hwp_epp);
1019 	msr |= HWP_ACTIVITY_WINDOW(hwp_req->hwp_window);
1020 	msr |= HWP_PACKAGE_CONTROL(hwp_req->hwp_use_pkg);
1021 
1022 	put_msr(cpu, msr_offset, msr);
1023 }
1024 
1025 static int get_epb_sysfs(int cpu)
1026 {
1027 	char path[SYSFS_PATH_MAX];
1028 	char linebuf[3];
1029 	char *endp;
1030 	long val;
1031 
1032 	if (!has_epb)
1033 		return -1;
1034 
1035 	snprintf(path, sizeof(path), PATH_TO_CPU "cpu%u/power/energy_perf_bias", cpu);
1036 
1037 	if (!read_sysfs(path, linebuf, 3))
1038 		return -1;
1039 
1040 	errno = 0;
1041 	val = strtol(linebuf, &endp, 0);
1042 	if (endp == linebuf || errno == ERANGE || val < 0 || val > 15)
1043 		return -1;
1044 
1045 	return (int)val;
1046 }
1047 
1048 static int set_epb_sysfs(int cpu, int val)
1049 {
1050 	char path[SYSFS_PATH_MAX];
1051 	char linebuf[3];
1052 	char *endp;
1053 
1054 	if (!has_epb)
1055 		return -1;
1056 
1057 	snprintf(path, sizeof(path), PATH_TO_CPU "cpu%u/power/energy_perf_bias", cpu);
1058 	snprintf(linebuf, sizeof(linebuf), "%d", val);
1059 
1060 	if (write_sysfs(path, linebuf, 3))
1061 		return -1;
1062 
1063 	errno = 0;
1064 	val = strtol(linebuf, &endp, 0);
1065 	if (endp == linebuf || errno == ERANGE || val < 0 || val > 15)
1066 		return -1;
1067 
1068 	return (int)val;
1069 }
1070 
1071 static void print_soc_slider(void)
1072 {
1073 	char buf[64];
1074 
1075 	if (!soc_slider_access(R_OK))
1076 		return;
1077 
1078 	if (sysfs_read_string(PATH_SOC_SLIDER_BALANCE, buf, sizeof(buf)) == 0)
1079 		printf("soc-slider-balance: %s\n", buf);
1080 
1081 	if (sysfs_read_string(PATH_SOC_SLIDER_OFFSET, buf, sizeof(buf)) == 0)
1082 		printf("soc-slider-offset: %s\n", buf);
1083 }
1084 
1085 static void print_platform_profile(void)
1086 {
1087 	char buf[64];
1088 
1089 	if (!platform_profile_access(R_OK))
1090 		return;
1091 
1092 	if (sysfs_read_string(PATH_PLATFORM_PROFILE_NAME, buf, sizeof(buf)) == 0)
1093 		printf("platform-profile-name: %s\n", buf);
1094 
1095 	if (sysfs_read_string(PATH_PLATFORM_PROFILE, buf, sizeof(buf)) == 0)
1096 		printf("platform-profile: %s\n", buf);
1097 }
1098 
1099 static int update_soc_slider(void)
1100 {
1101 	char tmp[32];
1102 
1103 	if (update_soc_slider_balance) {
1104 		snprintf(tmp, sizeof(tmp), "%d", soc_slider_balance);
1105 		if (sysfs_write_string(PATH_SOC_SLIDER_BALANCE, tmp))
1106 			err(1, "soc-slider-balance write failed");
1107 	}
1108 
1109 	if (update_soc_slider_offset) {
1110 		snprintf(tmp, sizeof(tmp), "%d", soc_slider_offset);
1111 		if (sysfs_write_string(PATH_SOC_SLIDER_OFFSET, tmp))
1112 			err(1, "soc-slider-offset write failed");
1113 	}
1114 
1115 	if (update_platform_profile) {
1116 		if (sysfs_write_string(PATH_PLATFORM_PROFILE, platform_profile))
1117 			err(1, "platform-profile write failed");
1118 	}
1119 
1120 	return 0;
1121 }
1122 
1123 int print_cpu_msrs(int cpu)
1124 {
1125 	struct msr_hwp_request req;
1126 	struct msr_hwp_cap cap;
1127 	int epb;
1128 
1129 	epb = get_epb_sysfs(cpu);
1130 	if (epb >= 0)
1131 		printf("cpu%d: EPB %u\n", cpu, (unsigned int)epb);
1132 
1133 	if (!has_hwp)
1134 		return 0;
1135 
1136 	read_hwp_request_msr(cpu, &req, MSR_HWP_REQUEST);
1137 	print_hwp_request(cpu, &req, "");
1138 
1139 	read_hwp_cap(cpu, &cap, MSR_HWP_CAPABILITIES);
1140 	print_hwp_cap(cpu, &cap, "");
1141 
1142 	return 0;
1143 }
1144 
1145 int print_pkg_msrs(int pkg)
1146 {
1147 	struct msr_hwp_request req;
1148 	unsigned long long msr;
1149 
1150 	if (!has_hwp)
1151 		return 0;
1152 
1153 	read_hwp_request_msr(first_cpu_in_pkg[pkg], &req, MSR_HWP_REQUEST_PKG);
1154 	print_hwp_request_pkg(pkg, &req, "");
1155 
1156 	if (has_hwp_notify) {
1157 		get_msr(first_cpu_in_pkg[pkg], MSR_HWP_INTERRUPT, &msr);
1158 		fprintf(stderr,
1159 			"pkg%d: MSR_HWP_INTERRUPT: 0x%08llx (Excursion_Min-%sabled, Guaranteed_Perf_Change-%sabled)\n",
1160 			pkg, msr, ((msr) & 0x2) ? "EN" : "Dis", ((msr) & 0x1) ? "EN" : "Dis");
1161 	}
1162 	get_msr(first_cpu_in_pkg[pkg], MSR_HWP_STATUS, &msr);
1163 	fprintf(stderr,
1164 		"pkg%d: MSR_HWP_STATUS: 0x%08llx (%sExcursion_Min, %sGuaranteed_Perf_Change)\n",
1165 		pkg, msr, ((msr) & 0x4) ? "" : "No-", ((msr) & 0x1) ? "" : "No-");
1166 
1167 	return 0;
1168 }
1169 
1170 /*
1171  * Assumption: All HWP systems have 100 MHz bus clock
1172  */
1173 int ratio_2_sysfs_khz(int ratio)
1174 {
1175 	int bclk_khz = BCLK_MHZ * KHZ_PER_MHZ; /* Convert MHz to KHz */
1176 
1177 	return ratio * bclk_khz;
1178 }
1179 
1180 /*
1181  * If HWP is enabled and cpufreq sysfs attribtes are present,
1182  * then update via sysfs. The intel_pstate driver may modify (clip)
1183  * this request, say, when HWP_CAP is outside of PLATFORM_INFO limits,
1184  * and the driver-chosen value takes precidence.
1185  *
1186  * (intel_pstate's max_perf_pct and min_perf_pct will follow cpufreq,
1187  *  so we don't have to touch that.)
1188  */
1189 void update_cpufreq_scaling_freq(int is_max, int cpu, unsigned int ratio)
1190 {
1191 	char pathname[96];
1192 	FILE *fp;
1193 	int retval;
1194 	int khz;
1195 
1196 	snprintf(pathname, sizeof(pathname), "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_%s_freq", cpu, is_max ? "max" : "min");
1197 
1198 	fp = fopen(pathname, "w");
1199 	if (!fp) {
1200 		if (debug)
1201 			perror(pathname);
1202 		return;
1203 	}
1204 
1205 	khz = ratio_2_sysfs_khz(ratio);
1206 	retval = fprintf(fp, "%d", khz);
1207 	if (retval < 0)
1208 		if (debug)
1209 			perror("fprintf");
1210 	if (debug)
1211 		printf("echo %d > %s\n", khz, pathname);
1212 
1213 	fclose(fp);
1214 }
1215 
1216 /*
1217  * We update all sysfs before updating any MSRs because of
1218  * bugs in cpufreq/intel_pstate where the sysfs writes
1219  * for a CPU may change the min/max values on other CPUS.
1220  */
1221 
1222 int update_sysfs(int cpu)
1223 {
1224 	if (!has_hwp)
1225 		return 0;
1226 
1227 	if (!hwp_update_enabled())
1228 		return 0;
1229 
1230 	if (access("/sys/devices/system/cpu/cpu0/cpufreq", F_OK))
1231 		return 0;
1232 
1233 	if (update_hwp_min)
1234 		update_cpufreq_scaling_freq(0, cpu, req_update.hwp_min);
1235 
1236 	if (update_hwp_max)
1237 		update_cpufreq_scaling_freq(1, cpu, req_update.hwp_max);
1238 
1239 	hwp_limits_done_via_sysfs = 1;
1240 
1241 	return 0;
1242 }
1243 
1244 int verify_hwp_req_self_consistency(int cpu, struct msr_hwp_request *req)
1245 {
1246 	/* fail if min > max requested */
1247 	if (req->hwp_min > req->hwp_max) {
1248 		errx(1, "cpu%d: requested hwp-min %d > hwp_max %d", cpu, req->hwp_min, req->hwp_max);
1249 	}
1250 
1251 	/* fail if desired > max requestd */
1252 	if (req->hwp_desired && (req->hwp_desired > req->hwp_max)) {
1253 		errx(1, "cpu%d: requested hwp-desired %d > hwp_max %d", cpu, req->hwp_desired, req->hwp_max);
1254 	}
1255 	/* fail if desired < min requestd */
1256 	if (req->hwp_desired && (req->hwp_desired < req->hwp_min)) {
1257 		errx(1, "cpu%d: requested hwp-desired %d < requested hwp_min %d", cpu, req->hwp_desired, req->hwp_min);
1258 	}
1259 
1260 	return 0;
1261 }
1262 
1263 int check_hwp_request_v_hwp_capabilities(int cpu, struct msr_hwp_request *req, struct msr_hwp_cap *cap)
1264 {
1265 	if (update_hwp_max) {
1266 		if (req->hwp_max > cap->highest)
1267 			errx(1, "cpu%d: requested max %d > capabilities highest %d, use --force?", cpu, req->hwp_max, cap->highest);
1268 		if (req->hwp_max < cap->lowest)
1269 			errx(1, "cpu%d: requested max %d < capabilities lowest %d, use --force?", cpu, req->hwp_max, cap->lowest);
1270 	}
1271 
1272 	if (update_hwp_min) {
1273 		if (req->hwp_min > cap->highest)
1274 			errx(1, "cpu%d: requested min %d > capabilities highest %d, use --force?", cpu, req->hwp_min, cap->highest);
1275 		if (req->hwp_min < cap->lowest)
1276 			errx(1, "cpu%d: requested min %d < capabilities lowest %d, use --force?", cpu, req->hwp_min, cap->lowest);
1277 	}
1278 
1279 	if (update_hwp_min && update_hwp_max && (req->hwp_min > req->hwp_max))
1280 		errx(1, "cpu%d: requested min %d > requested max %d", cpu, req->hwp_min, req->hwp_max);
1281 
1282 	if (update_hwp_desired && req->hwp_desired) {
1283 		if (req->hwp_desired > req->hwp_max)
1284 			errx(1, "cpu%d: requested desired %d > requested max %d, use --force?", cpu, req->hwp_desired, req->hwp_max);
1285 		if (req->hwp_desired < req->hwp_min)
1286 			errx(1, "cpu%d: requested desired %d < requested min %d, use --force?", cpu, req->hwp_desired, req->hwp_min);
1287 		if (req->hwp_desired < cap->lowest)
1288 			errx(1, "cpu%d: requested desired %d < capabilities lowest %d, use --force?", cpu, req->hwp_desired, cap->lowest);
1289 		if (req->hwp_desired > cap->highest)
1290 			errx(1, "cpu%d: requested desired %d > capabilities highest %d, use --force?", cpu, req->hwp_desired, cap->highest);
1291 	}
1292 
1293 	return 0;
1294 }
1295 
1296 int update_hwp_request_msr(int cpu)
1297 {
1298 	struct msr_hwp_request req;
1299 	struct msr_hwp_cap cap;
1300 
1301 	int msr_offset = MSR_HWP_REQUEST;
1302 
1303 	read_hwp_request_msr(cpu, &req, msr_offset);
1304 	if (debug)
1305 		print_hwp_request(cpu, &req, "old: ");
1306 
1307 	if (update_hwp_min && !hwp_limits_done_via_sysfs)
1308 		req.hwp_min = req_update.hwp_min;
1309 
1310 	if (update_hwp_max && !hwp_limits_done_via_sysfs)
1311 		req.hwp_max = req_update.hwp_max;
1312 
1313 	if (update_hwp_desired)
1314 		req.hwp_desired = req_update.hwp_desired;
1315 
1316 	if (update_hwp_window)
1317 		req.hwp_window = req_update.hwp_window;
1318 
1319 	if (update_hwp_epp)
1320 		req.hwp_epp = req_update.hwp_epp;
1321 
1322 	req.hwp_use_pkg = req_update.hwp_use_pkg;
1323 
1324 	read_hwp_cap(cpu, &cap, MSR_HWP_CAPABILITIES);
1325 	if (debug)
1326 		print_hwp_cap(cpu, &cap, "");
1327 
1328 	if (!force)
1329 		check_hwp_request_v_hwp_capabilities(cpu, &req, &cap);
1330 
1331 	verify_hwp_req_self_consistency(cpu, &req);
1332 
1333 	write_hwp_request_msr(cpu, &req, msr_offset);
1334 
1335 	if (debug) {
1336 		read_hwp_request_msr(cpu, &req, msr_offset);
1337 		print_hwp_request(cpu, &req, "new: ");
1338 	}
1339 	return 0;
1340 }
1341 
1342 int update_hwp_request_pkg_msr(int pkg)
1343 {
1344 	struct msr_hwp_request req;
1345 	struct msr_hwp_cap cap;
1346 	int cpu = first_cpu_in_pkg[pkg];
1347 
1348 	int msr_offset = MSR_HWP_REQUEST_PKG;
1349 
1350 	read_hwp_request_msr(cpu, &req, msr_offset);
1351 	if (debug)
1352 		print_hwp_request_pkg(pkg, &req, "old: ");
1353 
1354 	if (update_hwp_min)
1355 		req.hwp_min = req_update.hwp_min;
1356 
1357 	if (update_hwp_max)
1358 		req.hwp_max = req_update.hwp_max;
1359 
1360 	if (update_hwp_desired)
1361 		req.hwp_desired = req_update.hwp_desired;
1362 
1363 	if (update_hwp_window)
1364 		req.hwp_window = req_update.hwp_window;
1365 
1366 	if (update_hwp_epp)
1367 		req.hwp_epp = req_update.hwp_epp;
1368 
1369 	read_hwp_cap(cpu, &cap, MSR_HWP_CAPABILITIES);
1370 	if (debug)
1371 		print_hwp_cap(cpu, &cap, "");
1372 
1373 	if (!force)
1374 		check_hwp_request_v_hwp_capabilities(cpu, &req, &cap);
1375 
1376 	verify_hwp_req_self_consistency(cpu, &req);
1377 
1378 	write_hwp_request_msr(cpu, &req, msr_offset);
1379 
1380 	if (debug) {
1381 		read_hwp_request_msr(cpu, &req, msr_offset);
1382 		print_hwp_request_pkg(pkg, &req, "new: ");
1383 	}
1384 	return 0;
1385 }
1386 
1387 int enable_hwp_on_cpu(int cpu)
1388 {
1389 	unsigned long long old_msr, new_msr;
1390 
1391 	get_msr(cpu, MSR_PM_ENABLE, &old_msr);
1392 
1393 	if (old_msr & 1)
1394 		return 0;	/* already enabled */
1395 
1396 	new_msr = old_msr | 1;
1397 	put_msr(cpu, MSR_PM_ENABLE, new_msr);
1398 
1399 	if (verbose)
1400 		printf("cpu%d: MSR_PM_ENABLE old: %llX new: %llX\n", cpu, old_msr, new_msr);
1401 
1402 	return 0;
1403 }
1404 
1405 int update_cpu_epb_sysfs(int cpu)
1406 {
1407 	int epb;
1408 
1409 	epb = get_epb_sysfs(cpu);
1410 	set_epb_sysfs(cpu, new_epb);
1411 
1412 	if (verbose)
1413 		printf("cpu%d: ENERGY_PERF_BIAS old: %d new: %d\n", cpu, epb, (unsigned int)new_epb);
1414 
1415 	return 0;
1416 }
1417 
1418 int update_cpu_msrs(int cpu)
1419 {
1420 	unsigned long long msr;
1421 
1422 	if (update_turbo) {
1423 		int turbo_is_present_and_disabled;
1424 
1425 		get_msr(cpu, MSR_IA32_MISC_ENABLE, &msr);
1426 
1427 		turbo_is_present_and_disabled = ((msr & MSR_IA32_MISC_ENABLE_TURBO_DISABLE) != 0);
1428 
1429 		if (turbo_update_value == 1) {
1430 			if (turbo_is_present_and_disabled) {
1431 				msr &= ~MSR_IA32_MISC_ENABLE_TURBO_DISABLE;
1432 				put_msr(cpu, MSR_IA32_MISC_ENABLE, msr);
1433 				if (verbose)
1434 					printf("cpu%d: turbo ENABLE\n", cpu);
1435 			}
1436 		} else {
1437 			/*
1438 			 * if "turbo_is_enabled" were known to be describe this cpu
1439 			 * then we could use it here to skip redundant disable requests.
1440 			 * but cpu may be in a different package, so we always write.
1441 			 */
1442 			msr |= MSR_IA32_MISC_ENABLE_TURBO_DISABLE;
1443 			put_msr(cpu, MSR_IA32_MISC_ENABLE, msr);
1444 			if (verbose)
1445 				printf("cpu%d: turbo DISABLE\n", cpu);
1446 		}
1447 	}
1448 
1449 	if (!has_hwp)
1450 		return 0;
1451 
1452 	if (!hwp_update_enabled())
1453 		return 0;
1454 
1455 	update_hwp_request_msr(cpu);
1456 	return 0;
1457 }
1458 
1459 unsigned int get_pkg_num(int cpu)
1460 {
1461 	FILE *fp;
1462 	char pathname[128];
1463 	unsigned int pkg;
1464 	int retval;
1465 
1466 	sprintf(pathname, "/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
1467 
1468 	fp = fopen_or_die(pathname, "r");
1469 	retval = fscanf(fp, "%d\n", &pkg);
1470 	if (retval != 1)
1471 		errx(1, "%s: failed to parse", pathname);
1472 	fclose(fp);
1473 	return pkg;
1474 }
1475 
1476 int set_max_cpu_pkg_num(int cpu)
1477 {
1478 	unsigned int pkg;
1479 
1480 	if (max_cpu_num < cpu)
1481 		max_cpu_num = cpu;
1482 
1483 	pkg = get_pkg_num(cpu);
1484 
1485 	if (pkg >= MAX_PACKAGES)
1486 		errx(1, "cpu%d: %d >= MAX_PACKAGES (%d)", cpu, pkg, MAX_PACKAGES);
1487 
1488 	if (pkg > max_pkg_num)
1489 		max_pkg_num = pkg;
1490 
1491 	if ((pkg_present_set & (1ULL << pkg)) == 0) {
1492 		pkg_present_set |= (1ULL << pkg);
1493 		first_cpu_in_pkg[pkg] = cpu;
1494 	}
1495 
1496 	return 0;
1497 }
1498 
1499 int mark_cpu_present(int cpu)
1500 {
1501 	CPU_SET_S(cpu, cpu_setsize, cpu_present_set);
1502 	return 0;
1503 }
1504 
1505 /*
1506  * run func(cpu) on every cpu in /proc/stat
1507  * return max_cpu number
1508  */
1509 int for_all_proc_cpus(int (func) (int))
1510 {
1511 	FILE *fp;
1512 	int cpu_num;
1513 	int retval;
1514 
1515 	fp = fopen_or_die(proc_stat, "r");
1516 
1517 	retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
1518 	if (retval != 0)
1519 		err(1, "%s: failed to parse format", proc_stat);
1520 
1521 	while (1) {
1522 		retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
1523 		if (retval != 1)
1524 			break;
1525 
1526 		retval = func(cpu_num);
1527 		if (retval) {
1528 			fclose(fp);
1529 			return retval;
1530 		}
1531 	}
1532 	fclose(fp);
1533 	return 0;
1534 }
1535 
1536 void for_all_cpus_in_set(size_t set_size, cpu_set_t *cpu_set, int (func) (int))
1537 {
1538 	int cpu_num;
1539 
1540 	for (cpu_num = 0; cpu_num <= max_cpu_num; ++cpu_num)
1541 		if (CPU_ISSET_S(cpu_num, set_size, cpu_set))
1542 			func(cpu_num);
1543 }
1544 
1545 int for_all_cpus_in_set_and(size_t set_size, cpu_set_t *cpu_set, int (func) (int))
1546 {
1547 	int cpu_num;
1548 	int retval = 1;
1549 
1550 	for (cpu_num = 0; cpu_num <= max_cpu_num; ++cpu_num)
1551 		if (CPU_ISSET_S(cpu_num, set_size, cpu_set))
1552 			retval &= func(cpu_num);
1553 
1554 	return retval;
1555 }
1556 
1557 void init_data_structures(void)
1558 {
1559 	for_all_proc_cpus(set_max_cpu_pkg_num);
1560 
1561 	cpu_setsize = CPU_ALLOC_SIZE((max_cpu_num + 1));
1562 
1563 	cpu_present_set = CPU_ALLOC((max_cpu_num + 1));
1564 	if (cpu_present_set == NULL)
1565 		err(3, "CPU_ALLOC");
1566 	CPU_ZERO_S(cpu_setsize, cpu_present_set);
1567 	for_all_proc_cpus(mark_cpu_present);
1568 }
1569 
1570 int is_hwp_enabled_on_cpu(int cpu_num)
1571 {
1572 	unsigned long long msr;
1573 	int retval;
1574 
1575 	/* MSR_PM_ENABLE[1] == 1 if HWP is enabled and MSRs visible */
1576 	get_msr(cpu_num, MSR_PM_ENABLE, &msr);
1577 	retval = (msr & 1);
1578 
1579 	if (verbose)
1580 		fprintf(stderr, "cpu%d: %sHWP\n", cpu_num, retval ? "" : "No-");
1581 
1582 	return retval;
1583 }
1584 
1585 /*
1586  * verify_hwp_is_enabled()
1587  *
1588  * Set (has_hwp=0) if no HWP feature or any of selected CPU set does not have HWP enabled
1589  */
1590 void verify_hwp_is_enabled(void)
1591 {
1592 	int retval;
1593 
1594 	if (!has_hwp)		/* set in early_cpuid() */
1595 		return;
1596 
1597 	retval = for_all_cpus_in_set_and(cpu_setsize, cpu_selected_set, is_hwp_enabled_on_cpu);
1598 
1599 	if (retval == 0) {
1600 		fprintf(stderr, "HWP can be enabled using '--hwp-enable'\n");
1601 		has_hwp = 0;
1602 	}
1603 }
1604 
1605 int req_update_bounds_check(void)
1606 {
1607 	if (!hwp_update_enabled())
1608 		return 0;
1609 
1610 	/* fail if min > max requested */
1611 	if ((update_hwp_max && update_hwp_min) && (req_update.hwp_min > req_update.hwp_max)) {
1612 		printf("hwp-min %d > hwp_max %d\n", req_update.hwp_min, req_update.hwp_max);
1613 		return -EINVAL;
1614 	}
1615 
1616 	/* fail if desired > max requestd */
1617 	if (req_update.hwp_desired && update_hwp_max && (req_update.hwp_desired > req_update.hwp_max)) {
1618 		printf("hwp-desired cannot be greater than hwp_max\n");
1619 		return -EINVAL;
1620 	}
1621 	/* fail if desired < min requestd */
1622 	if (req_update.hwp_desired && update_hwp_min && (req_update.hwp_desired < req_update.hwp_min)) {
1623 		printf("hwp-desired cannot be less than hwp_min\n");
1624 		return -EINVAL;
1625 	}
1626 
1627 	return 0;
1628 }
1629 
1630 void set_base_cpu(void)
1631 {
1632 	base_cpu = sched_getcpu();
1633 	if (base_cpu < 0)
1634 		err(-ENODEV, "No valid cpus found");
1635 }
1636 
1637 /* return 0 if path exists */
1638 static int check_msr_path(void)
1639 {
1640 	struct stat sb;
1641 
1642 	return stat(msr_path, &sb);
1643 }
1644 
1645 /*
1646  * Check Linux MSR path
1647  * If it fails, try modprobe and check it again
1648  * If still no joy, enable Android path and try again
1649  */
1650 void probe_dev_msr(void)
1651 {
1652 	int retval;
1653 
1654 	use_android_msr_path = 0;
1655 	set_msr_path(base_cpu);
1656 	if (check_msr_path() == 0)
1657 		return;
1658 
1659 	retval = system("/sbin/modprobe msr > /dev/null 2>&1");
1660 
1661 	if (check_msr_path() == 0)
1662 		return;
1663 
1664 	use_android_msr_path = 1;
1665 	set_msr_path(base_cpu);
1666 	if (check_msr_path() == 0)
1667 		return;
1668 
1669 	if (WIFEXITED(retval))
1670 		retval = WEXITSTATUS(retval);
1671 	errx(-1, "\"msr\" driver support required, modprobe msr returned %d", retval);
1672 }
1673 
1674 static void get_cpuid_or_exit(unsigned int leaf, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx)
1675 {
1676 	if (!__get_cpuid(leaf, eax, ebx, ecx, edx))
1677 		errx(1, "Processor not supported\n");
1678 }
1679 
1680 /*
1681  * early_cpuid()
1682  * initialize turbo_is_enabled, has_hwp, has_epb
1683  * before cmdline is parsed
1684  */
1685 void early_cpuid(void)
1686 {
1687 	unsigned int eax, ebx, ecx, edx;
1688 	unsigned int fms, family, model;
1689 
1690 	get_cpuid_or_exit(1, &fms, &ebx, &ecx, &edx);
1691 	family = (fms >> 8) & 0xf;
1692 	model = (fms >> 4) & 0xf;
1693 	if (family == 6 || family == 0xf)
1694 		model += ((fms >> 16) & 0xf) << 4;
1695 
1696 	if (model == 0x4F) {
1697 		unsigned long long msr;
1698 
1699 		get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT, &msr);
1700 
1701 		bdx_highest_ratio = msr & 0xFF;
1702 	}
1703 
1704 	get_cpuid_or_exit(0x6, &eax, &ebx, &ecx, &edx);
1705 	turbo_is_enabled = (eax >> 1) & 1;
1706 	has_hwp = (eax >> 7) & 1;
1707 	has_epb = (ecx >> 3) & 1;
1708 }
1709 
1710 /*
1711  * parse_cpuid()
1712  * set
1713  * has_hwp, has_hwp_notify, has_hwp_activity_window, has_hwp_epp, has_hwp_request_pkg, has_epb
1714  */
1715 void parse_cpuid(void)
1716 {
1717 	unsigned int eax, ebx, ecx, edx, max_level;
1718 	unsigned int fms, family, model, stepping;
1719 
1720 	eax = ebx = ecx = edx = 0;
1721 
1722 	get_cpuid_or_exit(0, &max_level, &ebx, &ecx, &edx);
1723 
1724 	if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
1725 		genuine_intel = 1;
1726 
1727 	if (debug)
1728 		fprintf(stderr, "CPUID(0): %.4s%.4s%.4s ", (char *)&ebx, (char *)&edx, (char *)&ecx);
1729 
1730 	get_cpuid_or_exit(1, &fms, &ebx, &ecx, &edx);
1731 	family = (fms >> 8) & 0xf;
1732 	model = (fms >> 4) & 0xf;
1733 	stepping = fms & 0xf;
1734 	if (family == 6 || family == 0xf)
1735 		model += ((fms >> 16) & 0xf) << 4;
1736 
1737 	if (debug) {
1738 		fprintf(stderr, "%d CPUID levels; family:model:stepping 0x%x:%x:%x (%d:%d:%d)\n", max_level, family, model, stepping, family, model, stepping);
1739 		fprintf(stderr, "CPUID(1): %s %s %s %s %s %s %s %s\n",
1740 			ecx & (1 << 0) ? "SSE3" : "-",
1741 			ecx & (1 << 3) ? "MONITOR" : "-",
1742 			ecx & (1 << 7) ? "EIST" : "-",
1743 			ecx & (1 << 8) ? "TM2" : "-",
1744 			edx & (1 << 4) ? "TSC" : "-", edx & (1 << 5) ? "MSR" : "-", edx & (1 << 22) ? "ACPI-TM" : "-", edx & (1 << 29) ? "TM" : "-");
1745 	}
1746 
1747 	if (!(edx & (1 << 5)))
1748 		errx(1, "CPUID: no MSR");
1749 
1750 	get_cpuid_or_exit(0x6, &eax, &ebx, &ecx, &edx);
1751 	/* turbo_is_enabled already set */
1752 	/* has_hwp already set */
1753 	has_hwp_notify = eax & (1 << 8);
1754 	has_hwp_activity_window = eax & (1 << 9);
1755 	has_hwp_epp = eax & (1 << 10);
1756 	has_hwp_request_pkg = eax & (1 << 11);
1757 
1758 	if (!has_hwp_request_pkg && update_hwp_use_pkg)
1759 		errx(1, "--hwp-use-pkg is not available on this hardware");
1760 
1761 	/* has_epb already set */
1762 
1763 	if (debug)
1764 		fprintf(stderr,
1765 			"CPUID(6): %sTURBO, %sHWP, %sHWPnotify, %sHWPwindow, %sHWPepp, %sHWPpkg, %sEPB\n",
1766 			turbo_is_enabled ? "" : "No-",
1767 			has_hwp ? "" : "No-",
1768 			has_hwp_notify ? "" : "No-",
1769 			has_hwp_activity_window ? "" : "No-", has_hwp_epp ? "" : "No-", has_hwp_request_pkg ? "" : "No-", has_epb ? "" : "No-");
1770 
1771 	return;			/* success */
1772 }
1773 
1774 int main(int argc, char **argv)
1775 {
1776 	set_base_cpu();
1777 
1778 	probe_dev_msr();
1779 	init_data_structures();
1780 
1781 	early_cpuid();		/* initial cpuid parse before cmdline */
1782 
1783 	cmdline(argc, argv);
1784 
1785 	if (debug)
1786 		print_version();
1787 
1788 	parse_cpuid();
1789 
1790 	/* If CPU-set and PKG-set are not initialized, default to all CPUs */
1791 	if ((cpu_selected_set == 0) && (pkg_selected_set == 0))
1792 		cpu_selected_set = cpu_present_set;
1793 
1794 	/*
1795 	 * If HWP is being enabled, do it now, so that subsequent operations
1796 	 * that access HWP registers can work.
1797 	 */
1798 	if (update_hwp_enable)
1799 		for_all_cpus_in_set(cpu_setsize, cpu_selected_set, enable_hwp_on_cpu);
1800 
1801 	/* If HWP present, but disabled, warn and ignore from here forward */
1802 	verify_hwp_is_enabled();
1803 
1804 	if (req_update_bounds_check())
1805 		return -EINVAL;
1806 
1807 	/* display information only, no updates to settings */
1808 	if (!update_epb && !update_turbo && !hwp_update_enabled() && !update_soc_slider_balance && !update_soc_slider_offset && !update_platform_profile) {
1809 		if (cpu_selected_set)
1810 			for_all_cpus_in_set(cpu_setsize, cpu_selected_set, print_cpu_msrs);
1811 
1812 		print_soc_slider();
1813 		print_platform_profile();
1814 
1815 		if (has_hwp_request_pkg) {
1816 			if (pkg_selected_set == 0)
1817 				pkg_selected_set = pkg_present_set;
1818 
1819 			for_packages(pkg_selected_set, print_pkg_msrs);
1820 		}
1821 
1822 		return 0;
1823 	}
1824 
1825 	/* update CPU set */
1826 	if (cpu_selected_set) {
1827 		if (update_epb)
1828 			for_all_cpus_in_set(cpu_setsize, cpu_selected_set, update_cpu_epb_sysfs);
1829 		for_all_cpus_in_set(cpu_setsize, cpu_selected_set, update_sysfs);
1830 		for_all_cpus_in_set(cpu_setsize, cpu_selected_set, update_cpu_msrs);
1831 
1832 	} else if (pkg_selected_set)
1833 		for_packages(pkg_selected_set, update_hwp_request_pkg_msr);
1834 
1835 	if (update_soc_slider_balance || update_soc_slider_offset || update_platform_profile)
1836 		update_soc_slider();
1837 
1838 	return 0;
1839 }
1840