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") ||
883 g_str_equal(driver
, "xhci_hcd") ||
884 g_str_equal(driver
, "ehci-pci"))) {
889 if (sscanf(p
, "/%x:%x:%x.%x%n",
890 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
895 g_debug("unsupported driver or sysfs path '%s'", syspath
);
899 p
= strstr(syspath
, "/target");
900 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
901 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
905 p
= strstr(syspath
, "/ata");
910 p
= strstr(syspath
, "/host");
913 if (p
&& sscanf(q
, "%u", &host
) == 1) {
915 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
916 ARRAY_SIZE(hosts
), errp
);
922 pciaddr
->domain
= pci
[0];
923 pciaddr
->bus
= pci
[1];
924 pciaddr
->slot
= pci
[2];
925 pciaddr
->function
= pci
[3];
927 if (strcmp(driver
, "ata_piix") == 0) {
928 /* a host per ide bus, target*:0:<unit>:0 */
929 if (!has_host
|| !has_tgt
) {
930 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
933 for (i
= 0; i
< nhosts
; i
++) {
934 if (host
== hosts
[i
]) {
935 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
942 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
945 } else if (strcmp(driver
, "sym53c8xx") == 0) {
946 /* scsi(LSI Logic): target*:0:<unit>:0 */
948 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
951 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
953 } else if (strcmp(driver
, "virtio-pci") == 0) {
955 /* virtio-scsi: target*:0:0:<unit> */
956 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
959 /* virtio-blk: 1 disk per 1 device */
960 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
962 } else if (strcmp(driver
, "ahci") == 0) {
963 /* ahci: 1 host per 1 unit */
964 if (!has_host
|| !has_tgt
) {
965 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
968 for (i
= 0; i
< nhosts
; i
++) {
969 if (host
== hosts
[i
]) {
971 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
976 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
979 } else if (strcmp(driver
, "nvme") == 0) {
980 disk
->bus_type
= GUEST_DISK_BUS_TYPE_NVME
;
981 } else if (strcmp(driver
, "ehci-pci") == 0 || strcmp(driver
, "xhci_hcd") == 0) {
982 disk
->bus_type
= GUEST_DISK_BUS_TYPE_USB
;
984 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
996 * Store disk device info for non-PCI virtio devices (for example s390x
997 * channel I/O devices). Returns true if information has been stored, or
1000 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath
,
1001 GuestDiskAddress
*disk
,
1004 unsigned int tgt
[3];
1007 if (!strstr(syspath
, "/virtio") || !strstr(syspath
, "/block")) {
1008 g_debug("Unsupported virtio device '%s'", syspath
);
1012 p
= strstr(syspath
, "/target");
1013 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1014 &tgt
[0], &tgt
[1], &tgt
[2]) == 3) {
1015 /* virtio-scsi: target*:0:<target>:<unit> */
1016 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1018 disk
->target
= tgt
[1];
1019 disk
->unit
= tgt
[2];
1021 /* virtio-blk: 1 disk per 1 device */
1022 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
1029 * Store disk device info for CCW devices (s390x channel I/O devices).
1030 * Returns true if information has been stored, or false for failure.
1032 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath
,
1033 GuestDiskAddress
*disk
,
1036 unsigned int cssid
, ssid
, subchno
, devno
;
1039 p
= strstr(syspath
, "/devices/css");
1040 if (!p
|| sscanf(p
+ 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1041 &cssid
, &ssid
, &subchno
, &devno
) < 4) {
1042 g_debug("could not parse ccw device sysfs path: %s", syspath
);
1046 disk
->ccw_address
= g_new0(GuestCCWAddress
, 1);
1047 disk
->ccw_address
->cssid
= cssid
;
1048 disk
->ccw_address
->ssid
= ssid
;
1049 disk
->ccw_address
->subchno
= subchno
;
1050 disk
->ccw_address
->devno
= devno
;
1052 if (strstr(p
, "/virtio")) {
1053 build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1059 /* Store disk device info specified by @sysfs into @fs */
1060 static void build_guest_fsinfo_for_real_device(char const *syspath
,
1061 GuestFilesystemInfo
*fs
,
1064 GuestDiskAddress
*disk
;
1065 GuestPCIAddress
*pciaddr
;
1067 #ifdef CONFIG_LIBUDEV
1068 struct udev
*udev
= NULL
;
1069 struct udev_device
*udevice
= NULL
;
1072 pciaddr
= g_new0(GuestPCIAddress
, 1);
1073 pciaddr
->domain
= -1; /* -1 means field is invalid */
1076 pciaddr
->function
= -1;
1078 disk
= g_new0(GuestDiskAddress
, 1);
1079 disk
->pci_controller
= pciaddr
;
1080 disk
->bus_type
= GUEST_DISK_BUS_TYPE_UNKNOWN
;
1082 #ifdef CONFIG_LIBUDEV
1084 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1085 if (udev
== NULL
|| udevice
== NULL
) {
1086 g_debug("failed to query udev");
1088 const char *devnode
, *serial
;
1089 devnode
= udev_device_get_devnode(udevice
);
1090 if (devnode
!= NULL
) {
1091 disk
->dev
= g_strdup(devnode
);
1093 serial
= udev_device_get_property_value(udevice
, "ID_SERIAL");
1094 if (serial
!= NULL
&& *serial
!= 0) {
1095 disk
->serial
= g_strdup(serial
);
1100 udev_device_unref(udevice
);
1103 if (strstr(syspath
, "/devices/pci")) {
1104 has_hwinf
= build_guest_fsinfo_for_pci_dev(syspath
, disk
, errp
);
1105 } else if (strstr(syspath
, "/devices/css")) {
1106 has_hwinf
= build_guest_fsinfo_for_ccw_dev(syspath
, disk
, errp
);
1107 } else if (strstr(syspath
, "/virtio")) {
1108 has_hwinf
= build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1110 g_debug("Unsupported device type for '%s'", syspath
);
1114 if (has_hwinf
|| disk
->dev
|| disk
->serial
) {
1115 QAPI_LIST_PREPEND(fs
->disk
, disk
);
1117 qapi_free_GuestDiskAddress(disk
);
1121 static void build_guest_fsinfo_for_device(char const *devpath
,
1122 GuestFilesystemInfo
*fs
,
1125 /* Store a list of slave devices of virtual volume specified by @syspath into
1127 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1128 GuestFilesystemInfo
*fs
,
1134 struct dirent
*entry
;
1136 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1137 dir
= opendir(dirpath
);
1139 if (errno
!= ENOENT
) {
1140 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1148 entry
= readdir(dir
);
1149 if (entry
== NULL
) {
1151 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1156 if (entry
->d_type
== DT_LNK
) {
1159 g_debug(" slave device '%s'", entry
->d_name
);
1160 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1161 build_guest_fsinfo_for_device(path
, fs
, &err
);
1165 error_propagate(errp
, err
);
1175 static bool is_disk_virtual(const char *devpath
, Error
**errp
)
1177 g_autofree
char *syspath
= realpath(devpath
, NULL
);
1180 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1183 return strstr(syspath
, "/devices/virtual/block/") != NULL
;
1186 /* Dispatch to functions for virtual/real device */
1187 static void build_guest_fsinfo_for_device(char const *devpath
,
1188 GuestFilesystemInfo
*fs
,
1192 g_autofree
char *syspath
= NULL
;
1193 bool is_virtual
= false;
1195 syspath
= realpath(devpath
, NULL
);
1197 if (errno
!= ENOENT
) {
1198 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1202 /* ENOENT: This devpath may not exist because of container config */
1204 fs
->name
= g_path_get_basename(devpath
);
1210 fs
->name
= g_path_get_basename(syspath
);
1213 g_debug(" parse sysfs path '%s'", syspath
);
1214 is_virtual
= is_disk_virtual(syspath
, errp
);
1215 if (*errp
!= NULL
) {
1219 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1221 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1225 #ifdef CONFIG_LIBUDEV
1228 * Wrapper around build_guest_fsinfo_for_device() for getting just
1231 static GuestDiskAddress
*get_disk_address(const char *syspath
, Error
**errp
)
1233 g_autoptr(GuestFilesystemInfo
) fs
= NULL
;
1235 fs
= g_new0(GuestFilesystemInfo
, 1);
1236 build_guest_fsinfo_for_device(syspath
, fs
, errp
);
1237 if (fs
->disk
!= NULL
) {
1238 return g_steal_pointer(&fs
->disk
->value
);
1243 static char *get_alias_for_syspath(const char *syspath
)
1245 struct udev
*udev
= NULL
;
1246 struct udev_device
*udevice
= NULL
;
1251 g_debug("failed to query udev");
1254 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1255 if (udevice
== NULL
) {
1256 g_debug("failed to query udev for path: %s", syspath
);
1259 const char *alias
= udev_device_get_property_value(
1260 udevice
, "DM_NAME");
1262 * NULL means there was an error and empty string means there is no
1263 * alias. In case of no alias we return NULL instead of empty string.
1265 if (alias
== NULL
) {
1266 g_debug("failed to query udev for device alias for: %s",
1268 } else if (*alias
!= 0) {
1269 ret
= g_strdup(alias
);
1275 udev_device_unref(udevice
);
1279 static char *get_device_for_syspath(const char *syspath
)
1281 struct udev
*udev
= NULL
;
1282 struct udev_device
*udevice
= NULL
;
1287 g_debug("failed to query udev");
1290 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1291 if (udevice
== NULL
) {
1292 g_debug("failed to query udev for path: %s", syspath
);
1295 ret
= g_strdup(udev_device_get_devnode(udevice
));
1300 udev_device_unref(udevice
);
1304 static void get_disk_deps(const char *disk_dir
, GuestDiskInfo
*disk
)
1306 g_autofree
char *deps_dir
= NULL
;
1308 GDir
*dp_deps
= NULL
;
1310 /* List dependent disks */
1311 deps_dir
= g_strdup_printf("%s/slaves", disk_dir
);
1312 g_debug(" listing entries in: %s", deps_dir
);
1313 dp_deps
= g_dir_open(deps_dir
, 0, NULL
);
1314 if (dp_deps
== NULL
) {
1315 g_debug("failed to list entries in %s", deps_dir
);
1318 disk
->has_dependencies
= true;
1319 while ((dep
= g_dir_read_name(dp_deps
)) != NULL
) {
1320 g_autofree
char *dep_dir
= NULL
;
1323 /* Add dependent disks */
1324 dep_dir
= g_strdup_printf("%s/%s", deps_dir
, dep
);
1325 dev_name
= get_device_for_syspath(dep_dir
);
1326 if (dev_name
!= NULL
) {
1327 g_debug(" adding dependent device: %s", dev_name
);
1328 QAPI_LIST_PREPEND(disk
->dependencies
, dev_name
);
1331 g_dir_close(dp_deps
);
1335 * Detect partitions subdirectory, name is "<disk_name><number>" or
1336 * "<disk_name>p<number>"
1338 * @disk_name -- last component of /sys path (e.g. sda)
1339 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1340 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1342 static GuestDiskInfoList
*get_disk_partitions(
1343 GuestDiskInfoList
*list
,
1344 const char *disk_name
, const char *disk_dir
,
1345 const char *disk_dev
)
1347 GuestDiskInfoList
*ret
= list
;
1348 struct dirent
*de_disk
;
1349 DIR *dp_disk
= NULL
;
1350 size_t len
= strlen(disk_name
);
1352 dp_disk
= opendir(disk_dir
);
1353 while ((de_disk
= readdir(dp_disk
)) != NULL
) {
1354 g_autofree
char *partition_dir
= NULL
;
1356 GuestDiskInfo
*partition
;
1358 if (!(de_disk
->d_type
& DT_DIR
)) {
1362 if (!(strncmp(disk_name
, de_disk
->d_name
, len
) == 0 &&
1363 ((*(de_disk
->d_name
+ len
) == 'p' &&
1364 isdigit(*(de_disk
->d_name
+ len
+ 1))) ||
1365 isdigit(*(de_disk
->d_name
+ len
))))) {
1369 partition_dir
= g_strdup_printf("%s/%s",
1370 disk_dir
, de_disk
->d_name
);
1371 dev_name
= get_device_for_syspath(partition_dir
);
1372 if (dev_name
== NULL
) {
1373 g_debug("Failed to get device name for syspath: %s",
1377 partition
= g_new0(GuestDiskInfo
, 1);
1378 partition
->name
= dev_name
;
1379 partition
->partition
= true;
1380 partition
->has_dependencies
= true;
1381 /* Add parent disk as dependent for easier tracking of hierarchy */
1382 QAPI_LIST_PREPEND(partition
->dependencies
, g_strdup(disk_dev
));
1384 QAPI_LIST_PREPEND(ret
, partition
);
1391 static void get_nvme_smart(GuestDiskInfo
*disk
)
1394 GuestNVMeSmart
*smart
;
1395 NvmeSmartLog log
= {0};
1396 struct nvme_admin_cmd cmd
= {
1397 .opcode
= NVME_ADM_CMD_GET_LOG_PAGE
,
1398 .nsid
= NVME_NSID_BROADCAST
,
1399 .addr
= (uintptr_t)&log
,
1400 .data_len
= sizeof(log
),
1401 .cdw10
= NVME_LOG_SMART_INFO
| (1 << 15) /* RAE bit */
1402 | (((sizeof(log
) >> 2) - 1) << 16)
1405 fd
= qga_open_cloexec(disk
->name
, O_RDONLY
, 0);
1407 g_debug("Failed to open device: %s: %s", disk
->name
, g_strerror(errno
));
1411 if (ioctl(fd
, NVME_IOCTL_ADMIN_CMD
, &cmd
)) {
1412 g_debug("Failed to get smart: %s: %s", disk
->name
, g_strerror(errno
));
1417 disk
->smart
= g_new0(GuestDiskSmart
, 1);
1418 disk
->smart
->type
= GUEST_DISK_BUS_TYPE_NVME
;
1420 smart
= &disk
->smart
->u
.nvme
;
1421 smart
->critical_warning
= log
.critical_warning
;
1422 smart
->temperature
= lduw_le_p(&log
.temperature
); /* unaligned field */
1423 smart
->available_spare
= log
.available_spare
;
1424 smart
->available_spare_threshold
= log
.available_spare_threshold
;
1425 smart
->percentage_used
= log
.percentage_used
;
1426 smart
->data_units_read_lo
= le64_to_cpu(log
.data_units_read
[0]);
1427 smart
->data_units_read_hi
= le64_to_cpu(log
.data_units_read
[1]);
1428 smart
->data_units_written_lo
= le64_to_cpu(log
.data_units_written
[0]);
1429 smart
->data_units_written_hi
= le64_to_cpu(log
.data_units_written
[1]);
1430 smart
->host_read_commands_lo
= le64_to_cpu(log
.host_read_commands
[0]);
1431 smart
->host_read_commands_hi
= le64_to_cpu(log
.host_read_commands
[1]);
1432 smart
->host_write_commands_lo
= le64_to_cpu(log
.host_write_commands
[0]);
1433 smart
->host_write_commands_hi
= le64_to_cpu(log
.host_write_commands
[1]);
1434 smart
->controller_busy_time_lo
= le64_to_cpu(log
.controller_busy_time
[0]);
1435 smart
->controller_busy_time_hi
= le64_to_cpu(log
.controller_busy_time
[1]);
1436 smart
->power_cycles_lo
= le64_to_cpu(log
.power_cycles
[0]);
1437 smart
->power_cycles_hi
= le64_to_cpu(log
.power_cycles
[1]);
1438 smart
->power_on_hours_lo
= le64_to_cpu(log
.power_on_hours
[0]);
1439 smart
->power_on_hours_hi
= le64_to_cpu(log
.power_on_hours
[1]);
1440 smart
->unsafe_shutdowns_lo
= le64_to_cpu(log
.unsafe_shutdowns
[0]);
1441 smart
->unsafe_shutdowns_hi
= le64_to_cpu(log
.unsafe_shutdowns
[1]);
1442 smart
->media_errors_lo
= le64_to_cpu(log
.media_errors
[0]);
1443 smart
->media_errors_hi
= le64_to_cpu(log
.media_errors
[1]);
1444 smart
->number_of_error_log_entries_lo
=
1445 le64_to_cpu(log
.number_of_error_log_entries
[0]);
1446 smart
->number_of_error_log_entries_hi
=
1447 le64_to_cpu(log
.number_of_error_log_entries
[1]);
1452 static void get_disk_smart(GuestDiskInfo
*disk
)
1455 && (disk
->address
->bus_type
== GUEST_DISK_BUS_TYPE_NVME
)) {
1456 get_nvme_smart(disk
);
1460 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1462 GuestDiskInfoList
*ret
= NULL
;
1463 GuestDiskInfo
*disk
;
1465 struct dirent
*de
= NULL
;
1467 g_debug("listing /sys/block directory");
1468 dp
= opendir("/sys/block");
1470 error_setg_errno(errp
, errno
, "Can't open directory \"/sys/block\"");
1473 while ((de
= readdir(dp
)) != NULL
) {
1474 g_autofree
char *disk_dir
= NULL
, *line
= NULL
,
1477 Error
*local_err
= NULL
;
1478 if (de
->d_type
!= DT_LNK
) {
1479 g_debug(" skipping entry: %s", de
->d_name
);
1483 /* Check size and skip zero-sized disks */
1484 g_debug(" checking disk size");
1485 size_path
= g_strdup_printf("/sys/block/%s/size", de
->d_name
);
1486 if (!g_file_get_contents(size_path
, &line
, NULL
, NULL
)) {
1487 g_debug(" failed to read disk size");
1490 if (g_strcmp0(line
, "0\n") == 0) {
1491 g_debug(" skipping zero-sized disk");
1495 g_debug(" adding %s", de
->d_name
);
1496 disk_dir
= g_strdup_printf("/sys/block/%s", de
->d_name
);
1497 dev_name
= get_device_for_syspath(disk_dir
);
1498 if (dev_name
== NULL
) {
1499 g_debug("Failed to get device name for syspath: %s",
1503 disk
= g_new0(GuestDiskInfo
, 1);
1504 disk
->name
= dev_name
;
1505 disk
->partition
= false;
1506 disk
->alias
= get_alias_for_syspath(disk_dir
);
1507 QAPI_LIST_PREPEND(ret
, disk
);
1509 /* Get address for non-virtual devices */
1510 bool is_virtual
= is_disk_virtual(disk_dir
, &local_err
);
1511 if (local_err
!= NULL
) {
1512 g_debug(" failed to check disk path, ignoring error: %s",
1513 error_get_pretty(local_err
));
1514 error_free(local_err
);
1516 /* Don't try to get the address */
1520 disk
->address
= get_disk_address(disk_dir
, &local_err
);
1521 if (local_err
!= NULL
) {
1522 g_debug(" failed to get device info, ignoring error: %s",
1523 error_get_pretty(local_err
));
1524 error_free(local_err
);
1529 get_disk_deps(disk_dir
, disk
);
1530 get_disk_smart(disk
);
1531 ret
= get_disk_partitions(ret
, de
->d_name
, disk_dir
, dev_name
);
1541 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1543 error_setg(errp
, QERR_UNSUPPORTED
);
1549 /* Return a list of the disk device(s)' info which @mount lies on */
1550 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1553 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1555 unsigned long used
, nonroot_total
, fr_size
;
1556 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1557 mount
->devmajor
, mount
->devminor
);
1559 fs
->mountpoint
= g_strdup(mount
->dirname
);
1560 fs
->type
= g_strdup(mount
->devtype
);
1561 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1563 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1564 fr_size
= buf
.f_frsize
;
1565 used
= buf
.f_blocks
- buf
.f_bfree
;
1566 nonroot_total
= used
+ buf
.f_bavail
;
1567 fs
->used_bytes
= used
* fr_size
;
1568 fs
->total_bytes
= nonroot_total
* fr_size
;
1570 fs
->has_total_bytes
= true;
1571 fs
->has_used_bytes
= true;
1579 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1582 struct FsMount
*mount
;
1583 GuestFilesystemInfoList
*ret
= NULL
;
1584 Error
*local_err
= NULL
;
1586 QTAILQ_INIT(&mounts
);
1587 if (!build_fs_mount_list(&mounts
, &local_err
)) {
1588 error_propagate(errp
, local_err
);
1592 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1593 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1595 QAPI_LIST_PREPEND(ret
, build_guest_fsinfo(mount
, &local_err
));
1597 error_propagate(errp
, local_err
);
1598 qapi_free_GuestFilesystemInfoList(ret
);
1604 free_fs_mount_list(&mounts
);
1607 #endif /* CONFIG_FSFREEZE */
1609 #if defined(CONFIG_FSTRIM)
1611 * Walk list of mounted file systems in the guest, and trim them.
1613 GuestFilesystemTrimResponse
*
1614 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1616 GuestFilesystemTrimResponse
*response
;
1617 GuestFilesystemTrimResult
*result
;
1620 struct FsMount
*mount
;
1622 struct fstrim_range r
;
1624 slog("guest-fstrim called");
1626 QTAILQ_INIT(&mounts
);
1627 if (!build_fs_mount_list(&mounts
, errp
)) {
1631 response
= g_malloc0(sizeof(*response
));
1633 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1634 result
= g_malloc0(sizeof(*result
));
1635 result
->path
= g_strdup(mount
->dirname
);
1637 QAPI_LIST_PREPEND(response
->paths
, result
);
1639 fd
= qga_open_cloexec(mount
->dirname
, O_RDONLY
, 0);
1641 result
->error
= g_strdup_printf("failed to open: %s",
1646 /* We try to cull filesystems we know won't work in advance, but other
1647 * filesystems may not implement fstrim for less obvious reasons.
1648 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1649 * will be reported (e.g. CD-ROMs).
1650 * Any other error means an unexpected error.
1654 r
.minlen
= has_minimum
? minimum
: 0;
1655 ret
= ioctl(fd
, FITRIM
, &r
);
1657 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1658 result
->error
= g_strdup("trim not supported");
1660 result
->error
= g_strdup_printf("failed to trim: %s",
1667 result
->has_minimum
= true;
1668 result
->minimum
= r
.minlen
;
1669 result
->has_trimmed
= true;
1670 result
->trimmed
= r
.len
;
1674 free_fs_mount_list(&mounts
);
1677 #endif /* CONFIG_FSTRIM */
1680 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1681 #define SUSPEND_SUPPORTED 0
1682 #define SUSPEND_NOT_SUPPORTED 1
1685 SUSPEND_MODE_DISK
= 0,
1686 SUSPEND_MODE_RAM
= 1,
1687 SUSPEND_MODE_HYBRID
= 2,
1691 * Executes a command in a child process using g_spawn_sync,
1692 * returning an int >= 0 representing the exit status of the
1695 * If the program wasn't found in path, returns -1.
1697 * If a problem happened when creating the child process,
1698 * returns -1 and errp is set.
1700 static int run_process_child(const char *command
[], Error
**errp
)
1702 int exit_status
, spawn_flag
;
1703 GError
*g_err
= NULL
;
1706 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1707 G_SPAWN_STDERR_TO_DEV_NULL
;
1709 success
= g_spawn_sync(NULL
, (char **)command
, NULL
, spawn_flag
,
1710 NULL
, NULL
, NULL
, NULL
,
1711 &exit_status
, &g_err
);
1714 return WEXITSTATUS(exit_status
);
1717 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1718 error_setg(errp
, "failed to create child process, error '%s'",
1722 g_error_free(g_err
);
1726 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1728 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1729 "systemd-hybrid-sleep"};
1730 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
1733 status
= run_process_child(cmd
, errp
);
1736 * systemctl status uses LSB return codes so we can expect
1737 * status > 0 and be ok. To assert if the guest has support
1738 * for the selected suspend mode, status should be < 4. 4 is
1739 * the code for unknown service status, the return value when
1740 * the service does not exist. A common value is status = 3
1741 * (program is not running).
1743 if (status
> 0 && status
< 4) {
1750 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
1752 Error
*local_err
= NULL
;
1753 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
1754 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
1757 status
= run_process_child(cmd
, &local_err
);
1763 if ((status
== -1) && !local_err
) {
1764 error_setg(errp
, "the helper program 'systemctl %s' was not found",
1765 systemctl_args
[mode
]);
1770 error_propagate(errp
, local_err
);
1772 error_setg(errp
, "the helper program 'systemctl %s' returned an "
1773 "unexpected exit status code (%d)",
1774 systemctl_args
[mode
], status
);
1778 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
1780 Error
*local_err
= NULL
;
1781 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
1782 "--suspend-hybrid"};
1783 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
1786 status
= run_process_child(cmd
, &local_err
);
1788 if (status
== SUSPEND_SUPPORTED
) {
1792 if ((status
== -1) && !local_err
) {
1797 error_propagate(errp
, local_err
);
1800 "the helper program '%s' returned an unexpected exit"
1801 " status code (%d)", "pm-is-supported", status
);
1807 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
1809 Error
*local_err
= NULL
;
1810 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
1811 "pm-suspend-hybrid"};
1812 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
1815 status
= run_process_child(cmd
, &local_err
);
1821 if ((status
== -1) && !local_err
) {
1822 error_setg(errp
, "the helper program '%s' was not found",
1823 pmutils_binaries
[mode
]);
1828 error_propagate(errp
, local_err
);
1831 "the helper program '%s' returned an unexpected exit"
1832 " status code (%d)", pmutils_binaries
[mode
], status
);
1836 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
1838 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1839 const char *sysfile_str
= sysfile_strs
[mode
];
1840 char buf
[32]; /* hopefully big enough */
1845 error_setg(errp
, "unknown guest suspend mode");
1849 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1854 ret
= read(fd
, buf
, sizeof(buf
) - 1);
1861 if (strstr(buf
, sysfile_str
)) {
1867 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
1869 Error
*local_err
= NULL
;
1870 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1871 const char *sysfile_str
= sysfile_strs
[mode
];
1876 error_setg(errp
, "unknown guest suspend mode");
1886 reopen_fd_to_null(0);
1887 reopen_fd_to_null(1);
1888 reopen_fd_to_null(2);
1890 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1892 _exit(EXIT_FAILURE
);
1895 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1896 _exit(EXIT_FAILURE
);
1899 _exit(EXIT_SUCCESS
);
1900 } else if (pid
< 0) {
1901 error_setg_errno(errp
, errno
, "failed to create child process");
1905 ga_wait_child(pid
, &status
, &local_err
);
1907 error_propagate(errp
, local_err
);
1911 if (WEXITSTATUS(status
)) {
1912 error_setg(errp
, "child process has failed to suspend");
1917 static void guest_suspend(SuspendMode mode
, Error
**errp
)
1919 Error
*local_err
= NULL
;
1920 bool mode_supported
= false;
1922 if (systemd_supports_mode(mode
, &local_err
)) {
1923 mode_supported
= true;
1924 systemd_suspend(mode
, &local_err
);
1931 error_free(local_err
);
1934 if (pmutils_supports_mode(mode
, &local_err
)) {
1935 mode_supported
= true;
1936 pmutils_suspend(mode
, &local_err
);
1943 error_free(local_err
);
1946 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
1947 mode_supported
= true;
1948 linux_sys_state_suspend(mode
, &local_err
);
1951 if (!mode_supported
) {
1952 error_free(local_err
);
1954 "the requested suspend mode is not supported by the guest");
1956 error_propagate(errp
, local_err
);
1960 void qmp_guest_suspend_disk(Error
**errp
)
1962 guest_suspend(SUSPEND_MODE_DISK
, errp
);
1965 void qmp_guest_suspend_ram(Error
**errp
)
1967 guest_suspend(SUSPEND_MODE_RAM
, errp
);
1970 void qmp_guest_suspend_hybrid(Error
**errp
)
1972 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
1975 /* Transfer online/offline status between @vcpu and the guest system.
1977 * On input either @errp or *@errp must be NULL.
1979 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1980 * - R: vcpu->logical_id
1982 * - W: vcpu->can_offline
1984 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1985 * - R: vcpu->logical_id
1988 * Written members remain unmodified on error.
1990 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1991 char *dirpath
, Error
**errp
)
1996 static const char fn
[] = "online";
1998 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2000 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2004 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2006 if (errno
!= ENOENT
) {
2007 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2008 } else if (sys2vcpu
) {
2009 vcpu
->online
= true;
2010 vcpu
->can_offline
= false;
2011 } else if (!vcpu
->online
) {
2012 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2013 "offlined", vcpu
->logical_id
);
2014 } /* otherwise pretend successful re-onlining */
2016 unsigned char status
;
2018 res
= pread(fd
, &status
, 1, 0);
2020 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2021 } else if (res
== 0) {
2022 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2024 } else if (sys2vcpu
) {
2025 vcpu
->online
= (status
!= '0');
2026 vcpu
->can_offline
= true;
2027 } else if (vcpu
->online
!= (status
!= '0')) {
2028 status
= '0' + vcpu
->online
;
2029 if (pwrite(fd
, &status
, 1, 0) == -1) {
2030 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2033 } /* otherwise pretend successful re-(on|off)-lining */
2043 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2045 GuestLogicalProcessorList
*head
, **tail
;
2046 const char *cpu_dir
= "/sys/devices/system/cpu";
2048 g_autoptr(GDir
) cpu_gdir
= NULL
;
2049 Error
*local_err
= NULL
;
2053 cpu_gdir
= g_dir_open(cpu_dir
, 0, NULL
);
2055 if (cpu_gdir
== NULL
) {
2056 error_setg_errno(errp
, errno
, "failed to list entries: %s", cpu_dir
);
2060 while (local_err
== NULL
&& (line
= g_dir_read_name(cpu_gdir
)) != NULL
) {
2061 GuestLogicalProcessor
*vcpu
;
2063 if (sscanf(line
, "cpu%" PRId64
, &id
)) {
2064 g_autofree
char *path
= g_strdup_printf("/sys/devices/system/cpu/"
2065 "cpu%" PRId64
"/", id
);
2066 vcpu
= g_malloc0(sizeof *vcpu
);
2067 vcpu
->logical_id
= id
;
2068 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2069 transfer_vcpu(vcpu
, true, path
, &local_err
);
2070 QAPI_LIST_APPEND(tail
, vcpu
);
2074 if (local_err
== NULL
) {
2075 /* there's no guest with zero VCPUs */
2076 g_assert(head
!= NULL
);
2080 qapi_free_GuestLogicalProcessorList(head
);
2081 error_propagate(errp
, local_err
);
2085 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2088 Error
*local_err
= NULL
;
2091 while (vcpus
!= NULL
) {
2092 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2093 vcpus
->value
->logical_id
);
2095 transfer_vcpu(vcpus
->value
, false, path
, &local_err
);
2097 if (local_err
!= NULL
) {
2101 vcpus
= vcpus
->next
;
2104 if (local_err
!= NULL
) {
2105 if (processed
== 0) {
2106 error_propagate(errp
, local_err
);
2108 error_free(local_err
);
2114 #endif /* __linux__ */
2116 #if defined(__linux__) || defined(__FreeBSD__)
2117 void qmp_guest_set_user_password(const char *username
,
2118 const char *password
,
2122 Error
*local_err
= NULL
;
2123 char *passwd_path
= NULL
;
2126 int datafd
[2] = { -1, -1 };
2127 char *rawpasswddata
= NULL
;
2128 size_t rawpasswdlen
;
2129 char *chpasswddata
= NULL
;
2132 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2133 if (!rawpasswddata
) {
2136 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2137 rawpasswddata
[rawpasswdlen
] = '\0';
2139 if (strchr(rawpasswddata
, '\n')) {
2140 error_setg(errp
, "forbidden characters in raw password");
2144 if (strchr(username
, '\n') ||
2145 strchr(username
, ':')) {
2146 error_setg(errp
, "forbidden characters in username");
2151 chpasswddata
= g_strdup(rawpasswddata
);
2152 passwd_path
= g_find_program_in_path("pw");
2154 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
2155 passwd_path
= g_find_program_in_path("chpasswd");
2158 chpasswdlen
= strlen(chpasswddata
);
2161 error_setg(errp
, "cannot find 'passwd' program in PATH");
2165 if (!g_unix_open_pipe(datafd
, FD_CLOEXEC
, NULL
)) {
2166 error_setg(errp
, "cannot create pipe FDs");
2176 reopen_fd_to_null(1);
2177 reopen_fd_to_null(2);
2181 h_arg
= (crypted
) ? "-H" : "-h";
2182 execl(passwd_path
, "pw", "usermod", "-n", username
, h_arg
, "0", NULL
);
2185 execl(passwd_path
, "chpasswd", "-e", NULL
);
2187 execl(passwd_path
, "chpasswd", NULL
);
2190 _exit(EXIT_FAILURE
);
2191 } else if (pid
< 0) {
2192 error_setg_errno(errp
, errno
, "failed to create child process");
2198 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2199 error_setg_errno(errp
, errno
, "cannot write new account password");
2205 ga_wait_child(pid
, &status
, &local_err
);
2207 error_propagate(errp
, local_err
);
2211 if (!WIFEXITED(status
)) {
2212 error_setg(errp
, "child process has terminated abnormally");
2216 if (WEXITSTATUS(status
)) {
2217 error_setg(errp
, "child process has failed to set user password");
2222 g_free(chpasswddata
);
2223 g_free(rawpasswddata
);
2224 g_free(passwd_path
);
2225 if (datafd
[0] != -1) {
2228 if (datafd
[1] != -1) {
2232 #else /* __linux__ || __FreeBSD__ */
2233 void qmp_guest_set_user_password(const char *username
,
2234 const char *password
,
2238 error_setg(errp
, QERR_UNSUPPORTED
);
2240 #endif /* __linux__ || __FreeBSD__ */
2243 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2244 int size
, Error
**errp
)
2250 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2252 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2256 res
= pread(fd
, buf
, size
, 0);
2258 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2259 } else if (res
== 0) {
2260 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2265 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2266 const char *buf
, int size
, Error
**errp
)
2271 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2273 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2277 if (pwrite(fd
, buf
, size
, 0) == -1) {
2278 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2284 /* Transfer online/offline status between @mem_blk and the guest system.
2286 * On input either @errp or *@errp must be NULL.
2288 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2289 * - R: mem_blk->phys_index
2290 * - W: mem_blk->online
2291 * - W: mem_blk->can_offline
2293 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2294 * - R: mem_blk->phys_index
2295 * - R: mem_blk->online
2296 *- R: mem_blk->can_offline
2297 * Written members remain unmodified on error.
2299 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2300 GuestMemoryBlockResponse
*result
,
2306 Error
*local_err
= NULL
;
2312 error_setg(errp
, "Internal error, 'result' should not be NULL");
2316 dp
= opendir("/sys/devices/system/memory/");
2317 /* if there is no 'memory' directory in sysfs,
2318 * we think this VM does not support online/offline memory block,
2319 * any other solution?
2322 if (errno
== ENOENT
) {
2324 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2331 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2332 mem_blk
->phys_index
);
2333 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2336 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2338 if (errno
== ENOENT
) {
2339 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2342 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2350 status
= g_malloc0(10);
2351 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2353 /* treat with sysfs file that not exist in old kernel */
2354 if (errno
== ENOENT
) {
2355 error_free(local_err
);
2357 mem_blk
->online
= true;
2358 mem_blk
->can_offline
= false;
2359 } else if (!mem_blk
->online
) {
2361 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2365 error_propagate(errp
, local_err
);
2367 error_free(local_err
);
2369 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2376 char removable
= '0';
2378 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2380 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2382 /* if no 'removable' file, it doesn't support offline mem blk */
2383 if (errno
== ENOENT
) {
2384 error_free(local_err
);
2385 mem_blk
->can_offline
= false;
2387 error_propagate(errp
, local_err
);
2390 mem_blk
->can_offline
= (removable
!= '0');
2393 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2394 const char *new_state
= mem_blk
->online
? "online" : "offline";
2396 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2399 error_free(local_err
);
2401 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2405 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2406 result
->has_error_code
= false;
2407 } /* otherwise pretend successful re-(on|off)-lining */
2418 result
->has_error_code
= true;
2419 result
->error_code
= errno
;
2423 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2425 GuestMemoryBlockList
*head
, **tail
;
2426 Error
*local_err
= NULL
;
2433 dp
= opendir("/sys/devices/system/memory/");
2435 /* it's ok if this happens to be a system that doesn't expose
2436 * memory blocks via sysfs, but otherwise we should report
2439 if (errno
!= ENOENT
) {
2440 error_setg_errno(errp
, errno
, "Can't open directory"
2441 "\"/sys/devices/system/memory/\"");
2446 /* Note: the phys_index of memory block may be discontinuous,
2447 * this is because a memblk is the unit of the Sparse Memory design, which
2448 * allows discontinuous memory ranges (ex. NUMA), so here we should
2449 * traverse the memory block directory.
2451 while ((de
= readdir(dp
)) != NULL
) {
2452 GuestMemoryBlock
*mem_blk
;
2454 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2455 !(de
->d_type
& DT_DIR
)) {
2459 mem_blk
= g_malloc0(sizeof *mem_blk
);
2460 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2461 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2462 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2463 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2468 QAPI_LIST_APPEND(tail
, mem_blk
);
2472 if (local_err
== NULL
) {
2473 /* there's no guest with zero memory blocks */
2475 error_setg(errp
, "guest reported zero memory blocks!");
2480 qapi_free_GuestMemoryBlockList(head
);
2481 error_propagate(errp
, local_err
);
2485 GuestMemoryBlockResponseList
*
2486 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2488 GuestMemoryBlockResponseList
*head
, **tail
;
2489 Error
*local_err
= NULL
;
2494 while (mem_blks
!= NULL
) {
2495 GuestMemoryBlockResponse
*result
;
2496 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2498 result
= g_malloc0(sizeof(*result
));
2499 result
->phys_index
= current_mem_blk
->phys_index
;
2500 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2501 if (local_err
) { /* should never happen */
2505 QAPI_LIST_APPEND(tail
, result
);
2506 mem_blks
= mem_blks
->next
;
2511 qapi_free_GuestMemoryBlockResponseList(head
);
2512 error_propagate(errp
, local_err
);
2516 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2518 Error
*local_err
= NULL
;
2522 GuestMemoryBlockInfo
*info
;
2524 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2525 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2527 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2533 buf
= g_malloc0(20);
2534 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2538 error_propagate(errp
, local_err
);
2542 info
= g_new0(GuestMemoryBlockInfo
, 1);
2543 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2550 #define MAX_NAME_LEN 128
2551 static GuestDiskStatsInfoList
*guest_get_diskstats(Error
**errp
)
2554 GuestDiskStatsInfoList
*head
= NULL
, **tail
= &head
;
2555 const char *diskstats
= "/proc/diskstats";
2560 fp
= fopen(diskstats
, "r");
2562 error_setg_errno(errp
, errno
, "open(\"%s\")", diskstats
);
2566 while (getline(&line
, &n
, fp
) != -1) {
2567 g_autofree GuestDiskStatsInfo
*diskstatinfo
= NULL
;
2568 g_autofree GuestDiskStats
*diskstat
= NULL
;
2569 char dev_name
[MAX_NAME_LEN
];
2570 unsigned int ios_pgr
, tot_ticks
, rq_ticks
, wr_ticks
, dc_ticks
, fl_ticks
;
2571 unsigned long rd_ios
, rd_merges_or_rd_sec
, rd_ticks_or_wr_sec
, wr_ios
;
2572 unsigned long wr_merges
, rd_sec_or_wr_ios
, wr_sec
;
2573 unsigned long dc_ios
, dc_merges
, dc_sec
, fl_ios
;
2574 unsigned int major
, minor
;
2577 i
= sscanf(line
, "%u %u %s %lu %lu %lu"
2578 "%lu %lu %lu %lu %u %u %u %u"
2579 "%lu %lu %lu %u %lu %u",
2580 &major
, &minor
, dev_name
,
2581 &rd_ios
, &rd_merges_or_rd_sec
, &rd_sec_or_wr_ios
,
2582 &rd_ticks_or_wr_sec
, &wr_ios
, &wr_merges
, &wr_sec
,
2583 &wr_ticks
, &ios_pgr
, &tot_ticks
, &rq_ticks
,
2584 &dc_ios
, &dc_merges
, &dc_sec
, &dc_ticks
,
2585 &fl_ios
, &fl_ticks
);
2591 diskstatinfo
= g_new0(GuestDiskStatsInfo
, 1);
2592 diskstatinfo
->name
= g_strdup(dev_name
);
2593 diskstatinfo
->major
= major
;
2594 diskstatinfo
->minor
= minor
;
2596 diskstat
= g_new0(GuestDiskStats
, 1);
2598 diskstat
->has_read_ios
= true;
2599 diskstat
->read_ios
= rd_ios
;
2600 diskstat
->has_read_sectors
= true;
2601 diskstat
->read_sectors
= rd_merges_or_rd_sec
;
2602 diskstat
->has_write_ios
= true;
2603 diskstat
->write_ios
= rd_sec_or_wr_ios
;
2604 diskstat
->has_write_sectors
= true;
2605 diskstat
->write_sectors
= rd_ticks_or_wr_sec
;
2608 diskstat
->has_read_ios
= true;
2609 diskstat
->read_ios
= rd_ios
;
2610 diskstat
->has_read_sectors
= true;
2611 diskstat
->read_sectors
= rd_sec_or_wr_ios
;
2612 diskstat
->has_read_merges
= true;
2613 diskstat
->read_merges
= rd_merges_or_rd_sec
;
2614 diskstat
->has_read_ticks
= true;
2615 diskstat
->read_ticks
= rd_ticks_or_wr_sec
;
2616 diskstat
->has_write_ios
= true;
2617 diskstat
->write_ios
= wr_ios
;
2618 diskstat
->has_write_sectors
= true;
2619 diskstat
->write_sectors
= wr_sec
;
2620 diskstat
->has_write_merges
= true;
2621 diskstat
->write_merges
= wr_merges
;
2622 diskstat
->has_write_ticks
= true;
2623 diskstat
->write_ticks
= wr_ticks
;
2624 diskstat
->has_ios_pgr
= true;
2625 diskstat
->ios_pgr
= ios_pgr
;
2626 diskstat
->has_total_ticks
= true;
2627 diskstat
->total_ticks
= tot_ticks
;
2628 diskstat
->has_weight_ticks
= true;
2629 diskstat
->weight_ticks
= rq_ticks
;
2632 diskstat
->has_discard_ios
= true;
2633 diskstat
->discard_ios
= dc_ios
;
2634 diskstat
->has_discard_merges
= true;
2635 diskstat
->discard_merges
= dc_merges
;
2636 diskstat
->has_discard_sectors
= true;
2637 diskstat
->discard_sectors
= dc_sec
;
2638 diskstat
->has_discard_ticks
= true;
2639 diskstat
->discard_ticks
= dc_ticks
;
2642 diskstat
->has_flush_ios
= true;
2643 diskstat
->flush_ios
= fl_ios
;
2644 diskstat
->has_flush_ticks
= true;
2645 diskstat
->flush_ticks
= fl_ticks
;
2648 diskstatinfo
->stats
= g_steal_pointer(&diskstat
);
2649 QAPI_LIST_APPEND(tail
, diskstatinfo
);
2650 diskstatinfo
= NULL
;
2656 g_debug("disk stats reporting available only for Linux");
2661 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
2663 return guest_get_diskstats(errp
);
2666 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
2668 GuestCpuStatsList
*head
= NULL
, **tail
= &head
;
2669 const char *cpustats
= "/proc/stat";
2670 int clk_tck
= sysconf(_SC_CLK_TCK
);
2675 fp
= fopen(cpustats
, "r");
2677 error_setg_errno(errp
, errno
, "open(\"%s\")", cpustats
);
2681 while (getline(&line
, &n
, fp
) != -1) {
2682 GuestCpuStats
*cpustat
= NULL
;
2683 GuestLinuxCpuStats
*linuxcpustat
;
2685 unsigned long user
, system
, idle
, iowait
, irq
, softirq
, steal
, guest
;
2686 unsigned long nice
, guest_nice
;
2689 i
= sscanf(line
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2690 name
, &user
, &nice
, &system
, &idle
, &iowait
, &irq
, &softirq
,
2691 &steal
, &guest
, &guest_nice
);
2693 /* drop "cpu 1 2 3 ...", get "cpuX 1 2 3 ..." only */
2694 if ((i
== EOF
) || strncmp(name
, "cpu", 3) || (name
[3] == '\0')) {
2699 slog("Parsing cpu stat from %s failed, see \"man proc\"", cpustats
);
2703 cpustat
= g_new0(GuestCpuStats
, 1);
2704 cpustat
->type
= GUEST_CPU_STATS_TYPE_LINUX
;
2706 linuxcpustat
= &cpustat
->u
.q_linux
;
2707 linuxcpustat
->cpu
= atoi(&name
[3]);
2708 linuxcpustat
->user
= user
* 1000 / clk_tck
;
2709 linuxcpustat
->nice
= nice
* 1000 / clk_tck
;
2710 linuxcpustat
->system
= system
* 1000 / clk_tck
;
2711 linuxcpustat
->idle
= idle
* 1000 / clk_tck
;
2714 linuxcpustat
->has_iowait
= true;
2715 linuxcpustat
->iowait
= iowait
* 1000 / clk_tck
;
2719 linuxcpustat
->has_irq
= true;
2720 linuxcpustat
->irq
= irq
* 1000 / clk_tck
;
2721 linuxcpustat
->has_softirq
= true;
2722 linuxcpustat
->softirq
= softirq
* 1000 / clk_tck
;
2726 linuxcpustat
->has_steal
= true;
2727 linuxcpustat
->steal
= steal
* 1000 / clk_tck
;
2731 linuxcpustat
->has_guest
= true;
2732 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2736 linuxcpustat
->has_guest
= true;
2737 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2738 linuxcpustat
->has_guestnice
= true;
2739 linuxcpustat
->guestnice
= guest_nice
* 1000 / clk_tck
;
2742 QAPI_LIST_APPEND(tail
, cpustat
);
2750 #else /* defined(__linux__) */
2752 void qmp_guest_suspend_disk(Error
**errp
)
2754 error_setg(errp
, QERR_UNSUPPORTED
);
2757 void qmp_guest_suspend_ram(Error
**errp
)
2759 error_setg(errp
, QERR_UNSUPPORTED
);
2762 void qmp_guest_suspend_hybrid(Error
**errp
)
2764 error_setg(errp
, QERR_UNSUPPORTED
);
2767 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2769 error_setg(errp
, QERR_UNSUPPORTED
);
2773 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2775 error_setg(errp
, QERR_UNSUPPORTED
);
2779 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2781 error_setg(errp
, QERR_UNSUPPORTED
);
2785 GuestMemoryBlockResponseList
*
2786 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2788 error_setg(errp
, QERR_UNSUPPORTED
);
2792 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2794 error_setg(errp
, QERR_UNSUPPORTED
);
2800 #ifdef HAVE_GETIFADDRS
2801 static GuestNetworkInterface
*
2802 guest_find_interface(GuestNetworkInterfaceList
*head
,
2805 for (; head
; head
= head
->next
) {
2806 if (strcmp(head
->value
->name
, name
) == 0) {
2814 static int guest_get_network_stats(const char *name
,
2815 GuestNetworkInterfaceStat
*stats
)
2819 char const *devinfo
= "/proc/net/dev";
2821 char *line
= NULL
, *colon
;
2823 fp
= fopen(devinfo
, "r");
2825 g_debug("failed to open network stats %s: %s", devinfo
,
2829 name_len
= strlen(name
);
2830 while (getline(&line
, &n
, fp
) != -1) {
2833 long long rx_packets
;
2835 long long rx_dropped
;
2837 long long tx_packets
;
2839 long long tx_dropped
;
2841 trim_line
= g_strchug(line
);
2842 if (trim_line
[0] == '\0') {
2845 colon
= strchr(trim_line
, ':');
2849 if (colon
- name_len
== trim_line
&&
2850 strncmp(trim_line
, name
, name_len
) == 0) {
2851 if (sscanf(colon
+ 1,
2852 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2853 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
2854 &dummy
, &dummy
, &dummy
, &dummy
,
2855 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
2856 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
2859 stats
->rx_bytes
= rx_bytes
;
2860 stats
->rx_packets
= rx_packets
;
2861 stats
->rx_errs
= rx_errs
;
2862 stats
->rx_dropped
= rx_dropped
;
2863 stats
->tx_bytes
= tx_bytes
;
2864 stats
->tx_packets
= tx_packets
;
2865 stats
->tx_errs
= tx_errs
;
2866 stats
->tx_dropped
= tx_dropped
;
2874 g_debug("/proc/net/dev: Interface '%s' not found", name
);
2875 #else /* !CONFIG_LINUX */
2876 g_debug("Network stats reporting available only for Linux");
2877 #endif /* !CONFIG_LINUX */
2883 * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
2884 * buffer with ETHER_ADDR_LEN length at least.
2886 * Returns false in case of an error, otherwise true. "obtained" argument
2887 * is true if a MAC address was obtained successful, otherwise false.
2889 bool guest_get_hw_addr(struct ifaddrs
*ifa
, unsigned char *buf
,
2890 bool *obtained
, Error
**errp
)
2897 /* we haven't obtained HW address yet */
2898 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
2900 error_setg_errno(errp
, errno
, "failed to create socket");
2904 memset(&ifr
, 0, sizeof(ifr
));
2905 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, ifa
->ifa_name
);
2906 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
2908 * We can't get the hw addr of this interface, but that's not a
2911 if (errno
== EADDRNOTAVAIL
) {
2912 /* The interface doesn't have a hw addr (e.g. loopback). */
2913 g_debug("failed to get MAC address of %s: %s",
2914 ifa
->ifa_name
, strerror(errno
));
2916 g_warning("failed to get MAC address of %s: %s",
2917 ifa
->ifa_name
, strerror(errno
));
2920 #ifdef CONFIG_SOLARIS
2921 memcpy(buf
, &ifr
.ifr_addr
.sa_data
, ETHER_ADDR_LEN
);
2923 memcpy(buf
, &ifr
.ifr_hwaddr
.sa_data
, ETHER_ADDR_LEN
);
2930 #endif /* CONFIG_BSD */
2933 * Build information about guest interfaces
2935 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2937 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
2938 struct ifaddrs
*ifap
, *ifa
;
2940 if (getifaddrs(&ifap
) < 0) {
2941 error_setg_errno(errp
, errno
, "getifaddrs failed");
2945 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
2946 GuestNetworkInterface
*info
;
2947 GuestIpAddressList
**address_tail
;
2948 GuestIpAddress
*address_item
= NULL
;
2949 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
2950 char addr4
[INET_ADDRSTRLEN
];
2951 char addr6
[INET6_ADDRSTRLEN
];
2952 unsigned char mac_addr
[ETHER_ADDR_LEN
];
2956 g_debug("Processing %s interface", ifa
->ifa_name
);
2958 info
= guest_find_interface(head
, ifa
->ifa_name
);
2961 info
= g_malloc0(sizeof(*info
));
2962 info
->name
= g_strdup(ifa
->ifa_name
);
2964 QAPI_LIST_APPEND(tail
, info
);
2967 if (!info
->hardware_address
) {
2968 if (!guest_get_hw_addr(ifa
, mac_addr
, &obtained
, errp
)) {
2972 info
->hardware_address
=
2973 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2974 (int) mac_addr
[0], (int) mac_addr
[1],
2975 (int) mac_addr
[2], (int) mac_addr
[3],
2976 (int) mac_addr
[4], (int) mac_addr
[5]);
2980 if (ifa
->ifa_addr
&&
2981 ifa
->ifa_addr
->sa_family
== AF_INET
) {
2982 /* interface with IPv4 address */
2983 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
2984 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
2985 error_setg_errno(errp
, errno
, "inet_ntop failed");
2989 address_item
= g_malloc0(sizeof(*address_item
));
2990 address_item
->ip_address
= g_strdup(addr4
);
2991 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
2993 if (ifa
->ifa_netmask
) {
2994 /* Count the number of set bits in netmask.
2995 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2996 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
2997 address_item
->prefix
= ctpop32(((uint32_t *) p
)[0]);
2999 } else if (ifa
->ifa_addr
&&
3000 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
3001 /* interface with IPv6 address */
3002 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
3003 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
3004 error_setg_errno(errp
, errno
, "inet_ntop failed");
3008 address_item
= g_malloc0(sizeof(*address_item
));
3009 address_item
->ip_address
= g_strdup(addr6
);
3010 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
3012 if (ifa
->ifa_netmask
) {
3013 /* Count the number of set bits in netmask.
3014 * This is safe as '1' and '0' cannot be shuffled in netmask. */
3015 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
3016 address_item
->prefix
=
3017 ctpop32(((uint32_t *) p
)[0]) +
3018 ctpop32(((uint32_t *) p
)[1]) +
3019 ctpop32(((uint32_t *) p
)[2]) +
3020 ctpop32(((uint32_t *) p
)[3]);
3024 if (!address_item
) {
3028 address_tail
= &info
->ip_addresses
;
3029 while (*address_tail
) {
3030 address_tail
= &(*address_tail
)->next
;
3032 QAPI_LIST_APPEND(address_tail
, address_item
);
3034 info
->has_ip_addresses
= true;
3036 if (!info
->statistics
) {
3037 interface_stat
= g_malloc0(sizeof(*interface_stat
));
3038 if (guest_get_network_stats(info
->name
, interface_stat
) == -1) {
3039 g_free(interface_stat
);
3041 info
->statistics
= interface_stat
;
3051 qapi_free_GuestNetworkInterfaceList(head
);
3057 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
3059 error_setg(errp
, QERR_UNSUPPORTED
);
3063 #endif /* HAVE_GETIFADDRS */
3065 #if !defined(CONFIG_FSFREEZE)
3067 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
3069 error_setg(errp
, QERR_UNSUPPORTED
);
3073 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
3075 error_setg(errp
, QERR_UNSUPPORTED
);
3080 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
3082 error_setg(errp
, QERR_UNSUPPORTED
);
3087 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
3088 strList
*mountpoints
,
3091 error_setg(errp
, QERR_UNSUPPORTED
);
3096 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
3098 error_setg(errp
, QERR_UNSUPPORTED
);
3103 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
3105 error_setg(errp
, QERR_UNSUPPORTED
);
3109 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
3111 error_setg(errp
, QERR_UNSUPPORTED
);
3115 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
3117 error_setg(errp
, QERR_UNSUPPORTED
);
3121 #endif /* CONFIG_FSFREEZE */
3123 #if !defined(CONFIG_FSTRIM)
3124 GuestFilesystemTrimResponse
*
3125 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
3127 error_setg(errp
, QERR_UNSUPPORTED
);
3132 /* add unsupported commands to the list of blocked RPCs */
3133 GList
*ga_command_init_blockedrpcs(GList
*blockedrpcs
)
3135 #if !defined(__linux__)
3137 const char *list
[] = {
3138 "guest-suspend-disk", "guest-suspend-ram",
3139 "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
3140 "guest-get-memory-blocks", "guest-set-memory-blocks",
3141 "guest-get-memory-block-size", "guest-get-memory-block-info",
3143 char **p
= (char **)list
;
3146 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3151 #if !defined(HAVE_GETIFADDRS)
3152 blockedrpcs
= g_list_append(blockedrpcs
,
3153 g_strdup("guest-network-get-interfaces"));
3156 #if !defined(CONFIG_FSFREEZE)
3158 const char *list
[] = {
3159 "guest-get-fsinfo", "guest-fsfreeze-status",
3160 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3161 "guest-fsfreeze-thaw", "guest-get-fsinfo",
3162 "guest-get-disks", NULL
};
3163 char **p
= (char **)list
;
3166 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3171 #if !defined(CONFIG_FSTRIM)
3172 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-fstrim"));
3175 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-get-devices"));
3180 /* register init/cleanup routines for stateful command groups */
3181 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
3183 #if defined(CONFIG_FSFREEZE)
3184 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
3190 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3192 static double ga_get_login_time(struct utmpx
*user_info
)
3194 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
3195 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
3196 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
3197 return seconds
+ useconds
;
3200 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3202 GHashTable
*cache
= NULL
;
3203 GuestUserList
*head
= NULL
, **tail
= &head
;
3204 struct utmpx
*user_info
= NULL
;
3205 gpointer value
= NULL
;
3206 GuestUser
*user
= NULL
;
3207 double login_time
= 0;
3209 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
3213 user_info
= getutxent();
3214 if (user_info
== NULL
) {
3216 } else if (user_info
->ut_type
!= USER_PROCESS
) {
3218 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
3219 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
3220 user
= (GuestUser
*)value
;
3221 login_time
= ga_get_login_time(user_info
);
3222 /* We're ensuring the earliest login time to be sent */
3223 if (login_time
< user
->login_time
) {
3224 user
->login_time
= login_time
;
3229 user
= g_new0(GuestUser
, 1);
3230 user
->user
= g_strdup(user_info
->ut_user
);
3231 user
->login_time
= ga_get_login_time(user_info
);
3233 g_hash_table_insert(cache
, user
->user
, user
);
3235 QAPI_LIST_APPEND(tail
, user
);
3238 g_hash_table_destroy(cache
);
3244 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3246 error_setg(errp
, QERR_UNSUPPORTED
);
3252 /* Replace escaped special characters with their real values. The replacement
3253 * is done in place -- returned value is in the original string.
3255 static void ga_osrelease_replace_special(gchar
*value
)
3257 gchar
*p
, *p2
, quote
;
3259 /* Trim the string at first space or semicolon if it is not enclosed in
3260 * single or double quotes. */
3261 if ((value
[0] != '"') || (value
[0] == '\'')) {
3262 p
= strchr(value
, ' ');
3266 p
= strchr(value
, ';');
3287 /* Keep literal backslash followed by whatever is there */
3291 } else if (*p
== quote
) {
3299 static GKeyFile
*ga_parse_osrelease(const char *fname
)
3301 gchar
*content
= NULL
;
3302 gchar
*content2
= NULL
;
3304 GKeyFile
*keys
= g_key_file_new();
3305 const char *group
= "[os-release]\n";
3307 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
3308 slog("failed to read '%s', error: %s", fname
, err
->message
);
3312 if (!g_utf8_validate(content
, -1, NULL
)) {
3313 slog("file is not utf-8 encoded: %s", fname
);
3316 content2
= g_strdup_printf("%s%s", group
, content
);
3318 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
3320 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
3332 g_key_file_free(keys
);
3336 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
3338 GuestOSInfo
*info
= NULL
;
3339 struct utsname kinfo
;
3340 GKeyFile
*osrelease
= NULL
;
3341 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
3343 info
= g_new0(GuestOSInfo
, 1);
3345 if (uname(&kinfo
) != 0) {
3346 error_setg_errno(errp
, errno
, "uname failed");
3348 info
->kernel_version
= g_strdup(kinfo
.version
);
3349 info
->kernel_release
= g_strdup(kinfo
.release
);
3350 info
->machine
= g_strdup(kinfo
.machine
);
3353 if (qga_os_release
!= NULL
) {
3354 osrelease
= ga_parse_osrelease(qga_os_release
);
3356 osrelease
= ga_parse_osrelease("/etc/os-release");
3357 if (osrelease
== NULL
) {
3358 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
3362 if (osrelease
!= NULL
) {
3365 #define GET_FIELD(field, osfield) do { \
3366 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3367 if (value != NULL) { \
3368 ga_osrelease_replace_special(value); \
3369 info->field = value; \
3372 GET_FIELD(id
, "ID");
3373 GET_FIELD(name
, "NAME");
3374 GET_FIELD(pretty_name
, "PRETTY_NAME");
3375 GET_FIELD(version
, "VERSION");
3376 GET_FIELD(version_id
, "VERSION_ID");
3377 GET_FIELD(variant
, "VARIANT");
3378 GET_FIELD(variant_id
, "VARIANT_ID");
3381 g_key_file_free(osrelease
);
3387 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
3389 error_setg(errp
, QERR_UNSUPPORTED
);
3394 #ifndef HOST_NAME_MAX
3395 # ifdef _POSIX_HOST_NAME_MAX
3396 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
3398 # define HOST_NAME_MAX 255
3402 char *qga_get_host_name(Error
**errp
)
3405 g_autofree
char *hostname
= NULL
;
3407 #ifdef _SC_HOST_NAME_MAX
3408 len
= sysconf(_SC_HOST_NAME_MAX
);
3409 #endif /* _SC_HOST_NAME_MAX */
3412 len
= HOST_NAME_MAX
;
3415 /* Unfortunately, gethostname() below does not guarantee a
3416 * NULL terminated string. Therefore, allocate one byte more
3418 hostname
= g_new0(char, len
+ 1);
3420 if (gethostname(hostname
, len
) < 0) {
3421 error_setg_errno(errp
, errno
,
3422 "cannot get hostname");
3426 return g_steal_pointer(&hostname
);