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 static ssize_t
ga_pipe_read_str(int fd
[2], char **str
)
86 while ((n
= read(fd
[0], buf
, sizeof(buf
))) != 0) {
95 *str
= g_realloc(*str
, len
+ n
+ 1);
96 memcpy(*str
+ len
, buf
, n
);
107 * Helper to run command with input/output redirection,
108 * sending string to stdin and taking error message from
111 static int ga_run_command(const char *argv
[], const char *in_str
,
112 const char *action
, Error
**errp
)
117 int infd
[2] = { -1, -1 };
118 int outfd
[2] = { -1, -1 };
122 if ((in_str
&& !g_unix_open_pipe(infd
, FD_CLOEXEC
, NULL
)) ||
123 !g_unix_open_pipe(outfd
, FD_CLOEXEC
, NULL
)) {
124 error_setg(errp
, "cannot create pipe FDs");
135 /* Redirect stdin to infd. */
140 reopen_fd_to_null(0);
143 /* Redirect stdout/stderr to outfd. */
149 execvp(argv
[0], (char *const *)argv
);
151 /* Write the cause of failed exec to pipe for the parent to read it. */
152 cherr
= g_strdup_printf("failed to exec '%s'", argv
[0]);
156 } else if (pid
< 0) {
157 error_setg_errno(errp
, errno
, "failed to create child process");
164 if (qemu_write_full(infd
[1], in_str
, strlen(in_str
)) !=
166 error_setg_errno(errp
, errno
, "%s: cannot write to stdin pipe",
174 len
= ga_pipe_read_str(outfd
, &str
);
176 error_setg_errno(errp
, -len
, "%s: cannot read from stdout/stderr pipe",
181 ga_wait_child(pid
, &status
, errp
);
186 if (!WIFEXITED(status
)) {
188 error_setg(errp
, "child process has terminated abnormally: %s",
191 error_setg(errp
, "child process has terminated abnormally");
196 retcode
= WEXITSTATUS(status
);
198 if (WEXITSTATUS(status
)) {
200 error_setg(errp
, "child process has failed to %s: %s",
203 error_setg(errp
, "child process has failed to %s: exit status %d",
204 action
, WEXITSTATUS(status
));
218 if (outfd
[0] != -1) {
221 if (outfd
[1] != -1) {
228 void qmp_guest_shutdown(const char *mode
, Error
**errp
)
230 const char *shutdown_flag
;
231 Error
*local_err
= NULL
;
233 #ifdef CONFIG_SOLARIS
234 const char *powerdown_flag
= "-i5";
235 const char *halt_flag
= "-i0";
236 const char *reboot_flag
= "-i6";
237 #elif defined(CONFIG_BSD)
238 const char *powerdown_flag
= "-p";
239 const char *halt_flag
= "-h";
240 const char *reboot_flag
= "-r";
242 const char *powerdown_flag
= "-P";
243 const char *halt_flag
= "-H";
244 const char *reboot_flag
= "-r";
247 slog("guest-shutdown called, mode: %s", mode
);
248 if (!mode
|| strcmp(mode
, "powerdown") == 0) {
249 shutdown_flag
= powerdown_flag
;
250 } else if (strcmp(mode
, "halt") == 0) {
251 shutdown_flag
= halt_flag
;
252 } else if (strcmp(mode
, "reboot") == 0) {
253 shutdown_flag
= reboot_flag
;
256 "mode is invalid (valid values are: halt|powerdown|reboot");
260 const char *argv
[] = {"/sbin/shutdown",
261 #ifdef CONFIG_SOLARIS
262 shutdown_flag
, "-g0", "-y",
263 #elif defined(CONFIG_BSD)
266 "-h", shutdown_flag
, "+0",
268 "hypervisor initiated shutdown", (char *) NULL
};
270 ga_run_command(argv
, NULL
, "shutdown", &local_err
);
272 error_propagate(errp
, local_err
);
279 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
282 Error
*local_err
= NULL
;
284 const char *argv
[] = {"/sbin/hwclock", has_time
? "-w" : "-s", NULL
};
286 /* If user has passed a time, validate and set it. */
290 /* year-2038 will overflow in case time_t is 32bit */
291 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
292 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
296 tv
.tv_sec
= time_ns
/ 1000000000;
297 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
298 g_date_set_time_t(&date
, tv
.tv_sec
);
299 if (date
.year
< 1970 || date
.year
>= 2070) {
300 error_setg_errno(errp
, errno
, "Invalid time");
304 ret
= settimeofday(&tv
, NULL
);
306 error_setg_errno(errp
, errno
, "Failed to set time to guest");
311 /* Now, if user has passed a time to set and the system time is set, we
312 * just need to synchronize the hardware clock. However, if no time was
313 * passed, user is requesting the opposite: set the system time from the
314 * hardware clock (RTC). */
315 ga_run_command(argv
, NULL
, "set hardware clock to system time",
318 error_propagate(errp
, local_err
);
329 struct GuestFileHandle
{
333 QTAILQ_ENTRY(GuestFileHandle
) next
;
337 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
338 } guest_file_state
= {
339 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
342 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
344 GuestFileHandle
*gfh
;
347 handle
= ga_get_fd_handle(ga_state
, errp
);
352 gfh
= g_new0(GuestFileHandle
, 1);
355 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
360 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
362 GuestFileHandle
*gfh
;
364 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
371 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
375 typedef const char * const ccpc
;
381 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
382 static const struct {
385 } guest_file_open_modes
[] = {
386 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
387 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
388 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
389 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
390 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
391 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
392 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
393 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
394 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
395 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
396 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
397 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
401 find_open_flag(const char *mode_str
, Error
**errp
)
405 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
408 form
= guest_file_open_modes
[mode
].forms
;
409 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
417 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
418 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
421 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
424 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
425 S_IRGRP | S_IWGRP | \
429 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
435 oflag
= find_open_flag(mode
, errp
);
440 /* If the caller wants / allows creation of a new file, we implement it
441 * with a two step process: open() + (open() / fchmod()).
443 * First we insist on creating the file exclusively as a new file. If
444 * that succeeds, we're free to set any file-mode bits on it. (The
445 * motivation is that we want to set those file-mode bits independently
446 * of the current umask.)
448 * If the exclusive creation fails because the file already exists
449 * (EEXIST is not possible for any other reason), we just attempt to
450 * open the file, but in this case we won't be allowed to change the
451 * file-mode bits on the preexistent file.
453 * The pathname should never disappear between the two open()s in
454 * practice. If it happens, then someone very likely tried to race us.
455 * In this case just go ahead and report the ENOENT from the second
456 * open() to the caller.
458 * If the caller wants to open a preexistent file, then the first
459 * open() is decisive and its third argument is ignored, and the second
460 * open() and the fchmod() are never called.
462 fd
= qga_open_cloexec(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
463 if (fd
== -1 && errno
== EEXIST
) {
464 oflag
&= ~(unsigned)O_CREAT
;
465 fd
= qga_open_cloexec(path
, oflag
, 0);
468 error_setg_errno(errp
, errno
,
469 "failed to open file '%s' (mode: '%s')",
474 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
475 error_setg_errno(errp
, errno
, "failed to set permission "
476 "0%03o on new file '%s' (mode: '%s')",
477 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
481 f
= fdopen(fd
, mode
);
483 error_setg_errno(errp
, errno
, "failed to associate stdio stream with "
484 "file descriptor %d, file '%s' (mode: '%s')",
489 if (f
== NULL
&& fd
!= -1) {
491 if (oflag
& O_CREAT
) {
498 int64_t qmp_guest_file_open(const char *path
, const char *mode
,
502 Error
*local_err
= NULL
;
508 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
509 fh
= safe_open_or_create(path
, mode
, &local_err
);
510 if (local_err
!= NULL
) {
511 error_propagate(errp
, local_err
);
515 /* set fd non-blocking to avoid common use cases (like reading from a
516 * named pipe) from hanging the agent
518 if (!g_unix_set_fd_nonblocking(fileno(fh
), true, NULL
)) {
520 error_setg_errno(errp
, errno
, "Failed to set FD nonblocking");
524 handle
= guest_file_handle_add(fh
, errp
);
530 slog("guest-file-open, handle: %" PRId64
, handle
);
534 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
536 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
539 slog("guest-file-close called, handle: %" PRId64
, handle
);
544 ret
= fclose(gfh
->fh
);
546 error_setg_errno(errp
, errno
, "failed to close handle");
550 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
554 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
555 int64_t count
, Error
**errp
)
557 GuestFileRead
*read_data
= NULL
;
562 /* explicitly flush when switching from writing to reading */
563 if (gfh
->state
== RW_STATE_WRITING
) {
564 int ret
= fflush(fh
);
566 error_setg_errno(errp
, errno
, "failed to flush file");
569 gfh
->state
= RW_STATE_NEW
;
572 buf
= g_malloc0(count
+ 1);
573 read_count
= fread(buf
, 1, count
, fh
);
575 error_setg_errno(errp
, errno
, "failed to read file");
578 read_data
= g_new0(GuestFileRead
, 1);
579 read_data
->count
= read_count
;
580 read_data
->eof
= feof(fh
);
582 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
584 gfh
->state
= RW_STATE_READING
;
592 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
593 bool has_count
, int64_t count
,
596 GuestFileWrite
*write_data
= NULL
;
600 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
609 if (gfh
->state
== RW_STATE_READING
) {
610 int ret
= fseek(fh
, 0, SEEK_CUR
);
612 error_setg_errno(errp
, errno
, "failed to seek file");
615 gfh
->state
= RW_STATE_NEW
;
618 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
625 } else if (count
< 0 || count
> buf_len
) {
626 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
632 write_count
= fwrite(buf
, 1, count
, fh
);
634 error_setg_errno(errp
, errno
, "failed to write to file");
635 slog("guest-file-write failed, handle: %" PRId64
, handle
);
637 write_data
= g_new0(GuestFileWrite
, 1);
638 write_data
->count
= write_count
;
639 write_data
->eof
= feof(fh
);
640 gfh
->state
= RW_STATE_WRITING
;
648 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
649 GuestFileWhence
*whence_code
,
652 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
653 GuestFileSeek
*seek_data
= NULL
;
663 /* We stupidly exposed 'whence':'int' in our qapi */
664 whence
= ga_parse_whence(whence_code
, &err
);
666 error_propagate(errp
, err
);
671 ret
= fseek(fh
, offset
, whence
);
673 error_setg_errno(errp
, errno
, "failed to seek file");
674 if (errno
== ESPIPE
) {
675 /* file is non-seekable, stdio shouldn't be buffering anyways */
676 gfh
->state
= RW_STATE_NEW
;
679 seek_data
= g_new0(GuestFileSeek
, 1);
680 seek_data
->position
= ftell(fh
);
681 seek_data
->eof
= feof(fh
);
682 gfh
->state
= RW_STATE_NEW
;
689 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
691 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
702 error_setg_errno(errp
, errno
, "failed to flush file");
704 gfh
->state
= RW_STATE_NEW
;
708 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
709 void free_fs_mount_list(FsMountList
*mounts
)
711 FsMount
*mount
, *temp
;
717 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
718 QTAILQ_REMOVE(mounts
, mount
, next
);
719 g_free(mount
->dirname
);
720 g_free(mount
->devtype
);
726 #if defined(CONFIG_FSFREEZE)
728 FSFREEZE_HOOK_THAW
= 0,
729 FSFREEZE_HOOK_FREEZE
,
732 static const char *fsfreeze_hook_arg_string
[] = {
737 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
740 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
741 Error
*local_err
= NULL
;
743 hook
= ga_fsfreeze_hook(ga_state
);
748 const char *argv
[] = {hook
, arg_str
, NULL
};
750 slog("executing fsfreeze hook with arg '%s'", arg_str
);
751 ga_run_command(argv
, NULL
, "execute fsfreeze hook", &local_err
);
753 error_propagate(errp
, local_err
);
759 * Return status of freeze/thaw
761 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
763 if (ga_is_frozen(ga_state
)) {
764 return GUEST_FSFREEZE_STATUS_FROZEN
;
767 return GUEST_FSFREEZE_STATUS_THAWED
;
770 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
772 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
775 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
776 strList
*mountpoints
,
781 Error
*local_err
= NULL
;
783 slog("guest-fsfreeze called");
785 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
787 error_propagate(errp
, local_err
);
791 QTAILQ_INIT(&mounts
);
792 if (!build_fs_mount_list(&mounts
, &local_err
)) {
793 error_propagate(errp
, local_err
);
797 /* cannot risk guest agent blocking itself on a write in this state */
798 ga_set_frozen(ga_state
);
800 ret
= qmp_guest_fsfreeze_do_freeze_list(has_mountpoints
, mountpoints
,
803 free_fs_mount_list(&mounts
);
804 /* We may not issue any FIFREEZE here.
805 * Just unset ga_state here and ready for the next call.
808 ga_unset_frozen(ga_state
);
809 } else if (ret
< 0) {
810 qmp_guest_fsfreeze_thaw(NULL
);
815 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
819 ret
= qmp_guest_fsfreeze_do_thaw(errp
);
821 ga_unset_frozen(ga_state
);
822 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
830 static void guest_fsfreeze_cleanup(void)
834 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
835 qmp_guest_fsfreeze_thaw(&err
);
837 slog("failed to clean up frozen filesystems: %s",
838 error_get_pretty(err
));
845 /* linux-specific implementations. avoid this if at all possible. */
846 #if defined(__linux__)
847 #if defined(CONFIG_FSFREEZE)
849 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
857 path
= g_strndup(syspath
, pathlen
);
858 dpath
= g_strdup_printf("%s/driver", path
);
859 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
862 driver
= g_path_get_basename(buf
);
869 static int compare_uint(const void *_a
, const void *_b
)
871 unsigned int a
= *(unsigned int *)_a
;
872 unsigned int b
= *(unsigned int *)_b
;
874 return a
< b
? -1 : a
> b
? 1 : 0;
877 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
878 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
879 unsigned int *hosts
, int hosts_max
, Error
**errp
)
883 struct dirent
*entry
;
886 path
= g_strndup(syspath
, host
- syspath
);
889 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
894 while (i
< hosts_max
) {
895 entry
= readdir(dir
);
899 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
901 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
906 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
914 * Store disk device info for devices on the PCI bus.
915 * Returns true if information has been stored, or false for failure.
917 static bool build_guest_fsinfo_for_pci_dev(char const *syspath
,
918 GuestDiskAddress
*disk
,
921 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
922 int i
, nhosts
= 0, pcilen
;
923 GuestPCIAddress
*pciaddr
= disk
->pci_controller
;
924 bool has_ata
= false, has_host
= false, has_tgt
= false;
925 char *p
, *q
, *driver
= NULL
;
928 p
= strstr(syspath
, "/devices/pci");
929 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
930 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
931 g_debug("only pci device is supported: sysfs path '%s'", syspath
);
937 driver
= get_pci_driver(syspath
, p
- syspath
, errp
);
938 if (driver
&& (g_str_equal(driver
, "ata_piix") ||
939 g_str_equal(driver
, "sym53c8xx") ||
940 g_str_equal(driver
, "virtio-pci") ||
941 g_str_equal(driver
, "ahci") ||
942 g_str_equal(driver
, "nvme") ||
943 g_str_equal(driver
, "xhci_hcd") ||
944 g_str_equal(driver
, "ehci-pci"))) {
949 if (sscanf(p
, "/%x:%x:%x.%x%n",
950 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
955 g_debug("unsupported driver or sysfs path '%s'", syspath
);
959 p
= strstr(syspath
, "/target");
960 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
961 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
965 p
= strstr(syspath
, "/ata");
970 p
= strstr(syspath
, "/host");
973 if (p
&& sscanf(q
, "%u", &host
) == 1) {
975 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
976 ARRAY_SIZE(hosts
), errp
);
982 pciaddr
->domain
= pci
[0];
983 pciaddr
->bus
= pci
[1];
984 pciaddr
->slot
= pci
[2];
985 pciaddr
->function
= pci
[3];
987 if (strcmp(driver
, "ata_piix") == 0) {
988 /* a host per ide bus, target*:0:<unit>:0 */
989 if (!has_host
|| !has_tgt
) {
990 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
993 for (i
= 0; i
< nhosts
; i
++) {
994 if (host
== hosts
[i
]) {
995 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
1002 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
1005 } else if (strcmp(driver
, "sym53c8xx") == 0) {
1006 /* scsi(LSI Logic): target*:0:<unit>:0 */
1008 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
1011 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1012 disk
->unit
= tgt
[1];
1013 } else if (strcmp(driver
, "virtio-pci") == 0) {
1015 /* virtio-scsi: target*:0:0:<unit> */
1016 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1017 disk
->unit
= tgt
[2];
1019 /* virtio-blk: 1 disk per 1 device */
1020 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
1022 } else if (strcmp(driver
, "ahci") == 0) {
1023 /* ahci: 1 host per 1 unit */
1024 if (!has_host
|| !has_tgt
) {
1025 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
1028 for (i
= 0; i
< nhosts
; i
++) {
1029 if (host
== hosts
[i
]) {
1031 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
1036 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
1039 } else if (strcmp(driver
, "nvme") == 0) {
1040 disk
->bus_type
= GUEST_DISK_BUS_TYPE_NVME
;
1041 } else if (strcmp(driver
, "ehci-pci") == 0 || strcmp(driver
, "xhci_hcd") == 0) {
1042 disk
->bus_type
= GUEST_DISK_BUS_TYPE_USB
;
1044 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
1056 * Store disk device info for non-PCI virtio devices (for example s390x
1057 * channel I/O devices). Returns true if information has been stored, or
1058 * false for failure.
1060 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath
,
1061 GuestDiskAddress
*disk
,
1064 unsigned int tgt
[3];
1067 if (!strstr(syspath
, "/virtio") || !strstr(syspath
, "/block")) {
1068 g_debug("Unsupported virtio device '%s'", syspath
);
1072 p
= strstr(syspath
, "/target");
1073 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1074 &tgt
[0], &tgt
[1], &tgt
[2]) == 3) {
1075 /* virtio-scsi: target*:0:<target>:<unit> */
1076 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1078 disk
->target
= tgt
[1];
1079 disk
->unit
= tgt
[2];
1081 /* virtio-blk: 1 disk per 1 device */
1082 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
1089 * Store disk device info for CCW devices (s390x channel I/O devices).
1090 * Returns true if information has been stored, or false for failure.
1092 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath
,
1093 GuestDiskAddress
*disk
,
1096 unsigned int cssid
, ssid
, subchno
, devno
;
1099 p
= strstr(syspath
, "/devices/css");
1100 if (!p
|| sscanf(p
+ 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1101 &cssid
, &ssid
, &subchno
, &devno
) < 4) {
1102 g_debug("could not parse ccw device sysfs path: %s", syspath
);
1106 disk
->ccw_address
= g_new0(GuestCCWAddress
, 1);
1107 disk
->ccw_address
->cssid
= cssid
;
1108 disk
->ccw_address
->ssid
= ssid
;
1109 disk
->ccw_address
->subchno
= subchno
;
1110 disk
->ccw_address
->devno
= devno
;
1112 if (strstr(p
, "/virtio")) {
1113 build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1119 /* Store disk device info specified by @sysfs into @fs */
1120 static void build_guest_fsinfo_for_real_device(char const *syspath
,
1121 GuestFilesystemInfo
*fs
,
1124 GuestDiskAddress
*disk
;
1125 GuestPCIAddress
*pciaddr
;
1127 #ifdef CONFIG_LIBUDEV
1128 struct udev
*udev
= NULL
;
1129 struct udev_device
*udevice
= NULL
;
1132 pciaddr
= g_new0(GuestPCIAddress
, 1);
1133 pciaddr
->domain
= -1; /* -1 means field is invalid */
1136 pciaddr
->function
= -1;
1138 disk
= g_new0(GuestDiskAddress
, 1);
1139 disk
->pci_controller
= pciaddr
;
1140 disk
->bus_type
= GUEST_DISK_BUS_TYPE_UNKNOWN
;
1142 #ifdef CONFIG_LIBUDEV
1144 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1145 if (udev
== NULL
|| udevice
== NULL
) {
1146 g_debug("failed to query udev");
1148 const char *devnode
, *serial
;
1149 devnode
= udev_device_get_devnode(udevice
);
1150 if (devnode
!= NULL
) {
1151 disk
->dev
= g_strdup(devnode
);
1153 serial
= udev_device_get_property_value(udevice
, "ID_SERIAL");
1154 if (serial
!= NULL
&& *serial
!= 0) {
1155 disk
->serial
= g_strdup(serial
);
1160 udev_device_unref(udevice
);
1163 if (strstr(syspath
, "/devices/pci")) {
1164 has_hwinf
= build_guest_fsinfo_for_pci_dev(syspath
, disk
, errp
);
1165 } else if (strstr(syspath
, "/devices/css")) {
1166 has_hwinf
= build_guest_fsinfo_for_ccw_dev(syspath
, disk
, errp
);
1167 } else if (strstr(syspath
, "/virtio")) {
1168 has_hwinf
= build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1170 g_debug("Unsupported device type for '%s'", syspath
);
1174 if (has_hwinf
|| disk
->dev
|| disk
->serial
) {
1175 QAPI_LIST_PREPEND(fs
->disk
, disk
);
1177 qapi_free_GuestDiskAddress(disk
);
1181 static void build_guest_fsinfo_for_device(char const *devpath
,
1182 GuestFilesystemInfo
*fs
,
1185 /* Store a list of slave devices of virtual volume specified by @syspath into
1187 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1188 GuestFilesystemInfo
*fs
,
1194 struct dirent
*entry
;
1196 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1197 dir
= opendir(dirpath
);
1199 if (errno
!= ENOENT
) {
1200 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1208 entry
= readdir(dir
);
1209 if (entry
== NULL
) {
1211 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1216 if (entry
->d_type
== DT_LNK
) {
1219 g_debug(" slave device '%s'", entry
->d_name
);
1220 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1221 build_guest_fsinfo_for_device(path
, fs
, &err
);
1225 error_propagate(errp
, err
);
1235 static bool is_disk_virtual(const char *devpath
, Error
**errp
)
1237 g_autofree
char *syspath
= realpath(devpath
, NULL
);
1240 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1243 return strstr(syspath
, "/devices/virtual/block/") != NULL
;
1246 /* Dispatch to functions for virtual/real device */
1247 static void build_guest_fsinfo_for_device(char const *devpath
,
1248 GuestFilesystemInfo
*fs
,
1252 g_autofree
char *syspath
= NULL
;
1253 bool is_virtual
= false;
1255 syspath
= realpath(devpath
, NULL
);
1257 if (errno
!= ENOENT
) {
1258 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1262 /* ENOENT: This devpath may not exist because of container config */
1264 fs
->name
= g_path_get_basename(devpath
);
1270 fs
->name
= g_path_get_basename(syspath
);
1273 g_debug(" parse sysfs path '%s'", syspath
);
1274 is_virtual
= is_disk_virtual(syspath
, errp
);
1275 if (*errp
!= NULL
) {
1279 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1281 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1285 #ifdef CONFIG_LIBUDEV
1288 * Wrapper around build_guest_fsinfo_for_device() for getting just
1291 static GuestDiskAddress
*get_disk_address(const char *syspath
, Error
**errp
)
1293 g_autoptr(GuestFilesystemInfo
) fs
= NULL
;
1295 fs
= g_new0(GuestFilesystemInfo
, 1);
1296 build_guest_fsinfo_for_device(syspath
, fs
, errp
);
1297 if (fs
->disk
!= NULL
) {
1298 return g_steal_pointer(&fs
->disk
->value
);
1303 static char *get_alias_for_syspath(const char *syspath
)
1305 struct udev
*udev
= NULL
;
1306 struct udev_device
*udevice
= NULL
;
1311 g_debug("failed to query udev");
1314 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1315 if (udevice
== NULL
) {
1316 g_debug("failed to query udev for path: %s", syspath
);
1319 const char *alias
= udev_device_get_property_value(
1320 udevice
, "DM_NAME");
1322 * NULL means there was an error and empty string means there is no
1323 * alias. In case of no alias we return NULL instead of empty string.
1325 if (alias
== NULL
) {
1326 g_debug("failed to query udev for device alias for: %s",
1328 } else if (*alias
!= 0) {
1329 ret
= g_strdup(alias
);
1335 udev_device_unref(udevice
);
1339 static char *get_device_for_syspath(const char *syspath
)
1341 struct udev
*udev
= NULL
;
1342 struct udev_device
*udevice
= NULL
;
1347 g_debug("failed to query udev");
1350 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1351 if (udevice
== NULL
) {
1352 g_debug("failed to query udev for path: %s", syspath
);
1355 ret
= g_strdup(udev_device_get_devnode(udevice
));
1360 udev_device_unref(udevice
);
1364 static void get_disk_deps(const char *disk_dir
, GuestDiskInfo
*disk
)
1366 g_autofree
char *deps_dir
= NULL
;
1368 GDir
*dp_deps
= NULL
;
1370 /* List dependent disks */
1371 deps_dir
= g_strdup_printf("%s/slaves", disk_dir
);
1372 g_debug(" listing entries in: %s", deps_dir
);
1373 dp_deps
= g_dir_open(deps_dir
, 0, NULL
);
1374 if (dp_deps
== NULL
) {
1375 g_debug("failed to list entries in %s", deps_dir
);
1378 disk
->has_dependencies
= true;
1379 while ((dep
= g_dir_read_name(dp_deps
)) != NULL
) {
1380 g_autofree
char *dep_dir
= NULL
;
1383 /* Add dependent disks */
1384 dep_dir
= g_strdup_printf("%s/%s", deps_dir
, dep
);
1385 dev_name
= get_device_for_syspath(dep_dir
);
1386 if (dev_name
!= NULL
) {
1387 g_debug(" adding dependent device: %s", dev_name
);
1388 QAPI_LIST_PREPEND(disk
->dependencies
, dev_name
);
1391 g_dir_close(dp_deps
);
1395 * Detect partitions subdirectory, name is "<disk_name><number>" or
1396 * "<disk_name>p<number>"
1398 * @disk_name -- last component of /sys path (e.g. sda)
1399 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1400 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1402 static GuestDiskInfoList
*get_disk_partitions(
1403 GuestDiskInfoList
*list
,
1404 const char *disk_name
, const char *disk_dir
,
1405 const char *disk_dev
)
1407 GuestDiskInfoList
*ret
= list
;
1408 struct dirent
*de_disk
;
1409 DIR *dp_disk
= NULL
;
1410 size_t len
= strlen(disk_name
);
1412 dp_disk
= opendir(disk_dir
);
1413 while ((de_disk
= readdir(dp_disk
)) != NULL
) {
1414 g_autofree
char *partition_dir
= NULL
;
1416 GuestDiskInfo
*partition
;
1418 if (!(de_disk
->d_type
& DT_DIR
)) {
1422 if (!(strncmp(disk_name
, de_disk
->d_name
, len
) == 0 &&
1423 ((*(de_disk
->d_name
+ len
) == 'p' &&
1424 isdigit(*(de_disk
->d_name
+ len
+ 1))) ||
1425 isdigit(*(de_disk
->d_name
+ len
))))) {
1429 partition_dir
= g_strdup_printf("%s/%s",
1430 disk_dir
, de_disk
->d_name
);
1431 dev_name
= get_device_for_syspath(partition_dir
);
1432 if (dev_name
== NULL
) {
1433 g_debug("Failed to get device name for syspath: %s",
1437 partition
= g_new0(GuestDiskInfo
, 1);
1438 partition
->name
= dev_name
;
1439 partition
->partition
= true;
1440 partition
->has_dependencies
= true;
1441 /* Add parent disk as dependent for easier tracking of hierarchy */
1442 QAPI_LIST_PREPEND(partition
->dependencies
, g_strdup(disk_dev
));
1444 QAPI_LIST_PREPEND(ret
, partition
);
1451 static void get_nvme_smart(GuestDiskInfo
*disk
)
1454 GuestNVMeSmart
*smart
;
1455 NvmeSmartLog log
= {0};
1456 struct nvme_admin_cmd cmd
= {
1457 .opcode
= NVME_ADM_CMD_GET_LOG_PAGE
,
1458 .nsid
= NVME_NSID_BROADCAST
,
1459 .addr
= (uintptr_t)&log
,
1460 .data_len
= sizeof(log
),
1461 .cdw10
= NVME_LOG_SMART_INFO
| (1 << 15) /* RAE bit */
1462 | (((sizeof(log
) >> 2) - 1) << 16)
1465 fd
= qga_open_cloexec(disk
->name
, O_RDONLY
, 0);
1467 g_debug("Failed to open device: %s: %s", disk
->name
, g_strerror(errno
));
1471 if (ioctl(fd
, NVME_IOCTL_ADMIN_CMD
, &cmd
)) {
1472 g_debug("Failed to get smart: %s: %s", disk
->name
, g_strerror(errno
));
1477 disk
->smart
= g_new0(GuestDiskSmart
, 1);
1478 disk
->smart
->type
= GUEST_DISK_BUS_TYPE_NVME
;
1480 smart
= &disk
->smart
->u
.nvme
;
1481 smart
->critical_warning
= log
.critical_warning
;
1482 smart
->temperature
= lduw_le_p(&log
.temperature
); /* unaligned field */
1483 smart
->available_spare
= log
.available_spare
;
1484 smart
->available_spare_threshold
= log
.available_spare_threshold
;
1485 smart
->percentage_used
= log
.percentage_used
;
1486 smart
->data_units_read_lo
= le64_to_cpu(log
.data_units_read
[0]);
1487 smart
->data_units_read_hi
= le64_to_cpu(log
.data_units_read
[1]);
1488 smart
->data_units_written_lo
= le64_to_cpu(log
.data_units_written
[0]);
1489 smart
->data_units_written_hi
= le64_to_cpu(log
.data_units_written
[1]);
1490 smart
->host_read_commands_lo
= le64_to_cpu(log
.host_read_commands
[0]);
1491 smart
->host_read_commands_hi
= le64_to_cpu(log
.host_read_commands
[1]);
1492 smart
->host_write_commands_lo
= le64_to_cpu(log
.host_write_commands
[0]);
1493 smart
->host_write_commands_hi
= le64_to_cpu(log
.host_write_commands
[1]);
1494 smart
->controller_busy_time_lo
= le64_to_cpu(log
.controller_busy_time
[0]);
1495 smart
->controller_busy_time_hi
= le64_to_cpu(log
.controller_busy_time
[1]);
1496 smart
->power_cycles_lo
= le64_to_cpu(log
.power_cycles
[0]);
1497 smart
->power_cycles_hi
= le64_to_cpu(log
.power_cycles
[1]);
1498 smart
->power_on_hours_lo
= le64_to_cpu(log
.power_on_hours
[0]);
1499 smart
->power_on_hours_hi
= le64_to_cpu(log
.power_on_hours
[1]);
1500 smart
->unsafe_shutdowns_lo
= le64_to_cpu(log
.unsafe_shutdowns
[0]);
1501 smart
->unsafe_shutdowns_hi
= le64_to_cpu(log
.unsafe_shutdowns
[1]);
1502 smart
->media_errors_lo
= le64_to_cpu(log
.media_errors
[0]);
1503 smart
->media_errors_hi
= le64_to_cpu(log
.media_errors
[1]);
1504 smart
->number_of_error_log_entries_lo
=
1505 le64_to_cpu(log
.number_of_error_log_entries
[0]);
1506 smart
->number_of_error_log_entries_hi
=
1507 le64_to_cpu(log
.number_of_error_log_entries
[1]);
1512 static void get_disk_smart(GuestDiskInfo
*disk
)
1515 && (disk
->address
->bus_type
== GUEST_DISK_BUS_TYPE_NVME
)) {
1516 get_nvme_smart(disk
);
1520 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1522 GuestDiskInfoList
*ret
= NULL
;
1523 GuestDiskInfo
*disk
;
1525 struct dirent
*de
= NULL
;
1527 g_debug("listing /sys/block directory");
1528 dp
= opendir("/sys/block");
1530 error_setg_errno(errp
, errno
, "Can't open directory \"/sys/block\"");
1533 while ((de
= readdir(dp
)) != NULL
) {
1534 g_autofree
char *disk_dir
= NULL
, *line
= NULL
,
1537 Error
*local_err
= NULL
;
1538 if (de
->d_type
!= DT_LNK
) {
1539 g_debug(" skipping entry: %s", de
->d_name
);
1543 /* Check size and skip zero-sized disks */
1544 g_debug(" checking disk size");
1545 size_path
= g_strdup_printf("/sys/block/%s/size", de
->d_name
);
1546 if (!g_file_get_contents(size_path
, &line
, NULL
, NULL
)) {
1547 g_debug(" failed to read disk size");
1550 if (g_strcmp0(line
, "0\n") == 0) {
1551 g_debug(" skipping zero-sized disk");
1555 g_debug(" adding %s", de
->d_name
);
1556 disk_dir
= g_strdup_printf("/sys/block/%s", de
->d_name
);
1557 dev_name
= get_device_for_syspath(disk_dir
);
1558 if (dev_name
== NULL
) {
1559 g_debug("Failed to get device name for syspath: %s",
1563 disk
= g_new0(GuestDiskInfo
, 1);
1564 disk
->name
= dev_name
;
1565 disk
->partition
= false;
1566 disk
->alias
= get_alias_for_syspath(disk_dir
);
1567 QAPI_LIST_PREPEND(ret
, disk
);
1569 /* Get address for non-virtual devices */
1570 bool is_virtual
= is_disk_virtual(disk_dir
, &local_err
);
1571 if (local_err
!= NULL
) {
1572 g_debug(" failed to check disk path, ignoring error: %s",
1573 error_get_pretty(local_err
));
1574 error_free(local_err
);
1576 /* Don't try to get the address */
1580 disk
->address
= get_disk_address(disk_dir
, &local_err
);
1581 if (local_err
!= NULL
) {
1582 g_debug(" failed to get device info, ignoring error: %s",
1583 error_get_pretty(local_err
));
1584 error_free(local_err
);
1589 get_disk_deps(disk_dir
, disk
);
1590 get_disk_smart(disk
);
1591 ret
= get_disk_partitions(ret
, de
->d_name
, disk_dir
, dev_name
);
1601 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1603 error_setg(errp
, QERR_UNSUPPORTED
);
1609 /* Return a list of the disk device(s)' info which @mount lies on */
1610 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1613 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1615 unsigned long used
, nonroot_total
, fr_size
;
1616 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1617 mount
->devmajor
, mount
->devminor
);
1619 fs
->mountpoint
= g_strdup(mount
->dirname
);
1620 fs
->type
= g_strdup(mount
->devtype
);
1621 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1623 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1624 fr_size
= buf
.f_frsize
;
1625 used
= buf
.f_blocks
- buf
.f_bfree
;
1626 nonroot_total
= used
+ buf
.f_bavail
;
1627 fs
->used_bytes
= used
* fr_size
;
1628 fs
->total_bytes
= nonroot_total
* fr_size
;
1629 fs
->total_bytes_privileged
= buf
.f_blocks
* fr_size
;
1631 fs
->has_total_bytes
= true;
1632 fs
->has_total_bytes_privileged
= true;
1633 fs
->has_used_bytes
= true;
1641 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1644 struct FsMount
*mount
;
1645 GuestFilesystemInfoList
*ret
= NULL
;
1646 Error
*local_err
= NULL
;
1648 QTAILQ_INIT(&mounts
);
1649 if (!build_fs_mount_list(&mounts
, &local_err
)) {
1650 error_propagate(errp
, local_err
);
1654 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1655 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1657 QAPI_LIST_PREPEND(ret
, build_guest_fsinfo(mount
, &local_err
));
1659 error_propagate(errp
, local_err
);
1660 qapi_free_GuestFilesystemInfoList(ret
);
1666 free_fs_mount_list(&mounts
);
1669 #endif /* CONFIG_FSFREEZE */
1671 #if defined(CONFIG_FSTRIM)
1673 * Walk list of mounted file systems in the guest, and trim them.
1675 GuestFilesystemTrimResponse
*
1676 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1678 GuestFilesystemTrimResponse
*response
;
1679 GuestFilesystemTrimResult
*result
;
1682 struct FsMount
*mount
;
1684 struct fstrim_range r
;
1686 slog("guest-fstrim called");
1688 QTAILQ_INIT(&mounts
);
1689 if (!build_fs_mount_list(&mounts
, errp
)) {
1693 response
= g_malloc0(sizeof(*response
));
1695 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1696 result
= g_malloc0(sizeof(*result
));
1697 result
->path
= g_strdup(mount
->dirname
);
1699 QAPI_LIST_PREPEND(response
->paths
, result
);
1701 fd
= qga_open_cloexec(mount
->dirname
, O_RDONLY
, 0);
1703 result
->error
= g_strdup_printf("failed to open: %s",
1708 /* We try to cull filesystems we know won't work in advance, but other
1709 * filesystems may not implement fstrim for less obvious reasons.
1710 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1711 * will be reported (e.g. CD-ROMs).
1712 * Any other error means an unexpected error.
1716 r
.minlen
= has_minimum
? minimum
: 0;
1717 ret
= ioctl(fd
, FITRIM
, &r
);
1719 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1720 result
->error
= g_strdup("trim not supported");
1722 result
->error
= g_strdup_printf("failed to trim: %s",
1729 result
->has_minimum
= true;
1730 result
->minimum
= r
.minlen
;
1731 result
->has_trimmed
= true;
1732 result
->trimmed
= r
.len
;
1736 free_fs_mount_list(&mounts
);
1739 #endif /* CONFIG_FSTRIM */
1742 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1743 #define SUSPEND_SUPPORTED 0
1744 #define SUSPEND_NOT_SUPPORTED 1
1747 SUSPEND_MODE_DISK
= 0,
1748 SUSPEND_MODE_RAM
= 1,
1749 SUSPEND_MODE_HYBRID
= 2,
1753 * Executes a command in a child process using g_spawn_sync,
1754 * returning an int >= 0 representing the exit status of the
1757 * If the program wasn't found in path, returns -1.
1759 * If a problem happened when creating the child process,
1760 * returns -1 and errp is set.
1762 static int run_process_child(const char *command
[], Error
**errp
)
1764 int exit_status
, spawn_flag
;
1765 GError
*g_err
= NULL
;
1768 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1769 G_SPAWN_STDERR_TO_DEV_NULL
;
1771 success
= g_spawn_sync(NULL
, (char **)command
, NULL
, spawn_flag
,
1772 NULL
, NULL
, NULL
, NULL
,
1773 &exit_status
, &g_err
);
1776 return WEXITSTATUS(exit_status
);
1779 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1780 error_setg(errp
, "failed to create child process, error '%s'",
1784 g_error_free(g_err
);
1788 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1790 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1791 "systemd-hybrid-sleep"};
1792 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
1795 status
= run_process_child(cmd
, errp
);
1798 * systemctl status uses LSB return codes so we can expect
1799 * status > 0 and be ok. To assert if the guest has support
1800 * for the selected suspend mode, status should be < 4. 4 is
1801 * the code for unknown service status, the return value when
1802 * the service does not exist. A common value is status = 3
1803 * (program is not running).
1805 if (status
> 0 && status
< 4) {
1812 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
1814 Error
*local_err
= NULL
;
1815 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
1816 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
1819 status
= run_process_child(cmd
, &local_err
);
1825 if ((status
== -1) && !local_err
) {
1826 error_setg(errp
, "the helper program 'systemctl %s' was not found",
1827 systemctl_args
[mode
]);
1832 error_propagate(errp
, local_err
);
1834 error_setg(errp
, "the helper program 'systemctl %s' returned an "
1835 "unexpected exit status code (%d)",
1836 systemctl_args
[mode
], status
);
1840 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
1842 Error
*local_err
= NULL
;
1843 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
1844 "--suspend-hybrid"};
1845 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
1848 status
= run_process_child(cmd
, &local_err
);
1850 if (status
== SUSPEND_SUPPORTED
) {
1854 if ((status
== -1) && !local_err
) {
1859 error_propagate(errp
, local_err
);
1862 "the helper program '%s' returned an unexpected exit"
1863 " status code (%d)", "pm-is-supported", status
);
1869 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
1871 Error
*local_err
= NULL
;
1872 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
1873 "pm-suspend-hybrid"};
1874 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
1877 status
= run_process_child(cmd
, &local_err
);
1883 if ((status
== -1) && !local_err
) {
1884 error_setg(errp
, "the helper program '%s' was not found",
1885 pmutils_binaries
[mode
]);
1890 error_propagate(errp
, local_err
);
1893 "the helper program '%s' returned an unexpected exit"
1894 " status code (%d)", pmutils_binaries
[mode
], status
);
1898 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
1900 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1901 const char *sysfile_str
= sysfile_strs
[mode
];
1902 char buf
[32]; /* hopefully big enough */
1907 error_setg(errp
, "unknown guest suspend mode");
1911 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1916 ret
= read(fd
, buf
, sizeof(buf
) - 1);
1923 if (strstr(buf
, sysfile_str
)) {
1929 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
1931 g_autoptr(GError
) local_gerr
= NULL
;
1932 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
1933 const char *sysfile_str
= sysfile_strs
[mode
];
1936 error_setg(errp
, "unknown guest suspend mode");
1940 if (!g_file_set_contents(LINUX_SYS_STATE_FILE
, sysfile_str
,
1942 error_setg(errp
, "suspend: cannot write to '%s': %s",
1943 LINUX_SYS_STATE_FILE
, local_gerr
->message
);
1948 static void guest_suspend(SuspendMode mode
, Error
**errp
)
1950 Error
*local_err
= NULL
;
1951 bool mode_supported
= false;
1953 if (systemd_supports_mode(mode
, &local_err
)) {
1954 mode_supported
= true;
1955 systemd_suspend(mode
, &local_err
);
1962 error_free(local_err
);
1965 if (pmutils_supports_mode(mode
, &local_err
)) {
1966 mode_supported
= true;
1967 pmutils_suspend(mode
, &local_err
);
1974 error_free(local_err
);
1977 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
1978 mode_supported
= true;
1979 linux_sys_state_suspend(mode
, &local_err
);
1982 if (!mode_supported
) {
1983 error_free(local_err
);
1985 "the requested suspend mode is not supported by the guest");
1987 error_propagate(errp
, local_err
);
1991 void qmp_guest_suspend_disk(Error
**errp
)
1993 guest_suspend(SUSPEND_MODE_DISK
, errp
);
1996 void qmp_guest_suspend_ram(Error
**errp
)
1998 guest_suspend(SUSPEND_MODE_RAM
, errp
);
2001 void qmp_guest_suspend_hybrid(Error
**errp
)
2003 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
2006 /* Transfer online/offline status between @vcpu and the guest system.
2008 * On input either @errp or *@errp must be NULL.
2010 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2011 * - R: vcpu->logical_id
2013 * - W: vcpu->can_offline
2015 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2016 * - R: vcpu->logical_id
2019 * Written members remain unmodified on error.
2021 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
2022 char *dirpath
, Error
**errp
)
2027 static const char fn
[] = "online";
2029 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2031 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2035 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2037 if (errno
!= ENOENT
) {
2038 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2039 } else if (sys2vcpu
) {
2040 vcpu
->online
= true;
2041 vcpu
->can_offline
= false;
2042 } else if (!vcpu
->online
) {
2043 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2044 "offlined", vcpu
->logical_id
);
2045 } /* otherwise pretend successful re-onlining */
2047 unsigned char status
;
2049 res
= pread(fd
, &status
, 1, 0);
2051 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2052 } else if (res
== 0) {
2053 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2055 } else if (sys2vcpu
) {
2056 vcpu
->online
= (status
!= '0');
2057 vcpu
->can_offline
= true;
2058 } else if (vcpu
->online
!= (status
!= '0')) {
2059 status
= '0' + vcpu
->online
;
2060 if (pwrite(fd
, &status
, 1, 0) == -1) {
2061 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2064 } /* otherwise pretend successful re-(on|off)-lining */
2074 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2076 GuestLogicalProcessorList
*head
, **tail
;
2077 const char *cpu_dir
= "/sys/devices/system/cpu";
2079 g_autoptr(GDir
) cpu_gdir
= NULL
;
2080 Error
*local_err
= NULL
;
2084 cpu_gdir
= g_dir_open(cpu_dir
, 0, NULL
);
2086 if (cpu_gdir
== NULL
) {
2087 error_setg_errno(errp
, errno
, "failed to list entries: %s", cpu_dir
);
2091 while (local_err
== NULL
&& (line
= g_dir_read_name(cpu_gdir
)) != NULL
) {
2092 GuestLogicalProcessor
*vcpu
;
2094 if (sscanf(line
, "cpu%" PRId64
, &id
)) {
2095 g_autofree
char *path
= g_strdup_printf("/sys/devices/system/cpu/"
2096 "cpu%" PRId64
"/", id
);
2097 vcpu
= g_malloc0(sizeof *vcpu
);
2098 vcpu
->logical_id
= id
;
2099 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2100 transfer_vcpu(vcpu
, true, path
, &local_err
);
2101 QAPI_LIST_APPEND(tail
, vcpu
);
2105 if (local_err
== NULL
) {
2106 /* there's no guest with zero VCPUs */
2107 g_assert(head
!= NULL
);
2111 qapi_free_GuestLogicalProcessorList(head
);
2112 error_propagate(errp
, local_err
);
2116 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2119 Error
*local_err
= NULL
;
2122 while (vcpus
!= NULL
) {
2123 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2124 vcpus
->value
->logical_id
);
2126 transfer_vcpu(vcpus
->value
, false, path
, &local_err
);
2128 if (local_err
!= NULL
) {
2132 vcpus
= vcpus
->next
;
2135 if (local_err
!= NULL
) {
2136 if (processed
== 0) {
2137 error_propagate(errp
, local_err
);
2139 error_free(local_err
);
2145 #endif /* __linux__ */
2147 #if defined(__linux__) || defined(__FreeBSD__)
2148 void qmp_guest_set_user_password(const char *username
,
2149 const char *password
,
2153 Error
*local_err
= NULL
;
2154 g_autofree
char *rawpasswddata
= NULL
;
2155 size_t rawpasswdlen
;
2157 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2158 if (!rawpasswddata
) {
2161 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2162 rawpasswddata
[rawpasswdlen
] = '\0';
2164 if (strchr(rawpasswddata
, '\n')) {
2165 error_setg(errp
, "forbidden characters in raw password");
2169 if (strchr(username
, '\n') ||
2170 strchr(username
, ':')) {
2171 error_setg(errp
, "forbidden characters in username");
2176 g_autofree
char *chpasswddata
= g_strdup(rawpasswddata
);
2177 const char *crypt_flag
= crypted
? "-H" : "-h";
2178 const char *argv
[] = {"pw", "usermod", "-n", username
,
2179 crypt_flag
, "0", NULL
};
2181 g_autofree
char *chpasswddata
= g_strdup_printf("%s:%s\n", username
,
2183 const char *crypt_flag
= crypted
? "-e" : NULL
;
2184 const char *argv
[] = {"chpasswd", crypt_flag
, NULL
};
2187 ga_run_command(argv
, chpasswddata
, "set user password", &local_err
);
2189 error_propagate(errp
, local_err
);
2193 #else /* __linux__ || __FreeBSD__ */
2194 void qmp_guest_set_user_password(const char *username
,
2195 const char *password
,
2199 error_setg(errp
, QERR_UNSUPPORTED
);
2201 #endif /* __linux__ || __FreeBSD__ */
2204 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2205 int size
, Error
**errp
)
2211 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2213 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2217 res
= pread(fd
, buf
, size
, 0);
2219 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2220 } else if (res
== 0) {
2221 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2226 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2227 const char *buf
, int size
, Error
**errp
)
2232 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2234 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2238 if (pwrite(fd
, buf
, size
, 0) == -1) {
2239 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2245 /* Transfer online/offline status between @mem_blk and the guest system.
2247 * On input either @errp or *@errp must be NULL.
2249 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2250 * - R: mem_blk->phys_index
2251 * - W: mem_blk->online
2252 * - W: mem_blk->can_offline
2254 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2255 * - R: mem_blk->phys_index
2256 * - R: mem_blk->online
2257 *- R: mem_blk->can_offline
2258 * Written members remain unmodified on error.
2260 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2261 GuestMemoryBlockResponse
*result
,
2267 Error
*local_err
= NULL
;
2273 error_setg(errp
, "Internal error, 'result' should not be NULL");
2277 dp
= opendir("/sys/devices/system/memory/");
2278 /* if there is no 'memory' directory in sysfs,
2279 * we think this VM does not support online/offline memory block,
2280 * any other solution?
2283 if (errno
== ENOENT
) {
2285 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2292 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2293 mem_blk
->phys_index
);
2294 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2297 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2299 if (errno
== ENOENT
) {
2300 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2303 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2311 status
= g_malloc0(10);
2312 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2314 /* treat with sysfs file that not exist in old kernel */
2315 if (errno
== ENOENT
) {
2316 error_free(local_err
);
2318 mem_blk
->online
= true;
2319 mem_blk
->can_offline
= false;
2320 } else if (!mem_blk
->online
) {
2322 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2326 error_propagate(errp
, local_err
);
2328 error_free(local_err
);
2330 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2337 char removable
= '0';
2339 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2341 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2343 /* if no 'removable' file, it doesn't support offline mem blk */
2344 if (errno
== ENOENT
) {
2345 error_free(local_err
);
2346 mem_blk
->can_offline
= false;
2348 error_propagate(errp
, local_err
);
2351 mem_blk
->can_offline
= (removable
!= '0');
2354 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2355 const char *new_state
= mem_blk
->online
? "online" : "offline";
2357 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2360 error_free(local_err
);
2362 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2366 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2367 result
->has_error_code
= false;
2368 } /* otherwise pretend successful re-(on|off)-lining */
2379 result
->has_error_code
= true;
2380 result
->error_code
= errno
;
2384 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2386 GuestMemoryBlockList
*head
, **tail
;
2387 Error
*local_err
= NULL
;
2394 dp
= opendir("/sys/devices/system/memory/");
2396 /* it's ok if this happens to be a system that doesn't expose
2397 * memory blocks via sysfs, but otherwise we should report
2400 if (errno
!= ENOENT
) {
2401 error_setg_errno(errp
, errno
, "Can't open directory"
2402 "\"/sys/devices/system/memory/\"");
2407 /* Note: the phys_index of memory block may be discontinuous,
2408 * this is because a memblk is the unit of the Sparse Memory design, which
2409 * allows discontinuous memory ranges (ex. NUMA), so here we should
2410 * traverse the memory block directory.
2412 while ((de
= readdir(dp
)) != NULL
) {
2413 GuestMemoryBlock
*mem_blk
;
2415 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2416 !(de
->d_type
& DT_DIR
)) {
2420 mem_blk
= g_malloc0(sizeof *mem_blk
);
2421 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2422 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2423 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2424 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2429 QAPI_LIST_APPEND(tail
, mem_blk
);
2433 if (local_err
== NULL
) {
2434 /* there's no guest with zero memory blocks */
2436 error_setg(errp
, "guest reported zero memory blocks!");
2441 qapi_free_GuestMemoryBlockList(head
);
2442 error_propagate(errp
, local_err
);
2446 GuestMemoryBlockResponseList
*
2447 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2449 GuestMemoryBlockResponseList
*head
, **tail
;
2450 Error
*local_err
= NULL
;
2455 while (mem_blks
!= NULL
) {
2456 GuestMemoryBlockResponse
*result
;
2457 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2459 result
= g_malloc0(sizeof(*result
));
2460 result
->phys_index
= current_mem_blk
->phys_index
;
2461 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2462 if (local_err
) { /* should never happen */
2466 QAPI_LIST_APPEND(tail
, result
);
2467 mem_blks
= mem_blks
->next
;
2472 qapi_free_GuestMemoryBlockResponseList(head
);
2473 error_propagate(errp
, local_err
);
2477 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2479 Error
*local_err
= NULL
;
2483 GuestMemoryBlockInfo
*info
;
2485 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2486 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2488 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2494 buf
= g_malloc0(20);
2495 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2499 error_propagate(errp
, local_err
);
2503 info
= g_new0(GuestMemoryBlockInfo
, 1);
2504 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2511 #define MAX_NAME_LEN 128
2512 static GuestDiskStatsInfoList
*guest_get_diskstats(Error
**errp
)
2515 GuestDiskStatsInfoList
*head
= NULL
, **tail
= &head
;
2516 const char *diskstats
= "/proc/diskstats";
2521 fp
= fopen(diskstats
, "r");
2523 error_setg_errno(errp
, errno
, "open(\"%s\")", diskstats
);
2527 while (getline(&line
, &n
, fp
) != -1) {
2528 g_autofree GuestDiskStatsInfo
*diskstatinfo
= NULL
;
2529 g_autofree GuestDiskStats
*diskstat
= NULL
;
2530 char dev_name
[MAX_NAME_LEN
];
2531 unsigned int ios_pgr
, tot_ticks
, rq_ticks
, wr_ticks
, dc_ticks
, fl_ticks
;
2532 unsigned long rd_ios
, rd_merges_or_rd_sec
, rd_ticks_or_wr_sec
, wr_ios
;
2533 unsigned long wr_merges
, rd_sec_or_wr_ios
, wr_sec
;
2534 unsigned long dc_ios
, dc_merges
, dc_sec
, fl_ios
;
2535 unsigned int major
, minor
;
2538 i
= sscanf(line
, "%u %u %s %lu %lu %lu"
2539 "%lu %lu %lu %lu %u %u %u %u"
2540 "%lu %lu %lu %u %lu %u",
2541 &major
, &minor
, dev_name
,
2542 &rd_ios
, &rd_merges_or_rd_sec
, &rd_sec_or_wr_ios
,
2543 &rd_ticks_or_wr_sec
, &wr_ios
, &wr_merges
, &wr_sec
,
2544 &wr_ticks
, &ios_pgr
, &tot_ticks
, &rq_ticks
,
2545 &dc_ios
, &dc_merges
, &dc_sec
, &dc_ticks
,
2546 &fl_ios
, &fl_ticks
);
2552 diskstatinfo
= g_new0(GuestDiskStatsInfo
, 1);
2553 diskstatinfo
->name
= g_strdup(dev_name
);
2554 diskstatinfo
->major
= major
;
2555 diskstatinfo
->minor
= minor
;
2557 diskstat
= g_new0(GuestDiskStats
, 1);
2559 diskstat
->has_read_ios
= true;
2560 diskstat
->read_ios
= rd_ios
;
2561 diskstat
->has_read_sectors
= true;
2562 diskstat
->read_sectors
= rd_merges_or_rd_sec
;
2563 diskstat
->has_write_ios
= true;
2564 diskstat
->write_ios
= rd_sec_or_wr_ios
;
2565 diskstat
->has_write_sectors
= true;
2566 diskstat
->write_sectors
= rd_ticks_or_wr_sec
;
2569 diskstat
->has_read_ios
= true;
2570 diskstat
->read_ios
= rd_ios
;
2571 diskstat
->has_read_sectors
= true;
2572 diskstat
->read_sectors
= rd_sec_or_wr_ios
;
2573 diskstat
->has_read_merges
= true;
2574 diskstat
->read_merges
= rd_merges_or_rd_sec
;
2575 diskstat
->has_read_ticks
= true;
2576 diskstat
->read_ticks
= rd_ticks_or_wr_sec
;
2577 diskstat
->has_write_ios
= true;
2578 diskstat
->write_ios
= wr_ios
;
2579 diskstat
->has_write_sectors
= true;
2580 diskstat
->write_sectors
= wr_sec
;
2581 diskstat
->has_write_merges
= true;
2582 diskstat
->write_merges
= wr_merges
;
2583 diskstat
->has_write_ticks
= true;
2584 diskstat
->write_ticks
= wr_ticks
;
2585 diskstat
->has_ios_pgr
= true;
2586 diskstat
->ios_pgr
= ios_pgr
;
2587 diskstat
->has_total_ticks
= true;
2588 diskstat
->total_ticks
= tot_ticks
;
2589 diskstat
->has_weight_ticks
= true;
2590 diskstat
->weight_ticks
= rq_ticks
;
2593 diskstat
->has_discard_ios
= true;
2594 diskstat
->discard_ios
= dc_ios
;
2595 diskstat
->has_discard_merges
= true;
2596 diskstat
->discard_merges
= dc_merges
;
2597 diskstat
->has_discard_sectors
= true;
2598 diskstat
->discard_sectors
= dc_sec
;
2599 diskstat
->has_discard_ticks
= true;
2600 diskstat
->discard_ticks
= dc_ticks
;
2603 diskstat
->has_flush_ios
= true;
2604 diskstat
->flush_ios
= fl_ios
;
2605 diskstat
->has_flush_ticks
= true;
2606 diskstat
->flush_ticks
= fl_ticks
;
2609 diskstatinfo
->stats
= g_steal_pointer(&diskstat
);
2610 QAPI_LIST_APPEND(tail
, diskstatinfo
);
2611 diskstatinfo
= NULL
;
2617 g_debug("disk stats reporting available only for Linux");
2622 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
2624 return guest_get_diskstats(errp
);
2627 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
2629 GuestCpuStatsList
*head
= NULL
, **tail
= &head
;
2630 const char *cpustats
= "/proc/stat";
2631 int clk_tck
= sysconf(_SC_CLK_TCK
);
2636 fp
= fopen(cpustats
, "r");
2638 error_setg_errno(errp
, errno
, "open(\"%s\")", cpustats
);
2642 while (getline(&line
, &n
, fp
) != -1) {
2643 GuestCpuStats
*cpustat
= NULL
;
2644 GuestLinuxCpuStats
*linuxcpustat
;
2646 unsigned long user
, system
, idle
, iowait
, irq
, softirq
, steal
, guest
;
2647 unsigned long nice
, guest_nice
;
2650 i
= sscanf(line
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2651 name
, &user
, &nice
, &system
, &idle
, &iowait
, &irq
, &softirq
,
2652 &steal
, &guest
, &guest_nice
);
2654 /* drop "cpu 1 2 3 ...", get "cpuX 1 2 3 ..." only */
2655 if ((i
== EOF
) || strncmp(name
, "cpu", 3) || (name
[3] == '\0')) {
2660 slog("Parsing cpu stat from %s failed, see \"man proc\"", cpustats
);
2664 cpustat
= g_new0(GuestCpuStats
, 1);
2665 cpustat
->type
= GUEST_CPU_STATS_TYPE_LINUX
;
2667 linuxcpustat
= &cpustat
->u
.q_linux
;
2668 linuxcpustat
->cpu
= atoi(&name
[3]);
2669 linuxcpustat
->user
= user
* 1000 / clk_tck
;
2670 linuxcpustat
->nice
= nice
* 1000 / clk_tck
;
2671 linuxcpustat
->system
= system
* 1000 / clk_tck
;
2672 linuxcpustat
->idle
= idle
* 1000 / clk_tck
;
2675 linuxcpustat
->has_iowait
= true;
2676 linuxcpustat
->iowait
= iowait
* 1000 / clk_tck
;
2680 linuxcpustat
->has_irq
= true;
2681 linuxcpustat
->irq
= irq
* 1000 / clk_tck
;
2682 linuxcpustat
->has_softirq
= true;
2683 linuxcpustat
->softirq
= softirq
* 1000 / clk_tck
;
2687 linuxcpustat
->has_steal
= true;
2688 linuxcpustat
->steal
= steal
* 1000 / clk_tck
;
2692 linuxcpustat
->has_guest
= true;
2693 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2697 linuxcpustat
->has_guest
= true;
2698 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2699 linuxcpustat
->has_guestnice
= true;
2700 linuxcpustat
->guestnice
= guest_nice
* 1000 / clk_tck
;
2703 QAPI_LIST_APPEND(tail
, cpustat
);
2711 #else /* defined(__linux__) */
2713 void qmp_guest_suspend_disk(Error
**errp
)
2715 error_setg(errp
, QERR_UNSUPPORTED
);
2718 void qmp_guest_suspend_ram(Error
**errp
)
2720 error_setg(errp
, QERR_UNSUPPORTED
);
2723 void qmp_guest_suspend_hybrid(Error
**errp
)
2725 error_setg(errp
, QERR_UNSUPPORTED
);
2728 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2730 error_setg(errp
, QERR_UNSUPPORTED
);
2734 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2736 error_setg(errp
, QERR_UNSUPPORTED
);
2740 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2742 error_setg(errp
, QERR_UNSUPPORTED
);
2746 GuestMemoryBlockResponseList
*
2747 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2749 error_setg(errp
, QERR_UNSUPPORTED
);
2753 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2755 error_setg(errp
, QERR_UNSUPPORTED
);
2761 #ifdef HAVE_GETIFADDRS
2762 static GuestNetworkInterface
*
2763 guest_find_interface(GuestNetworkInterfaceList
*head
,
2766 for (; head
; head
= head
->next
) {
2767 if (strcmp(head
->value
->name
, name
) == 0) {
2775 static int guest_get_network_stats(const char *name
,
2776 GuestNetworkInterfaceStat
*stats
)
2780 char const *devinfo
= "/proc/net/dev";
2782 char *line
= NULL
, *colon
;
2784 fp
= fopen(devinfo
, "r");
2786 g_debug("failed to open network stats %s: %s", devinfo
,
2790 name_len
= strlen(name
);
2791 while (getline(&line
, &n
, fp
) != -1) {
2794 long long rx_packets
;
2796 long long rx_dropped
;
2798 long long tx_packets
;
2800 long long tx_dropped
;
2802 trim_line
= g_strchug(line
);
2803 if (trim_line
[0] == '\0') {
2806 colon
= strchr(trim_line
, ':');
2810 if (colon
- name_len
== trim_line
&&
2811 strncmp(trim_line
, name
, name_len
) == 0) {
2812 if (sscanf(colon
+ 1,
2813 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2814 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
2815 &dummy
, &dummy
, &dummy
, &dummy
,
2816 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
2817 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
2820 stats
->rx_bytes
= rx_bytes
;
2821 stats
->rx_packets
= rx_packets
;
2822 stats
->rx_errs
= rx_errs
;
2823 stats
->rx_dropped
= rx_dropped
;
2824 stats
->tx_bytes
= tx_bytes
;
2825 stats
->tx_packets
= tx_packets
;
2826 stats
->tx_errs
= tx_errs
;
2827 stats
->tx_dropped
= tx_dropped
;
2835 g_debug("/proc/net/dev: Interface '%s' not found", name
);
2836 #else /* !CONFIG_LINUX */
2837 g_debug("Network stats reporting available only for Linux");
2838 #endif /* !CONFIG_LINUX */
2844 * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
2845 * buffer with ETHER_ADDR_LEN length at least.
2847 * Returns false in case of an error, otherwise true. "obtained" argument
2848 * is true if a MAC address was obtained successful, otherwise false.
2850 bool guest_get_hw_addr(struct ifaddrs
*ifa
, unsigned char *buf
,
2851 bool *obtained
, Error
**errp
)
2858 /* we haven't obtained HW address yet */
2859 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
2861 error_setg_errno(errp
, errno
, "failed to create socket");
2865 memset(&ifr
, 0, sizeof(ifr
));
2866 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, ifa
->ifa_name
);
2867 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
2869 * We can't get the hw addr of this interface, but that's not a
2872 if (errno
== EADDRNOTAVAIL
) {
2873 /* The interface doesn't have a hw addr (e.g. loopback). */
2874 g_debug("failed to get MAC address of %s: %s",
2875 ifa
->ifa_name
, strerror(errno
));
2877 g_warning("failed to get MAC address of %s: %s",
2878 ifa
->ifa_name
, strerror(errno
));
2881 #ifdef CONFIG_SOLARIS
2882 memcpy(buf
, &ifr
.ifr_addr
.sa_data
, ETHER_ADDR_LEN
);
2884 memcpy(buf
, &ifr
.ifr_hwaddr
.sa_data
, ETHER_ADDR_LEN
);
2891 #endif /* CONFIG_BSD */
2894 * Build information about guest interfaces
2896 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2898 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
2899 struct ifaddrs
*ifap
, *ifa
;
2901 if (getifaddrs(&ifap
) < 0) {
2902 error_setg_errno(errp
, errno
, "getifaddrs failed");
2906 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
2907 GuestNetworkInterface
*info
;
2908 GuestIpAddressList
**address_tail
;
2909 GuestIpAddress
*address_item
= NULL
;
2910 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
2911 char addr4
[INET_ADDRSTRLEN
];
2912 char addr6
[INET6_ADDRSTRLEN
];
2913 unsigned char mac_addr
[ETHER_ADDR_LEN
];
2917 g_debug("Processing %s interface", ifa
->ifa_name
);
2919 info
= guest_find_interface(head
, ifa
->ifa_name
);
2922 info
= g_malloc0(sizeof(*info
));
2923 info
->name
= g_strdup(ifa
->ifa_name
);
2925 QAPI_LIST_APPEND(tail
, info
);
2928 if (!info
->hardware_address
) {
2929 if (!guest_get_hw_addr(ifa
, mac_addr
, &obtained
, errp
)) {
2933 info
->hardware_address
=
2934 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2935 (int) mac_addr
[0], (int) mac_addr
[1],
2936 (int) mac_addr
[2], (int) mac_addr
[3],
2937 (int) mac_addr
[4], (int) mac_addr
[5]);
2941 if (ifa
->ifa_addr
&&
2942 ifa
->ifa_addr
->sa_family
== AF_INET
) {
2943 /* interface with IPv4 address */
2944 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
2945 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
2946 error_setg_errno(errp
, errno
, "inet_ntop failed");
2950 address_item
= g_malloc0(sizeof(*address_item
));
2951 address_item
->ip_address
= g_strdup(addr4
);
2952 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
2954 if (ifa
->ifa_netmask
) {
2955 /* Count the number of set bits in netmask.
2956 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2957 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
2958 address_item
->prefix
= ctpop32(((uint32_t *) p
)[0]);
2960 } else if (ifa
->ifa_addr
&&
2961 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
2962 /* interface with IPv6 address */
2963 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
2964 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
2965 error_setg_errno(errp
, errno
, "inet_ntop failed");
2969 address_item
= g_malloc0(sizeof(*address_item
));
2970 address_item
->ip_address
= g_strdup(addr6
);
2971 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
2973 if (ifa
->ifa_netmask
) {
2974 /* Count the number of set bits in netmask.
2975 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2976 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
2977 address_item
->prefix
=
2978 ctpop32(((uint32_t *) p
)[0]) +
2979 ctpop32(((uint32_t *) p
)[1]) +
2980 ctpop32(((uint32_t *) p
)[2]) +
2981 ctpop32(((uint32_t *) p
)[3]);
2985 if (!address_item
) {
2989 address_tail
= &info
->ip_addresses
;
2990 while (*address_tail
) {
2991 address_tail
= &(*address_tail
)->next
;
2993 QAPI_LIST_APPEND(address_tail
, address_item
);
2995 info
->has_ip_addresses
= true;
2997 if (!info
->statistics
) {
2998 interface_stat
= g_malloc0(sizeof(*interface_stat
));
2999 if (guest_get_network_stats(info
->name
, interface_stat
) == -1) {
3000 g_free(interface_stat
);
3002 info
->statistics
= interface_stat
;
3012 qapi_free_GuestNetworkInterfaceList(head
);
3018 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
3020 error_setg(errp
, QERR_UNSUPPORTED
);
3024 #endif /* HAVE_GETIFADDRS */
3026 #if !defined(CONFIG_FSFREEZE)
3028 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
3030 error_setg(errp
, QERR_UNSUPPORTED
);
3034 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
3036 error_setg(errp
, QERR_UNSUPPORTED
);
3041 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
3043 error_setg(errp
, QERR_UNSUPPORTED
);
3048 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
3049 strList
*mountpoints
,
3052 error_setg(errp
, QERR_UNSUPPORTED
);
3057 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
3059 error_setg(errp
, QERR_UNSUPPORTED
);
3064 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
3066 error_setg(errp
, QERR_UNSUPPORTED
);
3070 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
3072 error_setg(errp
, QERR_UNSUPPORTED
);
3076 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
3078 error_setg(errp
, QERR_UNSUPPORTED
);
3082 #endif /* CONFIG_FSFREEZE */
3084 #if !defined(CONFIG_FSTRIM)
3085 GuestFilesystemTrimResponse
*
3086 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
3088 error_setg(errp
, QERR_UNSUPPORTED
);
3093 /* add unsupported commands to the list of blocked RPCs */
3094 GList
*ga_command_init_blockedrpcs(GList
*blockedrpcs
)
3096 #if !defined(__linux__)
3098 const char *list
[] = {
3099 "guest-suspend-disk", "guest-suspend-ram",
3100 "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
3101 "guest-get-memory-blocks", "guest-set-memory-blocks",
3102 "guest-get-memory-block-size", "guest-get-memory-block-info",
3104 char **p
= (char **)list
;
3107 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3112 #if !defined(HAVE_GETIFADDRS)
3113 blockedrpcs
= g_list_append(blockedrpcs
,
3114 g_strdup("guest-network-get-interfaces"));
3117 #if !defined(CONFIG_FSFREEZE)
3119 const char *list
[] = {
3120 "guest-get-fsinfo", "guest-fsfreeze-status",
3121 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3122 "guest-fsfreeze-thaw", "guest-get-fsinfo",
3123 "guest-get-disks", NULL
};
3124 char **p
= (char **)list
;
3127 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3132 #if !defined(CONFIG_FSTRIM)
3133 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-fstrim"));
3136 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-get-devices"));
3141 /* register init/cleanup routines for stateful command groups */
3142 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
3144 #if defined(CONFIG_FSFREEZE)
3145 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
3151 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3153 static double ga_get_login_time(struct utmpx
*user_info
)
3155 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
3156 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
3157 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
3158 return seconds
+ useconds
;
3161 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3163 GHashTable
*cache
= NULL
;
3164 GuestUserList
*head
= NULL
, **tail
= &head
;
3165 struct utmpx
*user_info
= NULL
;
3166 gpointer value
= NULL
;
3167 GuestUser
*user
= NULL
;
3168 double login_time
= 0;
3170 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
3174 user_info
= getutxent();
3175 if (user_info
== NULL
) {
3177 } else if (user_info
->ut_type
!= USER_PROCESS
) {
3179 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
3180 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
3181 user
= (GuestUser
*)value
;
3182 login_time
= ga_get_login_time(user_info
);
3183 /* We're ensuring the earliest login time to be sent */
3184 if (login_time
< user
->login_time
) {
3185 user
->login_time
= login_time
;
3190 user
= g_new0(GuestUser
, 1);
3191 user
->user
= g_strdup(user_info
->ut_user
);
3192 user
->login_time
= ga_get_login_time(user_info
);
3194 g_hash_table_insert(cache
, user
->user
, user
);
3196 QAPI_LIST_APPEND(tail
, user
);
3199 g_hash_table_destroy(cache
);
3205 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3207 error_setg(errp
, QERR_UNSUPPORTED
);
3213 /* Replace escaped special characters with their real values. The replacement
3214 * is done in place -- returned value is in the original string.
3216 static void ga_osrelease_replace_special(gchar
*value
)
3218 gchar
*p
, *p2
, quote
;
3220 /* Trim the string at first space or semicolon if it is not enclosed in
3221 * single or double quotes. */
3222 if ((value
[0] != '"') || (value
[0] == '\'')) {
3223 p
= strchr(value
, ' ');
3227 p
= strchr(value
, ';');
3248 /* Keep literal backslash followed by whatever is there */
3252 } else if (*p
== quote
) {
3260 static GKeyFile
*ga_parse_osrelease(const char *fname
)
3262 gchar
*content
= NULL
;
3263 gchar
*content2
= NULL
;
3265 GKeyFile
*keys
= g_key_file_new();
3266 const char *group
= "[os-release]\n";
3268 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
3269 slog("failed to read '%s', error: %s", fname
, err
->message
);
3273 if (!g_utf8_validate(content
, -1, NULL
)) {
3274 slog("file is not utf-8 encoded: %s", fname
);
3277 content2
= g_strdup_printf("%s%s", group
, content
);
3279 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
3281 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
3293 g_key_file_free(keys
);
3297 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
3299 GuestOSInfo
*info
= NULL
;
3300 struct utsname kinfo
;
3301 GKeyFile
*osrelease
= NULL
;
3302 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
3304 info
= g_new0(GuestOSInfo
, 1);
3306 if (uname(&kinfo
) != 0) {
3307 error_setg_errno(errp
, errno
, "uname failed");
3309 info
->kernel_version
= g_strdup(kinfo
.version
);
3310 info
->kernel_release
= g_strdup(kinfo
.release
);
3311 info
->machine
= g_strdup(kinfo
.machine
);
3314 if (qga_os_release
!= NULL
) {
3315 osrelease
= ga_parse_osrelease(qga_os_release
);
3317 osrelease
= ga_parse_osrelease("/etc/os-release");
3318 if (osrelease
== NULL
) {
3319 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
3323 if (osrelease
!= NULL
) {
3326 #define GET_FIELD(field, osfield) do { \
3327 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3328 if (value != NULL) { \
3329 ga_osrelease_replace_special(value); \
3330 info->field = value; \
3333 GET_FIELD(id
, "ID");
3334 GET_FIELD(name
, "NAME");
3335 GET_FIELD(pretty_name
, "PRETTY_NAME");
3336 GET_FIELD(version
, "VERSION");
3337 GET_FIELD(version_id
, "VERSION_ID");
3338 GET_FIELD(variant
, "VARIANT");
3339 GET_FIELD(variant_id
, "VARIANT_ID");
3342 g_key_file_free(osrelease
);
3348 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
3350 error_setg(errp
, QERR_UNSUPPORTED
);
3355 #ifndef HOST_NAME_MAX
3356 # ifdef _POSIX_HOST_NAME_MAX
3357 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
3359 # define HOST_NAME_MAX 255
3363 char *qga_get_host_name(Error
**errp
)
3366 g_autofree
char *hostname
= NULL
;
3368 #ifdef _SC_HOST_NAME_MAX
3369 len
= sysconf(_SC_HOST_NAME_MAX
);
3370 #endif /* _SC_HOST_NAME_MAX */
3373 len
= HOST_NAME_MAX
;
3376 /* Unfortunately, gethostname() below does not guarantee a
3377 * NULL terminated string. Therefore, allocate one byte more
3379 hostname
= g_new0(char, len
+ 1);
3381 if (gethostname(hostname
, len
) < 0) {
3382 error_setg_errno(errp
, errno
,
3383 "cannot get hostname");
3387 return g_steal_pointer(&hostname
);