1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2011 Lennart Poettering
8 #if defined(__i386__) || defined(__x86_64__)
17 #include "alloc-util.h"
18 #include "dirent-util.h"
23 #include "process-util.h"
24 #include "stat-util.h"
25 #include "string-table.h"
26 #include "string-util.h"
29 #if 0 /// UNNEEDED by elogind
30 static int detect_vm_cpuid(void) {
32 /* CPUID is an x86 specific interface. */
33 #if defined(__i386__) || defined(__x86_64__)
38 } cpuid_vendor_table[] = {
39 { "XenVMMXenVMM", VIRTUALIZATION_XEN },
40 { "KVMKVMKVM", VIRTUALIZATION_KVM },
41 { "TCGTCGTCGTCG", VIRTUALIZATION_QEMU },
42 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
43 { "VMwareVMware", VIRTUALIZATION_VMWARE },
44 /* https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/reference/tlfs */
45 { "Microsoft Hv", VIRTUALIZATION_MICROSOFT },
46 /* https://wiki.freebsd.org/bhyve */
47 { "bhyve bhyve ", VIRTUALIZATION_BHYVE },
48 { "QNXQVMBSQG", VIRTUALIZATION_QNX },
51 uint32_t eax, ebx, ecx, edx;
54 /* http://lwn.net/Articles/301888/ */
56 /* First detect whether there is a hypervisor */
57 if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0)
58 return VIRTUALIZATION_NONE;
60 hypervisor = !!(ecx & 0x80000000U);
69 /* There is a hypervisor, see what it is */
70 __cpuid(0x40000000U, eax, ebx, ecx, edx);
76 log_debug("Virtualization found, CPUID=%s", sig.text);
78 for (j = 0; j < ELEMENTSOF(cpuid_vendor_table); j ++)
79 if (streq(sig.text, cpuid_vendor_table[j].cpuid))
80 return cpuid_vendor_table[j].id;
82 return VIRTUALIZATION_VM_OTHER;
85 log_debug("No virtualization found in CPUID");
87 return VIRTUALIZATION_NONE;
90 static int detect_vm_device_tree(void) {
91 #if defined(__arm__) || defined(__aarch64__) || defined(__powerpc__) || defined(__powerpc64__)
92 _cleanup_free_ char *hvtype = NULL;
95 r = read_one_line_file("/proc/device-tree/hypervisor/compatible", &hvtype);
97 _cleanup_closedir_ DIR *dir = NULL;
100 dir = opendir("/proc/device-tree");
102 if (errno == ENOENT) {
103 log_debug_errno(errno, "/proc/device-tree: %m");
104 return VIRTUALIZATION_NONE;
109 FOREACH_DIRENT(dent, dir, return -errno)
110 if (strstr(dent->d_name, "fw-cfg")) {
111 log_debug("Virtualization QEMU: \"fw-cfg\" present in /proc/device-tree/%s", dent->d_name);
112 return VIRTUALIZATION_QEMU;
115 log_debug("No virtualization found in /proc/device-tree/*");
116 return VIRTUALIZATION_NONE;
120 log_debug("Virtualization %s found in /proc/device-tree/hypervisor/compatible", hvtype);
121 if (streq(hvtype, "linux,kvm"))
122 return VIRTUALIZATION_KVM;
123 else if (strstr(hvtype, "xen"))
124 return VIRTUALIZATION_XEN;
126 return VIRTUALIZATION_VM_OTHER;
128 log_debug("This platform does not support /proc/device-tree");
129 return VIRTUALIZATION_NONE;
133 static int detect_vm_dmi(void) {
134 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
136 static const char *const dmi_vendors[] = {
137 "/sys/class/dmi/id/product_name", /* Test this before sys_vendor to detect KVM over QEMU */
138 "/sys/class/dmi/id/sys_vendor",
139 "/sys/class/dmi/id/board_vendor",
140 "/sys/class/dmi/id/bios_vendor"
143 static const struct {
146 } dmi_vendor_table[] = {
147 { "KVM", VIRTUALIZATION_KVM },
148 { "QEMU", VIRTUALIZATION_QEMU },
149 /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
150 { "VMware", VIRTUALIZATION_VMWARE },
151 { "VMW", VIRTUALIZATION_VMWARE },
152 { "innotek GmbH", VIRTUALIZATION_ORACLE },
153 { "Xen", VIRTUALIZATION_XEN },
154 { "Bochs", VIRTUALIZATION_BOCHS },
155 { "Parallels", VIRTUALIZATION_PARALLELS },
156 /* https://wiki.freebsd.org/bhyve */
157 { "BHYVE", VIRTUALIZATION_BHYVE },
162 for (i = 0; i < ELEMENTSOF(dmi_vendors); i++) {
163 _cleanup_free_ char *s = NULL;
166 r = read_one_line_file(dmi_vendors[i], &s);
174 for (j = 0; j < ELEMENTSOF(dmi_vendor_table); j++)
175 if (startswith(s, dmi_vendor_table[j].vendor)) {
176 log_debug("Virtualization %s found in DMI (%s)", s, dmi_vendors[i]);
177 return dmi_vendor_table[j].id;
182 log_debug("No virtualization found in DMI");
184 return VIRTUALIZATION_NONE;
187 static int detect_vm_xen(void) {
189 /* Check for Dom0 will be executed later in detect_vm_xen_dom0
190 The presence of /proc/xen indicates some form of a Xen domain */
191 if (access("/proc/xen", F_OK) < 0) {
192 log_debug("Virtualization XEN not found, /proc/xen does not exist");
193 return VIRTUALIZATION_NONE;
196 log_debug("Virtualization XEN found (/proc/xen exists)");
197 return VIRTUALIZATION_XEN;
200 #define XENFEAT_dom0 11 /* xen/include/public/features.h */
201 #define PATH_FEATURES "/sys/hypervisor/properties/features"
202 /* Returns -errno, or 0 for domU, or 1 for dom0 */
203 static int detect_vm_xen_dom0(void) {
204 _cleanup_free_ char *domcap = NULL;
208 r = read_one_line_file(PATH_FEATURES, &domcap);
209 if (r < 0 && r != -ENOENT)
212 unsigned long features;
214 /* Here, we need to use sscanf() instead of safe_atoul()
215 * as the string lacks the leading "0x". */
216 r = sscanf(domcap, "%lx", &features);
218 r = !!(features & (1U << XENFEAT_dom0));
219 log_debug("Virtualization XEN, found %s with value %08lx, "
220 "XENFEAT_dom0 (indicating the 'hardware domain') is%s set.",
221 PATH_FEATURES, features, r ? "" : " not");
224 log_debug("Virtualization XEN, found %s, unhandled content '%s'",
225 PATH_FEATURES, domcap);
228 r = read_one_line_file("/proc/xen/capabilities", &domcap);
230 log_debug("Virtualization XEN because /proc/xen/capabilities does not exist");
237 while ((cap = strsep(&i, ",")))
238 if (streq(cap, "control_d"))
241 log_debug("Virtualization XEN DomU found (/proc/xen/capabilites)");
245 log_debug("Virtualization XEN Dom0 ignored (/proc/xen/capabilities)");
249 static int detect_vm_hypervisor(void) {
250 _cleanup_free_ char *hvtype = NULL;
253 r = read_one_line_file("/sys/hypervisor/type", &hvtype);
255 return VIRTUALIZATION_NONE;
259 log_debug("Virtualization %s found in /sys/hypervisor/type", hvtype);
261 if (streq(hvtype, "xen"))
262 return VIRTUALIZATION_XEN;
264 return VIRTUALIZATION_VM_OTHER;
267 static int detect_vm_uml(void) {
268 _cleanup_free_ char *cpuinfo_contents = NULL;
271 /* Detect User-Mode Linux by reading /proc/cpuinfo */
272 r = read_full_file("/proc/cpuinfo", &cpuinfo_contents, NULL);
274 log_debug("/proc/cpuinfo not found, assuming no UML virtualization.");
275 return VIRTUALIZATION_NONE;
280 if (strstr(cpuinfo_contents, "\nvendor_id\t: User Mode Linux\n")) {
281 log_debug("UML virtualization found in /proc/cpuinfo");
282 return VIRTUALIZATION_UML;
285 log_debug("UML virtualization not found in /proc/cpuinfo.");
286 return VIRTUALIZATION_NONE;
289 static int detect_vm_zvm(void) {
291 #if defined(__s390__)
292 _cleanup_free_ char *t = NULL;
295 r = get_proc_field("/proc/sysinfo", "VM00 Control Program", WHITESPACE, &t);
297 return VIRTUALIZATION_NONE;
301 log_debug("Virtualization %s found in /proc/sysinfo", t);
302 if (streq(t, "z/VM"))
303 return VIRTUALIZATION_ZVM;
305 return VIRTUALIZATION_KVM;
307 log_debug("This platform does not support /proc/sysinfo");
308 return VIRTUALIZATION_NONE;
312 /* Returns a short identifier for the various VM implementations */
313 int detect_vm(void) {
314 static thread_local int cached_found = _VIRTUALIZATION_INVALID;
318 if (cached_found >= 0)
321 /* We have to use the correct order here:
323 * → First, try to detect Oracle Virtualbox, even if it uses KVM, as well as Xen even if it cloaks as Microsoft
326 * → Second, try to detect from CPUID, this will report KVM for whatever software is used even if info in DMI is
329 * → Third, try to detect from DMI. */
331 dmi = detect_vm_dmi();
332 if (IN_SET(dmi, VIRTUALIZATION_ORACLE, VIRTUALIZATION_XEN)) {
337 r = detect_vm_cpuid();
340 if (r == VIRTUALIZATION_VM_OTHER)
342 else if (r != VIRTUALIZATION_NONE)
345 /* Now, let's get back to DMI */
348 if (dmi == VIRTUALIZATION_VM_OTHER)
350 else if (dmi != VIRTUALIZATION_NONE) {
355 /* x86 xen will most likely be detected by cpuid. If not (most likely
356 * because we're not an x86 guest), then we should try the /proc/xen
357 * directory next. If that's not found, then we check for the high-level
358 * hypervisor sysfs file.
364 if (r == VIRTUALIZATION_VM_OTHER)
366 else if (r != VIRTUALIZATION_NONE)
369 r = detect_vm_hypervisor();
372 if (r == VIRTUALIZATION_VM_OTHER)
374 else if (r != VIRTUALIZATION_NONE)
377 r = detect_vm_device_tree();
380 if (r == VIRTUALIZATION_VM_OTHER)
382 else if (r != VIRTUALIZATION_NONE)
388 if (r == VIRTUALIZATION_VM_OTHER)
390 else if (r != VIRTUALIZATION_NONE)
398 /* x86 xen Dom0 is detected as XEN in hypervisor and maybe others.
399 * In order to detect the Dom0 as not virtualization we need to
401 if (r == VIRTUALIZATION_XEN) {
404 dom0 = detect_vm_xen_dom0();
408 r = VIRTUALIZATION_NONE;
409 } else if (r == VIRTUALIZATION_NONE && other)
410 r = VIRTUALIZATION_VM_OTHER;
413 log_debug("Found VM virtualization %s", virtualization_to_string(r));
418 int detect_container(void) {
420 static const struct {
424 { "lxc", VIRTUALIZATION_LXC },
425 { "lxc-libvirt", VIRTUALIZATION_LXC_LIBVIRT },
426 { "systemd-nspawn", VIRTUALIZATION_SYSTEMD_NSPAWN },
427 { "docker", VIRTUALIZATION_DOCKER },
428 { "rkt", VIRTUALIZATION_RKT },
431 static thread_local int cached_found = _VIRTUALIZATION_INVALID;
432 _cleanup_free_ char *m = NULL;
433 const char *e = NULL;
437 if (cached_found >= 0)
440 /* /proc/vz exists in container and outside of the container, /proc/bc only outside of the container. */
441 if (access("/proc/vz", F_OK) >= 0 &&
442 access("/proc/bc", F_OK) < 0) {
443 r = VIRTUALIZATION_OPENVZ;
447 if (getpid_cached() == 1) {
448 /* If we are PID 1 we can just check our own environment variable, and that's authoritative. */
450 e = getenv("container");
452 r = VIRTUALIZATION_NONE;
459 /* Otherwise, PID 1 might have dropped this information into a file in /run. This is better than accessing
460 * /proc/1/environ, since we don't need CAP_SYS_PTRACE for that. */
461 r = read_one_line_file("/run/systemd/container", &m);
467 return log_debug_errno(r, "Failed to read /run/systemd/container: %m");
469 /* Fallback for cases where PID 1 was not systemd (for example, cases where init=/bin/sh is used. */
470 r = getenv_for_pid(1, "container", &m);
475 if (r < 0) /* This only works if we have CAP_SYS_PTRACE, hence let's better ignore failures here */
476 log_debug_errno(r, "Failed to read $container of PID 1, ignoring: %m");
478 /* Interestingly /proc/1/sched actually shows the host's PID for what we see as PID 1. Hence, if the PID shown
479 * there is not 1, we know we are in a PID namespace. and hence a container. */
480 r = read_one_line_file("/proc/1/sched", &m);
488 if (!startswith(t, "(1,")) {
489 r = VIRTUALIZATION_CONTAINER_OTHER;
492 } else if (r != -ENOENT)
495 /* If that didn't work, give up, assume no container manager. */
496 r = VIRTUALIZATION_NONE;
500 for (j = 0; j < ELEMENTSOF(value_table); j++)
501 if (streq(e, value_table[j].value)) {
502 r = value_table[j].id;
506 r = VIRTUALIZATION_CONTAINER_OTHER;
509 log_debug("Found container virtualization %s.", virtualization_to_string(r));
514 #if 0 /// UNNEEDED by elogind
515 int detect_virtualization(void) {
518 r = detect_container();
525 static int userns_has_mapping(const char *name) {
526 _cleanup_fclose_ FILE *f = NULL;
527 _cleanup_free_ char *buf = NULL;
528 size_t n_allocated = 0;
533 f = fopen(name, "re");
535 log_debug_errno(errno, "Failed to open %s: %m", name);
536 return errno == ENOENT ? false : -errno;
539 n = getline(&buf, &n_allocated, f);
542 log_debug("%s is empty, we're in an uninitialized user namespace", name);
546 return log_debug_errno(errno, "Failed to read %s: %m", name);
549 r = sscanf(buf, "%"PRIu32" %"PRIu32" %"PRIu32, &a, &b, &c);
551 return log_debug_errno(errno, "Failed to parse %s: %m", name);
553 if (a == 0 && b == 0 && c == UINT32_MAX) {
554 /* The kernel calls mappings_overlap() and does not allow overlaps */
555 log_debug("%s has a full 1:1 mapping", name);
559 /* Anything else implies that we are in a user namespace */
560 log_debug("Mapping found in %s, we're in a user namespace", name);
564 int running_in_userns(void) {
565 _cleanup_free_ char *line = NULL;
568 r = userns_has_mapping("/proc/self/uid_map");
572 r = userns_has_mapping("/proc/self/gid_map");
576 /* "setgroups" file was added in kernel v3.18-rc6-15-g9cc46516dd. It is also
577 * possible to compile a kernel without CONFIG_USER_NS, in which case "setgroups"
578 * also does not exist. We cannot distinguish those two cases, so assume that
579 * we're running on a stripped-down recent kernel, rather than on an old one,
580 * and if the file is not found, return false.
582 r = read_one_line_file("/proc/self/setgroups", &line);
584 log_debug_errno(r, "/proc/self/setgroups: %m");
585 return r == -ENOENT ? false : r;
589 r = streq(line, "deny");
590 /* See user_namespaces(7) for a description of this "setgroups" contents. */
591 log_debug("/proc/self/setgroups contains \"%s\", %s user namespace", line, r ? "in" : "not in");
596 int running_in_chroot(void) {
599 #if 0 /// elogind does not allow to ignore chroots, we are never init!
600 if (getenv_bool("SYSTEMD_IGNORE_CHROOT") > 0)
604 r = files_same("/proc/1/root", "/", 0);
611 static const char *const virtualization_table[_VIRTUALIZATION_MAX] = {
612 [VIRTUALIZATION_NONE] = "none",
613 [VIRTUALIZATION_KVM] = "kvm",
614 [VIRTUALIZATION_QEMU] = "qemu",
615 [VIRTUALIZATION_BOCHS] = "bochs",
616 [VIRTUALIZATION_XEN] = "xen",
617 [VIRTUALIZATION_UML] = "uml",
618 [VIRTUALIZATION_VMWARE] = "vmware",
619 [VIRTUALIZATION_ORACLE] = "oracle",
620 [VIRTUALIZATION_MICROSOFT] = "microsoft",
621 [VIRTUALIZATION_ZVM] = "zvm",
622 [VIRTUALIZATION_PARALLELS] = "parallels",
623 [VIRTUALIZATION_BHYVE] = "bhyve",
624 [VIRTUALIZATION_QNX] = "qnx",
625 [VIRTUALIZATION_VM_OTHER] = "vm-other",
627 [VIRTUALIZATION_SYSTEMD_NSPAWN] = "systemd-nspawn",
628 [VIRTUALIZATION_LXC_LIBVIRT] = "lxc-libvirt",
629 [VIRTUALIZATION_LXC] = "lxc",
630 [VIRTUALIZATION_OPENVZ] = "openvz",
631 [VIRTUALIZATION_DOCKER] = "docker",
632 [VIRTUALIZATION_RKT] = "rkt",
633 [VIRTUALIZATION_CONTAINER_OTHER] = "container-other",
636 DEFINE_STRING_TABLE_LOOKUP(virtualization, int);