2 * QEMU Guest Agent POSIX-specific command implementations
4 * Copyright IBM Corp. 2011
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
8 * Michal Privoznik <mprivozn@redhat.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
14 #include "qemu/osdep.h"
15 #include <sys/ioctl.h>
16 #include <sys/utsname.h>
19 #include "qga-qapi-commands.h"
20 #include "qapi/error.h"
21 #include "qapi/qmp/qerror.h"
22 #include "qemu/host-utils.h"
23 #include "qemu/sockets.h"
24 #include "qemu/base64.h"
25 #include "qemu/cutils.h"
26 #include "commands-common.h"
27 #include "block/nvme.h"
34 #if defined(__linux__)
36 #include <sys/statvfs.h>
37 #include <linux/nvme_ioctl.h>
44 #ifdef HAVE_GETIFADDRS
45 #include <arpa/inet.h>
46 #include <sys/socket.h>
48 #if defined(__NetBSD__) || defined(__OpenBSD__)
49 #include <net/if_arp.h>
50 #include <netinet/if_ether.h>
52 #include <net/ethernet.h>
55 #include <sys/sockio.h>
59 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
65 rpid
= RETRY_ON_EINTR(waitpid(pid
, status
, 0));
68 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
73 g_assert(rpid
== pid
);
76 void qmp_guest_shutdown(const char *mode
, Error
**errp
)
78 const char *shutdown_flag
;
79 Error
*local_err
= NULL
;
84 const char *powerdown_flag
= "-i5";
85 const char *halt_flag
= "-i0";
86 const char *reboot_flag
= "-i6";
87 #elif defined(CONFIG_BSD)
88 const char *powerdown_flag
= "-p";
89 const char *halt_flag
= "-h";
90 const char *reboot_flag
= "-r";
92 const char *powerdown_flag
= "-P";
93 const char *halt_flag
= "-H";
94 const char *reboot_flag
= "-r";
97 slog("guest-shutdown called, mode: %s", mode
);
98 if (!mode
|| strcmp(mode
, "powerdown") == 0) {
99 shutdown_flag
= powerdown_flag
;
100 } else if (strcmp(mode
, "halt") == 0) {
101 shutdown_flag
= halt_flag
;
102 } else if (strcmp(mode
, "reboot") == 0) {
103 shutdown_flag
= reboot_flag
;
106 "mode is invalid (valid values are: halt|powerdown|reboot");
112 /* child, start the shutdown */
114 reopen_fd_to_null(0);
115 reopen_fd_to_null(1);
116 reopen_fd_to_null(2);
118 #ifdef CONFIG_SOLARIS
119 execl("/sbin/shutdown", "shutdown", shutdown_flag
, "-g0", "-y",
120 "hypervisor initiated shutdown", (char *)NULL
);
121 #elif defined(CONFIG_BSD)
122 execl("/sbin/shutdown", "shutdown", shutdown_flag
, "+0",
123 "hypervisor initiated shutdown", (char *)NULL
);
125 execl("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
126 "hypervisor initiated shutdown", (char *)NULL
);
129 } else if (pid
< 0) {
130 error_setg_errno(errp
, errno
, "failed to create child process");
134 ga_wait_child(pid
, &status
, &local_err
);
136 error_propagate(errp
, local_err
);
140 if (!WIFEXITED(status
)) {
141 error_setg(errp
, "child process has terminated abnormally");
145 if (WEXITSTATUS(status
)) {
146 error_setg(errp
, "child process has failed to shutdown");
153 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
158 Error
*local_err
= NULL
;
160 static const char hwclock_path
[] = "/sbin/hwclock";
161 static int hwclock_available
= -1;
163 if (hwclock_available
< 0) {
164 hwclock_available
= (access(hwclock_path
, X_OK
) == 0);
167 if (!hwclock_available
) {
168 error_setg(errp
, QERR_UNSUPPORTED
);
172 /* If user has passed a time, validate and set it. */
176 /* year-2038 will overflow in case time_t is 32bit */
177 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
178 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
182 tv
.tv_sec
= time_ns
/ 1000000000;
183 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
184 g_date_set_time_t(&date
, tv
.tv_sec
);
185 if (date
.year
< 1970 || date
.year
>= 2070) {
186 error_setg_errno(errp
, errno
, "Invalid time");
190 ret
= settimeofday(&tv
, NULL
);
192 error_setg_errno(errp
, errno
, "Failed to set time to guest");
197 /* Now, if user has passed a time to set and the system time is set, we
198 * just need to synchronize the hardware clock. However, if no time was
199 * passed, user is requesting the opposite: set the system time from the
200 * hardware clock (RTC). */
204 reopen_fd_to_null(0);
205 reopen_fd_to_null(1);
206 reopen_fd_to_null(2);
208 /* Use '/sbin/hwclock -w' to set RTC from the system time,
209 * or '/sbin/hwclock -s' to set the system time from RTC. */
210 execl(hwclock_path
, "hwclock", has_time
? "-w" : "-s", NULL
);
212 } else if (pid
< 0) {
213 error_setg_errno(errp
, errno
, "failed to create child process");
217 ga_wait_child(pid
, &status
, &local_err
);
219 error_propagate(errp
, local_err
);
223 if (!WIFEXITED(status
)) {
224 error_setg(errp
, "child process has terminated abnormally");
228 if (WEXITSTATUS(status
)) {
229 error_setg(errp
, "hwclock failed to set hardware clock to system time");
240 struct GuestFileHandle
{
244 QTAILQ_ENTRY(GuestFileHandle
) next
;
248 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
249 } guest_file_state
= {
250 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
253 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
255 GuestFileHandle
*gfh
;
258 handle
= ga_get_fd_handle(ga_state
, errp
);
263 gfh
= g_new0(GuestFileHandle
, 1);
266 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
271 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
273 GuestFileHandle
*gfh
;
275 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
282 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
286 typedef const char * const ccpc
;
292 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
293 static const struct {
296 } guest_file_open_modes
[] = {
297 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
298 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
299 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
300 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
301 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
302 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
303 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
304 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
305 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
306 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
307 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
308 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
312 find_open_flag(const char *mode_str
, Error
**errp
)
316 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
319 form
= guest_file_open_modes
[mode
].forms
;
320 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
328 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
329 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
332 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
335 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
336 S_IRGRP | S_IWGRP | \
340 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
346 oflag
= find_open_flag(mode
, errp
);
351 /* If the caller wants / allows creation of a new file, we implement it
352 * with a two step process: open() + (open() / fchmod()).
354 * First we insist on creating the file exclusively as a new file. If
355 * that succeeds, we're free to set any file-mode bits on it. (The
356 * motivation is that we want to set those file-mode bits independently
357 * of the current umask.)
359 * If the exclusive creation fails because the file already exists
360 * (EEXIST is not possible for any other reason), we just attempt to
361 * open the file, but in this case we won't be allowed to change the
362 * file-mode bits on the preexistent file.
364 * The pathname should never disappear between the two open()s in
365 * practice. If it happens, then someone very likely tried to race us.
366 * In this case just go ahead and report the ENOENT from the second
367 * open() to the caller.
369 * If the caller wants to open a preexistent file, then the first
370 * open() is decisive and its third argument is ignored, and the second
371 * open() and the fchmod() are never called.
373 fd
= qga_open_cloexec(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
374 if (fd
== -1 && errno
== EEXIST
) {
375 oflag
&= ~(unsigned)O_CREAT
;
376 fd
= qga_open_cloexec(path
, oflag
, 0);
379 error_setg_errno(errp
, errno
,
380 "failed to open file '%s' (mode: '%s')",
385 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
386 error_setg_errno(errp
, errno
, "failed to set permission "
387 "0%03o on new file '%s' (mode: '%s')",
388 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
392 f
= fdopen(fd
, mode
);
394 error_setg_errno(errp
, errno
, "failed to associate stdio stream with "
395 "file descriptor %d, file '%s' (mode: '%s')",
400 if (f
== NULL
&& fd
!= -1) {
402 if (oflag
& O_CREAT
) {
409 int64_t qmp_guest_file_open(const char *path
, const char *mode
,
413 Error
*local_err
= NULL
;
419 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
420 fh
= safe_open_or_create(path
, mode
, &local_err
);
421 if (local_err
!= NULL
) {
422 error_propagate(errp
, local_err
);
426 /* set fd non-blocking to avoid common use cases (like reading from a
427 * named pipe) from hanging the agent
429 if (!g_unix_set_fd_nonblocking(fileno(fh
), true, NULL
)) {
431 error_setg_errno(errp
, errno
, "Failed to set FD nonblocking");
435 handle
= guest_file_handle_add(fh
, errp
);
441 slog("guest-file-open, handle: %" PRId64
, handle
);
445 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
447 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
450 slog("guest-file-close called, handle: %" PRId64
, handle
);
455 ret
= fclose(gfh
->fh
);
457 error_setg_errno(errp
, errno
, "failed to close handle");
461 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
465 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
466 int64_t count
, Error
**errp
)
468 GuestFileRead
*read_data
= NULL
;
473 /* explicitly flush when switching from writing to reading */
474 if (gfh
->state
== RW_STATE_WRITING
) {
475 int ret
= fflush(fh
);
477 error_setg_errno(errp
, errno
, "failed to flush file");
480 gfh
->state
= RW_STATE_NEW
;
483 buf
= g_malloc0(count
+ 1);
484 read_count
= fread(buf
, 1, count
, fh
);
486 error_setg_errno(errp
, errno
, "failed to read file");
489 read_data
= g_new0(GuestFileRead
, 1);
490 read_data
->count
= read_count
;
491 read_data
->eof
= feof(fh
);
493 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
495 gfh
->state
= RW_STATE_READING
;
503 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
504 bool has_count
, int64_t count
,
507 GuestFileWrite
*write_data
= NULL
;
511 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
520 if (gfh
->state
== RW_STATE_READING
) {
521 int ret
= fseek(fh
, 0, SEEK_CUR
);
523 error_setg_errno(errp
, errno
, "failed to seek file");
526 gfh
->state
= RW_STATE_NEW
;
529 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
536 } else if (count
< 0 || count
> buf_len
) {
537 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
543 write_count
= fwrite(buf
, 1, count
, fh
);
545 error_setg_errno(errp
, errno
, "failed to write to file");
546 slog("guest-file-write failed, handle: %" PRId64
, handle
);
548 write_data
= g_new0(GuestFileWrite
, 1);
549 write_data
->count
= write_count
;
550 write_data
->eof
= feof(fh
);
551 gfh
->state
= RW_STATE_WRITING
;
559 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
560 GuestFileWhence
*whence_code
,
563 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
564 GuestFileSeek
*seek_data
= NULL
;
574 /* We stupidly exposed 'whence':'int' in our qapi */
575 whence
= ga_parse_whence(whence_code
, &err
);
577 error_propagate(errp
, err
);
582 ret
= fseek(fh
, offset
, whence
);
584 error_setg_errno(errp
, errno
, "failed to seek file");
585 if (errno
== ESPIPE
) {
586 /* file is non-seekable, stdio shouldn't be buffering anyways */
587 gfh
->state
= RW_STATE_NEW
;
590 seek_data
= g_new0(GuestFileSeek
, 1);
591 seek_data
->position
= ftell(fh
);
592 seek_data
->eof
= feof(fh
);
593 gfh
->state
= RW_STATE_NEW
;
600 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
602 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
613 error_setg_errno(errp
, errno
, "failed to flush file");
615 gfh
->state
= RW_STATE_NEW
;
619 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
620 void free_fs_mount_list(FsMountList
*mounts
)
622 FsMount
*mount
, *temp
;
628 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
629 QTAILQ_REMOVE(mounts
, mount
, next
);
630 g_free(mount
->dirname
);
631 g_free(mount
->devtype
);
637 #if defined(CONFIG_FSFREEZE)
639 FSFREEZE_HOOK_THAW
= 0,
640 FSFREEZE_HOOK_FREEZE
,
643 static const char *fsfreeze_hook_arg_string
[] = {
648 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
653 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
654 Error
*local_err
= NULL
;
656 hook
= ga_fsfreeze_hook(ga_state
);
660 if (access(hook
, X_OK
) != 0) {
661 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
665 slog("executing fsfreeze hook with arg '%s'", arg_str
);
669 reopen_fd_to_null(0);
670 reopen_fd_to_null(1);
671 reopen_fd_to_null(2);
673 execl(hook
, hook
, arg_str
, NULL
);
675 } else if (pid
< 0) {
676 error_setg_errno(errp
, errno
, "failed to create child process");
680 ga_wait_child(pid
, &status
, &local_err
);
682 error_propagate(errp
, local_err
);
686 if (!WIFEXITED(status
)) {
687 error_setg(errp
, "fsfreeze hook has terminated abnormally");
691 status
= WEXITSTATUS(status
);
693 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
699 * Return status of freeze/thaw
701 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
703 if (ga_is_frozen(ga_state
)) {
704 return GUEST_FSFREEZE_STATUS_FROZEN
;
707 return GUEST_FSFREEZE_STATUS_THAWED
;
710 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
712 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
715 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
716 strList
*mountpoints
,
721 Error
*local_err
= NULL
;
723 slog("guest-fsfreeze called");
725 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
727 error_propagate(errp
, local_err
);
731 QTAILQ_INIT(&mounts
);
732 if (!build_fs_mount_list(&mounts
, &local_err
)) {
733 error_propagate(errp
, local_err
);
737 /* cannot risk guest agent blocking itself on a write in this state */
738 ga_set_frozen(ga_state
);
740 ret
= qmp_guest_fsfreeze_do_freeze_list(has_mountpoints
, mountpoints
,
743 free_fs_mount_list(&mounts
);
744 /* We may not issue any FIFREEZE here.
745 * Just unset ga_state here and ready for the next call.
748 ga_unset_frozen(ga_state
);
749 } else if (ret
< 0) {
750 qmp_guest_fsfreeze_thaw(NULL
);
755 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
759 ret
= qmp_guest_fsfreeze_do_thaw(errp
);
761 ga_unset_frozen(ga_state
);
762 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
770 static void guest_fsfreeze_cleanup(void)
774 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
775 qmp_guest_fsfreeze_thaw(&err
);
777 slog("failed to clean up frozen filesystems: %s",
778 error_get_pretty(err
));
785 /* linux-specific implementations. avoid this if at all possible. */
786 #if defined(__linux__)
787 #if defined(CONFIG_FSFREEZE)
789 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
797 path
= g_strndup(syspath
, pathlen
);
798 dpath
= g_strdup_printf("%s/driver", path
);
799 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
802 driver
= g_path_get_basename(buf
);
809 static int compare_uint(const void *_a
, const void *_b
)
811 unsigned int a
= *(unsigned int *)_a
;
812 unsigned int b
= *(unsigned int *)_b
;
814 return a
< b
? -1 : a
> b
? 1 : 0;
817 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
818 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
819 unsigned int *hosts
, int hosts_max
, Error
**errp
)
823 struct dirent
*entry
;
826 path
= g_strndup(syspath
, host
- syspath
);
829 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
834 while (i
< hosts_max
) {
835 entry
= readdir(dir
);
839 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
841 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
846 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
854 * Store disk device info for devices on the PCI bus.
855 * Returns true if information has been stored, or false for failure.
857 static bool build_guest_fsinfo_for_pci_dev(char const *syspath
,
858 GuestDiskAddress
*disk
,
861 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
862 int i
, nhosts
= 0, pcilen
;
863 GuestPCIAddress
*pciaddr
= disk
->pci_controller
;
864 bool has_ata
= false, has_host
= false, has_tgt
= false;
865 char *p
, *q
, *driver
= NULL
;
868 p
= strstr(syspath
, "/devices/pci");
869 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
870 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
871 g_debug("only pci device is supported: sysfs path '%s'", syspath
);
877 driver
= get_pci_driver(syspath
, p
- syspath
, errp
);
878 if (driver
&& (g_str_equal(driver
, "ata_piix") ||
879 g_str_equal(driver
, "sym53c8xx") ||
880 g_str_equal(driver
, "virtio-pci") ||
881 g_str_equal(driver
, "ahci") ||
882 g_str_equal(driver
, "nvme"))) {
887 if (sscanf(p
, "/%x:%x:%x.%x%n",
888 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
893 g_debug("unsupported driver or sysfs path '%s'", syspath
);
897 p
= strstr(syspath
, "/target");
898 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
899 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
903 p
= strstr(syspath
, "/ata");
908 p
= strstr(syspath
, "/host");
911 if (p
&& sscanf(q
, "%u", &host
) == 1) {
913 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
914 ARRAY_SIZE(hosts
), errp
);
920 pciaddr
->domain
= pci
[0];
921 pciaddr
->bus
= pci
[1];
922 pciaddr
->slot
= pci
[2];
923 pciaddr
->function
= pci
[3];
925 if (strcmp(driver
, "ata_piix") == 0) {
926 /* a host per ide bus, target*:0:<unit>:0 */
927 if (!has_host
|| !has_tgt
) {
928 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
931 for (i
= 0; i
< nhosts
; i
++) {
932 if (host
== hosts
[i
]) {
933 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
940 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
943 } else if (strcmp(driver
, "sym53c8xx") == 0) {
944 /* scsi(LSI Logic): target*:0:<unit>:0 */
946 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
949 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
951 } else if (strcmp(driver
, "virtio-pci") == 0) {
953 /* virtio-scsi: target*:0:0:<unit> */
954 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
957 /* virtio-blk: 1 disk per 1 device */
958 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
960 } else if (strcmp(driver
, "ahci") == 0) {
961 /* ahci: 1 host per 1 unit */
962 if (!has_host
|| !has_tgt
) {
963 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
966 for (i
= 0; i
< nhosts
; i
++) {
967 if (host
== hosts
[i
]) {
969 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
974 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
977 } else if (strcmp(driver
, "nvme") == 0) {
978 disk
->bus_type
= GUEST_DISK_BUS_TYPE_NVME
;
980 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
992 * Store disk device info for non-PCI virtio devices (for example s390x
993 * channel I/O devices). Returns true if information has been stored, or
996 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath
,
997 GuestDiskAddress
*disk
,
1000 unsigned int tgt
[3];
1003 if (!strstr(syspath
, "/virtio") || !strstr(syspath
, "/block")) {
1004 g_debug("Unsupported virtio device '%s'", syspath
);
1008 p
= strstr(syspath
, "/target");
1009 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1010 &tgt
[0], &tgt
[1], &tgt
[2]) == 3) {
1011 /* virtio-scsi: target*:0:<target>:<unit> */
1012 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1014 disk
->target
= tgt
[1];
1015 disk
->unit
= tgt
[2];
1017 /* virtio-blk: 1 disk per 1 device */
1018 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
1025 * Store disk device info for CCW devices (s390x channel I/O devices).
1026 * Returns true if information has been stored, or false for failure.
1028 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath
,
1029 GuestDiskAddress
*disk
,
1032 unsigned int cssid
, ssid
, subchno
, devno
;
1035 p
= strstr(syspath
, "/devices/css");
1036 if (!p
|| sscanf(p
+ 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1037 &cssid
, &ssid
, &subchno
, &devno
) < 4) {
1038 g_debug("could not parse ccw device sysfs path: %s", syspath
);
1042 disk
->ccw_address
= g_new0(GuestCCWAddress
, 1);
1043 disk
->ccw_address
->cssid
= cssid
;
1044 disk
->ccw_address
->ssid
= ssid
;
1045 disk
->ccw_address
->subchno
= subchno
;
1046 disk
->ccw_address
->devno
= devno
;
1048 if (strstr(p
, "/virtio")) {
1049 build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1055 /* Store disk device info specified by @sysfs into @fs */
1056 static void build_guest_fsinfo_for_real_device(char const *syspath
,
1057 GuestFilesystemInfo
*fs
,
1060 GuestDiskAddress
*disk
;
1061 GuestPCIAddress
*pciaddr
;
1063 #ifdef CONFIG_LIBUDEV
1064 struct udev
*udev
= NULL
;
1065 struct udev_device
*udevice
= NULL
;
1068 pciaddr
= g_new0(GuestPCIAddress
, 1);
1069 pciaddr
->domain
= -1; /* -1 means field is invalid */
1072 pciaddr
->function
= -1;
1074 disk
= g_new0(GuestDiskAddress
, 1);
1075 disk
->pci_controller
= pciaddr
;
1076 disk
->bus_type
= GUEST_DISK_BUS_TYPE_UNKNOWN
;
1078 #ifdef CONFIG_LIBUDEV
1080 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1081 if (udev
== NULL
|| udevice
== NULL
) {
1082 g_debug("failed to query udev");
1084 const char *devnode
, *serial
;
1085 devnode
= udev_device_get_devnode(udevice
);
1086 if (devnode
!= NULL
) {
1087 disk
->dev
= g_strdup(devnode
);
1089 serial
= udev_device_get_property_value(udevice
, "ID_SERIAL");
1090 if (serial
!= NULL
&& *serial
!= 0) {
1091 disk
->serial
= g_strdup(serial
);
1096 udev_device_unref(udevice
);
1099 if (strstr(syspath
, "/devices/pci")) {
1100 has_hwinf
= build_guest_fsinfo_for_pci_dev(syspath
, disk
, errp
);
1101 } else if (strstr(syspath
, "/devices/css")) {
1102 has_hwinf
= build_guest_fsinfo_for_ccw_dev(syspath
, disk
, errp
);
1103 } else if (strstr(syspath
, "/virtio")) {
1104 has_hwinf
= build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1106 g_debug("Unsupported device type for '%s'", syspath
);
1110 if (has_hwinf
|| disk
->dev
|| disk
->serial
) {
1111 QAPI_LIST_PREPEND(fs
->disk
, disk
);
1113 qapi_free_GuestDiskAddress(disk
);
1117 static void build_guest_fsinfo_for_device(char const *devpath
,
1118 GuestFilesystemInfo
*fs
,
1121 /* Store a list of slave devices of virtual volume specified by @syspath into
1123 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1124 GuestFilesystemInfo
*fs
,
1130 struct dirent
*entry
;
1132 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1133 dir
= opendir(dirpath
);
1135 if (errno
!= ENOENT
) {
1136 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1144 entry
= readdir(dir
);
1145 if (entry
== NULL
) {
1147 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1152 if (entry
->d_type
== DT_LNK
) {
1155 g_debug(" slave device '%s'", entry
->d_name
);
1156 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1157 build_guest_fsinfo_for_device(path
, fs
, &err
);
1161 error_propagate(errp
, err
);
1171 static bool is_disk_virtual(const char *devpath
, Error
**errp
)
1173 g_autofree
char *syspath
= realpath(devpath
, NULL
);
1176 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1179 return strstr(syspath
, "/devices/virtual/block/") != NULL
;
1182 /* Dispatch to functions for virtual/real device */
1183 static void build_guest_fsinfo_for_device(char const *devpath
,
1184 GuestFilesystemInfo
*fs
,
1188 g_autofree
char *syspath
= NULL
;
1189 bool is_virtual
= false;
1191 syspath
= realpath(devpath
, NULL
);
1193 if (errno
!= ENOENT
) {
1194 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1198 /* ENOENT: This devpath may not exist because of container config */
1200 fs
->name
= g_path_get_basename(devpath
);
1206 fs
->name
= g_path_get_basename(syspath
);
1209 g_debug(" parse sysfs path '%s'", syspath
);
1210 is_virtual
= is_disk_virtual(syspath
, errp
);
1211 if (*errp
!= NULL
) {
1215 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1217 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1221 #ifdef CONFIG_LIBUDEV
1224 * Wrapper around build_guest_fsinfo_for_device() for getting just
1227 static GuestDiskAddress
*get_disk_address(const char *syspath
, Error
**errp
)
1229 g_autoptr(GuestFilesystemInfo
) fs
= NULL
;
1231 fs
= g_new0(GuestFilesystemInfo
, 1);
1232 build_guest_fsinfo_for_device(syspath
, fs
, errp
);
1233 if (fs
->disk
!= NULL
) {
1234 return g_steal_pointer(&fs
->disk
->value
);
1239 static char *get_alias_for_syspath(const char *syspath
)
1241 struct udev
*udev
= NULL
;
1242 struct udev_device
*udevice
= NULL
;
1247 g_debug("failed to query udev");
1250 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1251 if (udevice
== NULL
) {
1252 g_debug("failed to query udev for path: %s", syspath
);
1255 const char *alias
= udev_device_get_property_value(
1256 udevice
, "DM_NAME");
1258 * NULL means there was an error and empty string means there is no
1259 * alias. In case of no alias we return NULL instead of empty string.
1261 if (alias
== NULL
) {
1262 g_debug("failed to query udev for device alias for: %s",
1264 } else if (*alias
!= 0) {
1265 ret
= g_strdup(alias
);
1271 udev_device_unref(udevice
);
1275 static char *get_device_for_syspath(const char *syspath
)
1277 struct udev
*udev
= NULL
;
1278 struct udev_device
*udevice
= NULL
;
1283 g_debug("failed to query udev");
1286 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1287 if (udevice
== NULL
) {
1288 g_debug("failed to query udev for path: %s", syspath
);
1291 ret
= g_strdup(udev_device_get_devnode(udevice
));
1296 udev_device_unref(udevice
);
1300 static void get_disk_deps(const char *disk_dir
, GuestDiskInfo
*disk
)
1302 g_autofree
char *deps_dir
= NULL
;
1304 GDir
*dp_deps
= NULL
;
1306 /* List dependent disks */
1307 deps_dir
= g_strdup_printf("%s/slaves", disk_dir
);
1308 g_debug(" listing entries in: %s", deps_dir
);
1309 dp_deps
= g_dir_open(deps_dir
, 0, NULL
);
1310 if (dp_deps
== NULL
) {
1311 g_debug("failed to list entries in %s", deps_dir
);
1314 disk
->has_dependencies
= true;
1315 while ((dep
= g_dir_read_name(dp_deps
)) != NULL
) {
1316 g_autofree
char *dep_dir
= NULL
;
1319 /* Add dependent disks */
1320 dep_dir
= g_strdup_printf("%s/%s", deps_dir
, dep
);
1321 dev_name
= get_device_for_syspath(dep_dir
);
1322 if (dev_name
!= NULL
) {
1323 g_debug(" adding dependent device: %s", dev_name
);
1324 QAPI_LIST_PREPEND(disk
->dependencies
, dev_name
);
1327 g_dir_close(dp_deps
);
1331 * Detect partitions subdirectory, name is "<disk_name><number>" or
1332 * "<disk_name>p<number>"
1334 * @disk_name -- last component of /sys path (e.g. sda)
1335 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1336 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1338 static GuestDiskInfoList
*get_disk_partitions(
1339 GuestDiskInfoList
*list
,
1340 const char *disk_name
, const char *disk_dir
,
1341 const char *disk_dev
)
1343 GuestDiskInfoList
*ret
= list
;
1344 struct dirent
*de_disk
;
1345 DIR *dp_disk
= NULL
;
1346 size_t len
= strlen(disk_name
);
1348 dp_disk
= opendir(disk_dir
);
1349 while ((de_disk
= readdir(dp_disk
)) != NULL
) {
1350 g_autofree
char *partition_dir
= NULL
;
1352 GuestDiskInfo
*partition
;
1354 if (!(de_disk
->d_type
& DT_DIR
)) {
1358 if (!(strncmp(disk_name
, de_disk
->d_name
, len
) == 0 &&
1359 ((*(de_disk
->d_name
+ len
) == 'p' &&
1360 isdigit(*(de_disk
->d_name
+ len
+ 1))) ||
1361 isdigit(*(de_disk
->d_name
+ len
))))) {
1365 partition_dir
= g_strdup_printf("%s/%s",
1366 disk_dir
, de_disk
->d_name
);
1367 dev_name
= get_device_for_syspath(partition_dir
);
1368 if (dev_name
== NULL
) {
1369 g_debug("Failed to get device name for syspath: %s",
1373 partition
= g_new0(GuestDiskInfo
, 1);
1374 partition
->name
= dev_name
;
1375 partition
->partition
= true;
1376 partition
->has_dependencies
= true;
1377 /* Add parent disk as dependent for easier tracking of hierarchy */
1378 QAPI_LIST_PREPEND(partition
->dependencies
, g_strdup(disk_dev
));
1380 QAPI_LIST_PREPEND(ret
, partition
);
1387 static void get_nvme_smart(GuestDiskInfo
*disk
)
1390 GuestNVMeSmart
*smart
;
1391 NvmeSmartLog log
= {0};
1392 struct nvme_admin_cmd cmd
= {
1393 .opcode
= NVME_ADM_CMD_GET_LOG_PAGE
,
1394 .nsid
= NVME_NSID_BROADCAST
,
1395 .addr
= (uintptr_t)&log
,
1396 .data_len
= sizeof(log
),
1397 .cdw10
= NVME_LOG_SMART_INFO
| (1 << 15) /* RAE bit */
1398 | (((sizeof(log
) >> 2) - 1) << 16)
1401 fd
= qga_open_cloexec(disk
->name
, O_RDONLY
, 0);
1403 g_debug("Failed to open device: %s: %s", disk
->name
, g_strerror(errno
));
1407 if (ioctl(fd
, NVME_IOCTL_ADMIN_CMD
, &cmd
)) {
1408 g_debug("Failed to get smart: %s: %s", disk
->name
, g_strerror(errno
));
1413 disk
->smart
= g_new0(GuestDiskSmart
, 1);
1414 disk
->smart
->type
= GUEST_DISK_BUS_TYPE_NVME
;
1416 smart
= &disk
->smart
->u
.nvme
;
1417 smart
->critical_warning
= log
.critical_warning
;
1418 smart
->temperature
= lduw_le_p(&log
.temperature
); /* unaligned field */
1419 smart
->available_spare
= log
.available_spare
;
1420 smart
->available_spare_threshold
= log
.available_spare_threshold
;
1421 smart
->percentage_used
= log
.percentage_used
;
1422 smart
->data_units_read_lo
= le64_to_cpu(log
.data_units_read
[0]);
1423 smart
->data_units_read_hi
= le64_to_cpu(log
.data_units_read
[1]);
1424 smart
->data_units_written_lo
= le64_to_cpu(log
.data_units_written
[0]);
1425 smart
->data_units_written_hi
= le64_to_cpu(log
.data_units_written
[1]);
1426 smart
->host_read_commands_lo
= le64_to_cpu(log
.host_read_commands
[0]);
1427 smart
->host_read_commands_hi
= le64_to_cpu(log
.host_read_commands
[1]);
1428 smart
->host_write_commands_lo
= le64_to_cpu(log
.host_write_commands
[0]);
1429 smart
->host_write_commands_hi
= le64_to_cpu(log
.host_write_commands
[1]);
1430 smart
->controller_busy_time_lo
= le64_to_cpu(log
.controller_busy_time
[0]);
1431 smart
->controller_busy_time_hi
= le64_to_cpu(log
.controller_busy_time
[1]);
1432 smart
->power_cycles_lo
= le64_to_cpu(log
.power_cycles
[0]);
1433 smart
->power_cycles_hi
= le64_to_cpu(log
.power_cycles
[1]);
1434 smart
->power_on_hours_lo
= le64_to_cpu(log
.power_on_hours
[0]);
1435 smart
->power_on_hours_hi
= le64_to_cpu(log
.power_on_hours
[1]);
1436 smart
->unsafe_shutdowns_lo
= le64_to_cpu(log
.unsafe_shutdowns
[0]);
1437 smart
->unsafe_shutdowns_hi
= le64_to_cpu(log
.unsafe_shutdowns
[1]);
1438 smart
->media_errors_lo
= le64_to_cpu(log
.media_errors
[0]);
1439 smart
->media_errors_hi
= le64_to_cpu(log
.media_errors
[1]);
1440 smart
->number_of_error_log_entries_lo
=
1441 le64_to_cpu(log
.number_of_error_log_entries
[0]);
1442 smart
->number_of_error_log_entries_hi
=
1443 le64_to_cpu(log
.number_of_error_log_entries
[1]);
1448 static void get_disk_smart(GuestDiskInfo
*disk
)
1451 && (disk
->address
->bus_type
== GUEST_DISK_BUS_TYPE_NVME
)) {
1452 get_nvme_smart(disk
);
1456 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1458 GuestDiskInfoList
*ret
= NULL
;
1459 GuestDiskInfo
*disk
;
1461 struct dirent
*de
= NULL
;
1463 g_debug("listing /sys/block directory");
1464 dp
= opendir("/sys/block");
1466 error_setg_errno(errp
, errno
, "Can't open directory \"/sys/block\"");
1469 while ((de
= readdir(dp
)) != NULL
) {
1470 g_autofree
char *disk_dir
= NULL
, *line
= NULL
,
1473 Error
*local_err
= NULL
;
1474 if (de
->d_type
!= DT_LNK
) {
1475 g_debug(" skipping entry: %s", de
->d_name
);
1479 /* Check size and skip zero-sized disks */
1480 g_debug(" checking disk size");
1481 size_path
= g_strdup_printf("/sys/block/%s/size", de
->d_name
);
1482 if (!g_file_get_contents(size_path
, &line
, NULL
, NULL
)) {
1483 g_debug(" failed to read disk size");
1486 if (g_strcmp0(line
, "0\n") == 0) {
1487 g_debug(" skipping zero-sized disk");
1491 g_debug(" adding %s", de
->d_name
);
1492 disk_dir
= g_strdup_printf("/sys/block/%s", de
->d_name
);
1493 dev_name
= get_device_for_syspath(disk_dir
);
1494 if (dev_name
== NULL
) {
1495 g_debug("Failed to get device name for syspath: %s",
1499 disk
= g_new0(GuestDiskInfo
, 1);
1500 disk
->name
= dev_name
;
1501 disk
->partition
= false;
1502 disk
->alias
= get_alias_for_syspath(disk_dir
);
1503 QAPI_LIST_PREPEND(ret
, disk
);
1505 /* Get address for non-virtual devices */
1506 bool is_virtual
= is_disk_virtual(disk_dir
, &local_err
);
1507 if (local_err
!= NULL
) {
1508 g_debug(" failed to check disk path, ignoring error: %s",
1509 error_get_pretty(local_err
));
1510 error_free(local_err
);
1512 /* Don't try to get the address */
1516 disk
->address
= get_disk_address(disk_dir
, &local_err
);
1517 if (local_err
!= NULL
) {
1518 g_debug(" failed to get device info, ignoring error: %s",
1519 error_get_pretty(local_err
));
1520 error_free(local_err
);
1525 get_disk_deps(disk_dir
, disk
);
1526 get_disk_smart(disk
);
1527 ret
= get_disk_partitions(ret
, de
->d_name
, disk_dir
, dev_name
);
1537 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1539 error_setg(errp
, QERR_UNSUPPORTED
);
1545 /* Return a list of the disk device(s)' info which @mount lies on */
1546 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1549 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1551 unsigned long used
, nonroot_total
, fr_size
;
1552 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1553 mount
->devmajor
, mount
->devminor
);
1555 fs
->mountpoint
= g_strdup(mount
->dirname
);
1556 fs
->type
= g_strdup(mount
->devtype
);
1557 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1559 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1560 fr_size
= buf
.f_frsize
;
1561 used
= buf
.f_blocks
- buf
.f_bfree
;
1562 nonroot_total
= used
+ buf
.f_bavail
;
1563 fs
->used_bytes
= used
* fr_size
;
1564 fs
->total_bytes
= nonroot_total
* fr_size
;
1566 fs
->has_total_bytes
= true;
1567 fs
->has_used_bytes
= true;
1575 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1578 struct FsMount
*mount
;
1579 GuestFilesystemInfoList
*ret
= NULL
;
1580 Error
*local_err
= NULL
;
1582 QTAILQ_INIT(&mounts
);
1583 if (!build_fs_mount_list(&mounts
, &local_err
)) {
1584 error_propagate(errp
, local_err
);
1588 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1589 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1591 QAPI_LIST_PREPEND(ret
, build_guest_fsinfo(mount
, &local_err
));
1593 error_propagate(errp
, local_err
);
1594 qapi_free_GuestFilesystemInfoList(ret
);
1600 free_fs_mount_list(&mounts
);
1603 #endif /* CONFIG_FSFREEZE */
1605 #if defined(CONFIG_FSTRIM)
1607 * Walk list of mounted file systems in the guest, and trim them.
1609 GuestFilesystemTrimResponse
*
1610 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1612 GuestFilesystemTrimResponse
*response
;
1613 GuestFilesystemTrimResult
*result
;
1616 struct FsMount
*mount
;
1618 struct fstrim_range r
;
1620 slog("guest-fstrim called");
1622 QTAILQ_INIT(&mounts
);
1623 if (!build_fs_mount_list(&mounts
, errp
)) {
1627 response
= g_malloc0(sizeof(*response
));
1629 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1630 result
= g_malloc0(sizeof(*result
));
1631 result
->path
= g_strdup(mount
->dirname
);
1633 QAPI_LIST_PREPEND(response
->paths
, result
);
1635 fd
= qga_open_cloexec(mount
->dirname
, O_RDONLY
, 0);
1637 result
->error
= g_strdup_printf("failed to open: %s",
1642 /* We try to cull filesystems we know won't work in advance, but other
1643 * filesystems may not implement fstrim for less obvious reasons.
1644 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1645 * will be reported (e.g. CD-ROMs).
1646 * Any other error means an unexpected error.
1650 r
.minlen
= has_minimum
? minimum
: 0;
1651 ret
= ioctl(fd
, FITRIM
, &r
);
1653 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1654 result
->error
= g_strdup("trim not supported");
1656 result
->error
= g_strdup_printf("failed to trim: %s",
1663 result
->has_minimum
= true;
1664 result
->minimum
= r
.minlen
;
1665 result
->has_trimmed
= true;
1666 result
->trimmed
= r
.len
;
1670 free_fs_mount_list(&mounts
);
1673 #endif /* CONFIG_FSTRIM */
1676 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1677 #define SUSPEND_SUPPORTED 0
1678 #define SUSPEND_NOT_SUPPORTED 1
1681 SUSPEND_MODE_DISK
= 0,
1682 SUSPEND_MODE_RAM
= 1,
1683 SUSPEND_MODE_HYBRID
= 2,
1687 * Executes a command in a child process using g_spawn_sync,
1688 * returning an int >= 0 representing the exit status of the
1691 * If the program wasn't found in path, returns -1.
1693 * If a problem happened when creating the child process,
1694 * returns -1 and errp is set.
1696 static int run_process_child(const char *command
[], Error
**errp
)
1698 int exit_status
, spawn_flag
;
1699 GError
*g_err
= NULL
;
1702 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1703 G_SPAWN_STDERR_TO_DEV_NULL
;
1705 success
= g_spawn_sync(NULL
, (char **)command
, NULL
, spawn_flag
,
1706 NULL
, NULL
, NULL
, NULL
,
1707 &exit_status
, &g_err
);
1710 return WEXITSTATUS(exit_status
);
1713 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1714 error_setg(errp
, "failed to create child process, error '%s'",
1718 g_error_free(g_err
);
1722 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1724 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1725 "systemd-hybrid-sleep"};
1726 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
1729 status
= run_process_child(cmd
, errp
);
1732 * systemctl status uses LSB return codes so we can expect
1733 * status > 0 and be ok. To assert if the guest has support
1734 * for the selected suspend mode, status should be < 4. 4 is
1735 * the code for unknown service status, the return value when
1736 * the service does not exist. A common value is status = 3
1737 * (program is not running).
1739 if (status
> 0 && status
< 4) {
1746 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
1748 Error
*local_err
= NULL
;
1749 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
1750 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
1753 status
= run_process_child(cmd
, &local_err
);
1759 if ((status
== -1) && !local_err
) {
1760 error_setg(errp
, "the helper program 'systemctl %s' was not found",
1761 systemctl_args
[mode
]);
1766 error_propagate(errp
, local_err
);
1768 error_setg(errp
, "the helper program 'systemctl %s' returned an "
1769 "unexpected exit status code (%d)",
1770 systemctl_args
[mode
], status
);
1774 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
1776 Error
*local_err
= NULL
;
1777 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
1778 "--suspend-hybrid"};
1779 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
1782 status
= run_process_child(cmd
, &local_err
);
1784 if (status
== SUSPEND_SUPPORTED
) {
1788 if ((status
== -1) && !local_err
) {
1793 error_propagate(errp
, local_err
);
1796 "the helper program '%s' returned an unexpected exit"
1797 " status code (%d)", "pm-is-supported", status
);
1803 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
1805 Error
*local_err
= NULL
;
1806 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
1807 "pm-suspend-hybrid"};
1808 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
1811 status
= run_process_child(cmd
, &local_err
);
1817 if ((status
== -1) && !local_err
) {
1818 error_setg(errp
, "the helper program '%s' was not found",
1819 pmutils_binaries
[mode
]);
1824 error_propagate(errp
, local_err
);
1827 "the helper program '%s' returned an unexpected exit"
1828 " status code (%d)", pmutils_binaries
[mode
], status
);
1832 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
1834 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1835 const char *sysfile_str
= sysfile_strs
[mode
];
1836 char buf
[32]; /* hopefully big enough */
1841 error_setg(errp
, "unknown guest suspend mode");
1845 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1850 ret
= read(fd
, buf
, sizeof(buf
) - 1);
1857 if (strstr(buf
, sysfile_str
)) {
1863 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
1865 Error
*local_err
= NULL
;
1866 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1867 const char *sysfile_str
= sysfile_strs
[mode
];
1872 error_setg(errp
, "unknown guest suspend mode");
1882 reopen_fd_to_null(0);
1883 reopen_fd_to_null(1);
1884 reopen_fd_to_null(2);
1886 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1888 _exit(EXIT_FAILURE
);
1891 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1892 _exit(EXIT_FAILURE
);
1895 _exit(EXIT_SUCCESS
);
1896 } else if (pid
< 0) {
1897 error_setg_errno(errp
, errno
, "failed to create child process");
1901 ga_wait_child(pid
, &status
, &local_err
);
1903 error_propagate(errp
, local_err
);
1907 if (WEXITSTATUS(status
)) {
1908 error_setg(errp
, "child process has failed to suspend");
1913 static void guest_suspend(SuspendMode mode
, Error
**errp
)
1915 Error
*local_err
= NULL
;
1916 bool mode_supported
= false;
1918 if (systemd_supports_mode(mode
, &local_err
)) {
1919 mode_supported
= true;
1920 systemd_suspend(mode
, &local_err
);
1927 error_free(local_err
);
1930 if (pmutils_supports_mode(mode
, &local_err
)) {
1931 mode_supported
= true;
1932 pmutils_suspend(mode
, &local_err
);
1939 error_free(local_err
);
1942 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
1943 mode_supported
= true;
1944 linux_sys_state_suspend(mode
, &local_err
);
1947 if (!mode_supported
) {
1948 error_free(local_err
);
1950 "the requested suspend mode is not supported by the guest");
1952 error_propagate(errp
, local_err
);
1956 void qmp_guest_suspend_disk(Error
**errp
)
1958 guest_suspend(SUSPEND_MODE_DISK
, errp
);
1961 void qmp_guest_suspend_ram(Error
**errp
)
1963 guest_suspend(SUSPEND_MODE_RAM
, errp
);
1966 void qmp_guest_suspend_hybrid(Error
**errp
)
1968 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
1971 /* Transfer online/offline status between @vcpu and the guest system.
1973 * On input either @errp or *@errp must be NULL.
1975 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1976 * - R: vcpu->logical_id
1978 * - W: vcpu->can_offline
1980 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1981 * - R: vcpu->logical_id
1984 * Written members remain unmodified on error.
1986 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1987 char *dirpath
, Error
**errp
)
1992 static const char fn
[] = "online";
1994 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
1996 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2000 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2002 if (errno
!= ENOENT
) {
2003 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2004 } else if (sys2vcpu
) {
2005 vcpu
->online
= true;
2006 vcpu
->can_offline
= false;
2007 } else if (!vcpu
->online
) {
2008 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2009 "offlined", vcpu
->logical_id
);
2010 } /* otherwise pretend successful re-onlining */
2012 unsigned char status
;
2014 res
= pread(fd
, &status
, 1, 0);
2016 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2017 } else if (res
== 0) {
2018 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2020 } else if (sys2vcpu
) {
2021 vcpu
->online
= (status
!= '0');
2022 vcpu
->can_offline
= true;
2023 } else if (vcpu
->online
!= (status
!= '0')) {
2024 status
= '0' + vcpu
->online
;
2025 if (pwrite(fd
, &status
, 1, 0) == -1) {
2026 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2029 } /* otherwise pretend successful re-(on|off)-lining */
2039 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2041 GuestLogicalProcessorList
*head
, **tail
;
2042 const char *cpu_dir
= "/sys/devices/system/cpu";
2044 g_autoptr(GDir
) cpu_gdir
= NULL
;
2045 Error
*local_err
= NULL
;
2049 cpu_gdir
= g_dir_open(cpu_dir
, 0, NULL
);
2051 if (cpu_gdir
== NULL
) {
2052 error_setg_errno(errp
, errno
, "failed to list entries: %s", cpu_dir
);
2056 while (local_err
== NULL
&& (line
= g_dir_read_name(cpu_gdir
)) != NULL
) {
2057 GuestLogicalProcessor
*vcpu
;
2059 if (sscanf(line
, "cpu%" PRId64
, &id
)) {
2060 g_autofree
char *path
= g_strdup_printf("/sys/devices/system/cpu/"
2061 "cpu%" PRId64
"/", id
);
2062 vcpu
= g_malloc0(sizeof *vcpu
);
2063 vcpu
->logical_id
= id
;
2064 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2065 transfer_vcpu(vcpu
, true, path
, &local_err
);
2066 QAPI_LIST_APPEND(tail
, vcpu
);
2070 if (local_err
== NULL
) {
2071 /* there's no guest with zero VCPUs */
2072 g_assert(head
!= NULL
);
2076 qapi_free_GuestLogicalProcessorList(head
);
2077 error_propagate(errp
, local_err
);
2081 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2084 Error
*local_err
= NULL
;
2087 while (vcpus
!= NULL
) {
2088 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2089 vcpus
->value
->logical_id
);
2091 transfer_vcpu(vcpus
->value
, false, path
, &local_err
);
2093 if (local_err
!= NULL
) {
2097 vcpus
= vcpus
->next
;
2100 if (local_err
!= NULL
) {
2101 if (processed
== 0) {
2102 error_propagate(errp
, local_err
);
2104 error_free(local_err
);
2110 #endif /* __linux__ */
2112 #if defined(__linux__) || defined(__FreeBSD__)
2113 void qmp_guest_set_user_password(const char *username
,
2114 const char *password
,
2118 Error
*local_err
= NULL
;
2119 char *passwd_path
= NULL
;
2122 int datafd
[2] = { -1, -1 };
2123 char *rawpasswddata
= NULL
;
2124 size_t rawpasswdlen
;
2125 char *chpasswddata
= NULL
;
2128 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2129 if (!rawpasswddata
) {
2132 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2133 rawpasswddata
[rawpasswdlen
] = '\0';
2135 if (strchr(rawpasswddata
, '\n')) {
2136 error_setg(errp
, "forbidden characters in raw password");
2140 if (strchr(username
, '\n') ||
2141 strchr(username
, ':')) {
2142 error_setg(errp
, "forbidden characters in username");
2147 chpasswddata
= g_strdup(rawpasswddata
);
2148 passwd_path
= g_find_program_in_path("pw");
2150 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
2151 passwd_path
= g_find_program_in_path("chpasswd");
2154 chpasswdlen
= strlen(chpasswddata
);
2157 error_setg(errp
, "cannot find 'passwd' program in PATH");
2161 if (!g_unix_open_pipe(datafd
, FD_CLOEXEC
, NULL
)) {
2162 error_setg(errp
, "cannot create pipe FDs");
2172 reopen_fd_to_null(1);
2173 reopen_fd_to_null(2);
2177 h_arg
= (crypted
) ? "-H" : "-h";
2178 execl(passwd_path
, "pw", "usermod", "-n", username
, h_arg
, "0", NULL
);
2181 execl(passwd_path
, "chpasswd", "-e", NULL
);
2183 execl(passwd_path
, "chpasswd", NULL
);
2186 _exit(EXIT_FAILURE
);
2187 } else if (pid
< 0) {
2188 error_setg_errno(errp
, errno
, "failed to create child process");
2194 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2195 error_setg_errno(errp
, errno
, "cannot write new account password");
2201 ga_wait_child(pid
, &status
, &local_err
);
2203 error_propagate(errp
, local_err
);
2207 if (!WIFEXITED(status
)) {
2208 error_setg(errp
, "child process has terminated abnormally");
2212 if (WEXITSTATUS(status
)) {
2213 error_setg(errp
, "child process has failed to set user password");
2218 g_free(chpasswddata
);
2219 g_free(rawpasswddata
);
2220 g_free(passwd_path
);
2221 if (datafd
[0] != -1) {
2224 if (datafd
[1] != -1) {
2228 #else /* __linux__ || __FreeBSD__ */
2229 void qmp_guest_set_user_password(const char *username
,
2230 const char *password
,
2234 error_setg(errp
, QERR_UNSUPPORTED
);
2236 #endif /* __linux__ || __FreeBSD__ */
2239 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2240 int size
, Error
**errp
)
2246 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2248 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2252 res
= pread(fd
, buf
, size
, 0);
2254 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2255 } else if (res
== 0) {
2256 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2261 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2262 const char *buf
, int size
, Error
**errp
)
2267 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2269 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2273 if (pwrite(fd
, buf
, size
, 0) == -1) {
2274 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2280 /* Transfer online/offline status between @mem_blk and the guest system.
2282 * On input either @errp or *@errp must be NULL.
2284 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2285 * - R: mem_blk->phys_index
2286 * - W: mem_blk->online
2287 * - W: mem_blk->can_offline
2289 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2290 * - R: mem_blk->phys_index
2291 * - R: mem_blk->online
2292 *- R: mem_blk->can_offline
2293 * Written members remain unmodified on error.
2295 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2296 GuestMemoryBlockResponse
*result
,
2302 Error
*local_err
= NULL
;
2308 error_setg(errp
, "Internal error, 'result' should not be NULL");
2312 dp
= opendir("/sys/devices/system/memory/");
2313 /* if there is no 'memory' directory in sysfs,
2314 * we think this VM does not support online/offline memory block,
2315 * any other solution?
2318 if (errno
== ENOENT
) {
2320 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2327 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2328 mem_blk
->phys_index
);
2329 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2332 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2334 if (errno
== ENOENT
) {
2335 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2338 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2346 status
= g_malloc0(10);
2347 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2349 /* treat with sysfs file that not exist in old kernel */
2350 if (errno
== ENOENT
) {
2351 error_free(local_err
);
2353 mem_blk
->online
= true;
2354 mem_blk
->can_offline
= false;
2355 } else if (!mem_blk
->online
) {
2357 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2361 error_propagate(errp
, local_err
);
2363 error_free(local_err
);
2365 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2372 char removable
= '0';
2374 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2376 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2378 /* if no 'removable' file, it doesn't support offline mem blk */
2379 if (errno
== ENOENT
) {
2380 error_free(local_err
);
2381 mem_blk
->can_offline
= false;
2383 error_propagate(errp
, local_err
);
2386 mem_blk
->can_offline
= (removable
!= '0');
2389 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2390 const char *new_state
= mem_blk
->online
? "online" : "offline";
2392 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2395 error_free(local_err
);
2397 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2401 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2402 result
->has_error_code
= false;
2403 } /* otherwise pretend successful re-(on|off)-lining */
2414 result
->has_error_code
= true;
2415 result
->error_code
= errno
;
2419 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2421 GuestMemoryBlockList
*head
, **tail
;
2422 Error
*local_err
= NULL
;
2429 dp
= opendir("/sys/devices/system/memory/");
2431 /* it's ok if this happens to be a system that doesn't expose
2432 * memory blocks via sysfs, but otherwise we should report
2435 if (errno
!= ENOENT
) {
2436 error_setg_errno(errp
, errno
, "Can't open directory"
2437 "\"/sys/devices/system/memory/\"");
2442 /* Note: the phys_index of memory block may be discontinuous,
2443 * this is because a memblk is the unit of the Sparse Memory design, which
2444 * allows discontinuous memory ranges (ex. NUMA), so here we should
2445 * traverse the memory block directory.
2447 while ((de
= readdir(dp
)) != NULL
) {
2448 GuestMemoryBlock
*mem_blk
;
2450 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2451 !(de
->d_type
& DT_DIR
)) {
2455 mem_blk
= g_malloc0(sizeof *mem_blk
);
2456 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2457 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2458 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2459 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2464 QAPI_LIST_APPEND(tail
, mem_blk
);
2468 if (local_err
== NULL
) {
2469 /* there's no guest with zero memory blocks */
2471 error_setg(errp
, "guest reported zero memory blocks!");
2476 qapi_free_GuestMemoryBlockList(head
);
2477 error_propagate(errp
, local_err
);
2481 GuestMemoryBlockResponseList
*
2482 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2484 GuestMemoryBlockResponseList
*head
, **tail
;
2485 Error
*local_err
= NULL
;
2490 while (mem_blks
!= NULL
) {
2491 GuestMemoryBlockResponse
*result
;
2492 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2494 result
= g_malloc0(sizeof(*result
));
2495 result
->phys_index
= current_mem_blk
->phys_index
;
2496 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2497 if (local_err
) { /* should never happen */
2501 QAPI_LIST_APPEND(tail
, result
);
2502 mem_blks
= mem_blks
->next
;
2507 qapi_free_GuestMemoryBlockResponseList(head
);
2508 error_propagate(errp
, local_err
);
2512 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2514 Error
*local_err
= NULL
;
2518 GuestMemoryBlockInfo
*info
;
2520 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2521 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2523 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2529 buf
= g_malloc0(20);
2530 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2534 error_propagate(errp
, local_err
);
2538 info
= g_new0(GuestMemoryBlockInfo
, 1);
2539 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2546 #define MAX_NAME_LEN 128
2547 static GuestDiskStatsInfoList
*guest_get_diskstats(Error
**errp
)
2550 GuestDiskStatsInfoList
*head
= NULL
, **tail
= &head
;
2551 const char *diskstats
= "/proc/diskstats";
2556 fp
= fopen(diskstats
, "r");
2558 error_setg_errno(errp
, errno
, "open(\"%s\")", diskstats
);
2562 while (getline(&line
, &n
, fp
) != -1) {
2563 g_autofree GuestDiskStatsInfo
*diskstatinfo
= NULL
;
2564 g_autofree GuestDiskStats
*diskstat
= NULL
;
2565 char dev_name
[MAX_NAME_LEN
];
2566 unsigned int ios_pgr
, tot_ticks
, rq_ticks
, wr_ticks
, dc_ticks
, fl_ticks
;
2567 unsigned long rd_ios
, rd_merges_or_rd_sec
, rd_ticks_or_wr_sec
, wr_ios
;
2568 unsigned long wr_merges
, rd_sec_or_wr_ios
, wr_sec
;
2569 unsigned long dc_ios
, dc_merges
, dc_sec
, fl_ios
;
2570 unsigned int major
, minor
;
2573 i
= sscanf(line
, "%u %u %s %lu %lu %lu"
2574 "%lu %lu %lu %lu %u %u %u %u"
2575 "%lu %lu %lu %u %lu %u",
2576 &major
, &minor
, dev_name
,
2577 &rd_ios
, &rd_merges_or_rd_sec
, &rd_sec_or_wr_ios
,
2578 &rd_ticks_or_wr_sec
, &wr_ios
, &wr_merges
, &wr_sec
,
2579 &wr_ticks
, &ios_pgr
, &tot_ticks
, &rq_ticks
,
2580 &dc_ios
, &dc_merges
, &dc_sec
, &dc_ticks
,
2581 &fl_ios
, &fl_ticks
);
2587 diskstatinfo
= g_new0(GuestDiskStatsInfo
, 1);
2588 diskstatinfo
->name
= g_strdup(dev_name
);
2589 diskstatinfo
->major
= major
;
2590 diskstatinfo
->minor
= minor
;
2592 diskstat
= g_new0(GuestDiskStats
, 1);
2594 diskstat
->has_read_ios
= true;
2595 diskstat
->read_ios
= rd_ios
;
2596 diskstat
->has_read_sectors
= true;
2597 diskstat
->read_sectors
= rd_merges_or_rd_sec
;
2598 diskstat
->has_write_ios
= true;
2599 diskstat
->write_ios
= rd_sec_or_wr_ios
;
2600 diskstat
->has_write_sectors
= true;
2601 diskstat
->write_sectors
= rd_ticks_or_wr_sec
;
2604 diskstat
->has_read_ios
= true;
2605 diskstat
->read_ios
= rd_ios
;
2606 diskstat
->has_read_sectors
= true;
2607 diskstat
->read_sectors
= rd_sec_or_wr_ios
;
2608 diskstat
->has_read_merges
= true;
2609 diskstat
->read_merges
= rd_merges_or_rd_sec
;
2610 diskstat
->has_read_ticks
= true;
2611 diskstat
->read_ticks
= rd_ticks_or_wr_sec
;
2612 diskstat
->has_write_ios
= true;
2613 diskstat
->write_ios
= wr_ios
;
2614 diskstat
->has_write_sectors
= true;
2615 diskstat
->write_sectors
= wr_sec
;
2616 diskstat
->has_write_merges
= true;
2617 diskstat
->write_merges
= wr_merges
;
2618 diskstat
->has_write_ticks
= true;
2619 diskstat
->write_ticks
= wr_ticks
;
2620 diskstat
->has_ios_pgr
= true;
2621 diskstat
->ios_pgr
= ios_pgr
;
2622 diskstat
->has_total_ticks
= true;
2623 diskstat
->total_ticks
= tot_ticks
;
2624 diskstat
->has_weight_ticks
= true;
2625 diskstat
->weight_ticks
= rq_ticks
;
2628 diskstat
->has_discard_ios
= true;
2629 diskstat
->discard_ios
= dc_ios
;
2630 diskstat
->has_discard_merges
= true;
2631 diskstat
->discard_merges
= dc_merges
;
2632 diskstat
->has_discard_sectors
= true;
2633 diskstat
->discard_sectors
= dc_sec
;
2634 diskstat
->has_discard_ticks
= true;
2635 diskstat
->discard_ticks
= dc_ticks
;
2638 diskstat
->has_flush_ios
= true;
2639 diskstat
->flush_ios
= fl_ios
;
2640 diskstat
->has_flush_ticks
= true;
2641 diskstat
->flush_ticks
= fl_ticks
;
2644 diskstatinfo
->stats
= g_steal_pointer(&diskstat
);
2645 QAPI_LIST_APPEND(tail
, diskstatinfo
);
2646 diskstatinfo
= NULL
;
2652 g_debug("disk stats reporting available only for Linux");
2657 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
2659 return guest_get_diskstats(errp
);
2662 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
2664 GuestCpuStatsList
*head
= NULL
, **tail
= &head
;
2665 const char *cpustats
= "/proc/stat";
2666 int clk_tck
= sysconf(_SC_CLK_TCK
);
2671 fp
= fopen(cpustats
, "r");
2673 error_setg_errno(errp
, errno
, "open(\"%s\")", cpustats
);
2677 while (getline(&line
, &n
, fp
) != -1) {
2678 GuestCpuStats
*cpustat
= NULL
;
2679 GuestLinuxCpuStats
*linuxcpustat
;
2681 unsigned long user
, system
, idle
, iowait
, irq
, softirq
, steal
, guest
;
2682 unsigned long nice
, guest_nice
;
2685 i
= sscanf(line
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2686 name
, &user
, &nice
, &system
, &idle
, &iowait
, &irq
, &softirq
,
2687 &steal
, &guest
, &guest_nice
);
2689 /* drop "cpu 1 2 3 ...", get "cpuX 1 2 3 ..." only */
2690 if ((i
== EOF
) || strncmp(name
, "cpu", 3) || (name
[3] == '\0')) {
2695 slog("Parsing cpu stat from %s failed, see \"man proc\"", cpustats
);
2699 cpustat
= g_new0(GuestCpuStats
, 1);
2700 cpustat
->type
= GUEST_CPU_STATS_TYPE_LINUX
;
2702 linuxcpustat
= &cpustat
->u
.q_linux
;
2703 linuxcpustat
->cpu
= atoi(&name
[3]);
2704 linuxcpustat
->user
= user
* 1000 / clk_tck
;
2705 linuxcpustat
->nice
= nice
* 1000 / clk_tck
;
2706 linuxcpustat
->system
= system
* 1000 / clk_tck
;
2707 linuxcpustat
->idle
= idle
* 1000 / clk_tck
;
2710 linuxcpustat
->has_iowait
= true;
2711 linuxcpustat
->iowait
= iowait
* 1000 / clk_tck
;
2715 linuxcpustat
->has_irq
= true;
2716 linuxcpustat
->irq
= irq
* 1000 / clk_tck
;
2717 linuxcpustat
->has_softirq
= true;
2718 linuxcpustat
->softirq
= softirq
* 1000 / clk_tck
;
2722 linuxcpustat
->has_steal
= true;
2723 linuxcpustat
->steal
= steal
* 1000 / clk_tck
;
2727 linuxcpustat
->has_guest
= true;
2728 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2732 linuxcpustat
->has_guest
= true;
2733 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2734 linuxcpustat
->has_guestnice
= true;
2735 linuxcpustat
->guestnice
= guest_nice
* 1000 / clk_tck
;
2738 QAPI_LIST_APPEND(tail
, cpustat
);
2746 #else /* defined(__linux__) */
2748 void qmp_guest_suspend_disk(Error
**errp
)
2750 error_setg(errp
, QERR_UNSUPPORTED
);
2753 void qmp_guest_suspend_ram(Error
**errp
)
2755 error_setg(errp
, QERR_UNSUPPORTED
);
2758 void qmp_guest_suspend_hybrid(Error
**errp
)
2760 error_setg(errp
, QERR_UNSUPPORTED
);
2763 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2765 error_setg(errp
, QERR_UNSUPPORTED
);
2769 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2771 error_setg(errp
, QERR_UNSUPPORTED
);
2775 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2777 error_setg(errp
, QERR_UNSUPPORTED
);
2781 GuestMemoryBlockResponseList
*
2782 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2784 error_setg(errp
, QERR_UNSUPPORTED
);
2788 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2790 error_setg(errp
, QERR_UNSUPPORTED
);
2796 #ifdef HAVE_GETIFADDRS
2797 static GuestNetworkInterface
*
2798 guest_find_interface(GuestNetworkInterfaceList
*head
,
2801 for (; head
; head
= head
->next
) {
2802 if (strcmp(head
->value
->name
, name
) == 0) {
2810 static int guest_get_network_stats(const char *name
,
2811 GuestNetworkInterfaceStat
*stats
)
2815 char const *devinfo
= "/proc/net/dev";
2817 char *line
= NULL
, *colon
;
2819 fp
= fopen(devinfo
, "r");
2821 g_debug("failed to open network stats %s: %s", devinfo
,
2825 name_len
= strlen(name
);
2826 while (getline(&line
, &n
, fp
) != -1) {
2829 long long rx_packets
;
2831 long long rx_dropped
;
2833 long long tx_packets
;
2835 long long tx_dropped
;
2837 trim_line
= g_strchug(line
);
2838 if (trim_line
[0] == '\0') {
2841 colon
= strchr(trim_line
, ':');
2845 if (colon
- name_len
== trim_line
&&
2846 strncmp(trim_line
, name
, name_len
) == 0) {
2847 if (sscanf(colon
+ 1,
2848 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2849 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
2850 &dummy
, &dummy
, &dummy
, &dummy
,
2851 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
2852 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
2855 stats
->rx_bytes
= rx_bytes
;
2856 stats
->rx_packets
= rx_packets
;
2857 stats
->rx_errs
= rx_errs
;
2858 stats
->rx_dropped
= rx_dropped
;
2859 stats
->tx_bytes
= tx_bytes
;
2860 stats
->tx_packets
= tx_packets
;
2861 stats
->tx_errs
= tx_errs
;
2862 stats
->tx_dropped
= tx_dropped
;
2870 g_debug("/proc/net/dev: Interface '%s' not found", name
);
2871 #else /* !CONFIG_LINUX */
2872 g_debug("Network stats reporting available only for Linux");
2873 #endif /* !CONFIG_LINUX */
2879 * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
2880 * buffer with ETHER_ADDR_LEN length at least.
2882 * Returns false in case of an error, otherwise true. "obtained" argument
2883 * is true if a MAC address was obtained successful, otherwise false.
2885 bool guest_get_hw_addr(struct ifaddrs
*ifa
, unsigned char *buf
,
2886 bool *obtained
, Error
**errp
)
2893 /* we haven't obtained HW address yet */
2894 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
2896 error_setg_errno(errp
, errno
, "failed to create socket");
2900 memset(&ifr
, 0, sizeof(ifr
));
2901 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, ifa
->ifa_name
);
2902 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
2904 * We can't get the hw addr of this interface, but that's not a
2907 if (errno
== EADDRNOTAVAIL
) {
2908 /* The interface doesn't have a hw addr (e.g. loopback). */
2909 g_debug("failed to get MAC address of %s: %s",
2910 ifa
->ifa_name
, strerror(errno
));
2912 g_warning("failed to get MAC address of %s: %s",
2913 ifa
->ifa_name
, strerror(errno
));
2916 #ifdef CONFIG_SOLARIS
2917 memcpy(buf
, &ifr
.ifr_addr
.sa_data
, ETHER_ADDR_LEN
);
2919 memcpy(buf
, &ifr
.ifr_hwaddr
.sa_data
, ETHER_ADDR_LEN
);
2926 #endif /* CONFIG_BSD */
2929 * Build information about guest interfaces
2931 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2933 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
2934 struct ifaddrs
*ifap
, *ifa
;
2936 if (getifaddrs(&ifap
) < 0) {
2937 error_setg_errno(errp
, errno
, "getifaddrs failed");
2941 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
2942 GuestNetworkInterface
*info
;
2943 GuestIpAddressList
**address_tail
;
2944 GuestIpAddress
*address_item
= NULL
;
2945 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
2946 char addr4
[INET_ADDRSTRLEN
];
2947 char addr6
[INET6_ADDRSTRLEN
];
2948 unsigned char mac_addr
[ETHER_ADDR_LEN
];
2952 g_debug("Processing %s interface", ifa
->ifa_name
);
2954 info
= guest_find_interface(head
, ifa
->ifa_name
);
2957 info
= g_malloc0(sizeof(*info
));
2958 info
->name
= g_strdup(ifa
->ifa_name
);
2960 QAPI_LIST_APPEND(tail
, info
);
2963 if (!info
->hardware_address
) {
2964 if (!guest_get_hw_addr(ifa
, mac_addr
, &obtained
, errp
)) {
2968 info
->hardware_address
=
2969 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2970 (int) mac_addr
[0], (int) mac_addr
[1],
2971 (int) mac_addr
[2], (int) mac_addr
[3],
2972 (int) mac_addr
[4], (int) mac_addr
[5]);
2976 if (ifa
->ifa_addr
&&
2977 ifa
->ifa_addr
->sa_family
== AF_INET
) {
2978 /* interface with IPv4 address */
2979 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
2980 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
2981 error_setg_errno(errp
, errno
, "inet_ntop failed");
2985 address_item
= g_malloc0(sizeof(*address_item
));
2986 address_item
->ip_address
= g_strdup(addr4
);
2987 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
2989 if (ifa
->ifa_netmask
) {
2990 /* Count the number of set bits in netmask.
2991 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2992 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
2993 address_item
->prefix
= ctpop32(((uint32_t *) p
)[0]);
2995 } else if (ifa
->ifa_addr
&&
2996 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
2997 /* interface with IPv6 address */
2998 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
2999 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
3000 error_setg_errno(errp
, errno
, "inet_ntop failed");
3004 address_item
= g_malloc0(sizeof(*address_item
));
3005 address_item
->ip_address
= g_strdup(addr6
);
3006 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
3008 if (ifa
->ifa_netmask
) {
3009 /* Count the number of set bits in netmask.
3010 * This is safe as '1' and '0' cannot be shuffled in netmask. */
3011 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
3012 address_item
->prefix
=
3013 ctpop32(((uint32_t *) p
)[0]) +
3014 ctpop32(((uint32_t *) p
)[1]) +
3015 ctpop32(((uint32_t *) p
)[2]) +
3016 ctpop32(((uint32_t *) p
)[3]);
3020 if (!address_item
) {
3024 address_tail
= &info
->ip_addresses
;
3025 while (*address_tail
) {
3026 address_tail
= &(*address_tail
)->next
;
3028 QAPI_LIST_APPEND(address_tail
, address_item
);
3030 info
->has_ip_addresses
= true;
3032 if (!info
->statistics
) {
3033 interface_stat
= g_malloc0(sizeof(*interface_stat
));
3034 if (guest_get_network_stats(info
->name
, interface_stat
) == -1) {
3035 g_free(interface_stat
);
3037 info
->statistics
= interface_stat
;
3047 qapi_free_GuestNetworkInterfaceList(head
);
3053 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
3055 error_setg(errp
, QERR_UNSUPPORTED
);
3059 #endif /* HAVE_GETIFADDRS */
3061 #if !defined(CONFIG_FSFREEZE)
3063 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
3065 error_setg(errp
, QERR_UNSUPPORTED
);
3069 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
3071 error_setg(errp
, QERR_UNSUPPORTED
);
3076 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
3078 error_setg(errp
, QERR_UNSUPPORTED
);
3083 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
3084 strList
*mountpoints
,
3087 error_setg(errp
, QERR_UNSUPPORTED
);
3092 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
3094 error_setg(errp
, QERR_UNSUPPORTED
);
3099 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
3101 error_setg(errp
, QERR_UNSUPPORTED
);
3105 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
3107 error_setg(errp
, QERR_UNSUPPORTED
);
3111 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
3113 error_setg(errp
, QERR_UNSUPPORTED
);
3117 #endif /* CONFIG_FSFREEZE */
3119 #if !defined(CONFIG_FSTRIM)
3120 GuestFilesystemTrimResponse
*
3121 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
3123 error_setg(errp
, QERR_UNSUPPORTED
);
3128 /* add unsupported commands to the list of blocked RPCs */
3129 GList
*ga_command_init_blockedrpcs(GList
*blockedrpcs
)
3131 #if !defined(__linux__)
3133 const char *list
[] = {
3134 "guest-suspend-disk", "guest-suspend-ram",
3135 "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
3136 "guest-get-memory-blocks", "guest-set-memory-blocks",
3137 "guest-get-memory-block-size", "guest-get-memory-block-info",
3139 char **p
= (char **)list
;
3142 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3147 #if !defined(HAVE_GETIFADDRS)
3148 blockedrpcs
= g_list_append(blockedrpcs
,
3149 g_strdup("guest-network-get-interfaces"));
3152 #if !defined(CONFIG_FSFREEZE)
3154 const char *list
[] = {
3155 "guest-get-fsinfo", "guest-fsfreeze-status",
3156 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3157 "guest-fsfreeze-thaw", "guest-get-fsinfo",
3158 "guest-get-disks", NULL
};
3159 char **p
= (char **)list
;
3162 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3167 #if !defined(CONFIG_FSTRIM)
3168 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-fstrim"));
3171 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-get-devices"));
3176 /* register init/cleanup routines for stateful command groups */
3177 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
3179 #if defined(CONFIG_FSFREEZE)
3180 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
3186 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3188 static double ga_get_login_time(struct utmpx
*user_info
)
3190 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
3191 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
3192 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
3193 return seconds
+ useconds
;
3196 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3198 GHashTable
*cache
= NULL
;
3199 GuestUserList
*head
= NULL
, **tail
= &head
;
3200 struct utmpx
*user_info
= NULL
;
3201 gpointer value
= NULL
;
3202 GuestUser
*user
= NULL
;
3203 double login_time
= 0;
3205 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
3209 user_info
= getutxent();
3210 if (user_info
== NULL
) {
3212 } else if (user_info
->ut_type
!= USER_PROCESS
) {
3214 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
3215 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
3216 user
= (GuestUser
*)value
;
3217 login_time
= ga_get_login_time(user_info
);
3218 /* We're ensuring the earliest login time to be sent */
3219 if (login_time
< user
->login_time
) {
3220 user
->login_time
= login_time
;
3225 user
= g_new0(GuestUser
, 1);
3226 user
->user
= g_strdup(user_info
->ut_user
);
3227 user
->login_time
= ga_get_login_time(user_info
);
3229 g_hash_table_insert(cache
, user
->user
, user
);
3231 QAPI_LIST_APPEND(tail
, user
);
3234 g_hash_table_destroy(cache
);
3240 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3242 error_setg(errp
, QERR_UNSUPPORTED
);
3248 /* Replace escaped special characters with theire real values. The replacement
3249 * is done in place -- returned value is in the original string.
3251 static void ga_osrelease_replace_special(gchar
*value
)
3253 gchar
*p
, *p2
, quote
;
3255 /* Trim the string at first space or semicolon if it is not enclosed in
3256 * single or double quotes. */
3257 if ((value
[0] != '"') || (value
[0] == '\'')) {
3258 p
= strchr(value
, ' ');
3262 p
= strchr(value
, ';');
3283 /* Keep literal backslash followed by whatever is there */
3287 } else if (*p
== quote
) {
3295 static GKeyFile
*ga_parse_osrelease(const char *fname
)
3297 gchar
*content
= NULL
;
3298 gchar
*content2
= NULL
;
3300 GKeyFile
*keys
= g_key_file_new();
3301 const char *group
= "[os-release]\n";
3303 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
3304 slog("failed to read '%s', error: %s", fname
, err
->message
);
3308 if (!g_utf8_validate(content
, -1, NULL
)) {
3309 slog("file is not utf-8 encoded: %s", fname
);
3312 content2
= g_strdup_printf("%s%s", group
, content
);
3314 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
3316 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
3328 g_key_file_free(keys
);
3332 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
3334 GuestOSInfo
*info
= NULL
;
3335 struct utsname kinfo
;
3336 GKeyFile
*osrelease
= NULL
;
3337 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
3339 info
= g_new0(GuestOSInfo
, 1);
3341 if (uname(&kinfo
) != 0) {
3342 error_setg_errno(errp
, errno
, "uname failed");
3344 info
->kernel_version
= g_strdup(kinfo
.version
);
3345 info
->kernel_release
= g_strdup(kinfo
.release
);
3346 info
->machine
= g_strdup(kinfo
.machine
);
3349 if (qga_os_release
!= NULL
) {
3350 osrelease
= ga_parse_osrelease(qga_os_release
);
3352 osrelease
= ga_parse_osrelease("/etc/os-release");
3353 if (osrelease
== NULL
) {
3354 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
3358 if (osrelease
!= NULL
) {
3361 #define GET_FIELD(field, osfield) do { \
3362 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3363 if (value != NULL) { \
3364 ga_osrelease_replace_special(value); \
3365 info->field = value; \
3368 GET_FIELD(id
, "ID");
3369 GET_FIELD(name
, "NAME");
3370 GET_FIELD(pretty_name
, "PRETTY_NAME");
3371 GET_FIELD(version
, "VERSION");
3372 GET_FIELD(version_id
, "VERSION_ID");
3373 GET_FIELD(variant
, "VARIANT");
3374 GET_FIELD(variant_id
, "VARIANT_ID");
3377 g_key_file_free(osrelease
);
3383 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
3385 error_setg(errp
, QERR_UNSUPPORTED
);
3390 #ifndef HOST_NAME_MAX
3391 # ifdef _POSIX_HOST_NAME_MAX
3392 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
3394 # define HOST_NAME_MAX 255
3398 char *qga_get_host_name(Error
**errp
)
3401 g_autofree
char *hostname
= NULL
;
3403 #ifdef _SC_HOST_NAME_MAX
3404 len
= sysconf(_SC_HOST_NAME_MAX
);
3405 #endif /* _SC_HOST_NAME_MAX */
3408 len
= HOST_NAME_MAX
;
3411 /* Unfortunately, gethostname() below does not guarantee a
3412 * NULL terminated string. Therefore, allocate one byte more
3414 hostname
= g_new0(char, len
+ 1);
3416 if (gethostname(hostname
, len
) < 0) {
3417 error_setg_errno(errp
, errno
,
3418 "cannot get hostname");
3422 return g_steal_pointer(&hostname
);