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.
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
25 #include "qga/guest-agent-core.h"
26 #include "qga-qmp-commands.h"
27 #include "qapi/qmp/qerror.h"
28 #include "qemu/queue.h"
29 #include "qemu/host-utils.h"
31 #ifndef CONFIG_HAS_ENVIRON
33 #include <crt_externs.h>
34 #define environ (*_NSGetEnviron())
36 extern char **environ
;
40 #if defined(__linux__)
44 #include <arpa/inet.h>
45 #include <sys/socket.h>
49 #define CONFIG_FSFREEZE
56 static void ga_wait_child(pid_t pid
, int *status
, Error
**err
)
63 rpid
= waitpid(pid
, status
, 0);
64 } while (rpid
== -1 && errno
== EINTR
);
67 error_setg_errno(err
, errno
, "failed to wait for child (pid: %d)", pid
);
71 g_assert(rpid
== pid
);
74 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**err
)
76 const char *shutdown_flag
;
77 Error
*local_err
= NULL
;
81 slog("guest-shutdown called, mode: %s", mode
);
82 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
84 } else if (strcmp(mode
, "halt") == 0) {
86 } else if (strcmp(mode
, "reboot") == 0) {
90 "mode is invalid (valid values are: halt|powerdown|reboot");
96 /* child, start the shutdown */
100 reopen_fd_to_null(2);
102 execle("/sbin/shutdown", "shutdown", shutdown_flag
, "+0",
103 "hypervisor initiated shutdown", (char*)NULL
, environ
);
105 } else if (pid
< 0) {
106 error_setg_errno(err
, errno
, "failed to create child process");
110 ga_wait_child(pid
, &status
, &local_err
);
111 if (error_is_set(&local_err
)) {
112 error_propagate(err
, local_err
);
116 if (!WIFEXITED(status
)) {
117 error_setg(err
, "child process has terminated abnormally");
121 if (WEXITSTATUS(status
)) {
122 error_setg(err
, "child process has failed to shutdown");
129 int64_t qmp_guest_get_time(Error
**errp
)
135 ret
= qemu_gettimeofday(&tq
);
137 error_setg_errno(errp
, errno
, "Failed to get time");
141 time_ns
= tq
.tv_sec
* 1000000000LL + tq
.tv_usec
* 1000;
145 void qmp_guest_set_time(int64_t time_ns
, Error
**errp
)
150 Error
*local_err
= NULL
;
153 /* year-2038 will overflow in case time_t is 32bit */
154 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
155 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
159 tv
.tv_sec
= time_ns
/ 1000000000;
160 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
162 ret
= settimeofday(&tv
, NULL
);
164 error_setg_errno(errp
, errno
, "Failed to set time to guest");
168 /* Set the Hardware Clock to the current System Time. */
172 reopen_fd_to_null(0);
173 reopen_fd_to_null(1);
174 reopen_fd_to_null(2);
176 execle("/sbin/hwclock", "hwclock", "-w", NULL
, environ
);
178 } else if (pid
< 0) {
179 error_setg_errno(errp
, errno
, "failed to create child process");
183 ga_wait_child(pid
, &status
, &local_err
);
184 if (error_is_set(&local_err
)) {
185 error_propagate(errp
, local_err
);
189 if (!WIFEXITED(status
)) {
190 error_setg(errp
, "child process has terminated abnormally");
194 if (WEXITSTATUS(status
)) {
195 error_setg(errp
, "hwclock failed to set hardware clock to system time");
200 typedef struct GuestFileHandle
{
203 QTAILQ_ENTRY(GuestFileHandle
) next
;
207 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
210 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
212 GuestFileHandle
*gfh
;
215 handle
= ga_get_fd_handle(ga_state
, errp
);
216 if (error_is_set(errp
)) {
220 gfh
= g_malloc0(sizeof(GuestFileHandle
));
223 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
228 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**err
)
230 GuestFileHandle
*gfh
;
232 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
239 error_setg(err
, "handle '%" PRId64
"' has not been found", id
);
243 typedef const char * const ccpc
;
249 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
250 static const struct {
253 } guest_file_open_modes
[] = {
254 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
255 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
256 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
257 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
258 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
259 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
260 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
261 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
262 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
263 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
264 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
265 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
269 find_open_flag(const char *mode_str
, Error
**err
)
273 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
276 form
= guest_file_open_modes
[mode
].forms
;
277 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
285 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
286 error_setg(err
, "invalid file open mode '%s'", mode_str
);
289 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
292 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
293 S_IRGRP | S_IWGRP | \
297 safe_open_or_create(const char *path
, const char *mode
, Error
**err
)
299 Error
*local_err
= NULL
;
302 oflag
= find_open_flag(mode
, &local_err
);
303 if (local_err
== NULL
) {
306 /* If the caller wants / allows creation of a new file, we implement it
307 * with a two step process: open() + (open() / fchmod()).
309 * First we insist on creating the file exclusively as a new file. If
310 * that succeeds, we're free to set any file-mode bits on it. (The
311 * motivation is that we want to set those file-mode bits independently
312 * of the current umask.)
314 * If the exclusive creation fails because the file already exists
315 * (EEXIST is not possible for any other reason), we just attempt to
316 * open the file, but in this case we won't be allowed to change the
317 * file-mode bits on the preexistent file.
319 * The pathname should never disappear between the two open()s in
320 * practice. If it happens, then someone very likely tried to race us.
321 * In this case just go ahead and report the ENOENT from the second
322 * open() to the caller.
324 * If the caller wants to open a preexistent file, then the first
325 * open() is decisive and its third argument is ignored, and the second
326 * open() and the fchmod() are never called.
328 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
329 if (fd
== -1 && errno
== EEXIST
) {
330 oflag
&= ~(unsigned)O_CREAT
;
331 fd
= open(path
, oflag
);
335 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
336 "(mode: '%s')", path
, mode
);
338 qemu_set_cloexec(fd
);
340 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
341 error_setg_errno(&local_err
, errno
, "failed to set permission "
342 "0%03o on new file '%s' (mode: '%s')",
343 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
347 f
= fdopen(fd
, mode
);
349 error_setg_errno(&local_err
, errno
, "failed to associate "
350 "stdio stream with file descriptor %d, "
351 "file '%s' (mode: '%s')", fd
, path
, mode
);
361 error_propagate(err
, local_err
);
365 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
, Error
**err
)
368 Error
*local_err
= NULL
;
370 int64_t ret
= -1, handle
;
375 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
376 fh
= safe_open_or_create(path
, mode
, &local_err
);
377 if (local_err
!= NULL
) {
378 error_propagate(err
, local_err
);
382 /* set fd non-blocking to avoid common use cases (like reading from a
383 * named pipe) from hanging the agent
386 ret
= fcntl(fd
, F_GETFL
);
387 ret
= fcntl(fd
, F_SETFL
, ret
| O_NONBLOCK
);
389 error_setg_errno(err
, errno
, "failed to make file '%s' non-blocking",
395 handle
= guest_file_handle_add(fh
, err
);
396 if (error_is_set(err
)) {
401 slog("guest-file-open, handle: %d", handle
);
405 void qmp_guest_file_close(int64_t handle
, Error
**err
)
407 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, err
);
410 slog("guest-file-close called, handle: %ld", handle
);
415 ret
= fclose(gfh
->fh
);
417 error_setg_errno(err
, errno
, "failed to close handle");
421 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
425 struct GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
426 int64_t count
, Error
**err
)
428 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, err
);
429 GuestFileRead
*read_data
= NULL
;
439 count
= QGA_READ_COUNT_DEFAULT
;
440 } else if (count
< 0) {
441 error_setg(err
, "value '%" PRId64
"' is invalid for argument count",
447 buf
= g_malloc0(count
+1);
448 read_count
= fread(buf
, 1, count
, fh
);
450 error_setg_errno(err
, errno
, "failed to read file");
451 slog("guest-file-read failed, handle: %ld", handle
);
454 read_data
= g_malloc0(sizeof(GuestFileRead
));
455 read_data
->count
= read_count
;
456 read_data
->eof
= feof(fh
);
458 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
467 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
468 bool has_count
, int64_t count
, Error
**err
)
470 GuestFileWrite
*write_data
= NULL
;
474 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, err
);
482 buf
= g_base64_decode(buf_b64
, &buf_len
);
486 } else if (count
< 0 || count
> buf_len
) {
487 error_setg(err
, "value '%" PRId64
"' is invalid for argument count",
493 write_count
= fwrite(buf
, 1, count
, fh
);
495 error_setg_errno(err
, errno
, "failed to write to file");
496 slog("guest-file-write failed, handle: %ld", handle
);
498 write_data
= g_malloc0(sizeof(GuestFileWrite
));
499 write_data
->count
= write_count
;
500 write_data
->eof
= feof(fh
);
508 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
509 int64_t whence
, Error
**err
)
511 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, err
);
512 GuestFileSeek
*seek_data
= NULL
;
521 ret
= fseek(fh
, offset
, whence
);
523 error_setg_errno(err
, errno
, "failed to seek file");
525 seek_data
= g_malloc0(sizeof(GuestFileRead
));
526 seek_data
->position
= ftell(fh
);
527 seek_data
->eof
= feof(fh
);
534 void qmp_guest_file_flush(int64_t handle
, Error
**err
)
536 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, err
);
547 error_setg_errno(err
, errno
, "failed to flush file");
551 static void guest_file_init(void)
553 QTAILQ_INIT(&guest_file_state
.filehandles
);
556 /* linux-specific implementations. avoid this if at all possible. */
557 #if defined(__linux__)
559 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
560 typedef struct FsMount
{
563 QTAILQ_ENTRY(FsMount
) next
;
566 typedef QTAILQ_HEAD(, FsMount
) FsMountList
;
568 static void free_fs_mount_list(FsMountList
*mounts
)
570 FsMount
*mount
, *temp
;
576 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
577 QTAILQ_REMOVE(mounts
, mount
, next
);
578 g_free(mount
->dirname
);
579 g_free(mount
->devtype
);
585 * Walk the mount table and build a list of local file systems
587 static void build_fs_mount_list(FsMountList
*mounts
, Error
**err
)
591 char const *mtab
= "/proc/self/mounts";
594 fp
= setmntent(mtab
, "r");
596 error_setg(err
, "failed to open mtab file: '%s'", mtab
);
600 while ((ment
= getmntent(fp
))) {
602 * An entry which device name doesn't start with a '/' is
603 * either a dummy file system or a network file system.
604 * Add special handling for smbfs and cifs as is done by
607 if ((ment
->mnt_fsname
[0] != '/') ||
608 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
609 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
613 mount
= g_malloc0(sizeof(FsMount
));
614 mount
->dirname
= g_strdup(ment
->mnt_dir
);
615 mount
->devtype
= g_strdup(ment
->mnt_type
);
617 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
624 #if defined(CONFIG_FSFREEZE)
627 FSFREEZE_HOOK_THAW
= 0,
628 FSFREEZE_HOOK_FREEZE
,
631 const char *fsfreeze_hook_arg_string
[] = {
636 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**err
)
641 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
642 Error
*local_err
= NULL
;
644 hook
= ga_fsfreeze_hook(ga_state
);
648 if (access(hook
, X_OK
) != 0) {
649 error_setg_errno(err
, errno
, "can't access fsfreeze hook '%s'", hook
);
653 slog("executing fsfreeze hook with arg '%s'", arg_str
);
657 reopen_fd_to_null(0);
658 reopen_fd_to_null(1);
659 reopen_fd_to_null(2);
661 execle(hook
, hook
, arg_str
, NULL
, environ
);
663 } else if (pid
< 0) {
664 error_setg_errno(err
, errno
, "failed to create child process");
668 ga_wait_child(pid
, &status
, &local_err
);
669 if (error_is_set(&local_err
)) {
670 error_propagate(err
, local_err
);
674 if (!WIFEXITED(status
)) {
675 error_setg(err
, "fsfreeze hook has terminated abnormally");
679 status
= WEXITSTATUS(status
);
681 error_setg(err
, "fsfreeze hook has failed with status %d", status
);
687 * Return status of freeze/thaw
689 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**err
)
691 if (ga_is_frozen(ga_state
)) {
692 return GUEST_FSFREEZE_STATUS_FROZEN
;
695 return GUEST_FSFREEZE_STATUS_THAWED
;
699 * Walk list of mounted file systems in the guest, and freeze the ones which
700 * are real local file systems.
702 int64_t qmp_guest_fsfreeze_freeze(Error
**err
)
706 struct FsMount
*mount
;
707 Error
*local_err
= NULL
;
710 slog("guest-fsfreeze called");
712 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
713 if (error_is_set(&local_err
)) {
714 error_propagate(err
, local_err
);
718 QTAILQ_INIT(&mounts
);
719 build_fs_mount_list(&mounts
, &local_err
);
720 if (error_is_set(&local_err
)) {
721 error_propagate(err
, local_err
);
725 /* cannot risk guest agent blocking itself on a write in this state */
726 ga_set_frozen(ga_state
);
728 QTAILQ_FOREACH(mount
, &mounts
, next
) {
729 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
731 error_setg_errno(err
, errno
, "failed to open %s", mount
->dirname
);
735 /* we try to cull filesytems we know won't work in advance, but other
736 * filesytems may not implement fsfreeze for less obvious reasons.
737 * these will report EOPNOTSUPP. we simply ignore these when tallying
738 * the number of frozen filesystems.
740 * any other error means a failure to freeze a filesystem we
741 * expect to be freezable, so return an error in those cases
742 * and return system to thawed state.
744 ret
= ioctl(fd
, FIFREEZE
);
746 if (errno
!= EOPNOTSUPP
) {
747 error_setg_errno(err
, errno
, "failed to freeze %s",
758 free_fs_mount_list(&mounts
);
762 free_fs_mount_list(&mounts
);
763 qmp_guest_fsfreeze_thaw(NULL
);
768 * Walk list of frozen file systems in the guest, and thaw them.
770 int64_t qmp_guest_fsfreeze_thaw(Error
**err
)
775 int fd
, i
= 0, logged
;
776 Error
*local_err
= NULL
;
778 QTAILQ_INIT(&mounts
);
779 build_fs_mount_list(&mounts
, &local_err
);
780 if (error_is_set(&local_err
)) {
781 error_propagate(err
, local_err
);
785 QTAILQ_FOREACH(mount
, &mounts
, next
) {
787 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
791 /* we have no way of knowing whether a filesystem was actually unfrozen
792 * as a result of a successful call to FITHAW, only that if an error
793 * was returned the filesystem was *not* unfrozen by that particular
796 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
797 * to unfreeze, continuing issuing FITHAW until an error is returned,
798 * in which case either the filesystem is in an unfreezable state, or,
799 * more likely, it was thawed previously (and remains so afterward).
801 * also, since the most recent successful call is the one that did
802 * the actual unfreeze, we can use this to provide an accurate count
803 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
804 * may * be useful for determining whether a filesystem was unfrozen
805 * during the freeze/thaw phase by a process other than qemu-ga.
808 ret
= ioctl(fd
, FITHAW
);
809 if (ret
== 0 && !logged
) {
817 ga_unset_frozen(ga_state
);
818 free_fs_mount_list(&mounts
);
820 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, err
);
825 static void guest_fsfreeze_cleanup(void)
829 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
830 qmp_guest_fsfreeze_thaw(&err
);
832 slog("failed to clean up frozen filesystems: %s",
833 error_get_pretty(err
));
838 #endif /* CONFIG_FSFREEZE */
840 #if defined(CONFIG_FSTRIM)
842 * Walk list of mounted file systems in the guest, and trim them.
844 void qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**err
)
848 struct FsMount
*mount
;
850 Error
*local_err
= NULL
;
851 struct fstrim_range r
= {
854 .minlen
= has_minimum
? minimum
: 0,
857 slog("guest-fstrim called");
859 QTAILQ_INIT(&mounts
);
860 build_fs_mount_list(&mounts
, &local_err
);
861 if (error_is_set(&local_err
)) {
862 error_propagate(err
, local_err
);
866 QTAILQ_FOREACH(mount
, &mounts
, next
) {
867 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
869 error_setg_errno(err
, errno
, "failed to open %s", mount
->dirname
);
873 /* We try to cull filesytems we know won't work in advance, but other
874 * filesytems may not implement fstrim for less obvious reasons. These
875 * will report EOPNOTSUPP; we simply ignore these errors. Any other
876 * error means an unexpected error, so return it in those cases. In
877 * some other cases ENOTTY will be reported (e.g. CD-ROMs).
879 ret
= ioctl(fd
, FITRIM
, &r
);
881 if (errno
!= ENOTTY
&& errno
!= EOPNOTSUPP
) {
882 error_setg_errno(err
, errno
, "failed to trim %s",
892 free_fs_mount_list(&mounts
);
894 #endif /* CONFIG_FSTRIM */
897 #define LINUX_SYS_STATE_FILE "/sys/power/state"
898 #define SUSPEND_SUPPORTED 0
899 #define SUSPEND_NOT_SUPPORTED 1
901 static void bios_supports_mode(const char *pmutils_bin
, const char *pmutils_arg
,
902 const char *sysfile_str
, Error
**err
)
904 Error
*local_err
= NULL
;
909 pmutils_path
= g_find_program_in_path(pmutils_bin
);
913 char buf
[32]; /* hopefully big enough */
918 reopen_fd_to_null(0);
919 reopen_fd_to_null(1);
920 reopen_fd_to_null(2);
923 execle(pmutils_path
, pmutils_bin
, pmutils_arg
, NULL
, environ
);
927 * If we get here either pm-utils is not installed or execle() has
928 * failed. Let's try the manual method if the caller wants it.
932 _exit(SUSPEND_NOT_SUPPORTED
);
935 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
937 _exit(SUSPEND_NOT_SUPPORTED
);
940 ret
= read(fd
, buf
, sizeof(buf
)-1);
942 _exit(SUSPEND_NOT_SUPPORTED
);
946 if (strstr(buf
, sysfile_str
)) {
947 _exit(SUSPEND_SUPPORTED
);
950 _exit(SUSPEND_NOT_SUPPORTED
);
951 } else if (pid
< 0) {
952 error_setg_errno(err
, errno
, "failed to create child process");
956 ga_wait_child(pid
, &status
, &local_err
);
957 if (error_is_set(&local_err
)) {
958 error_propagate(err
, local_err
);
962 if (!WIFEXITED(status
)) {
963 error_setg(err
, "child process has terminated abnormally");
967 switch (WEXITSTATUS(status
)) {
968 case SUSPEND_SUPPORTED
:
970 case SUSPEND_NOT_SUPPORTED
:
972 "the requested suspend mode is not supported by the guest");
976 "the helper program '%s' returned an unexpected exit status"
977 " code (%d)", pmutils_path
, WEXITSTATUS(status
));
982 g_free(pmutils_path
);
985 static void guest_suspend(const char *pmutils_bin
, const char *sysfile_str
,
988 Error
*local_err
= NULL
;
993 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1001 reopen_fd_to_null(0);
1002 reopen_fd_to_null(1);
1003 reopen_fd_to_null(2);
1006 execle(pmutils_path
, pmutils_bin
, NULL
, environ
);
1010 * If we get here either pm-utils is not installed or execle() has
1011 * failed. Let's try the manual method if the caller wants it.
1015 _exit(EXIT_FAILURE
);
1018 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1020 _exit(EXIT_FAILURE
);
1023 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1024 _exit(EXIT_FAILURE
);
1027 _exit(EXIT_SUCCESS
);
1028 } else if (pid
< 0) {
1029 error_setg_errno(err
, errno
, "failed to create child process");
1033 ga_wait_child(pid
, &status
, &local_err
);
1034 if (error_is_set(&local_err
)) {
1035 error_propagate(err
, local_err
);
1039 if (!WIFEXITED(status
)) {
1040 error_setg(err
, "child process has terminated abnormally");
1044 if (WEXITSTATUS(status
)) {
1045 error_setg(err
, "child process has failed to suspend");
1050 g_free(pmutils_path
);
1053 void qmp_guest_suspend_disk(Error
**err
)
1055 bios_supports_mode("pm-is-supported", "--hibernate", "disk", err
);
1056 if (error_is_set(err
)) {
1060 guest_suspend("pm-hibernate", "disk", err
);
1063 void qmp_guest_suspend_ram(Error
**err
)
1065 bios_supports_mode("pm-is-supported", "--suspend", "mem", err
);
1066 if (error_is_set(err
)) {
1070 guest_suspend("pm-suspend", "mem", err
);
1073 void qmp_guest_suspend_hybrid(Error
**err
)
1075 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL
, err
);
1076 if (error_is_set(err
)) {
1080 guest_suspend("pm-suspend-hybrid", NULL
, err
);
1083 static GuestNetworkInterfaceList
*
1084 guest_find_interface(GuestNetworkInterfaceList
*head
,
1087 for (; head
; head
= head
->next
) {
1088 if (strcmp(head
->value
->name
, name
) == 0) {
1097 * Build information about guest interfaces
1099 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1101 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1102 struct ifaddrs
*ifap
, *ifa
;
1104 if (getifaddrs(&ifap
) < 0) {
1105 error_setg_errno(errp
, errno
, "getifaddrs failed");
1109 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1110 GuestNetworkInterfaceList
*info
;
1111 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
1112 char addr4
[INET_ADDRSTRLEN
];
1113 char addr6
[INET6_ADDRSTRLEN
];
1116 unsigned char *mac_addr
;
1119 g_debug("Processing %s interface", ifa
->ifa_name
);
1121 info
= guest_find_interface(head
, ifa
->ifa_name
);
1124 info
= g_malloc0(sizeof(*info
));
1125 info
->value
= g_malloc0(sizeof(*info
->value
));
1126 info
->value
->name
= g_strdup(ifa
->ifa_name
);
1129 head
= cur_item
= info
;
1131 cur_item
->next
= info
;
1136 if (!info
->value
->has_hardware_address
&&
1137 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
1138 /* we haven't obtained HW address yet */
1139 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
1141 error_setg_errno(errp
, errno
, "failed to create socket");
1145 memset(&ifr
, 0, sizeof(ifr
));
1146 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
1147 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
1148 error_setg_errno(errp
, errno
,
1149 "failed to get MAC address of %s",
1156 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
1158 info
->value
->hardware_address
=
1159 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1160 (int) mac_addr
[0], (int) mac_addr
[1],
1161 (int) mac_addr
[2], (int) mac_addr
[3],
1162 (int) mac_addr
[4], (int) mac_addr
[5]);
1164 info
->value
->has_hardware_address
= true;
1167 if (ifa
->ifa_addr
&&
1168 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1169 /* interface with IPv4 address */
1170 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1171 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1172 error_setg_errno(errp
, errno
, "inet_ntop failed");
1176 address_item
= g_malloc0(sizeof(*address_item
));
1177 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1178 address_item
->value
->ip_address
= g_strdup(addr4
);
1179 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1181 if (ifa
->ifa_netmask
) {
1182 /* Count the number of set bits in netmask.
1183 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1184 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1185 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1187 } else if (ifa
->ifa_addr
&&
1188 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1189 /* interface with IPv6 address */
1190 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1191 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1192 error_setg_errno(errp
, errno
, "inet_ntop failed");
1196 address_item
= g_malloc0(sizeof(*address_item
));
1197 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1198 address_item
->value
->ip_address
= g_strdup(addr6
);
1199 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1201 if (ifa
->ifa_netmask
) {
1202 /* Count the number of set bits in netmask.
1203 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1204 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1205 address_item
->value
->prefix
=
1206 ctpop32(((uint32_t *) p
)[0]) +
1207 ctpop32(((uint32_t *) p
)[1]) +
1208 ctpop32(((uint32_t *) p
)[2]) +
1209 ctpop32(((uint32_t *) p
)[3]);
1213 if (!address_item
) {
1217 address_list
= &info
->value
->ip_addresses
;
1219 while (*address_list
&& (*address_list
)->next
) {
1220 address_list
= &(*address_list
)->next
;
1223 if (!*address_list
) {
1224 *address_list
= address_item
;
1226 (*address_list
)->next
= address_item
;
1229 info
->value
->has_ip_addresses
= true;
1239 qapi_free_GuestNetworkInterfaceList(head
);
1243 #define SYSCONF_EXACT(name, err) sysconf_exact((name), #name, (err))
1245 static long sysconf_exact(int name
, const char *name_str
, Error
**err
)
1250 ret
= sysconf(name
);
1253 error_setg(err
, "sysconf(%s): value indefinite", name_str
);
1255 error_setg_errno(err
, errno
, "sysconf(%s)", name_str
);
1261 /* Transfer online/offline status between @vcpu and the guest system.
1263 * On input either @errp or *@errp must be NULL.
1265 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1266 * - R: vcpu->logical_id
1268 * - W: vcpu->can_offline
1270 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1271 * - R: vcpu->logical_id
1274 * Written members remain unmodified on error.
1276 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1282 dirpath
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
1284 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
1286 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
1288 static const char fn
[] = "online";
1292 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
1294 if (errno
!= ENOENT
) {
1295 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
1296 } else if (sys2vcpu
) {
1297 vcpu
->online
= true;
1298 vcpu
->can_offline
= false;
1299 } else if (!vcpu
->online
) {
1300 error_setg(errp
, "logical processor #%" PRId64
" can't be "
1301 "offlined", vcpu
->logical_id
);
1302 } /* otherwise pretend successful re-onlining */
1304 unsigned char status
;
1306 res
= pread(fd
, &status
, 1, 0);
1308 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
1309 } else if (res
== 0) {
1310 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
1312 } else if (sys2vcpu
) {
1313 vcpu
->online
= (status
!= '0');
1314 vcpu
->can_offline
= true;
1315 } else if (vcpu
->online
!= (status
!= '0')) {
1316 status
= '0' + vcpu
->online
;
1317 if (pwrite(fd
, &status
, 1, 0) == -1) {
1318 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
1321 } /* otherwise pretend successful re-(on|off)-lining */
1334 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1337 GuestLogicalProcessorList
*head
, **link
;
1339 Error
*local_err
= NULL
;
1344 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
1346 while (local_err
== NULL
&& current
< sc_max
) {
1347 GuestLogicalProcessor
*vcpu
;
1348 GuestLogicalProcessorList
*entry
;
1350 vcpu
= g_malloc0(sizeof *vcpu
);
1351 vcpu
->logical_id
= current
++;
1352 vcpu
->has_can_offline
= true; /* lolspeak ftw */
1353 transfer_vcpu(vcpu
, true, &local_err
);
1355 entry
= g_malloc0(sizeof *entry
);
1356 entry
->value
= vcpu
;
1359 link
= &entry
->next
;
1362 if (local_err
== NULL
) {
1363 /* there's no guest with zero VCPUs */
1364 g_assert(head
!= NULL
);
1368 qapi_free_GuestLogicalProcessorList(head
);
1369 error_propagate(errp
, local_err
);
1373 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1376 Error
*local_err
= NULL
;
1379 while (vcpus
!= NULL
) {
1380 transfer_vcpu(vcpus
->value
, false, &local_err
);
1381 if (local_err
!= NULL
) {
1385 vcpus
= vcpus
->next
;
1388 if (local_err
!= NULL
) {
1389 if (processed
== 0) {
1390 error_propagate(errp
, local_err
);
1392 error_free(local_err
);
1399 #else /* defined(__linux__) */
1401 void qmp_guest_suspend_disk(Error
**err
)
1403 error_set(err
, QERR_UNSUPPORTED
);
1406 void qmp_guest_suspend_ram(Error
**err
)
1408 error_set(err
, QERR_UNSUPPORTED
);
1411 void qmp_guest_suspend_hybrid(Error
**err
)
1413 error_set(err
, QERR_UNSUPPORTED
);
1416 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1418 error_set(errp
, QERR_UNSUPPORTED
);
1422 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1424 error_set(errp
, QERR_UNSUPPORTED
);
1428 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1430 error_set(errp
, QERR_UNSUPPORTED
);
1436 #if !defined(CONFIG_FSFREEZE)
1438 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**err
)
1440 error_set(err
, QERR_UNSUPPORTED
);
1445 int64_t qmp_guest_fsfreeze_freeze(Error
**err
)
1447 error_set(err
, QERR_UNSUPPORTED
);
1452 int64_t qmp_guest_fsfreeze_thaw(Error
**err
)
1454 error_set(err
, QERR_UNSUPPORTED
);
1458 #endif /* CONFIG_FSFREEZE */
1460 #if !defined(CONFIG_FSTRIM)
1461 void qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**err
)
1463 error_set(err
, QERR_UNSUPPORTED
);
1467 /* register init/cleanup routines for stateful command groups */
1468 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
1470 #if defined(CONFIG_FSFREEZE)
1471 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
1473 ga_command_state_add(cs
, guest_file_init
, NULL
);