xref: /openbmc/qemu/tools/i386/qemu-vmsr-helper.c (revision caf2e8de4ed056acad4fbdb6fe420d8124d38f11)
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 static bool verbose;
58 
59 #ifdef CONFIG_LIBCAP_NG
60 static int uid = -1;
61 static int gid = -1;
62 #endif
63 
64 static void compute_default_paths(void)
65 {
66     g_autofree char *state = qemu_get_local_state_dir();
67 
68     socket_path = g_build_filename(state, "run", "qemu-vmsr-helper.sock", NULL);
69     pidfile = g_build_filename(state, "run", "qemu-vmsr-helper.pid", NULL);
70 }
71 
72 static int is_intel_processor(void)
73 {
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     return (ebx == 0x756e6547) && (edx == 0x49656e69) && (ecx == 0x6c65746e);
90 }
91 
92 static int is_rapl_enabled(void)
93 {
94     const char *path = "/sys/class/powercap/intel-rapl/enabled";
95     FILE *file = fopen(path, "r");
96     int value = 0;
97 
98     if (file != NULL) {
99         if (fscanf(file, "%d", &value) != 1) {
100             error_report("INTEL RAPL not enabled");
101         }
102         fclose(file);
103     } else {
104         error_report("Error opening %s", path);
105     }
106 
107     return value;
108 }
109 
110 /*
111  * Check if the TID that request the MSR read
112  * belongs to the peer. It be should a TID of a vCPU.
113  */
114 static bool is_tid_present(pid_t pid, pid_t tid)
115 {
116     g_autofree char *tidPath = g_strdup_printf("/proc/%d/task/%d", pid, tid);
117 
118     /* Check if the TID directory exists within the PID directory */
119     if (access(tidPath, F_OK) == 0) {
120         return true;
121     }
122 
123     error_report("Failed to open /proc at %s", tidPath);
124     return false;
125 }
126 
127 /*
128  * Only the RAPL MSR in target/i386/cpu.h are allowed
129  */
130 static bool is_msr_allowed(uint32_t reg)
131 {
132     switch (reg) {
133     case MSR_RAPL_POWER_UNIT:
134     case MSR_PKG_POWER_LIMIT:
135     case MSR_PKG_ENERGY_STATUS:
136     case MSR_PKG_POWER_INFO:
137         return true;
138     default:
139         return false;
140     }
141 }
142 
143 static uint64_t vmsr_read_msr(uint32_t msr_register, unsigned int cpu_id)
144 {
145     int fd;
146     uint64_t result = 0;
147 
148     g_autofree char *path = g_strdup_printf(MSR_PATH_TEMPLATE, cpu_id);
149 
150     fd = open(path, O_RDONLY);
151     if (fd < 0) {
152         error_report("Failed to open MSR file at %s", path);
153         return result;
154     }
155 
156     if (pread(fd, &result, sizeof(result), msr_register) != sizeof(result)) {
157         error_report("Failed to read MSR");
158         result = 0;
159     }
160 
161     close(fd);
162     return result;
163 }
164 
165 static void usage(const char *name)
166 {
167     (printf) (
168 "Usage: %s [OPTIONS] FILE\n"
169 "Virtual RAPL MSR helper program for QEMU\n"
170 "\n"
171 "  -h, --help                display this help and exit\n"
172 "  -V, --version             output version information and exit\n"
173 "\n"
174 "  -d, --daemon              run in the background\n"
175 "  -f, --pidfile=PATH        PID file when running as a daemon\n"
176 "                            (default '%s')\n"
177 "  -k, --socket=PATH         path to the unix socket\n"
178 "                            (default '%s')\n"
179 "  -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
180 "                            specify tracing options\n"
181 #ifdef CONFIG_LIBCAP_NG
182 "  -u, --user=USER           user to drop privileges to\n"
183 "  -g, --group=GROUP         group to drop privileges to\n"
184 #endif
185 "\n"
186 QEMU_HELP_BOTTOM "\n"
187     , name, pidfile, socket_path);
188 }
189 
190 static void version(const char *name)
191 {
192     printf(
193 "%s " QEMU_FULL_VERSION "\n"
194 "Written by Anthony Harivel.\n"
195 "\n"
196 QEMU_COPYRIGHT "\n"
197 "This is free software; see the source for copying conditions.  There is NO\n"
198 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
199     , name);
200 }
201 
202 typedef struct VMSRHelperClient {
203     QIOChannelSocket *ioc;
204     Coroutine *co;
205 } VMSRHelperClient;
206 
207 static void coroutine_fn vh_co_entry(void *opaque)
208 {
209     VMSRHelperClient *client = opaque;
210     Error *local_err = NULL;
211     unsigned int peer_pid;
212     uint32_t request[3];
213     uint64_t vmsr;
214     int r;
215 
216     if (!qio_channel_set_blocking(QIO_CHANNEL(client->ioc),
217                                   false, &local_err)) {
218         goto out;
219     }
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         if (!verbose) {
269             error_free(local_err);
270         } else {
271             error_report_err(local_err);
272         }
273     }
274 
275     object_unref(OBJECT(client->ioc));
276     g_free(client);
277 }
278 
279 static gboolean accept_client(QIOChannel *ioc,
280                               GIOCondition cond,
281                               gpointer opaque)
282 {
283     QIOChannelSocket *cioc;
284     VMSRHelperClient *vmsrh;
285 
286     cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
287                                      NULL);
288     if (!cioc) {
289         return TRUE;
290     }
291 
292     vmsrh = g_new(VMSRHelperClient, 1);
293     vmsrh->ioc = cioc;
294     vmsrh->co = qemu_coroutine_create(vh_co_entry, vmsrh);
295     qemu_coroutine_enter(vmsrh->co);
296 
297     return TRUE;
298 }
299 
300 static void termsig_handler(int signum)
301 {
302     qatomic_cmpxchg(&state, RUNNING, TERMINATE);
303     qemu_notify_event();
304 }
305 
306 static void close_server_socket(void)
307 {
308     assert(server_ioc);
309 
310     g_source_remove(server_watch);
311     server_watch = -1;
312     object_unref(OBJECT(server_ioc));
313     num_active_sockets--;
314 }
315 
316 #ifdef CONFIG_LIBCAP_NG
317 static int drop_privileges(void)
318 {
319     /* clear all capabilities */
320     capng_clear(CAPNG_SELECT_BOTH);
321 
322     if (capng_update(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
323                      CAP_SYS_RAWIO) < 0) {
324         return -1;
325     }
326 
327     return 0;
328 }
329 #endif
330 
331 int main(int argc, char **argv)
332 {
333     const char *sopt = "hVk:f:dT:u:g:vq";
334     struct option lopt[] = {
335         { "help", no_argument, NULL, 'h' },
336         { "version", no_argument, NULL, 'V' },
337         { "socket", required_argument, NULL, 'k' },
338         { "pidfile", required_argument, NULL, 'f' },
339         { "daemon", no_argument, NULL, 'd' },
340         { "trace", required_argument, NULL, 'T' },
341         { "verbose", no_argument, NULL, 'v' },
342         { NULL, 0, NULL, 0 }
343     };
344     int opt_ind = 0;
345     int ch;
346     Error *local_err = NULL;
347     bool daemonize = false;
348     bool pidfile_specified = false;
349     bool socket_path_specified = false;
350     unsigned socket_activation;
351 
352     struct sigaction sa_sigterm;
353     memset(&sa_sigterm, 0, sizeof(sa_sigterm));
354     sa_sigterm.sa_handler = termsig_handler;
355     sigaction(SIGTERM, &sa_sigterm, NULL);
356     sigaction(SIGINT, &sa_sigterm, NULL);
357     sigaction(SIGHUP, &sa_sigterm, NULL);
358 
359     signal(SIGPIPE, SIG_IGN);
360 
361     error_init(argv[0]);
362     module_call_init(MODULE_INIT_TRACE);
363     module_call_init(MODULE_INIT_QOM);
364     qemu_add_opts(&qemu_trace_opts);
365     qemu_init_exec_dir(argv[0]);
366 
367     compute_default_paths();
368 
369     /*
370      * Sanity check
371      * 1. cpu must be Intel cpu
372      * 2. RAPL must be enabled
373      */
374     if (!is_intel_processor()) {
375         error_report("error: CPU is not INTEL cpu");
376         exit(EXIT_FAILURE);
377     }
378 
379     if (!is_rapl_enabled()) {
380         error_report("error: RAPL driver not enable");
381         exit(EXIT_FAILURE);
382     }
383 
384     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
385         switch (ch) {
386         case 'k':
387             g_free(socket_path);
388             socket_path = g_strdup(optarg);
389             socket_path_specified = true;
390             if (socket_path[0] != '/') {
391                 error_report("socket path must be absolute");
392                 exit(EXIT_FAILURE);
393             }
394             break;
395         case 'f':
396             g_free(pidfile);
397             pidfile = g_strdup(optarg);
398             pidfile_specified = true;
399             break;
400 #ifdef CONFIG_LIBCAP_NG
401         case 'u': {
402             unsigned long res;
403             struct passwd *userinfo = getpwnam(optarg);
404             if (userinfo) {
405                 uid = userinfo->pw_uid;
406             } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
407                        (uid_t)res == res) {
408                 uid = res;
409             } else {
410                 error_report("invalid user '%s'", optarg);
411                 exit(EXIT_FAILURE);
412             }
413             break;
414         }
415         case 'g': {
416             unsigned long res;
417             struct group *groupinfo = getgrnam(optarg);
418             if (groupinfo) {
419                 gid = groupinfo->gr_gid;
420             } else if (qemu_strtoul(optarg, NULL, 10, &res) == 0 &&
421                        (gid_t)res == res) {
422                 gid = res;
423             } else {
424                 error_report("invalid group '%s'", optarg);
425                 exit(EXIT_FAILURE);
426             }
427             break;
428         }
429 #else
430         case 'u':
431         case 'g':
432             error_report("-%c not supported by this %s", ch, argv[0]);
433             exit(1);
434 #endif
435         case 'd':
436             daemonize = true;
437             break;
438         case 'v':
439             verbose = true;
440             break;
441         case 'T':
442             trace_opt_parse(optarg);
443             break;
444         case 'V':
445             version(argv[0]);
446             exit(EXIT_SUCCESS);
447             break;
448         case 'h':
449             usage(argv[0]);
450             exit(EXIT_SUCCESS);
451             break;
452         case '?':
453             error_report("Try `%s --help' for more information.", argv[0]);
454             exit(EXIT_FAILURE);
455         }
456     }
457 
458     if (!trace_init_backends()) {
459         exit(EXIT_FAILURE);
460     }
461     trace_init_file();
462     qemu_set_log(LOG_TRACE, &error_fatal);
463 
464     socket_activation = check_socket_activation();
465     if (socket_activation == 0) {
466         SocketAddress saddr;
467         saddr = (SocketAddress){
468             .type = SOCKET_ADDRESS_TYPE_UNIX,
469             .u.q_unix.path = socket_path,
470         };
471         server_ioc = qio_channel_socket_new();
472         if (qio_channel_socket_listen_sync(server_ioc, &saddr,
473                                            1, &local_err) < 0) {
474             object_unref(OBJECT(server_ioc));
475             error_report_err(local_err);
476             return 1;
477         }
478     } else {
479         /* Using socket activation - check user didn't use -p etc. */
480         if (socket_path_specified) {
481             error_report("Unix socket can't be set when"
482                          "using socket activation");
483             exit(EXIT_FAILURE);
484         }
485 
486         /* Can only listen on a single socket.  */
487         if (socket_activation > 1) {
488             error_report("%s does not support socket activation"
489                          "with LISTEN_FDS > 1",
490                         argv[0]);
491             exit(EXIT_FAILURE);
492         }
493         server_ioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD,
494                                                &local_err);
495         if (server_ioc == NULL) {
496             error_reportf_err(local_err,
497                               "Failed to use socket activation: ");
498             exit(EXIT_FAILURE);
499         }
500     }
501 
502     qemu_init_main_loop(&error_fatal);
503 
504     server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
505                                          G_IO_IN,
506                                          accept_client,
507                                          NULL, NULL);
508 
509     if (daemonize) {
510         if (daemon(0, 0) < 0) {
511             error_report("Failed to daemonize: %s", strerror(errno));
512             exit(EXIT_FAILURE);
513         }
514     }
515 
516     if (daemonize || pidfile_specified) {
517         qemu_write_pidfile(pidfile, &error_fatal);
518     }
519 
520 #ifdef CONFIG_LIBCAP_NG
521     if (drop_privileges() < 0) {
522         error_report("Failed to drop privileges: %s", strerror(errno));
523         exit(EXIT_FAILURE);
524     }
525 #endif
526 
527     info_report("Listening on %s", socket_path);
528 
529     state = RUNNING;
530     do {
531         main_loop_wait(false);
532         if (state == TERMINATE) {
533             state = TERMINATING;
534             close_server_socket();
535         }
536     } while (num_active_sockets > 0);
537 
538     exit(EXIT_SUCCESS);
539 }
540