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__) || defined(CONFIG_SOLARIS)
49 #include <net/if_arp.h>
50 #include <netinet/if_ether.h>
51 #if !defined(ETHER_ADDR_LEN) && defined(ETHERADDRL)
52 #define ETHER_ADDR_LEN ETHERADDRL
55 #include <net/ethernet.h>
58 #include <sys/sockio.h>
62 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
68 rpid
= RETRY_ON_EINTR(waitpid(pid
, status
, 0));
71 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
76 g_assert(rpid
== pid
);
79 void qmp_guest_shutdown(const char *mode
, Error
**errp
)
81 const char *shutdown_flag
;
82 Error
*local_err
= NULL
;
87 const char *powerdown_flag
= "-i5";
88 const char *halt_flag
= "-i0";
89 const char *reboot_flag
= "-i6";
90 #elif defined(CONFIG_BSD)
91 const char *powerdown_flag
= "-p";
92 const char *halt_flag
= "-h";
93 const char *reboot_flag
= "-r";
95 const char *powerdown_flag
= "-P";
96 const char *halt_flag
= "-H";
97 const char *reboot_flag
= "-r";
100 slog("guest-shutdown called, mode: %s", mode
);
101 if (!mode
|| strcmp(mode
, "powerdown") == 0) {
102 shutdown_flag
= powerdown_flag
;
103 } else if (strcmp(mode
, "halt") == 0) {
104 shutdown_flag
= halt_flag
;
105 } else if (strcmp(mode
, "reboot") == 0) {
106 shutdown_flag
= reboot_flag
;
109 "mode is invalid (valid values are: halt|powerdown|reboot");
115 /* child, start the shutdown */
117 reopen_fd_to_null(0);
118 reopen_fd_to_null(1);
119 reopen_fd_to_null(2);
121 #ifdef CONFIG_SOLARIS
122 execl("/sbin/shutdown", "shutdown", shutdown_flag
, "-g0", "-y",
123 "hypervisor initiated shutdown", (char *)NULL
);
124 #elif defined(CONFIG_BSD)
125 execl("/sbin/shutdown", "shutdown", shutdown_flag
, "+0",
126 "hypervisor initiated shutdown", (char *)NULL
);
128 execl("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
129 "hypervisor initiated shutdown", (char *)NULL
);
132 } else if (pid
< 0) {
133 error_setg_errno(errp
, errno
, "failed to create child process");
137 ga_wait_child(pid
, &status
, &local_err
);
139 error_propagate(errp
, local_err
);
143 if (!WIFEXITED(status
)) {
144 error_setg(errp
, "child process has terminated abnormally");
148 if (WEXITSTATUS(status
)) {
149 error_setg(errp
, "child process has failed to shutdown");
156 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
161 Error
*local_err
= NULL
;
163 static const char hwclock_path
[] = "/sbin/hwclock";
164 static int hwclock_available
= -1;
166 if (hwclock_available
< 0) {
167 hwclock_available
= (access(hwclock_path
, X_OK
) == 0);
170 if (!hwclock_available
) {
171 error_setg(errp
, QERR_UNSUPPORTED
);
175 /* If user has passed a time, validate and set it. */
179 /* year-2038 will overflow in case time_t is 32bit */
180 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
181 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
185 tv
.tv_sec
= time_ns
/ 1000000000;
186 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
187 g_date_set_time_t(&date
, tv
.tv_sec
);
188 if (date
.year
< 1970 || date
.year
>= 2070) {
189 error_setg_errno(errp
, errno
, "Invalid time");
193 ret
= settimeofday(&tv
, NULL
);
195 error_setg_errno(errp
, errno
, "Failed to set time to guest");
200 /* Now, if user has passed a time to set and the system time is set, we
201 * just need to synchronize the hardware clock. However, if no time was
202 * passed, user is requesting the opposite: set the system time from the
203 * hardware clock (RTC). */
207 reopen_fd_to_null(0);
208 reopen_fd_to_null(1);
209 reopen_fd_to_null(2);
211 /* Use '/sbin/hwclock -w' to set RTC from the system time,
212 * or '/sbin/hwclock -s' to set the system time from RTC. */
213 execl(hwclock_path
, "hwclock", has_time
? "-w" : "-s", NULL
);
215 } else if (pid
< 0) {
216 error_setg_errno(errp
, errno
, "failed to create child process");
220 ga_wait_child(pid
, &status
, &local_err
);
222 error_propagate(errp
, local_err
);
226 if (!WIFEXITED(status
)) {
227 error_setg(errp
, "child process has terminated abnormally");
231 if (WEXITSTATUS(status
)) {
232 error_setg(errp
, "hwclock failed to set hardware clock to system time");
243 struct GuestFileHandle
{
247 QTAILQ_ENTRY(GuestFileHandle
) next
;
251 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
252 } guest_file_state
= {
253 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
256 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
258 GuestFileHandle
*gfh
;
261 handle
= ga_get_fd_handle(ga_state
, errp
);
266 gfh
= g_new0(GuestFileHandle
, 1);
269 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
274 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
276 GuestFileHandle
*gfh
;
278 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
285 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
289 typedef const char * const ccpc
;
295 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
296 static const struct {
299 } guest_file_open_modes
[] = {
300 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
301 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
302 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
303 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
304 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
305 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
306 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
307 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
308 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
309 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
310 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
311 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
315 find_open_flag(const char *mode_str
, Error
**errp
)
319 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
322 form
= guest_file_open_modes
[mode
].forms
;
323 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
331 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
332 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
335 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
338 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
339 S_IRGRP | S_IWGRP | \
343 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
349 oflag
= find_open_flag(mode
, errp
);
354 /* If the caller wants / allows creation of a new file, we implement it
355 * with a two step process: open() + (open() / fchmod()).
357 * First we insist on creating the file exclusively as a new file. If
358 * that succeeds, we're free to set any file-mode bits on it. (The
359 * motivation is that we want to set those file-mode bits independently
360 * of the current umask.)
362 * If the exclusive creation fails because the file already exists
363 * (EEXIST is not possible for any other reason), we just attempt to
364 * open the file, but in this case we won't be allowed to change the
365 * file-mode bits on the preexistent file.
367 * The pathname should never disappear between the two open()s in
368 * practice. If it happens, then someone very likely tried to race us.
369 * In this case just go ahead and report the ENOENT from the second
370 * open() to the caller.
372 * If the caller wants to open a preexistent file, then the first
373 * open() is decisive and its third argument is ignored, and the second
374 * open() and the fchmod() are never called.
376 fd
= qga_open_cloexec(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
377 if (fd
== -1 && errno
== EEXIST
) {
378 oflag
&= ~(unsigned)O_CREAT
;
379 fd
= qga_open_cloexec(path
, oflag
, 0);
382 error_setg_errno(errp
, errno
,
383 "failed to open file '%s' (mode: '%s')",
388 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
389 error_setg_errno(errp
, errno
, "failed to set permission "
390 "0%03o on new file '%s' (mode: '%s')",
391 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
395 f
= fdopen(fd
, mode
);
397 error_setg_errno(errp
, errno
, "failed to associate stdio stream with "
398 "file descriptor %d, file '%s' (mode: '%s')",
403 if (f
== NULL
&& fd
!= -1) {
405 if (oflag
& O_CREAT
) {
412 int64_t qmp_guest_file_open(const char *path
, const char *mode
,
416 Error
*local_err
= NULL
;
422 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
423 fh
= safe_open_or_create(path
, mode
, &local_err
);
424 if (local_err
!= NULL
) {
425 error_propagate(errp
, local_err
);
429 /* set fd non-blocking to avoid common use cases (like reading from a
430 * named pipe) from hanging the agent
432 if (!g_unix_set_fd_nonblocking(fileno(fh
), true, NULL
)) {
434 error_setg_errno(errp
, errno
, "Failed to set FD nonblocking");
438 handle
= guest_file_handle_add(fh
, errp
);
444 slog("guest-file-open, handle: %" PRId64
, handle
);
448 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
450 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
453 slog("guest-file-close called, handle: %" PRId64
, handle
);
458 ret
= fclose(gfh
->fh
);
460 error_setg_errno(errp
, errno
, "failed to close handle");
464 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
468 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
469 int64_t count
, Error
**errp
)
471 GuestFileRead
*read_data
= NULL
;
476 /* explicitly flush when switching from writing to reading */
477 if (gfh
->state
== RW_STATE_WRITING
) {
478 int ret
= fflush(fh
);
480 error_setg_errno(errp
, errno
, "failed to flush file");
483 gfh
->state
= RW_STATE_NEW
;
486 buf
= g_malloc0(count
+ 1);
487 read_count
= fread(buf
, 1, count
, fh
);
489 error_setg_errno(errp
, errno
, "failed to read file");
492 read_data
= g_new0(GuestFileRead
, 1);
493 read_data
->count
= read_count
;
494 read_data
->eof
= feof(fh
);
496 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
498 gfh
->state
= RW_STATE_READING
;
506 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
507 bool has_count
, int64_t count
,
510 GuestFileWrite
*write_data
= NULL
;
514 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
523 if (gfh
->state
== RW_STATE_READING
) {
524 int ret
= fseek(fh
, 0, SEEK_CUR
);
526 error_setg_errno(errp
, errno
, "failed to seek file");
529 gfh
->state
= RW_STATE_NEW
;
532 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
539 } else if (count
< 0 || count
> buf_len
) {
540 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
546 write_count
= fwrite(buf
, 1, count
, fh
);
548 error_setg_errno(errp
, errno
, "failed to write to file");
549 slog("guest-file-write failed, handle: %" PRId64
, handle
);
551 write_data
= g_new0(GuestFileWrite
, 1);
552 write_data
->count
= write_count
;
553 write_data
->eof
= feof(fh
);
554 gfh
->state
= RW_STATE_WRITING
;
562 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
563 GuestFileWhence
*whence_code
,
566 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
567 GuestFileSeek
*seek_data
= NULL
;
577 /* We stupidly exposed 'whence':'int' in our qapi */
578 whence
= ga_parse_whence(whence_code
, &err
);
580 error_propagate(errp
, err
);
585 ret
= fseek(fh
, offset
, whence
);
587 error_setg_errno(errp
, errno
, "failed to seek file");
588 if (errno
== ESPIPE
) {
589 /* file is non-seekable, stdio shouldn't be buffering anyways */
590 gfh
->state
= RW_STATE_NEW
;
593 seek_data
= g_new0(GuestFileSeek
, 1);
594 seek_data
->position
= ftell(fh
);
595 seek_data
->eof
= feof(fh
);
596 gfh
->state
= RW_STATE_NEW
;
603 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
605 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
616 error_setg_errno(errp
, errno
, "failed to flush file");
618 gfh
->state
= RW_STATE_NEW
;
622 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
623 void free_fs_mount_list(FsMountList
*mounts
)
625 FsMount
*mount
, *temp
;
631 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
632 QTAILQ_REMOVE(mounts
, mount
, next
);
633 g_free(mount
->dirname
);
634 g_free(mount
->devtype
);
640 #if defined(CONFIG_FSFREEZE)
642 FSFREEZE_HOOK_THAW
= 0,
643 FSFREEZE_HOOK_FREEZE
,
646 static const char *fsfreeze_hook_arg_string
[] = {
651 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
656 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
657 Error
*local_err
= NULL
;
659 hook
= ga_fsfreeze_hook(ga_state
);
663 if (access(hook
, X_OK
) != 0) {
664 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
668 slog("executing fsfreeze hook with arg '%s'", arg_str
);
672 reopen_fd_to_null(0);
673 reopen_fd_to_null(1);
674 reopen_fd_to_null(2);
676 execl(hook
, hook
, arg_str
, NULL
);
678 } else if (pid
< 0) {
679 error_setg_errno(errp
, errno
, "failed to create child process");
683 ga_wait_child(pid
, &status
, &local_err
);
685 error_propagate(errp
, local_err
);
689 if (!WIFEXITED(status
)) {
690 error_setg(errp
, "fsfreeze hook has terminated abnormally");
694 status
= WEXITSTATUS(status
);
696 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
702 * Return status of freeze/thaw
704 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
706 if (ga_is_frozen(ga_state
)) {
707 return GUEST_FSFREEZE_STATUS_FROZEN
;
710 return GUEST_FSFREEZE_STATUS_THAWED
;
713 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
715 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
718 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
719 strList
*mountpoints
,
724 Error
*local_err
= NULL
;
726 slog("guest-fsfreeze called");
728 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
730 error_propagate(errp
, local_err
);
734 QTAILQ_INIT(&mounts
);
735 if (!build_fs_mount_list(&mounts
, &local_err
)) {
736 error_propagate(errp
, local_err
);
740 /* cannot risk guest agent blocking itself on a write in this state */
741 ga_set_frozen(ga_state
);
743 ret
= qmp_guest_fsfreeze_do_freeze_list(has_mountpoints
, mountpoints
,
746 free_fs_mount_list(&mounts
);
747 /* We may not issue any FIFREEZE here.
748 * Just unset ga_state here and ready for the next call.
751 ga_unset_frozen(ga_state
);
752 } else if (ret
< 0) {
753 qmp_guest_fsfreeze_thaw(NULL
);
758 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
762 ret
= qmp_guest_fsfreeze_do_thaw(errp
);
764 ga_unset_frozen(ga_state
);
765 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
773 static void guest_fsfreeze_cleanup(void)
777 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
778 qmp_guest_fsfreeze_thaw(&err
);
780 slog("failed to clean up frozen filesystems: %s",
781 error_get_pretty(err
));
788 /* linux-specific implementations. avoid this if at all possible. */
789 #if defined(__linux__)
790 #if defined(CONFIG_FSFREEZE)
792 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
800 path
= g_strndup(syspath
, pathlen
);
801 dpath
= g_strdup_printf("%s/driver", path
);
802 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
805 driver
= g_path_get_basename(buf
);
812 static int compare_uint(const void *_a
, const void *_b
)
814 unsigned int a
= *(unsigned int *)_a
;
815 unsigned int b
= *(unsigned int *)_b
;
817 return a
< b
? -1 : a
> b
? 1 : 0;
820 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
821 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
822 unsigned int *hosts
, int hosts_max
, Error
**errp
)
826 struct dirent
*entry
;
829 path
= g_strndup(syspath
, host
- syspath
);
832 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
837 while (i
< hosts_max
) {
838 entry
= readdir(dir
);
842 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
844 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
849 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
857 * Store disk device info for devices on the PCI bus.
858 * Returns true if information has been stored, or false for failure.
860 static bool build_guest_fsinfo_for_pci_dev(char const *syspath
,
861 GuestDiskAddress
*disk
,
864 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
865 int i
, nhosts
= 0, pcilen
;
866 GuestPCIAddress
*pciaddr
= disk
->pci_controller
;
867 bool has_ata
= false, has_host
= false, has_tgt
= false;
868 char *p
, *q
, *driver
= NULL
;
871 p
= strstr(syspath
, "/devices/pci");
872 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
873 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
874 g_debug("only pci device is supported: sysfs path '%s'", syspath
);
880 driver
= get_pci_driver(syspath
, p
- syspath
, errp
);
881 if (driver
&& (g_str_equal(driver
, "ata_piix") ||
882 g_str_equal(driver
, "sym53c8xx") ||
883 g_str_equal(driver
, "virtio-pci") ||
884 g_str_equal(driver
, "ahci") ||
885 g_str_equal(driver
, "nvme") ||
886 g_str_equal(driver
, "xhci_hcd") ||
887 g_str_equal(driver
, "ehci-pci"))) {
892 if (sscanf(p
, "/%x:%x:%x.%x%n",
893 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
898 g_debug("unsupported driver or sysfs path '%s'", syspath
);
902 p
= strstr(syspath
, "/target");
903 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
904 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
908 p
= strstr(syspath
, "/ata");
913 p
= strstr(syspath
, "/host");
916 if (p
&& sscanf(q
, "%u", &host
) == 1) {
918 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
919 ARRAY_SIZE(hosts
), errp
);
925 pciaddr
->domain
= pci
[0];
926 pciaddr
->bus
= pci
[1];
927 pciaddr
->slot
= pci
[2];
928 pciaddr
->function
= pci
[3];
930 if (strcmp(driver
, "ata_piix") == 0) {
931 /* a host per ide bus, target*:0:<unit>:0 */
932 if (!has_host
|| !has_tgt
) {
933 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
936 for (i
= 0; i
< nhosts
; i
++) {
937 if (host
== hosts
[i
]) {
938 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
945 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
948 } else if (strcmp(driver
, "sym53c8xx") == 0) {
949 /* scsi(LSI Logic): target*:0:<unit>:0 */
951 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
954 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
956 } else if (strcmp(driver
, "virtio-pci") == 0) {
958 /* virtio-scsi: target*:0:0:<unit> */
959 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
962 /* virtio-blk: 1 disk per 1 device */
963 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
965 } else if (strcmp(driver
, "ahci") == 0) {
966 /* ahci: 1 host per 1 unit */
967 if (!has_host
|| !has_tgt
) {
968 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
971 for (i
= 0; i
< nhosts
; i
++) {
972 if (host
== hosts
[i
]) {
974 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
979 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
982 } else if (strcmp(driver
, "nvme") == 0) {
983 disk
->bus_type
= GUEST_DISK_BUS_TYPE_NVME
;
984 } else if (strcmp(driver
, "ehci-pci") == 0 || strcmp(driver
, "xhci_hcd") == 0) {
985 disk
->bus_type
= GUEST_DISK_BUS_TYPE_USB
;
987 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
999 * Store disk device info for non-PCI virtio devices (for example s390x
1000 * channel I/O devices). Returns true if information has been stored, or
1001 * false for failure.
1003 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath
,
1004 GuestDiskAddress
*disk
,
1007 unsigned int tgt
[3];
1010 if (!strstr(syspath
, "/virtio") || !strstr(syspath
, "/block")) {
1011 g_debug("Unsupported virtio device '%s'", syspath
);
1015 p
= strstr(syspath
, "/target");
1016 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1017 &tgt
[0], &tgt
[1], &tgt
[2]) == 3) {
1018 /* virtio-scsi: target*:0:<target>:<unit> */
1019 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1021 disk
->target
= tgt
[1];
1022 disk
->unit
= tgt
[2];
1024 /* virtio-blk: 1 disk per 1 device */
1025 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
1032 * Store disk device info for CCW devices (s390x channel I/O devices).
1033 * Returns true if information has been stored, or false for failure.
1035 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath
,
1036 GuestDiskAddress
*disk
,
1039 unsigned int cssid
, ssid
, subchno
, devno
;
1042 p
= strstr(syspath
, "/devices/css");
1043 if (!p
|| sscanf(p
+ 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1044 &cssid
, &ssid
, &subchno
, &devno
) < 4) {
1045 g_debug("could not parse ccw device sysfs path: %s", syspath
);
1049 disk
->ccw_address
= g_new0(GuestCCWAddress
, 1);
1050 disk
->ccw_address
->cssid
= cssid
;
1051 disk
->ccw_address
->ssid
= ssid
;
1052 disk
->ccw_address
->subchno
= subchno
;
1053 disk
->ccw_address
->devno
= devno
;
1055 if (strstr(p
, "/virtio")) {
1056 build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1062 /* Store disk device info specified by @sysfs into @fs */
1063 static void build_guest_fsinfo_for_real_device(char const *syspath
,
1064 GuestFilesystemInfo
*fs
,
1067 GuestDiskAddress
*disk
;
1068 GuestPCIAddress
*pciaddr
;
1070 #ifdef CONFIG_LIBUDEV
1071 struct udev
*udev
= NULL
;
1072 struct udev_device
*udevice
= NULL
;
1075 pciaddr
= g_new0(GuestPCIAddress
, 1);
1076 pciaddr
->domain
= -1; /* -1 means field is invalid */
1079 pciaddr
->function
= -1;
1081 disk
= g_new0(GuestDiskAddress
, 1);
1082 disk
->pci_controller
= pciaddr
;
1083 disk
->bus_type
= GUEST_DISK_BUS_TYPE_UNKNOWN
;
1085 #ifdef CONFIG_LIBUDEV
1087 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1088 if (udev
== NULL
|| udevice
== NULL
) {
1089 g_debug("failed to query udev");
1091 const char *devnode
, *serial
;
1092 devnode
= udev_device_get_devnode(udevice
);
1093 if (devnode
!= NULL
) {
1094 disk
->dev
= g_strdup(devnode
);
1096 serial
= udev_device_get_property_value(udevice
, "ID_SERIAL");
1097 if (serial
!= NULL
&& *serial
!= 0) {
1098 disk
->serial
= g_strdup(serial
);
1103 udev_device_unref(udevice
);
1106 if (strstr(syspath
, "/devices/pci")) {
1107 has_hwinf
= build_guest_fsinfo_for_pci_dev(syspath
, disk
, errp
);
1108 } else if (strstr(syspath
, "/devices/css")) {
1109 has_hwinf
= build_guest_fsinfo_for_ccw_dev(syspath
, disk
, errp
);
1110 } else if (strstr(syspath
, "/virtio")) {
1111 has_hwinf
= build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1113 g_debug("Unsupported device type for '%s'", syspath
);
1117 if (has_hwinf
|| disk
->dev
|| disk
->serial
) {
1118 QAPI_LIST_PREPEND(fs
->disk
, disk
);
1120 qapi_free_GuestDiskAddress(disk
);
1124 static void build_guest_fsinfo_for_device(char const *devpath
,
1125 GuestFilesystemInfo
*fs
,
1128 /* Store a list of slave devices of virtual volume specified by @syspath into
1130 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1131 GuestFilesystemInfo
*fs
,
1137 struct dirent
*entry
;
1139 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1140 dir
= opendir(dirpath
);
1142 if (errno
!= ENOENT
) {
1143 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1151 entry
= readdir(dir
);
1152 if (entry
== NULL
) {
1154 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1159 if (entry
->d_type
== DT_LNK
) {
1162 g_debug(" slave device '%s'", entry
->d_name
);
1163 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1164 build_guest_fsinfo_for_device(path
, fs
, &err
);
1168 error_propagate(errp
, err
);
1178 static bool is_disk_virtual(const char *devpath
, Error
**errp
)
1180 g_autofree
char *syspath
= realpath(devpath
, NULL
);
1183 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1186 return strstr(syspath
, "/devices/virtual/block/") != NULL
;
1189 /* Dispatch to functions for virtual/real device */
1190 static void build_guest_fsinfo_for_device(char const *devpath
,
1191 GuestFilesystemInfo
*fs
,
1195 g_autofree
char *syspath
= NULL
;
1196 bool is_virtual
= false;
1198 syspath
= realpath(devpath
, NULL
);
1200 if (errno
!= ENOENT
) {
1201 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1205 /* ENOENT: This devpath may not exist because of container config */
1207 fs
->name
= g_path_get_basename(devpath
);
1213 fs
->name
= g_path_get_basename(syspath
);
1216 g_debug(" parse sysfs path '%s'", syspath
);
1217 is_virtual
= is_disk_virtual(syspath
, errp
);
1218 if (*errp
!= NULL
) {
1222 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1224 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1228 #ifdef CONFIG_LIBUDEV
1231 * Wrapper around build_guest_fsinfo_for_device() for getting just
1234 static GuestDiskAddress
*get_disk_address(const char *syspath
, Error
**errp
)
1236 g_autoptr(GuestFilesystemInfo
) fs
= NULL
;
1238 fs
= g_new0(GuestFilesystemInfo
, 1);
1239 build_guest_fsinfo_for_device(syspath
, fs
, errp
);
1240 if (fs
->disk
!= NULL
) {
1241 return g_steal_pointer(&fs
->disk
->value
);
1246 static char *get_alias_for_syspath(const char *syspath
)
1248 struct udev
*udev
= NULL
;
1249 struct udev_device
*udevice
= NULL
;
1254 g_debug("failed to query udev");
1257 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1258 if (udevice
== NULL
) {
1259 g_debug("failed to query udev for path: %s", syspath
);
1262 const char *alias
= udev_device_get_property_value(
1263 udevice
, "DM_NAME");
1265 * NULL means there was an error and empty string means there is no
1266 * alias. In case of no alias we return NULL instead of empty string.
1268 if (alias
== NULL
) {
1269 g_debug("failed to query udev for device alias for: %s",
1271 } else if (*alias
!= 0) {
1272 ret
= g_strdup(alias
);
1278 udev_device_unref(udevice
);
1282 static char *get_device_for_syspath(const char *syspath
)
1284 struct udev
*udev
= NULL
;
1285 struct udev_device
*udevice
= NULL
;
1290 g_debug("failed to query udev");
1293 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1294 if (udevice
== NULL
) {
1295 g_debug("failed to query udev for path: %s", syspath
);
1298 ret
= g_strdup(udev_device_get_devnode(udevice
));
1303 udev_device_unref(udevice
);
1307 static void get_disk_deps(const char *disk_dir
, GuestDiskInfo
*disk
)
1309 g_autofree
char *deps_dir
= NULL
;
1311 GDir
*dp_deps
= NULL
;
1313 /* List dependent disks */
1314 deps_dir
= g_strdup_printf("%s/slaves", disk_dir
);
1315 g_debug(" listing entries in: %s", deps_dir
);
1316 dp_deps
= g_dir_open(deps_dir
, 0, NULL
);
1317 if (dp_deps
== NULL
) {
1318 g_debug("failed to list entries in %s", deps_dir
);
1321 disk
->has_dependencies
= true;
1322 while ((dep
= g_dir_read_name(dp_deps
)) != NULL
) {
1323 g_autofree
char *dep_dir
= NULL
;
1326 /* Add dependent disks */
1327 dep_dir
= g_strdup_printf("%s/%s", deps_dir
, dep
);
1328 dev_name
= get_device_for_syspath(dep_dir
);
1329 if (dev_name
!= NULL
) {
1330 g_debug(" adding dependent device: %s", dev_name
);
1331 QAPI_LIST_PREPEND(disk
->dependencies
, dev_name
);
1334 g_dir_close(dp_deps
);
1338 * Detect partitions subdirectory, name is "<disk_name><number>" or
1339 * "<disk_name>p<number>"
1341 * @disk_name -- last component of /sys path (e.g. sda)
1342 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1343 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1345 static GuestDiskInfoList
*get_disk_partitions(
1346 GuestDiskInfoList
*list
,
1347 const char *disk_name
, const char *disk_dir
,
1348 const char *disk_dev
)
1350 GuestDiskInfoList
*ret
= list
;
1351 struct dirent
*de_disk
;
1352 DIR *dp_disk
= NULL
;
1353 size_t len
= strlen(disk_name
);
1355 dp_disk
= opendir(disk_dir
);
1356 while ((de_disk
= readdir(dp_disk
)) != NULL
) {
1357 g_autofree
char *partition_dir
= NULL
;
1359 GuestDiskInfo
*partition
;
1361 if (!(de_disk
->d_type
& DT_DIR
)) {
1365 if (!(strncmp(disk_name
, de_disk
->d_name
, len
) == 0 &&
1366 ((*(de_disk
->d_name
+ len
) == 'p' &&
1367 isdigit(*(de_disk
->d_name
+ len
+ 1))) ||
1368 isdigit(*(de_disk
->d_name
+ len
))))) {
1372 partition_dir
= g_strdup_printf("%s/%s",
1373 disk_dir
, de_disk
->d_name
);
1374 dev_name
= get_device_for_syspath(partition_dir
);
1375 if (dev_name
== NULL
) {
1376 g_debug("Failed to get device name for syspath: %s",
1380 partition
= g_new0(GuestDiskInfo
, 1);
1381 partition
->name
= dev_name
;
1382 partition
->partition
= true;
1383 partition
->has_dependencies
= true;
1384 /* Add parent disk as dependent for easier tracking of hierarchy */
1385 QAPI_LIST_PREPEND(partition
->dependencies
, g_strdup(disk_dev
));
1387 QAPI_LIST_PREPEND(ret
, partition
);
1394 static void get_nvme_smart(GuestDiskInfo
*disk
)
1397 GuestNVMeSmart
*smart
;
1398 NvmeSmartLog log
= {0};
1399 struct nvme_admin_cmd cmd
= {
1400 .opcode
= NVME_ADM_CMD_GET_LOG_PAGE
,
1401 .nsid
= NVME_NSID_BROADCAST
,
1402 .addr
= (uintptr_t)&log
,
1403 .data_len
= sizeof(log
),
1404 .cdw10
= NVME_LOG_SMART_INFO
| (1 << 15) /* RAE bit */
1405 | (((sizeof(log
) >> 2) - 1) << 16)
1408 fd
= qga_open_cloexec(disk
->name
, O_RDONLY
, 0);
1410 g_debug("Failed to open device: %s: %s", disk
->name
, g_strerror(errno
));
1414 if (ioctl(fd
, NVME_IOCTL_ADMIN_CMD
, &cmd
)) {
1415 g_debug("Failed to get smart: %s: %s", disk
->name
, g_strerror(errno
));
1420 disk
->smart
= g_new0(GuestDiskSmart
, 1);
1421 disk
->smart
->type
= GUEST_DISK_BUS_TYPE_NVME
;
1423 smart
= &disk
->smart
->u
.nvme
;
1424 smart
->critical_warning
= log
.critical_warning
;
1425 smart
->temperature
= lduw_le_p(&log
.temperature
); /* unaligned field */
1426 smart
->available_spare
= log
.available_spare
;
1427 smart
->available_spare_threshold
= log
.available_spare_threshold
;
1428 smart
->percentage_used
= log
.percentage_used
;
1429 smart
->data_units_read_lo
= le64_to_cpu(log
.data_units_read
[0]);
1430 smart
->data_units_read_hi
= le64_to_cpu(log
.data_units_read
[1]);
1431 smart
->data_units_written_lo
= le64_to_cpu(log
.data_units_written
[0]);
1432 smart
->data_units_written_hi
= le64_to_cpu(log
.data_units_written
[1]);
1433 smart
->host_read_commands_lo
= le64_to_cpu(log
.host_read_commands
[0]);
1434 smart
->host_read_commands_hi
= le64_to_cpu(log
.host_read_commands
[1]);
1435 smart
->host_write_commands_lo
= le64_to_cpu(log
.host_write_commands
[0]);
1436 smart
->host_write_commands_hi
= le64_to_cpu(log
.host_write_commands
[1]);
1437 smart
->controller_busy_time_lo
= le64_to_cpu(log
.controller_busy_time
[0]);
1438 smart
->controller_busy_time_hi
= le64_to_cpu(log
.controller_busy_time
[1]);
1439 smart
->power_cycles_lo
= le64_to_cpu(log
.power_cycles
[0]);
1440 smart
->power_cycles_hi
= le64_to_cpu(log
.power_cycles
[1]);
1441 smart
->power_on_hours_lo
= le64_to_cpu(log
.power_on_hours
[0]);
1442 smart
->power_on_hours_hi
= le64_to_cpu(log
.power_on_hours
[1]);
1443 smart
->unsafe_shutdowns_lo
= le64_to_cpu(log
.unsafe_shutdowns
[0]);
1444 smart
->unsafe_shutdowns_hi
= le64_to_cpu(log
.unsafe_shutdowns
[1]);
1445 smart
->media_errors_lo
= le64_to_cpu(log
.media_errors
[0]);
1446 smart
->media_errors_hi
= le64_to_cpu(log
.media_errors
[1]);
1447 smart
->number_of_error_log_entries_lo
=
1448 le64_to_cpu(log
.number_of_error_log_entries
[0]);
1449 smart
->number_of_error_log_entries_hi
=
1450 le64_to_cpu(log
.number_of_error_log_entries
[1]);
1455 static void get_disk_smart(GuestDiskInfo
*disk
)
1458 && (disk
->address
->bus_type
== GUEST_DISK_BUS_TYPE_NVME
)) {
1459 get_nvme_smart(disk
);
1463 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1465 GuestDiskInfoList
*ret
= NULL
;
1466 GuestDiskInfo
*disk
;
1468 struct dirent
*de
= NULL
;
1470 g_debug("listing /sys/block directory");
1471 dp
= opendir("/sys/block");
1473 error_setg_errno(errp
, errno
, "Can't open directory \"/sys/block\"");
1476 while ((de
= readdir(dp
)) != NULL
) {
1477 g_autofree
char *disk_dir
= NULL
, *line
= NULL
,
1480 Error
*local_err
= NULL
;
1481 if (de
->d_type
!= DT_LNK
) {
1482 g_debug(" skipping entry: %s", de
->d_name
);
1486 /* Check size and skip zero-sized disks */
1487 g_debug(" checking disk size");
1488 size_path
= g_strdup_printf("/sys/block/%s/size", de
->d_name
);
1489 if (!g_file_get_contents(size_path
, &line
, NULL
, NULL
)) {
1490 g_debug(" failed to read disk size");
1493 if (g_strcmp0(line
, "0\n") == 0) {
1494 g_debug(" skipping zero-sized disk");
1498 g_debug(" adding %s", de
->d_name
);
1499 disk_dir
= g_strdup_printf("/sys/block/%s", de
->d_name
);
1500 dev_name
= get_device_for_syspath(disk_dir
);
1501 if (dev_name
== NULL
) {
1502 g_debug("Failed to get device name for syspath: %s",
1506 disk
= g_new0(GuestDiskInfo
, 1);
1507 disk
->name
= dev_name
;
1508 disk
->partition
= false;
1509 disk
->alias
= get_alias_for_syspath(disk_dir
);
1510 QAPI_LIST_PREPEND(ret
, disk
);
1512 /* Get address for non-virtual devices */
1513 bool is_virtual
= is_disk_virtual(disk_dir
, &local_err
);
1514 if (local_err
!= NULL
) {
1515 g_debug(" failed to check disk path, ignoring error: %s",
1516 error_get_pretty(local_err
));
1517 error_free(local_err
);
1519 /* Don't try to get the address */
1523 disk
->address
= get_disk_address(disk_dir
, &local_err
);
1524 if (local_err
!= NULL
) {
1525 g_debug(" failed to get device info, ignoring error: %s",
1526 error_get_pretty(local_err
));
1527 error_free(local_err
);
1532 get_disk_deps(disk_dir
, disk
);
1533 get_disk_smart(disk
);
1534 ret
= get_disk_partitions(ret
, de
->d_name
, disk_dir
, dev_name
);
1544 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1546 error_setg(errp
, QERR_UNSUPPORTED
);
1552 /* Return a list of the disk device(s)' info which @mount lies on */
1553 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1556 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1558 unsigned long used
, nonroot_total
, fr_size
;
1559 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1560 mount
->devmajor
, mount
->devminor
);
1562 fs
->mountpoint
= g_strdup(mount
->dirname
);
1563 fs
->type
= g_strdup(mount
->devtype
);
1564 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1566 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1567 fr_size
= buf
.f_frsize
;
1568 used
= buf
.f_blocks
- buf
.f_bfree
;
1569 nonroot_total
= used
+ buf
.f_bavail
;
1570 fs
->used_bytes
= used
* fr_size
;
1571 fs
->total_bytes
= nonroot_total
* fr_size
;
1573 fs
->has_total_bytes
= true;
1574 fs
->has_used_bytes
= true;
1582 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1585 struct FsMount
*mount
;
1586 GuestFilesystemInfoList
*ret
= NULL
;
1587 Error
*local_err
= NULL
;
1589 QTAILQ_INIT(&mounts
);
1590 if (!build_fs_mount_list(&mounts
, &local_err
)) {
1591 error_propagate(errp
, local_err
);
1595 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1596 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1598 QAPI_LIST_PREPEND(ret
, build_guest_fsinfo(mount
, &local_err
));
1600 error_propagate(errp
, local_err
);
1601 qapi_free_GuestFilesystemInfoList(ret
);
1607 free_fs_mount_list(&mounts
);
1610 #endif /* CONFIG_FSFREEZE */
1612 #if defined(CONFIG_FSTRIM)
1614 * Walk list of mounted file systems in the guest, and trim them.
1616 GuestFilesystemTrimResponse
*
1617 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1619 GuestFilesystemTrimResponse
*response
;
1620 GuestFilesystemTrimResult
*result
;
1623 struct FsMount
*mount
;
1625 struct fstrim_range r
;
1627 slog("guest-fstrim called");
1629 QTAILQ_INIT(&mounts
);
1630 if (!build_fs_mount_list(&mounts
, errp
)) {
1634 response
= g_malloc0(sizeof(*response
));
1636 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1637 result
= g_malloc0(sizeof(*result
));
1638 result
->path
= g_strdup(mount
->dirname
);
1640 QAPI_LIST_PREPEND(response
->paths
, result
);
1642 fd
= qga_open_cloexec(mount
->dirname
, O_RDONLY
, 0);
1644 result
->error
= g_strdup_printf("failed to open: %s",
1649 /* We try to cull filesystems we know won't work in advance, but other
1650 * filesystems may not implement fstrim for less obvious reasons.
1651 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1652 * will be reported (e.g. CD-ROMs).
1653 * Any other error means an unexpected error.
1657 r
.minlen
= has_minimum
? minimum
: 0;
1658 ret
= ioctl(fd
, FITRIM
, &r
);
1660 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1661 result
->error
= g_strdup("trim not supported");
1663 result
->error
= g_strdup_printf("failed to trim: %s",
1670 result
->has_minimum
= true;
1671 result
->minimum
= r
.minlen
;
1672 result
->has_trimmed
= true;
1673 result
->trimmed
= r
.len
;
1677 free_fs_mount_list(&mounts
);
1680 #endif /* CONFIG_FSTRIM */
1683 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1684 #define SUSPEND_SUPPORTED 0
1685 #define SUSPEND_NOT_SUPPORTED 1
1688 SUSPEND_MODE_DISK
= 0,
1689 SUSPEND_MODE_RAM
= 1,
1690 SUSPEND_MODE_HYBRID
= 2,
1694 * Executes a command in a child process using g_spawn_sync,
1695 * returning an int >= 0 representing the exit status of the
1698 * If the program wasn't found in path, returns -1.
1700 * If a problem happened when creating the child process,
1701 * returns -1 and errp is set.
1703 static int run_process_child(const char *command
[], Error
**errp
)
1705 int exit_status
, spawn_flag
;
1706 GError
*g_err
= NULL
;
1709 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1710 G_SPAWN_STDERR_TO_DEV_NULL
;
1712 success
= g_spawn_sync(NULL
, (char **)command
, NULL
, spawn_flag
,
1713 NULL
, NULL
, NULL
, NULL
,
1714 &exit_status
, &g_err
);
1717 return WEXITSTATUS(exit_status
);
1720 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1721 error_setg(errp
, "failed to create child process, error '%s'",
1725 g_error_free(g_err
);
1729 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1731 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1732 "systemd-hybrid-sleep"};
1733 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
1736 status
= run_process_child(cmd
, errp
);
1739 * systemctl status uses LSB return codes so we can expect
1740 * status > 0 and be ok. To assert if the guest has support
1741 * for the selected suspend mode, status should be < 4. 4 is
1742 * the code for unknown service status, the return value when
1743 * the service does not exist. A common value is status = 3
1744 * (program is not running).
1746 if (status
> 0 && status
< 4) {
1753 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
1755 Error
*local_err
= NULL
;
1756 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
1757 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
1760 status
= run_process_child(cmd
, &local_err
);
1766 if ((status
== -1) && !local_err
) {
1767 error_setg(errp
, "the helper program 'systemctl %s' was not found",
1768 systemctl_args
[mode
]);
1773 error_propagate(errp
, local_err
);
1775 error_setg(errp
, "the helper program 'systemctl %s' returned an "
1776 "unexpected exit status code (%d)",
1777 systemctl_args
[mode
], status
);
1781 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
1783 Error
*local_err
= NULL
;
1784 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
1785 "--suspend-hybrid"};
1786 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
1789 status
= run_process_child(cmd
, &local_err
);
1791 if (status
== SUSPEND_SUPPORTED
) {
1795 if ((status
== -1) && !local_err
) {
1800 error_propagate(errp
, local_err
);
1803 "the helper program '%s' returned an unexpected exit"
1804 " status code (%d)", "pm-is-supported", status
);
1810 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
1812 Error
*local_err
= NULL
;
1813 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
1814 "pm-suspend-hybrid"};
1815 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
1818 status
= run_process_child(cmd
, &local_err
);
1824 if ((status
== -1) && !local_err
) {
1825 error_setg(errp
, "the helper program '%s' was not found",
1826 pmutils_binaries
[mode
]);
1831 error_propagate(errp
, local_err
);
1834 "the helper program '%s' returned an unexpected exit"
1835 " status code (%d)", pmutils_binaries
[mode
], status
);
1839 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
1841 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1842 const char *sysfile_str
= sysfile_strs
[mode
];
1843 char buf
[32]; /* hopefully big enough */
1848 error_setg(errp
, "unknown guest suspend mode");
1852 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1857 ret
= read(fd
, buf
, sizeof(buf
) - 1);
1864 if (strstr(buf
, sysfile_str
)) {
1870 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
1872 Error
*local_err
= NULL
;
1873 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1874 const char *sysfile_str
= sysfile_strs
[mode
];
1879 error_setg(errp
, "unknown guest suspend mode");
1889 reopen_fd_to_null(0);
1890 reopen_fd_to_null(1);
1891 reopen_fd_to_null(2);
1893 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1895 _exit(EXIT_FAILURE
);
1898 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1899 _exit(EXIT_FAILURE
);
1902 _exit(EXIT_SUCCESS
);
1903 } else if (pid
< 0) {
1904 error_setg_errno(errp
, errno
, "failed to create child process");
1908 ga_wait_child(pid
, &status
, &local_err
);
1910 error_propagate(errp
, local_err
);
1914 if (WEXITSTATUS(status
)) {
1915 error_setg(errp
, "child process has failed to suspend");
1920 static void guest_suspend(SuspendMode mode
, Error
**errp
)
1922 Error
*local_err
= NULL
;
1923 bool mode_supported
= false;
1925 if (systemd_supports_mode(mode
, &local_err
)) {
1926 mode_supported
= true;
1927 systemd_suspend(mode
, &local_err
);
1934 error_free(local_err
);
1937 if (pmutils_supports_mode(mode
, &local_err
)) {
1938 mode_supported
= true;
1939 pmutils_suspend(mode
, &local_err
);
1946 error_free(local_err
);
1949 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
1950 mode_supported
= true;
1951 linux_sys_state_suspend(mode
, &local_err
);
1954 if (!mode_supported
) {
1955 error_free(local_err
);
1957 "the requested suspend mode is not supported by the guest");
1959 error_propagate(errp
, local_err
);
1963 void qmp_guest_suspend_disk(Error
**errp
)
1965 guest_suspend(SUSPEND_MODE_DISK
, errp
);
1968 void qmp_guest_suspend_ram(Error
**errp
)
1970 guest_suspend(SUSPEND_MODE_RAM
, errp
);
1973 void qmp_guest_suspend_hybrid(Error
**errp
)
1975 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
1978 /* Transfer online/offline status between @vcpu and the guest system.
1980 * On input either @errp or *@errp must be NULL.
1982 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1983 * - R: vcpu->logical_id
1985 * - W: vcpu->can_offline
1987 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1988 * - R: vcpu->logical_id
1991 * Written members remain unmodified on error.
1993 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1994 char *dirpath
, Error
**errp
)
1999 static const char fn
[] = "online";
2001 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2003 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2007 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2009 if (errno
!= ENOENT
) {
2010 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2011 } else if (sys2vcpu
) {
2012 vcpu
->online
= true;
2013 vcpu
->can_offline
= false;
2014 } else if (!vcpu
->online
) {
2015 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2016 "offlined", vcpu
->logical_id
);
2017 } /* otherwise pretend successful re-onlining */
2019 unsigned char status
;
2021 res
= pread(fd
, &status
, 1, 0);
2023 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2024 } else if (res
== 0) {
2025 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2027 } else if (sys2vcpu
) {
2028 vcpu
->online
= (status
!= '0');
2029 vcpu
->can_offline
= true;
2030 } else if (vcpu
->online
!= (status
!= '0')) {
2031 status
= '0' + vcpu
->online
;
2032 if (pwrite(fd
, &status
, 1, 0) == -1) {
2033 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2036 } /* otherwise pretend successful re-(on|off)-lining */
2046 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2048 GuestLogicalProcessorList
*head
, **tail
;
2049 const char *cpu_dir
= "/sys/devices/system/cpu";
2051 g_autoptr(GDir
) cpu_gdir
= NULL
;
2052 Error
*local_err
= NULL
;
2056 cpu_gdir
= g_dir_open(cpu_dir
, 0, NULL
);
2058 if (cpu_gdir
== NULL
) {
2059 error_setg_errno(errp
, errno
, "failed to list entries: %s", cpu_dir
);
2063 while (local_err
== NULL
&& (line
= g_dir_read_name(cpu_gdir
)) != NULL
) {
2064 GuestLogicalProcessor
*vcpu
;
2066 if (sscanf(line
, "cpu%" PRId64
, &id
)) {
2067 g_autofree
char *path
= g_strdup_printf("/sys/devices/system/cpu/"
2068 "cpu%" PRId64
"/", id
);
2069 vcpu
= g_malloc0(sizeof *vcpu
);
2070 vcpu
->logical_id
= id
;
2071 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2072 transfer_vcpu(vcpu
, true, path
, &local_err
);
2073 QAPI_LIST_APPEND(tail
, vcpu
);
2077 if (local_err
== NULL
) {
2078 /* there's no guest with zero VCPUs */
2079 g_assert(head
!= NULL
);
2083 qapi_free_GuestLogicalProcessorList(head
);
2084 error_propagate(errp
, local_err
);
2088 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2091 Error
*local_err
= NULL
;
2094 while (vcpus
!= NULL
) {
2095 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2096 vcpus
->value
->logical_id
);
2098 transfer_vcpu(vcpus
->value
, false, path
, &local_err
);
2100 if (local_err
!= NULL
) {
2104 vcpus
= vcpus
->next
;
2107 if (local_err
!= NULL
) {
2108 if (processed
== 0) {
2109 error_propagate(errp
, local_err
);
2111 error_free(local_err
);
2117 #endif /* __linux__ */
2119 #if defined(__linux__) || defined(__FreeBSD__)
2120 void qmp_guest_set_user_password(const char *username
,
2121 const char *password
,
2125 Error
*local_err
= NULL
;
2126 char *passwd_path
= NULL
;
2129 int datafd
[2] = { -1, -1 };
2130 char *rawpasswddata
= NULL
;
2131 size_t rawpasswdlen
;
2132 char *chpasswddata
= NULL
;
2135 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2136 if (!rawpasswddata
) {
2139 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2140 rawpasswddata
[rawpasswdlen
] = '\0';
2142 if (strchr(rawpasswddata
, '\n')) {
2143 error_setg(errp
, "forbidden characters in raw password");
2147 if (strchr(username
, '\n') ||
2148 strchr(username
, ':')) {
2149 error_setg(errp
, "forbidden characters in username");
2154 chpasswddata
= g_strdup(rawpasswddata
);
2155 passwd_path
= g_find_program_in_path("pw");
2157 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
2158 passwd_path
= g_find_program_in_path("chpasswd");
2161 chpasswdlen
= strlen(chpasswddata
);
2164 error_setg(errp
, "cannot find 'passwd' program in PATH");
2168 if (!g_unix_open_pipe(datafd
, FD_CLOEXEC
, NULL
)) {
2169 error_setg(errp
, "cannot create pipe FDs");
2179 reopen_fd_to_null(1);
2180 reopen_fd_to_null(2);
2184 h_arg
= (crypted
) ? "-H" : "-h";
2185 execl(passwd_path
, "pw", "usermod", "-n", username
, h_arg
, "0", NULL
);
2188 execl(passwd_path
, "chpasswd", "-e", NULL
);
2190 execl(passwd_path
, "chpasswd", NULL
);
2193 _exit(EXIT_FAILURE
);
2194 } else if (pid
< 0) {
2195 error_setg_errno(errp
, errno
, "failed to create child process");
2201 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2202 error_setg_errno(errp
, errno
, "cannot write new account password");
2208 ga_wait_child(pid
, &status
, &local_err
);
2210 error_propagate(errp
, local_err
);
2214 if (!WIFEXITED(status
)) {
2215 error_setg(errp
, "child process has terminated abnormally");
2219 if (WEXITSTATUS(status
)) {
2220 error_setg(errp
, "child process has failed to set user password");
2225 g_free(chpasswddata
);
2226 g_free(rawpasswddata
);
2227 g_free(passwd_path
);
2228 if (datafd
[0] != -1) {
2231 if (datafd
[1] != -1) {
2235 #else /* __linux__ || __FreeBSD__ */
2236 void qmp_guest_set_user_password(const char *username
,
2237 const char *password
,
2241 error_setg(errp
, QERR_UNSUPPORTED
);
2243 #endif /* __linux__ || __FreeBSD__ */
2246 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2247 int size
, Error
**errp
)
2253 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2255 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2259 res
= pread(fd
, buf
, size
, 0);
2261 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2262 } else if (res
== 0) {
2263 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2268 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2269 const char *buf
, int size
, Error
**errp
)
2274 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2276 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2280 if (pwrite(fd
, buf
, size
, 0) == -1) {
2281 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2287 /* Transfer online/offline status between @mem_blk and the guest system.
2289 * On input either @errp or *@errp must be NULL.
2291 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2292 * - R: mem_blk->phys_index
2293 * - W: mem_blk->online
2294 * - W: mem_blk->can_offline
2296 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2297 * - R: mem_blk->phys_index
2298 * - R: mem_blk->online
2299 *- R: mem_blk->can_offline
2300 * Written members remain unmodified on error.
2302 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2303 GuestMemoryBlockResponse
*result
,
2309 Error
*local_err
= NULL
;
2315 error_setg(errp
, "Internal error, 'result' should not be NULL");
2319 dp
= opendir("/sys/devices/system/memory/");
2320 /* if there is no 'memory' directory in sysfs,
2321 * we think this VM does not support online/offline memory block,
2322 * any other solution?
2325 if (errno
== ENOENT
) {
2327 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2334 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2335 mem_blk
->phys_index
);
2336 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2339 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2341 if (errno
== ENOENT
) {
2342 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2345 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2353 status
= g_malloc0(10);
2354 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2356 /* treat with sysfs file that not exist in old kernel */
2357 if (errno
== ENOENT
) {
2358 error_free(local_err
);
2360 mem_blk
->online
= true;
2361 mem_blk
->can_offline
= false;
2362 } else if (!mem_blk
->online
) {
2364 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2368 error_propagate(errp
, local_err
);
2370 error_free(local_err
);
2372 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2379 char removable
= '0';
2381 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2383 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2385 /* if no 'removable' file, it doesn't support offline mem blk */
2386 if (errno
== ENOENT
) {
2387 error_free(local_err
);
2388 mem_blk
->can_offline
= false;
2390 error_propagate(errp
, local_err
);
2393 mem_blk
->can_offline
= (removable
!= '0');
2396 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2397 const char *new_state
= mem_blk
->online
? "online" : "offline";
2399 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2402 error_free(local_err
);
2404 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2408 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2409 result
->has_error_code
= false;
2410 } /* otherwise pretend successful re-(on|off)-lining */
2421 result
->has_error_code
= true;
2422 result
->error_code
= errno
;
2426 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2428 GuestMemoryBlockList
*head
, **tail
;
2429 Error
*local_err
= NULL
;
2436 dp
= opendir("/sys/devices/system/memory/");
2438 /* it's ok if this happens to be a system that doesn't expose
2439 * memory blocks via sysfs, but otherwise we should report
2442 if (errno
!= ENOENT
) {
2443 error_setg_errno(errp
, errno
, "Can't open directory"
2444 "\"/sys/devices/system/memory/\"");
2449 /* Note: the phys_index of memory block may be discontinuous,
2450 * this is because a memblk is the unit of the Sparse Memory design, which
2451 * allows discontinuous memory ranges (ex. NUMA), so here we should
2452 * traverse the memory block directory.
2454 while ((de
= readdir(dp
)) != NULL
) {
2455 GuestMemoryBlock
*mem_blk
;
2457 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2458 !(de
->d_type
& DT_DIR
)) {
2462 mem_blk
= g_malloc0(sizeof *mem_blk
);
2463 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2464 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2465 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2466 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2471 QAPI_LIST_APPEND(tail
, mem_blk
);
2475 if (local_err
== NULL
) {
2476 /* there's no guest with zero memory blocks */
2478 error_setg(errp
, "guest reported zero memory blocks!");
2483 qapi_free_GuestMemoryBlockList(head
);
2484 error_propagate(errp
, local_err
);
2488 GuestMemoryBlockResponseList
*
2489 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2491 GuestMemoryBlockResponseList
*head
, **tail
;
2492 Error
*local_err
= NULL
;
2497 while (mem_blks
!= NULL
) {
2498 GuestMemoryBlockResponse
*result
;
2499 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2501 result
= g_malloc0(sizeof(*result
));
2502 result
->phys_index
= current_mem_blk
->phys_index
;
2503 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2504 if (local_err
) { /* should never happen */
2508 QAPI_LIST_APPEND(tail
, result
);
2509 mem_blks
= mem_blks
->next
;
2514 qapi_free_GuestMemoryBlockResponseList(head
);
2515 error_propagate(errp
, local_err
);
2519 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2521 Error
*local_err
= NULL
;
2525 GuestMemoryBlockInfo
*info
;
2527 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2528 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2530 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2536 buf
= g_malloc0(20);
2537 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2541 error_propagate(errp
, local_err
);
2545 info
= g_new0(GuestMemoryBlockInfo
, 1);
2546 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2553 #define MAX_NAME_LEN 128
2554 static GuestDiskStatsInfoList
*guest_get_diskstats(Error
**errp
)
2557 GuestDiskStatsInfoList
*head
= NULL
, **tail
= &head
;
2558 const char *diskstats
= "/proc/diskstats";
2563 fp
= fopen(diskstats
, "r");
2565 error_setg_errno(errp
, errno
, "open(\"%s\")", diskstats
);
2569 while (getline(&line
, &n
, fp
) != -1) {
2570 g_autofree GuestDiskStatsInfo
*diskstatinfo
= NULL
;
2571 g_autofree GuestDiskStats
*diskstat
= NULL
;
2572 char dev_name
[MAX_NAME_LEN
];
2573 unsigned int ios_pgr
, tot_ticks
, rq_ticks
, wr_ticks
, dc_ticks
, fl_ticks
;
2574 unsigned long rd_ios
, rd_merges_or_rd_sec
, rd_ticks_or_wr_sec
, wr_ios
;
2575 unsigned long wr_merges
, rd_sec_or_wr_ios
, wr_sec
;
2576 unsigned long dc_ios
, dc_merges
, dc_sec
, fl_ios
;
2577 unsigned int major
, minor
;
2580 i
= sscanf(line
, "%u %u %s %lu %lu %lu"
2581 "%lu %lu %lu %lu %u %u %u %u"
2582 "%lu %lu %lu %u %lu %u",
2583 &major
, &minor
, dev_name
,
2584 &rd_ios
, &rd_merges_or_rd_sec
, &rd_sec_or_wr_ios
,
2585 &rd_ticks_or_wr_sec
, &wr_ios
, &wr_merges
, &wr_sec
,
2586 &wr_ticks
, &ios_pgr
, &tot_ticks
, &rq_ticks
,
2587 &dc_ios
, &dc_merges
, &dc_sec
, &dc_ticks
,
2588 &fl_ios
, &fl_ticks
);
2594 diskstatinfo
= g_new0(GuestDiskStatsInfo
, 1);
2595 diskstatinfo
->name
= g_strdup(dev_name
);
2596 diskstatinfo
->major
= major
;
2597 diskstatinfo
->minor
= minor
;
2599 diskstat
= g_new0(GuestDiskStats
, 1);
2601 diskstat
->has_read_ios
= true;
2602 diskstat
->read_ios
= rd_ios
;
2603 diskstat
->has_read_sectors
= true;
2604 diskstat
->read_sectors
= rd_merges_or_rd_sec
;
2605 diskstat
->has_write_ios
= true;
2606 diskstat
->write_ios
= rd_sec_or_wr_ios
;
2607 diskstat
->has_write_sectors
= true;
2608 diskstat
->write_sectors
= rd_ticks_or_wr_sec
;
2611 diskstat
->has_read_ios
= true;
2612 diskstat
->read_ios
= rd_ios
;
2613 diskstat
->has_read_sectors
= true;
2614 diskstat
->read_sectors
= rd_sec_or_wr_ios
;
2615 diskstat
->has_read_merges
= true;
2616 diskstat
->read_merges
= rd_merges_or_rd_sec
;
2617 diskstat
->has_read_ticks
= true;
2618 diskstat
->read_ticks
= rd_ticks_or_wr_sec
;
2619 diskstat
->has_write_ios
= true;
2620 diskstat
->write_ios
= wr_ios
;
2621 diskstat
->has_write_sectors
= true;
2622 diskstat
->write_sectors
= wr_sec
;
2623 diskstat
->has_write_merges
= true;
2624 diskstat
->write_merges
= wr_merges
;
2625 diskstat
->has_write_ticks
= true;
2626 diskstat
->write_ticks
= wr_ticks
;
2627 diskstat
->has_ios_pgr
= true;
2628 diskstat
->ios_pgr
= ios_pgr
;
2629 diskstat
->has_total_ticks
= true;
2630 diskstat
->total_ticks
= tot_ticks
;
2631 diskstat
->has_weight_ticks
= true;
2632 diskstat
->weight_ticks
= rq_ticks
;
2635 diskstat
->has_discard_ios
= true;
2636 diskstat
->discard_ios
= dc_ios
;
2637 diskstat
->has_discard_merges
= true;
2638 diskstat
->discard_merges
= dc_merges
;
2639 diskstat
->has_discard_sectors
= true;
2640 diskstat
->discard_sectors
= dc_sec
;
2641 diskstat
->has_discard_ticks
= true;
2642 diskstat
->discard_ticks
= dc_ticks
;
2645 diskstat
->has_flush_ios
= true;
2646 diskstat
->flush_ios
= fl_ios
;
2647 diskstat
->has_flush_ticks
= true;
2648 diskstat
->flush_ticks
= fl_ticks
;
2651 diskstatinfo
->stats
= g_steal_pointer(&diskstat
);
2652 QAPI_LIST_APPEND(tail
, diskstatinfo
);
2653 diskstatinfo
= NULL
;
2659 g_debug("disk stats reporting available only for Linux");
2664 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
2666 return guest_get_diskstats(errp
);
2669 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
2671 GuestCpuStatsList
*head
= NULL
, **tail
= &head
;
2672 const char *cpustats
= "/proc/stat";
2673 int clk_tck
= sysconf(_SC_CLK_TCK
);
2678 fp
= fopen(cpustats
, "r");
2680 error_setg_errno(errp
, errno
, "open(\"%s\")", cpustats
);
2684 while (getline(&line
, &n
, fp
) != -1) {
2685 GuestCpuStats
*cpustat
= NULL
;
2686 GuestLinuxCpuStats
*linuxcpustat
;
2688 unsigned long user
, system
, idle
, iowait
, irq
, softirq
, steal
, guest
;
2689 unsigned long nice
, guest_nice
;
2692 i
= sscanf(line
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2693 name
, &user
, &nice
, &system
, &idle
, &iowait
, &irq
, &softirq
,
2694 &steal
, &guest
, &guest_nice
);
2696 /* drop "cpu 1 2 3 ...", get "cpuX 1 2 3 ..." only */
2697 if ((i
== EOF
) || strncmp(name
, "cpu", 3) || (name
[3] == '\0')) {
2702 slog("Parsing cpu stat from %s failed, see \"man proc\"", cpustats
);
2706 cpustat
= g_new0(GuestCpuStats
, 1);
2707 cpustat
->type
= GUEST_CPU_STATS_TYPE_LINUX
;
2709 linuxcpustat
= &cpustat
->u
.q_linux
;
2710 linuxcpustat
->cpu
= atoi(&name
[3]);
2711 linuxcpustat
->user
= user
* 1000 / clk_tck
;
2712 linuxcpustat
->nice
= nice
* 1000 / clk_tck
;
2713 linuxcpustat
->system
= system
* 1000 / clk_tck
;
2714 linuxcpustat
->idle
= idle
* 1000 / clk_tck
;
2717 linuxcpustat
->has_iowait
= true;
2718 linuxcpustat
->iowait
= iowait
* 1000 / clk_tck
;
2722 linuxcpustat
->has_irq
= true;
2723 linuxcpustat
->irq
= irq
* 1000 / clk_tck
;
2724 linuxcpustat
->has_softirq
= true;
2725 linuxcpustat
->softirq
= softirq
* 1000 / clk_tck
;
2729 linuxcpustat
->has_steal
= true;
2730 linuxcpustat
->steal
= steal
* 1000 / clk_tck
;
2734 linuxcpustat
->has_guest
= true;
2735 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2739 linuxcpustat
->has_guest
= true;
2740 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2741 linuxcpustat
->has_guestnice
= true;
2742 linuxcpustat
->guestnice
= guest_nice
* 1000 / clk_tck
;
2745 QAPI_LIST_APPEND(tail
, cpustat
);
2753 #else /* defined(__linux__) */
2755 void qmp_guest_suspend_disk(Error
**errp
)
2757 error_setg(errp
, QERR_UNSUPPORTED
);
2760 void qmp_guest_suspend_ram(Error
**errp
)
2762 error_setg(errp
, QERR_UNSUPPORTED
);
2765 void qmp_guest_suspend_hybrid(Error
**errp
)
2767 error_setg(errp
, QERR_UNSUPPORTED
);
2770 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2772 error_setg(errp
, QERR_UNSUPPORTED
);
2776 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2778 error_setg(errp
, QERR_UNSUPPORTED
);
2782 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2784 error_setg(errp
, QERR_UNSUPPORTED
);
2788 GuestMemoryBlockResponseList
*
2789 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2791 error_setg(errp
, QERR_UNSUPPORTED
);
2795 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2797 error_setg(errp
, QERR_UNSUPPORTED
);
2803 #ifdef HAVE_GETIFADDRS
2804 static GuestNetworkInterface
*
2805 guest_find_interface(GuestNetworkInterfaceList
*head
,
2808 for (; head
; head
= head
->next
) {
2809 if (strcmp(head
->value
->name
, name
) == 0) {
2817 static int guest_get_network_stats(const char *name
,
2818 GuestNetworkInterfaceStat
*stats
)
2822 char const *devinfo
= "/proc/net/dev";
2824 char *line
= NULL
, *colon
;
2826 fp
= fopen(devinfo
, "r");
2828 g_debug("failed to open network stats %s: %s", devinfo
,
2832 name_len
= strlen(name
);
2833 while (getline(&line
, &n
, fp
) != -1) {
2836 long long rx_packets
;
2838 long long rx_dropped
;
2840 long long tx_packets
;
2842 long long tx_dropped
;
2844 trim_line
= g_strchug(line
);
2845 if (trim_line
[0] == '\0') {
2848 colon
= strchr(trim_line
, ':');
2852 if (colon
- name_len
== trim_line
&&
2853 strncmp(trim_line
, name
, name_len
) == 0) {
2854 if (sscanf(colon
+ 1,
2855 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2856 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
2857 &dummy
, &dummy
, &dummy
, &dummy
,
2858 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
2859 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
2862 stats
->rx_bytes
= rx_bytes
;
2863 stats
->rx_packets
= rx_packets
;
2864 stats
->rx_errs
= rx_errs
;
2865 stats
->rx_dropped
= rx_dropped
;
2866 stats
->tx_bytes
= tx_bytes
;
2867 stats
->tx_packets
= tx_packets
;
2868 stats
->tx_errs
= tx_errs
;
2869 stats
->tx_dropped
= tx_dropped
;
2877 g_debug("/proc/net/dev: Interface '%s' not found", name
);
2878 #else /* !CONFIG_LINUX */
2879 g_debug("Network stats reporting available only for Linux");
2880 #endif /* !CONFIG_LINUX */
2886 * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
2887 * buffer with ETHER_ADDR_LEN length at least.
2889 * Returns false in case of an error, otherwise true. "obtained" argument
2890 * is true if a MAC address was obtained successful, otherwise false.
2892 bool guest_get_hw_addr(struct ifaddrs
*ifa
, unsigned char *buf
,
2893 bool *obtained
, Error
**errp
)
2900 /* we haven't obtained HW address yet */
2901 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
2903 error_setg_errno(errp
, errno
, "failed to create socket");
2907 memset(&ifr
, 0, sizeof(ifr
));
2908 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, ifa
->ifa_name
);
2909 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
2911 * We can't get the hw addr of this interface, but that's not a
2914 if (errno
== EADDRNOTAVAIL
) {
2915 /* The interface doesn't have a hw addr (e.g. loopback). */
2916 g_debug("failed to get MAC address of %s: %s",
2917 ifa
->ifa_name
, strerror(errno
));
2919 g_warning("failed to get MAC address of %s: %s",
2920 ifa
->ifa_name
, strerror(errno
));
2923 #ifdef CONFIG_SOLARIS
2924 memcpy(buf
, &ifr
.ifr_addr
.sa_data
, ETHER_ADDR_LEN
);
2926 memcpy(buf
, &ifr
.ifr_hwaddr
.sa_data
, ETHER_ADDR_LEN
);
2933 #endif /* CONFIG_BSD */
2936 * Build information about guest interfaces
2938 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2940 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
2941 struct ifaddrs
*ifap
, *ifa
;
2943 if (getifaddrs(&ifap
) < 0) {
2944 error_setg_errno(errp
, errno
, "getifaddrs failed");
2948 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
2949 GuestNetworkInterface
*info
;
2950 GuestIpAddressList
**address_tail
;
2951 GuestIpAddress
*address_item
= NULL
;
2952 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
2953 char addr4
[INET_ADDRSTRLEN
];
2954 char addr6
[INET6_ADDRSTRLEN
];
2955 unsigned char mac_addr
[ETHER_ADDR_LEN
];
2959 g_debug("Processing %s interface", ifa
->ifa_name
);
2961 info
= guest_find_interface(head
, ifa
->ifa_name
);
2964 info
= g_malloc0(sizeof(*info
));
2965 info
->name
= g_strdup(ifa
->ifa_name
);
2967 QAPI_LIST_APPEND(tail
, info
);
2970 if (!info
->hardware_address
) {
2971 if (!guest_get_hw_addr(ifa
, mac_addr
, &obtained
, errp
)) {
2975 info
->hardware_address
=
2976 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2977 (int) mac_addr
[0], (int) mac_addr
[1],
2978 (int) mac_addr
[2], (int) mac_addr
[3],
2979 (int) mac_addr
[4], (int) mac_addr
[5]);
2983 if (ifa
->ifa_addr
&&
2984 ifa
->ifa_addr
->sa_family
== AF_INET
) {
2985 /* interface with IPv4 address */
2986 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
2987 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
2988 error_setg_errno(errp
, errno
, "inet_ntop failed");
2992 address_item
= g_malloc0(sizeof(*address_item
));
2993 address_item
->ip_address
= g_strdup(addr4
);
2994 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
2996 if (ifa
->ifa_netmask
) {
2997 /* Count the number of set bits in netmask.
2998 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2999 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
3000 address_item
->prefix
= ctpop32(((uint32_t *) p
)[0]);
3002 } else if (ifa
->ifa_addr
&&
3003 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
3004 /* interface with IPv6 address */
3005 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
3006 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
3007 error_setg_errno(errp
, errno
, "inet_ntop failed");
3011 address_item
= g_malloc0(sizeof(*address_item
));
3012 address_item
->ip_address
= g_strdup(addr6
);
3013 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
3015 if (ifa
->ifa_netmask
) {
3016 /* Count the number of set bits in netmask.
3017 * This is safe as '1' and '0' cannot be shuffled in netmask. */
3018 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
3019 address_item
->prefix
=
3020 ctpop32(((uint32_t *) p
)[0]) +
3021 ctpop32(((uint32_t *) p
)[1]) +
3022 ctpop32(((uint32_t *) p
)[2]) +
3023 ctpop32(((uint32_t *) p
)[3]);
3027 if (!address_item
) {
3031 address_tail
= &info
->ip_addresses
;
3032 while (*address_tail
) {
3033 address_tail
= &(*address_tail
)->next
;
3035 QAPI_LIST_APPEND(address_tail
, address_item
);
3037 info
->has_ip_addresses
= true;
3039 if (!info
->statistics
) {
3040 interface_stat
= g_malloc0(sizeof(*interface_stat
));
3041 if (guest_get_network_stats(info
->name
, interface_stat
) == -1) {
3042 g_free(interface_stat
);
3044 info
->statistics
= interface_stat
;
3054 qapi_free_GuestNetworkInterfaceList(head
);
3060 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
3062 error_setg(errp
, QERR_UNSUPPORTED
);
3066 #endif /* HAVE_GETIFADDRS */
3068 #if !defined(CONFIG_FSFREEZE)
3070 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
3072 error_setg(errp
, QERR_UNSUPPORTED
);
3076 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
3078 error_setg(errp
, QERR_UNSUPPORTED
);
3083 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
3085 error_setg(errp
, QERR_UNSUPPORTED
);
3090 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
3091 strList
*mountpoints
,
3094 error_setg(errp
, QERR_UNSUPPORTED
);
3099 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
3101 error_setg(errp
, QERR_UNSUPPORTED
);
3106 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
3108 error_setg(errp
, QERR_UNSUPPORTED
);
3112 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
3114 error_setg(errp
, QERR_UNSUPPORTED
);
3118 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
3120 error_setg(errp
, QERR_UNSUPPORTED
);
3124 #endif /* CONFIG_FSFREEZE */
3126 #if !defined(CONFIG_FSTRIM)
3127 GuestFilesystemTrimResponse
*
3128 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
3130 error_setg(errp
, QERR_UNSUPPORTED
);
3135 /* add unsupported commands to the list of blocked RPCs */
3136 GList
*ga_command_init_blockedrpcs(GList
*blockedrpcs
)
3138 #if !defined(__linux__)
3140 const char *list
[] = {
3141 "guest-suspend-disk", "guest-suspend-ram",
3142 "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
3143 "guest-get-memory-blocks", "guest-set-memory-blocks",
3144 "guest-get-memory-block-size", "guest-get-memory-block-info",
3146 char **p
= (char **)list
;
3149 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3154 #if !defined(HAVE_GETIFADDRS)
3155 blockedrpcs
= g_list_append(blockedrpcs
,
3156 g_strdup("guest-network-get-interfaces"));
3159 #if !defined(CONFIG_FSFREEZE)
3161 const char *list
[] = {
3162 "guest-get-fsinfo", "guest-fsfreeze-status",
3163 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3164 "guest-fsfreeze-thaw", "guest-get-fsinfo",
3165 "guest-get-disks", NULL
};
3166 char **p
= (char **)list
;
3169 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3174 #if !defined(CONFIG_FSTRIM)
3175 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-fstrim"));
3178 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-get-devices"));
3183 /* register init/cleanup routines for stateful command groups */
3184 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
3186 #if defined(CONFIG_FSFREEZE)
3187 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
3193 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3195 static double ga_get_login_time(struct utmpx
*user_info
)
3197 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
3198 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
3199 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
3200 return seconds
+ useconds
;
3203 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3205 GHashTable
*cache
= NULL
;
3206 GuestUserList
*head
= NULL
, **tail
= &head
;
3207 struct utmpx
*user_info
= NULL
;
3208 gpointer value
= NULL
;
3209 GuestUser
*user
= NULL
;
3210 double login_time
= 0;
3212 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
3216 user_info
= getutxent();
3217 if (user_info
== NULL
) {
3219 } else if (user_info
->ut_type
!= USER_PROCESS
) {
3221 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
3222 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
3223 user
= (GuestUser
*)value
;
3224 login_time
= ga_get_login_time(user_info
);
3225 /* We're ensuring the earliest login time to be sent */
3226 if (login_time
< user
->login_time
) {
3227 user
->login_time
= login_time
;
3232 user
= g_new0(GuestUser
, 1);
3233 user
->user
= g_strdup(user_info
->ut_user
);
3234 user
->login_time
= ga_get_login_time(user_info
);
3236 g_hash_table_insert(cache
, user
->user
, user
);
3238 QAPI_LIST_APPEND(tail
, user
);
3241 g_hash_table_destroy(cache
);
3247 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3249 error_setg(errp
, QERR_UNSUPPORTED
);
3255 /* Replace escaped special characters with their real values. The replacement
3256 * is done in place -- returned value is in the original string.
3258 static void ga_osrelease_replace_special(gchar
*value
)
3260 gchar
*p
, *p2
, quote
;
3262 /* Trim the string at first space or semicolon if it is not enclosed in
3263 * single or double quotes. */
3264 if ((value
[0] != '"') || (value
[0] == '\'')) {
3265 p
= strchr(value
, ' ');
3269 p
= strchr(value
, ';');
3290 /* Keep literal backslash followed by whatever is there */
3294 } else if (*p
== quote
) {
3302 static GKeyFile
*ga_parse_osrelease(const char *fname
)
3304 gchar
*content
= NULL
;
3305 gchar
*content2
= NULL
;
3307 GKeyFile
*keys
= g_key_file_new();
3308 const char *group
= "[os-release]\n";
3310 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
3311 slog("failed to read '%s', error: %s", fname
, err
->message
);
3315 if (!g_utf8_validate(content
, -1, NULL
)) {
3316 slog("file is not utf-8 encoded: %s", fname
);
3319 content2
= g_strdup_printf("%s%s", group
, content
);
3321 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
3323 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
3335 g_key_file_free(keys
);
3339 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
3341 GuestOSInfo
*info
= NULL
;
3342 struct utsname kinfo
;
3343 GKeyFile
*osrelease
= NULL
;
3344 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
3346 info
= g_new0(GuestOSInfo
, 1);
3348 if (uname(&kinfo
) != 0) {
3349 error_setg_errno(errp
, errno
, "uname failed");
3351 info
->kernel_version
= g_strdup(kinfo
.version
);
3352 info
->kernel_release
= g_strdup(kinfo
.release
);
3353 info
->machine
= g_strdup(kinfo
.machine
);
3356 if (qga_os_release
!= NULL
) {
3357 osrelease
= ga_parse_osrelease(qga_os_release
);
3359 osrelease
= ga_parse_osrelease("/etc/os-release");
3360 if (osrelease
== NULL
) {
3361 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
3365 if (osrelease
!= NULL
) {
3368 #define GET_FIELD(field, osfield) do { \
3369 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3370 if (value != NULL) { \
3371 ga_osrelease_replace_special(value); \
3372 info->field = value; \
3375 GET_FIELD(id
, "ID");
3376 GET_FIELD(name
, "NAME");
3377 GET_FIELD(pretty_name
, "PRETTY_NAME");
3378 GET_FIELD(version
, "VERSION");
3379 GET_FIELD(version_id
, "VERSION_ID");
3380 GET_FIELD(variant
, "VARIANT");
3381 GET_FIELD(variant_id
, "VARIANT_ID");
3384 g_key_file_free(osrelease
);
3390 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
3392 error_setg(errp
, QERR_UNSUPPORTED
);
3397 #ifndef HOST_NAME_MAX
3398 # ifdef _POSIX_HOST_NAME_MAX
3399 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
3401 # define HOST_NAME_MAX 255
3405 char *qga_get_host_name(Error
**errp
)
3408 g_autofree
char *hostname
= NULL
;
3410 #ifdef _SC_HOST_NAME_MAX
3411 len
= sysconf(_SC_HOST_NAME_MAX
);
3412 #endif /* _SC_HOST_NAME_MAX */
3415 len
= HOST_NAME_MAX
;
3418 /* Unfortunately, gethostname() below does not guarantee a
3419 * NULL terminated string. Therefore, allocate one byte more
3421 hostname
= g_new0(char, len
+ 1);
3423 if (gethostname(hostname
, len
) < 0) {
3424 error_setg_errno(errp
, errno
,
3425 "cannot get hostname");
3429 return g_steal_pointer(&hostname
);