1 /* 2 * Privileged RAPL MSR helper commands for QEMU 3 * 4 * Copyright (C) 2024 Red Hat, Inc. <aharivel@redhat.com> 5 * 6 * Author: Anthony Harivel <aharivel@redhat.com> 7 * 8 * This program is free software; you can redistribute it and/or modify 9 * it under the terms of the GNU General Public License as published by 10 * the Free Software Foundation; under version 2 of the License. 11 * 12 * This program is distributed in the hope that it will be useful, 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 * GNU General Public License for more details. 16 * 17 * You should have received a copy of the GNU General Public License 18 * along with this program; if not, see <http://www.gnu.org/licenses/>. 19 */ 20 21 #include "qemu/osdep.h" 22 #include <getopt.h> 23 #include <stdbool.h> 24 #include <sys/ioctl.h> 25 #ifdef CONFIG_LIBCAP_NG 26 #include <cap-ng.h> 27 #endif 28 #include <pwd.h> 29 #include <grp.h> 30 31 #include "qemu/help-texts.h" 32 #include "qapi/error.h" 33 #include "qemu/cutils.h" 34 #include "qemu/main-loop.h" 35 #include "qemu/module.h" 36 #include "qemu/error-report.h" 37 #include "qemu/config-file.h" 38 #include "qemu-version.h" 39 #include "qapi/error.h" 40 #include "qemu/error-report.h" 41 #include "qemu/log.h" 42 #include "qemu/systemd.h" 43 #include "io/channel.h" 44 #include "io/channel-socket.h" 45 #include "trace/control.h" 46 #include "qemu-version.h" 47 #include "rapl-msr-index.h" 48 49 #define MSR_PATH_TEMPLATE "/dev/cpu/%u/msr" 50 51 static char *socket_path; 52 static char *pidfile; 53 static enum { RUNNING, TERMINATE, TERMINATING } state; 54 static QIOChannelSocket *server_ioc; 55 static int server_watch; 56 static int num_active_sockets = 1; 57 58 #ifdef CONFIG_LIBCAP_NG 59 static int uid = -1; 60 static int gid = -1; 61 #endif 62 63 static void compute_default_paths(void) 64 { 65 g_autofree char *state = qemu_get_local_state_dir(); 66 67 socket_path = g_build_filename(state, "run", "qemu-vmsr-helper.sock", NULL); 68 pidfile = g_build_filename(state, "run", "qemu-vmsr-helper.pid", NULL); 69 } 70 71 static int is_intel_processor(void) 72 { 73 int result; 74 int ebx, ecx, edx; 75 76 /* Execute CPUID instruction with eax=0 (basic identification) */ 77 asm volatile ( 78 "cpuid" 79 : "=b" (ebx), "=c" (ecx), "=d" (edx) 80 : "a" (0) 81 ); 82 83 /* 84 * Check if processor is "GenuineIntel" 85 * 0x756e6547 = "Genu" 86 * 0x49656e69 = "ineI" 87 * 0x6c65746e = "ntel" 88 */ 89 result = (ebx == 0x756e6547) && (edx == 0x49656e69) && (ecx == 0x6c65746e); 90 91 return result; 92 } 93 94 static int is_rapl_enabled(void) 95 { 96 const char *path = "/sys/class/powercap/intel-rapl/enabled"; 97 FILE *file = fopen(path, "r"); 98 int value = 0; 99 100 if (file != NULL) { 101 if (fscanf(file, "%d", &value) != 1) { 102 error_report("INTEL RAPL not enabled"); 103 } 104 fclose(file); 105 } else { 106 error_report("Error opening %s", path); 107 } 108 109 return value; 110 } 111 112 /* 113 * Check if the TID that request the MSR read 114 * belongs to the peer. It be should a TID of a vCPU. 115 */ 116 static bool is_tid_present(pid_t pid, pid_t tid) 117 { 118 g_autofree char *tidPath = g_strdup_printf("/proc/%d/task/%d", pid, tid); 119 120 /* Check if the TID directory exists within the PID directory */ 121 if (access(tidPath, F_OK) == 0) { 122 return true; 123 } 124 125 error_report("Failed to open /proc at %s", tidPath); 126 return false; 127 } 128 129 /* 130 * Only the RAPL MSR in target/i386/cpu.h are allowed 131 */ 132 static bool is_msr_allowed(uint32_t reg) 133 { 134 switch (reg) { 135 case MSR_RAPL_POWER_UNIT: 136 case MSR_PKG_POWER_LIMIT: 137 case MSR_PKG_ENERGY_STATUS: 138 case MSR_PKG_POWER_INFO: 139 return true; 140 default: 141 return false; 142 } 143 } 144 145 static uint64_t vmsr_read_msr(uint32_t msr_register, unsigned int cpu_id) 146 { 147 int fd; 148 uint64_t result = 0; 149 150 g_autofree char *path = g_strdup_printf(MSR_PATH_TEMPLATE, cpu_id); 151 152 fd = open(path, O_RDONLY); 153 if (fd < 0) { 154 error_report("Failed to open MSR file at %s", path); 155 return result; 156 } 157 158 if (pread(fd, &result, sizeof(result), msr_register) != sizeof(result)) { 159 error_report("Failed to read MSR"); 160 result = 0; 161 } 162 163 close(fd); 164 return result; 165 } 166 167 static void usage(const char *name) 168 { 169 (printf) ( 170 "Usage: %s [OPTIONS] FILE\n" 171 "Virtual RAPL MSR helper program for QEMU\n" 172 "\n" 173 " -h, --help display this help and exit\n" 174 " -V, --version output version information and exit\n" 175 "\n" 176 " -d, --daemon run in the background\n" 177 " -f, --pidfile=PATH PID file when running as a daemon\n" 178 " (default '%s')\n" 179 " -k, --socket=PATH path to the unix socket\n" 180 " (default '%s')\n" 181 " -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n" 182 " specify tracing options\n" 183 #ifdef CONFIG_LIBCAP_NG 184 " -u, --user=USER user to drop privileges to\n" 185 " -g, --group=GROUP group to drop privileges to\n" 186 #endif 187 "\n" 188 QEMU_HELP_BOTTOM "\n" 189 , name, pidfile, socket_path); 190 } 191 192 static void version(const char *name) 193 { 194 printf( 195 "%s " QEMU_FULL_VERSION "\n" 196 "Written by Anthony Harivel.\n" 197 "\n" 198 QEMU_COPYRIGHT "\n" 199 "This is free software; see the source for copying conditions. There is NO\n" 200 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n" 201 , name); 202 } 203 204 typedef struct VMSRHelperClient { 205 QIOChannelSocket *ioc; 206 Coroutine *co; 207 } VMSRHelperClient; 208 209 static void coroutine_fn vh_co_entry(void *opaque) 210 { 211 VMSRHelperClient *client = opaque; 212 Error *local_err = NULL; 213 unsigned int peer_pid; 214 uint32_t request[3]; 215 uint64_t vmsr; 216 int r; 217 218 qio_channel_set_blocking(QIO_CHANNEL(client->ioc), 219 false, NULL); 220 221 qio_channel_set_follow_coroutine_ctx(QIO_CHANNEL(client->ioc), true); 222 223 /* 224 * Check peer credentials 225 */ 226 r = qio_channel_get_peerpid(QIO_CHANNEL(client->ioc), 227 &peer_pid, 228 &local_err); 229 if (r < 0) { 230 goto out; 231 } 232 233 for (;;) { 234 /* 235 * Read the requested MSR 236 * Only RAPL MSR in rapl-msr-index.h is allowed 237 */ 238 r = qio_channel_read_all_eof(QIO_CHANNEL(client->ioc), 239 (char *) &request, sizeof(request), &local_err); 240 if (r <= 0) { 241 break; 242 } 243 244 if (!is_msr_allowed(request[0])) { 245 error_report("Requested unallowed msr: %d", request[0]); 246 break; 247 } 248 249 vmsr = vmsr_read_msr(request[0], request[1]); 250 251 if (!is_tid_present(peer_pid, request[2])) { 252 error_report("Requested TID not in peer PID: %d %d", 253 peer_pid, request[2]); 254 vmsr = 0; 255 } 256 257 r = qio_channel_write_all(QIO_CHANNEL(client->ioc), 258 (char *) &vmsr, 259 sizeof(vmsr), 260 &local_err); 261 if (r < 0) { 262 break; 263 } 264 } 265 266 out: 267 if (local_err) { 268 error_report_err(local_err); 269 } 270 271 object_unref(OBJECT(client->ioc)); 272 g_free(client); 273 } 274 275 static gboolean accept_client(QIOChannel *ioc, 276 GIOCondition cond, 277 gpointer opaque) 278 { 279 QIOChannelSocket *cioc; 280 VMSRHelperClient *vmsrh; 281 282 cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc), 283 NULL); 284 if (!cioc) { 285 return TRUE; 286 } 287 288 vmsrh = g_new(VMSRHelperClient, 1); 289 vmsrh->ioc = cioc; 290 vmsrh->co = qemu_coroutine_create(vh_co_entry, vmsrh); 291 qemu_coroutine_enter(vmsrh->co); 292 293 return TRUE; 294 } 295 296 static void termsig_handler(int signum) 297 { 298 qatomic_cmpxchg(&state, RUNNING, TERMINATE); 299 qemu_notify_event(); 300 } 301 302 static void close_server_socket(void) 303 { 304 assert(server_ioc); 305 306 g_source_remove(server_watch); 307 server_watch = -1; 308 object_unref(OBJECT(server_ioc)); 309 num_active_sockets--; 310 } 311 312 #ifdef CONFIG_LIBCAP_NG 313 static int drop_privileges(void) 314 { 315 /* clear all capabilities */ 316 capng_clear(CAPNG_SELECT_BOTH); 317 318 if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED, 319 CAP_SYS_RAWIO) < 0) { 320 return -1; 321 } 322 323 return 0; 324 } 325 #endif 326 327 int main(int argc, char **argv) 328 { 329 const char *sopt = "hVk:f:dT:u:g:vq"; 330 struct option lopt[] = { 331 { "help", no_argument, NULL, 'h' }, 332 { "version", no_argument, NULL, 'V' }, 333 { "socket", required_argument, NULL, 'k' }, 334 { "pidfile", required_argument, NULL, 'f' }, 335 { "daemon", no_argument, NULL, 'd' }, 336 { "trace", required_argument, NULL, 'T' }, 337 { "verbose", no_argument, NULL, 'v' }, 338 { NULL, 0, NULL, 0 } 339 }; 340 int opt_ind = 0; 341 int ch; 342 Error *local_err = NULL; 343 bool daemonize = false; 344 bool pidfile_specified = false; 345 bool socket_path_specified = false; 346 unsigned socket_activation; 347 348 struct sigaction sa_sigterm; 349 memset(&sa_sigterm, 0, sizeof(sa_sigterm)); 350 sa_sigterm.sa_handler = termsig_handler; 351 sigaction(SIGTERM, &sa_sigterm, NULL); 352 sigaction(SIGINT, &sa_sigterm, NULL); 353 sigaction(SIGHUP, &sa_sigterm, NULL); 354 355 signal(SIGPIPE, SIG_IGN); 356 357 error_init(argv[0]); 358 module_call_init(MODULE_INIT_TRACE); 359 module_call_init(MODULE_INIT_QOM); 360 qemu_add_opts(&qemu_trace_opts); 361 qemu_init_exec_dir(argv[0]); 362 363 compute_default_paths(); 364 365 /* 366 * Sanity check 367 * 1. cpu must be Intel cpu 368 * 2. RAPL must be enabled 369 */ 370 if (!is_intel_processor()) { 371 error_report("error: CPU is not INTEL cpu"); 372 exit(EXIT_FAILURE); 373 } 374 375 if (!is_rapl_enabled()) { 376 error_report("error: RAPL driver not enable"); 377 exit(EXIT_FAILURE); 378 } 379 380 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) { 381 switch (ch) { 382 case 'k': 383 g_free(socket_path); 384 socket_path = g_strdup(optarg); 385 socket_path_specified = true; 386 if (socket_path[0] != '/') { 387 error_report("socket path must be absolute"); 388 exit(EXIT_FAILURE); 389 } 390 break; 391 case 'f': 392 g_free(pidfile); 393 pidfile = g_strdup(optarg); 394 pidfile_specified = true; 395 break; 396 #ifdef CONFIG_LIBCAP_NG 397 case 'u': { 398 unsigned long res; 399 struct passwd *userinfo = getpwnam(optarg); 400 if (userinfo) { 401 uid = userinfo->pw_uid; 402 } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 && 403 (uid_t)res == res) { 404 uid = res; 405 } else { 406 error_report("invalid user '%s'", optarg); 407 exit(EXIT_FAILURE); 408 } 409 break; 410 } 411 case 'g': { 412 unsigned long res; 413 struct group *groupinfo = getgrnam(optarg); 414 if (groupinfo) { 415 gid = groupinfo->gr_gid; 416 } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 && 417 (gid_t)res == res) { 418 gid = res; 419 } else { 420 error_report("invalid group '%s'", optarg); 421 exit(EXIT_FAILURE); 422 } 423 break; 424 } 425 #else 426 case 'u': 427 case 'g': 428 error_report("-%c not supported by this %s", ch, argv[0]); 429 exit(1); 430 #endif 431 case 'd': 432 daemonize = true; 433 break; 434 case 'T': 435 trace_opt_parse(optarg); 436 break; 437 case 'V': 438 version(argv[0]); 439 exit(EXIT_SUCCESS); 440 break; 441 case 'h': 442 usage(argv[0]); 443 exit(EXIT_SUCCESS); 444 break; 445 case '?': 446 error_report("Try `%s --help' for more information.", argv[0]); 447 exit(EXIT_FAILURE); 448 } 449 } 450 451 if (!trace_init_backends()) { 452 exit(EXIT_FAILURE); 453 } 454 trace_init_file(); 455 qemu_set_log(LOG_TRACE, &error_fatal); 456 457 socket_activation = check_socket_activation(); 458 if (socket_activation == 0) { 459 SocketAddress saddr; 460 saddr = (SocketAddress){ 461 .type = SOCKET_ADDRESS_TYPE_UNIX, 462 .u.q_unix.path = socket_path, 463 }; 464 server_ioc = qio_channel_socket_new(); 465 if (qio_channel_socket_listen_sync(server_ioc, &saddr, 466 1, &local_err) < 0) { 467 object_unref(OBJECT(server_ioc)); 468 error_report_err(local_err); 469 return 1; 470 } 471 } else { 472 /* Using socket activation - check user didn't use -p etc. */ 473 if (socket_path_specified) { 474 error_report("Unix socket can't be set when" 475 "using socket activation"); 476 exit(EXIT_FAILURE); 477 } 478 479 /* Can only listen on a single socket. */ 480 if (socket_activation > 1) { 481 error_report("%s does not support socket activation" 482 "with LISTEN_FDS > 1", 483 argv[0]); 484 exit(EXIT_FAILURE); 485 } 486 server_ioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD, 487 &local_err); 488 if (server_ioc == NULL) { 489 error_reportf_err(local_err, 490 "Failed to use socket activation: "); 491 exit(EXIT_FAILURE); 492 } 493 } 494 495 qemu_init_main_loop(&error_fatal); 496 497 server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc), 498 G_IO_IN, 499 accept_client, 500 NULL, NULL); 501 502 if (daemonize) { 503 if (daemon(0, 0) < 0) { 504 error_report("Failed to daemonize: %s", strerror(errno)); 505 exit(EXIT_FAILURE); 506 } 507 } 508 509 if (daemonize || pidfile_specified) { 510 qemu_write_pidfile(pidfile, &error_fatal); 511 } 512 513 #ifdef CONFIG_LIBCAP_NG 514 if (drop_privileges() < 0) { 515 error_report("Failed to drop privileges: %s", strerror(errno)); 516 exit(EXIT_FAILURE); 517 } 518 #endif 519 520 info_report("Listening on %s", socket_path); 521 522 state = RUNNING; 523 do { 524 main_loop_wait(false); 525 if (state == TERMINATE) { 526 state = TERMINATING; 527 close_server_socket(); 528 } 529 } while (num_active_sockets > 0); 530 531 exit(EXIT_SUCCESS); 532 } 533