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 "guest-agent-core.h"
20 #include "qga-qapi-commands.h"
21 #include "qapi/error.h"
22 #include "qapi/qmp/qerror.h"
23 #include "qemu/queue.h"
24 #include "qemu/host-utils.h"
25 #include "qemu/sockets.h"
26 #include "qemu/base64.h"
27 #include "qemu/cutils.h"
28 #include "commands-common.h"
29 #include "block/nvme.h"
36 #if defined(__linux__)
39 #include <sys/statvfs.h>
40 #include <linux/nvme_ioctl.h>
47 #define CONFIG_FSFREEZE
56 * The code under HAVE_GETIFADDRS condition can't be compiled in FreeBSD.
57 * Fix it in one of the following patches.
59 #undef HAVE_GETIFADDRS
62 #ifdef HAVE_GETIFADDRS
63 #include <arpa/inet.h>
64 #include <sys/socket.h>
66 #include <sys/types.h>
69 #include <sys/sockio.h>
73 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
80 rpid
= waitpid(pid
, status
, 0);
81 } while (rpid
== -1 && errno
== EINTR
);
84 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
89 g_assert(rpid
== pid
);
92 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
94 const char *shutdown_flag
;
95 Error
*local_err
= NULL
;
100 const char *powerdown_flag
= "-i5";
101 const char *halt_flag
= "-i0";
102 const char *reboot_flag
= "-i6";
104 const char *powerdown_flag
= "-P";
105 const char *halt_flag
= "-H";
106 const char *reboot_flag
= "-r";
109 slog("guest-shutdown called, mode: %s", mode
);
110 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
111 shutdown_flag
= powerdown_flag
;
112 } else if (strcmp(mode
, "halt") == 0) {
113 shutdown_flag
= halt_flag
;
114 } else if (strcmp(mode
, "reboot") == 0) {
115 shutdown_flag
= reboot_flag
;
118 "mode is invalid (valid values are: halt|powerdown|reboot");
124 /* child, start the shutdown */
126 reopen_fd_to_null(0);
127 reopen_fd_to_null(1);
128 reopen_fd_to_null(2);
130 #ifdef CONFIG_SOLARIS
131 execl("/sbin/shutdown", "shutdown", shutdown_flag
, "-g0", "-y",
132 "hypervisor initiated shutdown", (char *)NULL
);
134 execl("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
135 "hypervisor initiated shutdown", (char *)NULL
);
138 } else if (pid
< 0) {
139 error_setg_errno(errp
, errno
, "failed to create child process");
143 ga_wait_child(pid
, &status
, &local_err
);
145 error_propagate(errp
, local_err
);
149 if (!WIFEXITED(status
)) {
150 error_setg(errp
, "child process has terminated abnormally");
154 if (WEXITSTATUS(status
)) {
155 error_setg(errp
, "child process has failed to shutdown");
162 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
167 Error
*local_err
= NULL
;
169 static const char hwclock_path
[] = "/sbin/hwclock";
170 static int hwclock_available
= -1;
172 if (hwclock_available
< 0) {
173 hwclock_available
= (access(hwclock_path
, X_OK
) == 0);
176 if (!hwclock_available
) {
177 error_setg(errp
, QERR_UNSUPPORTED
);
181 /* If user has passed a time, validate and set it. */
185 /* year-2038 will overflow in case time_t is 32bit */
186 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
187 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
191 tv
.tv_sec
= time_ns
/ 1000000000;
192 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
193 g_date_set_time_t(&date
, tv
.tv_sec
);
194 if (date
.year
< 1970 || date
.year
>= 2070) {
195 error_setg_errno(errp
, errno
, "Invalid time");
199 ret
= settimeofday(&tv
, NULL
);
201 error_setg_errno(errp
, errno
, "Failed to set time to guest");
206 /* Now, if user has passed a time to set and the system time is set, we
207 * just need to synchronize the hardware clock. However, if no time was
208 * passed, user is requesting the opposite: set the system time from the
209 * hardware clock (RTC). */
213 reopen_fd_to_null(0);
214 reopen_fd_to_null(1);
215 reopen_fd_to_null(2);
217 /* Use '/sbin/hwclock -w' to set RTC from the system time,
218 * or '/sbin/hwclock -s' to set the system time from RTC. */
219 execl(hwclock_path
, "hwclock", has_time
? "-w" : "-s", NULL
);
221 } else if (pid
< 0) {
222 error_setg_errno(errp
, errno
, "failed to create child process");
226 ga_wait_child(pid
, &status
, &local_err
);
228 error_propagate(errp
, local_err
);
232 if (!WIFEXITED(status
)) {
233 error_setg(errp
, "child process has terminated abnormally");
237 if (WEXITSTATUS(status
)) {
238 error_setg(errp
, "hwclock failed to set hardware clock to system time");
249 struct GuestFileHandle
{
253 QTAILQ_ENTRY(GuestFileHandle
) next
;
257 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
258 } guest_file_state
= {
259 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
262 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
264 GuestFileHandle
*gfh
;
267 handle
= ga_get_fd_handle(ga_state
, errp
);
272 gfh
= g_new0(GuestFileHandle
, 1);
275 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
280 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
282 GuestFileHandle
*gfh
;
284 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
291 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
295 typedef const char * const ccpc
;
301 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
302 static const struct {
305 } guest_file_open_modes
[] = {
306 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
307 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
308 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
309 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
310 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
311 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
312 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
313 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
314 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
315 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
316 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
317 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
321 find_open_flag(const char *mode_str
, Error
**errp
)
325 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
328 form
= guest_file_open_modes
[mode
].forms
;
329 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
337 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
338 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
341 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
344 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
345 S_IRGRP | S_IWGRP | \
349 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
355 oflag
= find_open_flag(mode
, errp
);
360 /* If the caller wants / allows creation of a new file, we implement it
361 * with a two step process: open() + (open() / fchmod()).
363 * First we insist on creating the file exclusively as a new file. If
364 * that succeeds, we're free to set any file-mode bits on it. (The
365 * motivation is that we want to set those file-mode bits independently
366 * of the current umask.)
368 * If the exclusive creation fails because the file already exists
369 * (EEXIST is not possible for any other reason), we just attempt to
370 * open the file, but in this case we won't be allowed to change the
371 * file-mode bits on the preexistent file.
373 * The pathname should never disappear between the two open()s in
374 * practice. If it happens, then someone very likely tried to race us.
375 * In this case just go ahead and report the ENOENT from the second
376 * open() to the caller.
378 * If the caller wants to open a preexistent file, then the first
379 * open() is decisive and its third argument is ignored, and the second
380 * open() and the fchmod() are never called.
382 fd
= qga_open_cloexec(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
383 if (fd
== -1 && errno
== EEXIST
) {
384 oflag
&= ~(unsigned)O_CREAT
;
385 fd
= qga_open_cloexec(path
, oflag
, 0);
388 error_setg_errno(errp
, errno
,
389 "failed to open file '%s' (mode: '%s')",
394 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
395 error_setg_errno(errp
, errno
, "failed to set permission "
396 "0%03o on new file '%s' (mode: '%s')",
397 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
401 f
= fdopen(fd
, mode
);
403 error_setg_errno(errp
, errno
, "failed to associate stdio stream with "
404 "file descriptor %d, file '%s' (mode: '%s')",
409 if (f
== NULL
&& fd
!= -1) {
411 if (oflag
& O_CREAT
) {
418 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
422 Error
*local_err
= NULL
;
428 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
429 fh
= safe_open_or_create(path
, mode
, &local_err
);
430 if (local_err
!= NULL
) {
431 error_propagate(errp
, local_err
);
435 /* set fd non-blocking to avoid common use cases (like reading from a
436 * named pipe) from hanging the agent
438 if (!g_unix_set_fd_nonblocking(fileno(fh
), true, NULL
)) {
440 error_setg_errno(errp
, errno
, "Failed to set FD nonblocking");
444 handle
= guest_file_handle_add(fh
, errp
);
450 slog("guest-file-open, handle: %" PRId64
, handle
);
454 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
456 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
459 slog("guest-file-close called, handle: %" PRId64
, handle
);
464 ret
= fclose(gfh
->fh
);
466 error_setg_errno(errp
, errno
, "failed to close handle");
470 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
474 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
475 int64_t count
, Error
**errp
)
477 GuestFileRead
*read_data
= NULL
;
482 /* explicitly flush when switching from writing to reading */
483 if (gfh
->state
== RW_STATE_WRITING
) {
484 int ret
= fflush(fh
);
486 error_setg_errno(errp
, errno
, "failed to flush file");
489 gfh
->state
= RW_STATE_NEW
;
492 buf
= g_malloc0(count
+ 1);
493 read_count
= fread(buf
, 1, count
, fh
);
495 error_setg_errno(errp
, errno
, "failed to read file");
498 read_data
= g_new0(GuestFileRead
, 1);
499 read_data
->count
= read_count
;
500 read_data
->eof
= feof(fh
);
502 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
504 gfh
->state
= RW_STATE_READING
;
512 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
513 bool has_count
, int64_t count
,
516 GuestFileWrite
*write_data
= NULL
;
520 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
529 if (gfh
->state
== RW_STATE_READING
) {
530 int ret
= fseek(fh
, 0, SEEK_CUR
);
532 error_setg_errno(errp
, errno
, "failed to seek file");
535 gfh
->state
= RW_STATE_NEW
;
538 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
545 } else if (count
< 0 || count
> buf_len
) {
546 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
552 write_count
= fwrite(buf
, 1, count
, fh
);
554 error_setg_errno(errp
, errno
, "failed to write to file");
555 slog("guest-file-write failed, handle: %" PRId64
, handle
);
557 write_data
= g_new0(GuestFileWrite
, 1);
558 write_data
->count
= write_count
;
559 write_data
->eof
= feof(fh
);
560 gfh
->state
= RW_STATE_WRITING
;
568 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
569 GuestFileWhence
*whence_code
,
572 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
573 GuestFileSeek
*seek_data
= NULL
;
583 /* We stupidly exposed 'whence':'int' in our qapi */
584 whence
= ga_parse_whence(whence_code
, &err
);
586 error_propagate(errp
, err
);
591 ret
= fseek(fh
, offset
, whence
);
593 error_setg_errno(errp
, errno
, "failed to seek file");
594 if (errno
== ESPIPE
) {
595 /* file is non-seekable, stdio shouldn't be buffering anyways */
596 gfh
->state
= RW_STATE_NEW
;
599 seek_data
= g_new0(GuestFileSeek
, 1);
600 seek_data
->position
= ftell(fh
);
601 seek_data
->eof
= feof(fh
);
602 gfh
->state
= RW_STATE_NEW
;
609 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
611 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
622 error_setg_errno(errp
, errno
, "failed to flush file");
624 gfh
->state
= RW_STATE_NEW
;
628 /* linux-specific implementations. avoid this if at all possible. */
629 #if defined(__linux__)
631 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
632 typedef struct FsMount
{
635 unsigned int devmajor
, devminor
;
636 QTAILQ_ENTRY(FsMount
) next
;
639 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
641 static void free_fs_mount_list(FsMountList
*mounts
)
643 FsMount
*mount
, *temp
;
649 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
650 QTAILQ_REMOVE(mounts
, mount
, next
);
651 g_free(mount
->dirname
);
652 g_free(mount
->devtype
);
657 static int dev_major_minor(const char *devpath
,
658 unsigned int *devmajor
, unsigned int *devminor
)
665 if (stat(devpath
, &st
) < 0) {
666 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
669 if (S_ISDIR(st
.st_mode
)) {
670 /* It is bind mount */
673 if (S_ISBLK(st
.st_mode
)) {
674 *devmajor
= major(st
.st_rdev
);
675 *devminor
= minor(st
.st_rdev
);
682 * Walk the mount table and build a list of local file systems
684 static bool build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
688 char const *mtab
= "/proc/self/mounts";
690 unsigned int devmajor
, devminor
;
692 fp
= setmntent(mtab
, "r");
694 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
698 while ((ment
= getmntent(fp
))) {
700 * An entry which device name doesn't start with a '/' is
701 * either a dummy file system or a network file system.
702 * Add special handling for smbfs and cifs as is done by
705 if ((ment
->mnt_fsname
[0] != '/') ||
706 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
707 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
710 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
711 /* Skip bind mounts */
715 mount
= g_new0(FsMount
, 1);
716 mount
->dirname
= g_strdup(ment
->mnt_dir
);
717 mount
->devtype
= g_strdup(ment
->mnt_type
);
718 mount
->devmajor
= devmajor
;
719 mount
->devminor
= devminor
;
721 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
728 static void decode_mntname(char *name
, int len
)
731 for (i
= 0; i
<= len
; i
++) {
732 if (name
[i
] != '\\') {
734 } else if (name
[i
+ 1] == '\\') {
737 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
738 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
739 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
740 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
741 (name
[i
+ 2] - '0') * 8 +
750 static bool build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
753 char const *mountinfo
= "/proc/self/mountinfo";
755 char *line
= NULL
, *dash
;
758 unsigned int devmajor
, devminor
;
759 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
761 fp
= fopen(mountinfo
, "r");
763 return build_fs_mount_list_from_mtab(mounts
, errp
);
766 while (getline(&line
, &n
, fp
) != -1) {
767 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
768 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
772 dash
= strstr(line
+ dir_e
, " - ");
776 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
777 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
784 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
785 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
787 /* btrfs reports major number = 0 */
788 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
789 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
794 mount
= g_new0(FsMount
, 1);
795 mount
->dirname
= g_strdup(line
+ dir_s
);
796 mount
->devtype
= g_strdup(dash
+ type_s
);
797 mount
->devmajor
= devmajor
;
798 mount
->devminor
= devminor
;
800 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
809 #if defined(CONFIG_FSFREEZE)
811 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
819 path
= g_strndup(syspath
, pathlen
);
820 dpath
= g_strdup_printf("%s/driver", path
);
821 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
824 driver
= g_path_get_basename(buf
);
831 static int compare_uint(const void *_a
, const void *_b
)
833 unsigned int a
= *(unsigned int *)_a
;
834 unsigned int b
= *(unsigned int *)_b
;
836 return a
< b
? -1 : a
> b
? 1 : 0;
839 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
840 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
841 unsigned int *hosts
, int hosts_max
, Error
**errp
)
845 struct dirent
*entry
;
848 path
= g_strndup(syspath
, host
- syspath
);
851 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
856 while (i
< hosts_max
) {
857 entry
= readdir(dir
);
861 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
863 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
868 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
876 * Store disk device info for devices on the PCI bus.
877 * Returns true if information has been stored, or false for failure.
879 static bool build_guest_fsinfo_for_pci_dev(char const *syspath
,
880 GuestDiskAddress
*disk
,
883 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
884 int i
, nhosts
= 0, pcilen
;
885 GuestPCIAddress
*pciaddr
= disk
->pci_controller
;
886 bool has_ata
= false, has_host
= false, has_tgt
= false;
887 char *p
, *q
, *driver
= NULL
;
890 p
= strstr(syspath
, "/devices/pci");
891 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
892 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
893 g_debug("only pci device is supported: sysfs path '%s'", syspath
);
899 driver
= get_pci_driver(syspath
, p
- syspath
, errp
);
900 if (driver
&& (g_str_equal(driver
, "ata_piix") ||
901 g_str_equal(driver
, "sym53c8xx") ||
902 g_str_equal(driver
, "virtio-pci") ||
903 g_str_equal(driver
, "ahci") ||
904 g_str_equal(driver
, "nvme"))) {
909 if (sscanf(p
, "/%x:%x:%x.%x%n",
910 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
915 g_debug("unsupported driver or sysfs path '%s'", syspath
);
919 p
= strstr(syspath
, "/target");
920 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
921 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
925 p
= strstr(syspath
, "/ata");
930 p
= strstr(syspath
, "/host");
933 if (p
&& sscanf(q
, "%u", &host
) == 1) {
935 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
936 ARRAY_SIZE(hosts
), errp
);
942 pciaddr
->domain
= pci
[0];
943 pciaddr
->bus
= pci
[1];
944 pciaddr
->slot
= pci
[2];
945 pciaddr
->function
= pci
[3];
947 if (strcmp(driver
, "ata_piix") == 0) {
948 /* a host per ide bus, target*:0:<unit>:0 */
949 if (!has_host
|| !has_tgt
) {
950 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
953 for (i
= 0; i
< nhosts
; i
++) {
954 if (host
== hosts
[i
]) {
955 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
962 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
965 } else if (strcmp(driver
, "sym53c8xx") == 0) {
966 /* scsi(LSI Logic): target*:0:<unit>:0 */
968 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
971 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
973 } else if (strcmp(driver
, "virtio-pci") == 0) {
975 /* virtio-scsi: target*:0:0:<unit> */
976 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
979 /* virtio-blk: 1 disk per 1 device */
980 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
982 } else if (strcmp(driver
, "ahci") == 0) {
983 /* ahci: 1 host per 1 unit */
984 if (!has_host
|| !has_tgt
) {
985 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
988 for (i
= 0; i
< nhosts
; i
++) {
989 if (host
== hosts
[i
]) {
991 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
996 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
999 } else if (strcmp(driver
, "nvme") == 0) {
1000 disk
->bus_type
= GUEST_DISK_BUS_TYPE_NVME
;
1002 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
1014 * Store disk device info for non-PCI virtio devices (for example s390x
1015 * channel I/O devices). Returns true if information has been stored, or
1016 * false for failure.
1018 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath
,
1019 GuestDiskAddress
*disk
,
1022 unsigned int tgt
[3];
1025 if (!strstr(syspath
, "/virtio") || !strstr(syspath
, "/block")) {
1026 g_debug("Unsupported virtio device '%s'", syspath
);
1030 p
= strstr(syspath
, "/target");
1031 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1032 &tgt
[0], &tgt
[1], &tgt
[2]) == 3) {
1033 /* virtio-scsi: target*:0:<target>:<unit> */
1034 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1036 disk
->target
= tgt
[1];
1037 disk
->unit
= tgt
[2];
1039 /* virtio-blk: 1 disk per 1 device */
1040 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
1047 * Store disk device info for CCW devices (s390x channel I/O devices).
1048 * Returns true if information has been stored, or false for failure.
1050 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath
,
1051 GuestDiskAddress
*disk
,
1054 unsigned int cssid
, ssid
, subchno
, devno
;
1057 p
= strstr(syspath
, "/devices/css");
1058 if (!p
|| sscanf(p
+ 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1059 &cssid
, &ssid
, &subchno
, &devno
) < 4) {
1060 g_debug("could not parse ccw device sysfs path: %s", syspath
);
1064 disk
->has_ccw_address
= true;
1065 disk
->ccw_address
= g_new0(GuestCCWAddress
, 1);
1066 disk
->ccw_address
->cssid
= cssid
;
1067 disk
->ccw_address
->ssid
= ssid
;
1068 disk
->ccw_address
->subchno
= subchno
;
1069 disk
->ccw_address
->devno
= devno
;
1071 if (strstr(p
, "/virtio")) {
1072 build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1078 /* Store disk device info specified by @sysfs into @fs */
1079 static void build_guest_fsinfo_for_real_device(char const *syspath
,
1080 GuestFilesystemInfo
*fs
,
1083 GuestDiskAddress
*disk
;
1084 GuestPCIAddress
*pciaddr
;
1086 #ifdef CONFIG_LIBUDEV
1087 struct udev
*udev
= NULL
;
1088 struct udev_device
*udevice
= NULL
;
1091 pciaddr
= g_new0(GuestPCIAddress
, 1);
1092 pciaddr
->domain
= -1; /* -1 means field is invalid */
1095 pciaddr
->function
= -1;
1097 disk
= g_new0(GuestDiskAddress
, 1);
1098 disk
->pci_controller
= pciaddr
;
1099 disk
->bus_type
= GUEST_DISK_BUS_TYPE_UNKNOWN
;
1101 #ifdef CONFIG_LIBUDEV
1103 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1104 if (udev
== NULL
|| udevice
== NULL
) {
1105 g_debug("failed to query udev");
1107 const char *devnode
, *serial
;
1108 devnode
= udev_device_get_devnode(udevice
);
1109 if (devnode
!= NULL
) {
1110 disk
->dev
= g_strdup(devnode
);
1111 disk
->has_dev
= true;
1113 serial
= udev_device_get_property_value(udevice
, "ID_SERIAL");
1114 if (serial
!= NULL
&& *serial
!= 0) {
1115 disk
->serial
= g_strdup(serial
);
1116 disk
->has_serial
= true;
1121 udev_device_unref(udevice
);
1124 if (strstr(syspath
, "/devices/pci")) {
1125 has_hwinf
= build_guest_fsinfo_for_pci_dev(syspath
, disk
, errp
);
1126 } else if (strstr(syspath
, "/devices/css")) {
1127 has_hwinf
= build_guest_fsinfo_for_ccw_dev(syspath
, disk
, errp
);
1128 } else if (strstr(syspath
, "/virtio")) {
1129 has_hwinf
= build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1131 g_debug("Unsupported device type for '%s'", syspath
);
1135 if (has_hwinf
|| disk
->has_dev
|| disk
->has_serial
) {
1136 QAPI_LIST_PREPEND(fs
->disk
, disk
);
1138 qapi_free_GuestDiskAddress(disk
);
1142 static void build_guest_fsinfo_for_device(char const *devpath
,
1143 GuestFilesystemInfo
*fs
,
1146 /* Store a list of slave devices of virtual volume specified by @syspath into
1148 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1149 GuestFilesystemInfo
*fs
,
1155 struct dirent
*entry
;
1157 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1158 dir
= opendir(dirpath
);
1160 if (errno
!= ENOENT
) {
1161 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1169 entry
= readdir(dir
);
1170 if (entry
== NULL
) {
1172 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1177 if (entry
->d_type
== DT_LNK
) {
1180 g_debug(" slave device '%s'", entry
->d_name
);
1181 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1182 build_guest_fsinfo_for_device(path
, fs
, &err
);
1186 error_propagate(errp
, err
);
1196 static bool is_disk_virtual(const char *devpath
, Error
**errp
)
1198 g_autofree
char *syspath
= realpath(devpath
, NULL
);
1201 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1204 return strstr(syspath
, "/devices/virtual/block/") != NULL
;
1207 /* Dispatch to functions for virtual/real device */
1208 static void build_guest_fsinfo_for_device(char const *devpath
,
1209 GuestFilesystemInfo
*fs
,
1213 g_autofree
char *syspath
= NULL
;
1214 bool is_virtual
= false;
1216 syspath
= realpath(devpath
, NULL
);
1218 if (errno
!= ENOENT
) {
1219 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1223 /* ENOENT: This devpath may not exist because of container config */
1225 fs
->name
= g_path_get_basename(devpath
);
1231 fs
->name
= g_path_get_basename(syspath
);
1234 g_debug(" parse sysfs path '%s'", syspath
);
1235 is_virtual
= is_disk_virtual(syspath
, errp
);
1236 if (*errp
!= NULL
) {
1240 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1242 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1246 #ifdef CONFIG_LIBUDEV
1249 * Wrapper around build_guest_fsinfo_for_device() for getting just
1252 static GuestDiskAddress
*get_disk_address(const char *syspath
, Error
**errp
)
1254 g_autoptr(GuestFilesystemInfo
) fs
= NULL
;
1256 fs
= g_new0(GuestFilesystemInfo
, 1);
1257 build_guest_fsinfo_for_device(syspath
, fs
, errp
);
1258 if (fs
->disk
!= NULL
) {
1259 return g_steal_pointer(&fs
->disk
->value
);
1264 static char *get_alias_for_syspath(const char *syspath
)
1266 struct udev
*udev
= NULL
;
1267 struct udev_device
*udevice
= NULL
;
1272 g_debug("failed to query udev");
1275 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1276 if (udevice
== NULL
) {
1277 g_debug("failed to query udev for path: %s", syspath
);
1280 const char *alias
= udev_device_get_property_value(
1281 udevice
, "DM_NAME");
1283 * NULL means there was an error and empty string means there is no
1284 * alias. In case of no alias we return NULL instead of empty string.
1286 if (alias
== NULL
) {
1287 g_debug("failed to query udev for device alias for: %s",
1289 } else if (*alias
!= 0) {
1290 ret
= g_strdup(alias
);
1296 udev_device_unref(udevice
);
1300 static char *get_device_for_syspath(const char *syspath
)
1302 struct udev
*udev
= NULL
;
1303 struct udev_device
*udevice
= NULL
;
1308 g_debug("failed to query udev");
1311 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1312 if (udevice
== NULL
) {
1313 g_debug("failed to query udev for path: %s", syspath
);
1316 ret
= g_strdup(udev_device_get_devnode(udevice
));
1321 udev_device_unref(udevice
);
1325 static void get_disk_deps(const char *disk_dir
, GuestDiskInfo
*disk
)
1327 g_autofree
char *deps_dir
= NULL
;
1329 GDir
*dp_deps
= NULL
;
1331 /* List dependent disks */
1332 deps_dir
= g_strdup_printf("%s/slaves", disk_dir
);
1333 g_debug(" listing entries in: %s", deps_dir
);
1334 dp_deps
= g_dir_open(deps_dir
, 0, NULL
);
1335 if (dp_deps
== NULL
) {
1336 g_debug("failed to list entries in %s", deps_dir
);
1339 disk
->has_dependencies
= true;
1340 while ((dep
= g_dir_read_name(dp_deps
)) != NULL
) {
1341 g_autofree
char *dep_dir
= NULL
;
1344 /* Add dependent disks */
1345 dep_dir
= g_strdup_printf("%s/%s", deps_dir
, dep
);
1346 dev_name
= get_device_for_syspath(dep_dir
);
1347 if (dev_name
!= NULL
) {
1348 g_debug(" adding dependent device: %s", dev_name
);
1349 QAPI_LIST_PREPEND(disk
->dependencies
, dev_name
);
1352 g_dir_close(dp_deps
);
1356 * Detect partitions subdirectory, name is "<disk_name><number>" or
1357 * "<disk_name>p<number>"
1359 * @disk_name -- last component of /sys path (e.g. sda)
1360 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1361 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1363 static GuestDiskInfoList
*get_disk_partitions(
1364 GuestDiskInfoList
*list
,
1365 const char *disk_name
, const char *disk_dir
,
1366 const char *disk_dev
)
1368 GuestDiskInfoList
*ret
= list
;
1369 struct dirent
*de_disk
;
1370 DIR *dp_disk
= NULL
;
1371 size_t len
= strlen(disk_name
);
1373 dp_disk
= opendir(disk_dir
);
1374 while ((de_disk
= readdir(dp_disk
)) != NULL
) {
1375 g_autofree
char *partition_dir
= NULL
;
1377 GuestDiskInfo
*partition
;
1379 if (!(de_disk
->d_type
& DT_DIR
)) {
1383 if (!(strncmp(disk_name
, de_disk
->d_name
, len
) == 0 &&
1384 ((*(de_disk
->d_name
+ len
) == 'p' &&
1385 isdigit(*(de_disk
->d_name
+ len
+ 1))) ||
1386 isdigit(*(de_disk
->d_name
+ len
))))) {
1390 partition_dir
= g_strdup_printf("%s/%s",
1391 disk_dir
, de_disk
->d_name
);
1392 dev_name
= get_device_for_syspath(partition_dir
);
1393 if (dev_name
== NULL
) {
1394 g_debug("Failed to get device name for syspath: %s",
1398 partition
= g_new0(GuestDiskInfo
, 1);
1399 partition
->name
= dev_name
;
1400 partition
->partition
= true;
1401 partition
->has_dependencies
= true;
1402 /* Add parent disk as dependent for easier tracking of hierarchy */
1403 QAPI_LIST_PREPEND(partition
->dependencies
, g_strdup(disk_dev
));
1405 QAPI_LIST_PREPEND(ret
, partition
);
1412 static void get_nvme_smart(GuestDiskInfo
*disk
)
1415 GuestNVMeSmart
*smart
;
1416 NvmeSmartLog log
= {0};
1417 struct nvme_admin_cmd cmd
= {
1418 .opcode
= NVME_ADM_CMD_GET_LOG_PAGE
,
1419 .nsid
= NVME_NSID_BROADCAST
,
1420 .addr
= (uintptr_t)&log
,
1421 .data_len
= sizeof(log
),
1422 .cdw10
= NVME_LOG_SMART_INFO
| (1 << 15) /* RAE bit */
1423 | (((sizeof(log
) >> 2) - 1) << 16)
1426 fd
= qga_open_cloexec(disk
->name
, O_RDONLY
, 0);
1428 g_debug("Failed to open device: %s: %s", disk
->name
, g_strerror(errno
));
1432 if (ioctl(fd
, NVME_IOCTL_ADMIN_CMD
, &cmd
)) {
1433 g_debug("Failed to get smart: %s: %s", disk
->name
, g_strerror(errno
));
1438 disk
->has_smart
= true;
1439 disk
->smart
= g_new0(GuestDiskSmart
, 1);
1440 disk
->smart
->type
= GUEST_DISK_BUS_TYPE_NVME
;
1442 smart
= &disk
->smart
->u
.nvme
;
1443 smart
->critical_warning
= log
.critical_warning
;
1444 smart
->temperature
= lduw_le_p(&log
.temperature
); /* unaligned field */
1445 smart
->available_spare
= log
.available_spare
;
1446 smart
->available_spare_threshold
= log
.available_spare_threshold
;
1447 smart
->percentage_used
= log
.percentage_used
;
1448 smart
->data_units_read_lo
= le64_to_cpu(log
.data_units_read
[0]);
1449 smart
->data_units_read_hi
= le64_to_cpu(log
.data_units_read
[1]);
1450 smart
->data_units_written_lo
= le64_to_cpu(log
.data_units_written
[0]);
1451 smart
->data_units_written_hi
= le64_to_cpu(log
.data_units_written
[1]);
1452 smart
->host_read_commands_lo
= le64_to_cpu(log
.host_read_commands
[0]);
1453 smart
->host_read_commands_hi
= le64_to_cpu(log
.host_read_commands
[1]);
1454 smart
->host_write_commands_lo
= le64_to_cpu(log
.host_write_commands
[0]);
1455 smart
->host_write_commands_hi
= le64_to_cpu(log
.host_write_commands
[1]);
1456 smart
->controller_busy_time_lo
= le64_to_cpu(log
.controller_busy_time
[0]);
1457 smart
->controller_busy_time_hi
= le64_to_cpu(log
.controller_busy_time
[1]);
1458 smart
->power_cycles_lo
= le64_to_cpu(log
.power_cycles
[0]);
1459 smart
->power_cycles_hi
= le64_to_cpu(log
.power_cycles
[1]);
1460 smart
->power_on_hours_lo
= le64_to_cpu(log
.power_on_hours
[0]);
1461 smart
->power_on_hours_hi
= le64_to_cpu(log
.power_on_hours
[1]);
1462 smart
->unsafe_shutdowns_lo
= le64_to_cpu(log
.unsafe_shutdowns
[0]);
1463 smart
->unsafe_shutdowns_hi
= le64_to_cpu(log
.unsafe_shutdowns
[1]);
1464 smart
->media_errors_lo
= le64_to_cpu(log
.media_errors
[0]);
1465 smart
->media_errors_hi
= le64_to_cpu(log
.media_errors
[1]);
1466 smart
->number_of_error_log_entries_lo
=
1467 le64_to_cpu(log
.number_of_error_log_entries
[0]);
1468 smart
->number_of_error_log_entries_hi
=
1469 le64_to_cpu(log
.number_of_error_log_entries
[1]);
1474 static void get_disk_smart(GuestDiskInfo
*disk
)
1476 if (disk
->has_address
1477 && (disk
->address
->bus_type
== GUEST_DISK_BUS_TYPE_NVME
)) {
1478 get_nvme_smart(disk
);
1482 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1484 GuestDiskInfoList
*ret
= NULL
;
1485 GuestDiskInfo
*disk
;
1487 struct dirent
*de
= NULL
;
1489 g_debug("listing /sys/block directory");
1490 dp
= opendir("/sys/block");
1492 error_setg_errno(errp
, errno
, "Can't open directory \"/sys/block\"");
1495 while ((de
= readdir(dp
)) != NULL
) {
1496 g_autofree
char *disk_dir
= NULL
, *line
= NULL
,
1499 Error
*local_err
= NULL
;
1500 if (de
->d_type
!= DT_LNK
) {
1501 g_debug(" skipping entry: %s", de
->d_name
);
1505 /* Check size and skip zero-sized disks */
1506 g_debug(" checking disk size");
1507 size_path
= g_strdup_printf("/sys/block/%s/size", de
->d_name
);
1508 if (!g_file_get_contents(size_path
, &line
, NULL
, NULL
)) {
1509 g_debug(" failed to read disk size");
1512 if (g_strcmp0(line
, "0\n") == 0) {
1513 g_debug(" skipping zero-sized disk");
1517 g_debug(" adding %s", de
->d_name
);
1518 disk_dir
= g_strdup_printf("/sys/block/%s", de
->d_name
);
1519 dev_name
= get_device_for_syspath(disk_dir
);
1520 if (dev_name
== NULL
) {
1521 g_debug("Failed to get device name for syspath: %s",
1525 disk
= g_new0(GuestDiskInfo
, 1);
1526 disk
->name
= dev_name
;
1527 disk
->partition
= false;
1528 disk
->alias
= get_alias_for_syspath(disk_dir
);
1529 disk
->has_alias
= (disk
->alias
!= NULL
);
1530 QAPI_LIST_PREPEND(ret
, disk
);
1532 /* Get address for non-virtual devices */
1533 bool is_virtual
= is_disk_virtual(disk_dir
, &local_err
);
1534 if (local_err
!= NULL
) {
1535 g_debug(" failed to check disk path, ignoring error: %s",
1536 error_get_pretty(local_err
));
1537 error_free(local_err
);
1539 /* Don't try to get the address */
1543 disk
->address
= get_disk_address(disk_dir
, &local_err
);
1544 if (local_err
!= NULL
) {
1545 g_debug(" failed to get device info, ignoring error: %s",
1546 error_get_pretty(local_err
));
1547 error_free(local_err
);
1549 } else if (disk
->address
!= NULL
) {
1550 disk
->has_address
= true;
1554 get_disk_deps(disk_dir
, disk
);
1555 get_disk_smart(disk
);
1556 ret
= get_disk_partitions(ret
, de
->d_name
, disk_dir
, dev_name
);
1566 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1568 error_setg(errp
, QERR_UNSUPPORTED
);
1574 /* Return a list of the disk device(s)' info which @mount lies on */
1575 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1578 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1580 unsigned long used
, nonroot_total
, fr_size
;
1581 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1582 mount
->devmajor
, mount
->devminor
);
1584 fs
->mountpoint
= g_strdup(mount
->dirname
);
1585 fs
->type
= g_strdup(mount
->devtype
);
1586 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1588 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1589 fr_size
= buf
.f_frsize
;
1590 used
= buf
.f_blocks
- buf
.f_bfree
;
1591 nonroot_total
= used
+ buf
.f_bavail
;
1592 fs
->used_bytes
= used
* fr_size
;
1593 fs
->total_bytes
= nonroot_total
* fr_size
;
1595 fs
->has_total_bytes
= true;
1596 fs
->has_used_bytes
= true;
1604 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1607 struct FsMount
*mount
;
1608 GuestFilesystemInfoList
*ret
= NULL
;
1609 Error
*local_err
= NULL
;
1611 QTAILQ_INIT(&mounts
);
1612 if (!build_fs_mount_list(&mounts
, &local_err
)) {
1613 error_propagate(errp
, local_err
);
1617 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1618 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1620 QAPI_LIST_PREPEND(ret
, build_guest_fsinfo(mount
, &local_err
));
1622 error_propagate(errp
, local_err
);
1623 qapi_free_GuestFilesystemInfoList(ret
);
1629 free_fs_mount_list(&mounts
);
1635 FSFREEZE_HOOK_THAW
= 0,
1636 FSFREEZE_HOOK_FREEZE
,
1639 static const char *fsfreeze_hook_arg_string
[] = {
1644 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1649 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1650 Error
*local_err
= NULL
;
1652 hook
= ga_fsfreeze_hook(ga_state
);
1656 if (access(hook
, X_OK
) != 0) {
1657 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1661 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1665 reopen_fd_to_null(0);
1666 reopen_fd_to_null(1);
1667 reopen_fd_to_null(2);
1669 execl(hook
, hook
, arg_str
, NULL
);
1670 _exit(EXIT_FAILURE
);
1671 } else if (pid
< 0) {
1672 error_setg_errno(errp
, errno
, "failed to create child process");
1676 ga_wait_child(pid
, &status
, &local_err
);
1678 error_propagate(errp
, local_err
);
1682 if (!WIFEXITED(status
)) {
1683 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1687 status
= WEXITSTATUS(status
);
1689 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1695 * Return status of freeze/thaw
1697 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1699 if (ga_is_frozen(ga_state
)) {
1700 return GUEST_FSFREEZE_STATUS_FROZEN
;
1703 return GUEST_FSFREEZE_STATUS_THAWED
;
1706 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1708 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1712 * Walk list of mounted file systems in the guest, and freeze the ones which
1713 * are real local file systems.
1715 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1716 strList
*mountpoints
,
1722 struct FsMount
*mount
;
1723 Error
*local_err
= NULL
;
1726 slog("guest-fsfreeze called");
1728 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1730 error_propagate(errp
, local_err
);
1734 QTAILQ_INIT(&mounts
);
1735 if (!build_fs_mount_list(&mounts
, &local_err
)) {
1736 error_propagate(errp
, local_err
);
1740 /* cannot risk guest agent blocking itself on a write in this state */
1741 ga_set_frozen(ga_state
);
1743 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, next
) {
1744 /* To issue fsfreeze in the reverse order of mounts, check if the
1745 * mount is listed in the list here */
1746 if (has_mountpoints
) {
1747 for (list
= mountpoints
; list
; list
= list
->next
) {
1748 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1757 fd
= qga_open_cloexec(mount
->dirname
, O_RDONLY
, 0);
1759 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1763 /* we try to cull filesystems we know won't work in advance, but other
1764 * filesystems may not implement fsfreeze for less obvious reasons.
1765 * these will report EOPNOTSUPP. we simply ignore these when tallying
1766 * the number of frozen filesystems.
1767 * if a filesystem is mounted more than once (aka bind mount) a
1768 * consecutive attempt to freeze an already frozen filesystem will
1771 * any other error means a failure to freeze a filesystem we
1772 * expect to be freezable, so return an error in those cases
1773 * and return system to thawed state.
1775 ret
= ioctl(fd
, FIFREEZE
);
1777 if (errno
!= EOPNOTSUPP
&& errno
!= EBUSY
) {
1778 error_setg_errno(errp
, errno
, "failed to freeze %s",
1789 free_fs_mount_list(&mounts
);
1790 /* We may not issue any FIFREEZE here.
1791 * Just unset ga_state here and ready for the next call.
1794 ga_unset_frozen(ga_state
);
1799 free_fs_mount_list(&mounts
);
1800 qmp_guest_fsfreeze_thaw(NULL
);
1805 * Walk list of frozen file systems in the guest, and thaw them.
1807 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1812 int fd
, i
= 0, logged
;
1813 Error
*local_err
= NULL
;
1815 QTAILQ_INIT(&mounts
);
1816 if (!build_fs_mount_list(&mounts
, &local_err
)) {
1817 error_propagate(errp
, local_err
);
1821 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1823 fd
= qga_open_cloexec(mount
->dirname
, O_RDONLY
, 0);
1827 /* we have no way of knowing whether a filesystem was actually unfrozen
1828 * as a result of a successful call to FITHAW, only that if an error
1829 * was returned the filesystem was *not* unfrozen by that particular
1832 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1833 * to unfreeze, continuing issuing FITHAW until an error is returned,
1834 * in which case either the filesystem is in an unfreezable state, or,
1835 * more likely, it was thawed previously (and remains so afterward).
1837 * also, since the most recent successful call is the one that did
1838 * the actual unfreeze, we can use this to provide an accurate count
1839 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1840 * may * be useful for determining whether a filesystem was unfrozen
1841 * during the freeze/thaw phase by a process other than qemu-ga.
1844 ret
= ioctl(fd
, FITHAW
);
1845 if (ret
== 0 && !logged
) {
1853 ga_unset_frozen(ga_state
);
1854 free_fs_mount_list(&mounts
);
1856 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1861 static void guest_fsfreeze_cleanup(void)
1865 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1866 qmp_guest_fsfreeze_thaw(&err
);
1868 slog("failed to clean up frozen filesystems: %s",
1869 error_get_pretty(err
));
1874 #endif /* CONFIG_FSFREEZE */
1876 #if defined(CONFIG_FSTRIM)
1878 * Walk list of mounted file systems in the guest, and trim them.
1880 GuestFilesystemTrimResponse
*
1881 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1883 GuestFilesystemTrimResponse
*response
;
1884 GuestFilesystemTrimResult
*result
;
1887 struct FsMount
*mount
;
1889 struct fstrim_range r
;
1891 slog("guest-fstrim called");
1893 QTAILQ_INIT(&mounts
);
1894 if (!build_fs_mount_list(&mounts
, errp
)) {
1898 response
= g_malloc0(sizeof(*response
));
1900 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1901 result
= g_malloc0(sizeof(*result
));
1902 result
->path
= g_strdup(mount
->dirname
);
1904 QAPI_LIST_PREPEND(response
->paths
, result
);
1906 fd
= qga_open_cloexec(mount
->dirname
, O_RDONLY
, 0);
1908 result
->error
= g_strdup_printf("failed to open: %s",
1910 result
->has_error
= true;
1914 /* We try to cull filesystems we know won't work in advance, but other
1915 * filesystems may not implement fstrim for less obvious reasons.
1916 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1917 * will be reported (e.g. CD-ROMs).
1918 * Any other error means an unexpected error.
1922 r
.minlen
= has_minimum
? minimum
: 0;
1923 ret
= ioctl(fd
, FITRIM
, &r
);
1925 result
->has_error
= true;
1926 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1927 result
->error
= g_strdup("trim not supported");
1929 result
->error
= g_strdup_printf("failed to trim: %s",
1936 result
->has_minimum
= true;
1937 result
->minimum
= r
.minlen
;
1938 result
->has_trimmed
= true;
1939 result
->trimmed
= r
.len
;
1943 free_fs_mount_list(&mounts
);
1946 #endif /* CONFIG_FSTRIM */
1949 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1950 #define SUSPEND_SUPPORTED 0
1951 #define SUSPEND_NOT_SUPPORTED 1
1954 SUSPEND_MODE_DISK
= 0,
1955 SUSPEND_MODE_RAM
= 1,
1956 SUSPEND_MODE_HYBRID
= 2,
1960 * Executes a command in a child process using g_spawn_sync,
1961 * returning an int >= 0 representing the exit status of the
1964 * If the program wasn't found in path, returns -1.
1966 * If a problem happened when creating the child process,
1967 * returns -1 and errp is set.
1969 static int run_process_child(const char *command
[], Error
**errp
)
1971 int exit_status
, spawn_flag
;
1972 GError
*g_err
= NULL
;
1975 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1976 G_SPAWN_STDERR_TO_DEV_NULL
;
1978 success
= g_spawn_sync(NULL
, (char **)command
, NULL
, spawn_flag
,
1979 NULL
, NULL
, NULL
, NULL
,
1980 &exit_status
, &g_err
);
1983 return WEXITSTATUS(exit_status
);
1986 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1987 error_setg(errp
, "failed to create child process, error '%s'",
1991 g_error_free(g_err
);
1995 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1997 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1998 "systemd-hybrid-sleep"};
1999 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
2002 status
= run_process_child(cmd
, errp
);
2005 * systemctl status uses LSB return codes so we can expect
2006 * status > 0 and be ok. To assert if the guest has support
2007 * for the selected suspend mode, status should be < 4. 4 is
2008 * the code for unknown service status, the return value when
2009 * the service does not exist. A common value is status = 3
2010 * (program is not running).
2012 if (status
> 0 && status
< 4) {
2019 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
2021 Error
*local_err
= NULL
;
2022 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
2023 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
2026 status
= run_process_child(cmd
, &local_err
);
2032 if ((status
== -1) && !local_err
) {
2033 error_setg(errp
, "the helper program 'systemctl %s' was not found",
2034 systemctl_args
[mode
]);
2039 error_propagate(errp
, local_err
);
2041 error_setg(errp
, "the helper program 'systemctl %s' returned an "
2042 "unexpected exit status code (%d)",
2043 systemctl_args
[mode
], status
);
2047 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
2049 Error
*local_err
= NULL
;
2050 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
2051 "--suspend-hybrid"};
2052 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
2055 status
= run_process_child(cmd
, &local_err
);
2057 if (status
== SUSPEND_SUPPORTED
) {
2061 if ((status
== -1) && !local_err
) {
2066 error_propagate(errp
, local_err
);
2069 "the helper program '%s' returned an unexpected exit"
2070 " status code (%d)", "pm-is-supported", status
);
2076 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
2078 Error
*local_err
= NULL
;
2079 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
2080 "pm-suspend-hybrid"};
2081 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
2084 status
= run_process_child(cmd
, &local_err
);
2090 if ((status
== -1) && !local_err
) {
2091 error_setg(errp
, "the helper program '%s' was not found",
2092 pmutils_binaries
[mode
]);
2097 error_propagate(errp
, local_err
);
2100 "the helper program '%s' returned an unexpected exit"
2101 " status code (%d)", pmutils_binaries
[mode
], status
);
2105 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
2107 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
2108 const char *sysfile_str
= sysfile_strs
[mode
];
2109 char buf
[32]; /* hopefully big enough */
2114 error_setg(errp
, "unknown guest suspend mode");
2118 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
2123 ret
= read(fd
, buf
, sizeof(buf
) - 1);
2130 if (strstr(buf
, sysfile_str
)) {
2136 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
2138 Error
*local_err
= NULL
;
2139 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
2140 const char *sysfile_str
= sysfile_strs
[mode
];
2145 error_setg(errp
, "unknown guest suspend mode");
2155 reopen_fd_to_null(0);
2156 reopen_fd_to_null(1);
2157 reopen_fd_to_null(2);
2159 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
2161 _exit(EXIT_FAILURE
);
2164 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
2165 _exit(EXIT_FAILURE
);
2168 _exit(EXIT_SUCCESS
);
2169 } else if (pid
< 0) {
2170 error_setg_errno(errp
, errno
, "failed to create child process");
2174 ga_wait_child(pid
, &status
, &local_err
);
2176 error_propagate(errp
, local_err
);
2180 if (WEXITSTATUS(status
)) {
2181 error_setg(errp
, "child process has failed to suspend");
2186 static void guest_suspend(SuspendMode mode
, Error
**errp
)
2188 Error
*local_err
= NULL
;
2189 bool mode_supported
= false;
2191 if (systemd_supports_mode(mode
, &local_err
)) {
2192 mode_supported
= true;
2193 systemd_suspend(mode
, &local_err
);
2200 error_free(local_err
);
2203 if (pmutils_supports_mode(mode
, &local_err
)) {
2204 mode_supported
= true;
2205 pmutils_suspend(mode
, &local_err
);
2212 error_free(local_err
);
2215 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
2216 mode_supported
= true;
2217 linux_sys_state_suspend(mode
, &local_err
);
2220 if (!mode_supported
) {
2221 error_free(local_err
);
2223 "the requested suspend mode is not supported by the guest");
2225 error_propagate(errp
, local_err
);
2229 void qmp_guest_suspend_disk(Error
**errp
)
2231 guest_suspend(SUSPEND_MODE_DISK
, errp
);
2234 void qmp_guest_suspend_ram(Error
**errp
)
2236 guest_suspend(SUSPEND_MODE_RAM
, errp
);
2239 void qmp_guest_suspend_hybrid(Error
**errp
)
2241 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
2244 /* Transfer online/offline status between @vcpu and the guest system.
2246 * On input either @errp or *@errp must be NULL.
2248 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2249 * - R: vcpu->logical_id
2251 * - W: vcpu->can_offline
2253 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2254 * - R: vcpu->logical_id
2257 * Written members remain unmodified on error.
2259 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
2260 char *dirpath
, Error
**errp
)
2265 static const char fn
[] = "online";
2267 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2269 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2273 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2275 if (errno
!= ENOENT
) {
2276 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2277 } else if (sys2vcpu
) {
2278 vcpu
->online
= true;
2279 vcpu
->can_offline
= false;
2280 } else if (!vcpu
->online
) {
2281 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2282 "offlined", vcpu
->logical_id
);
2283 } /* otherwise pretend successful re-onlining */
2285 unsigned char status
;
2287 res
= pread(fd
, &status
, 1, 0);
2289 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2290 } else if (res
== 0) {
2291 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2293 } else if (sys2vcpu
) {
2294 vcpu
->online
= (status
!= '0');
2295 vcpu
->can_offline
= true;
2296 } else if (vcpu
->online
!= (status
!= '0')) {
2297 status
= '0' + vcpu
->online
;
2298 if (pwrite(fd
, &status
, 1, 0) == -1) {
2299 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2302 } /* otherwise pretend successful re-(on|off)-lining */
2312 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2314 GuestLogicalProcessorList
*head
, **tail
;
2315 const char *cpu_dir
= "/sys/devices/system/cpu";
2317 g_autoptr(GDir
) cpu_gdir
= NULL
;
2318 Error
*local_err
= NULL
;
2322 cpu_gdir
= g_dir_open(cpu_dir
, 0, NULL
);
2324 if (cpu_gdir
== NULL
) {
2325 error_setg_errno(errp
, errno
, "failed to list entries: %s", cpu_dir
);
2329 while (local_err
== NULL
&& (line
= g_dir_read_name(cpu_gdir
)) != NULL
) {
2330 GuestLogicalProcessor
*vcpu
;
2332 if (sscanf(line
, "cpu%" PRId64
, &id
)) {
2333 g_autofree
char *path
= g_strdup_printf("/sys/devices/system/cpu/"
2334 "cpu%" PRId64
"/", id
);
2335 vcpu
= g_malloc0(sizeof *vcpu
);
2336 vcpu
->logical_id
= id
;
2337 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2338 transfer_vcpu(vcpu
, true, path
, &local_err
);
2339 QAPI_LIST_APPEND(tail
, vcpu
);
2343 if (local_err
== NULL
) {
2344 /* there's no guest with zero VCPUs */
2345 g_assert(head
!= NULL
);
2349 qapi_free_GuestLogicalProcessorList(head
);
2350 error_propagate(errp
, local_err
);
2354 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2357 Error
*local_err
= NULL
;
2360 while (vcpus
!= NULL
) {
2361 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2362 vcpus
->value
->logical_id
);
2364 transfer_vcpu(vcpus
->value
, false, path
, &local_err
);
2366 if (local_err
!= NULL
) {
2370 vcpus
= vcpus
->next
;
2373 if (local_err
!= NULL
) {
2374 if (processed
== 0) {
2375 error_propagate(errp
, local_err
);
2377 error_free(local_err
);
2384 void qmp_guest_set_user_password(const char *username
,
2385 const char *password
,
2389 Error
*local_err
= NULL
;
2390 char *passwd_path
= NULL
;
2393 int datafd
[2] = { -1, -1 };
2394 char *rawpasswddata
= NULL
;
2395 size_t rawpasswdlen
;
2396 char *chpasswddata
= NULL
;
2399 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2400 if (!rawpasswddata
) {
2403 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2404 rawpasswddata
[rawpasswdlen
] = '\0';
2406 if (strchr(rawpasswddata
, '\n')) {
2407 error_setg(errp
, "forbidden characters in raw password");
2411 if (strchr(username
, '\n') ||
2412 strchr(username
, ':')) {
2413 error_setg(errp
, "forbidden characters in username");
2417 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
2418 chpasswdlen
= strlen(chpasswddata
);
2420 passwd_path
= g_find_program_in_path("chpasswd");
2423 error_setg(errp
, "cannot find 'passwd' program in PATH");
2427 if (!g_unix_open_pipe(datafd
, FD_CLOEXEC
, NULL
)) {
2428 error_setg(errp
, "cannot create pipe FDs");
2438 reopen_fd_to_null(1);
2439 reopen_fd_to_null(2);
2442 execl(passwd_path
, "chpasswd", "-e", NULL
);
2444 execl(passwd_path
, "chpasswd", NULL
);
2446 _exit(EXIT_FAILURE
);
2447 } else if (pid
< 0) {
2448 error_setg_errno(errp
, errno
, "failed to create child process");
2454 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2455 error_setg_errno(errp
, errno
, "cannot write new account password");
2461 ga_wait_child(pid
, &status
, &local_err
);
2463 error_propagate(errp
, local_err
);
2467 if (!WIFEXITED(status
)) {
2468 error_setg(errp
, "child process has terminated abnormally");
2472 if (WEXITSTATUS(status
)) {
2473 error_setg(errp
, "child process has failed to set user password");
2478 g_free(chpasswddata
);
2479 g_free(rawpasswddata
);
2480 g_free(passwd_path
);
2481 if (datafd
[0] != -1) {
2484 if (datafd
[1] != -1) {
2489 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2490 int size
, Error
**errp
)
2496 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2498 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2502 res
= pread(fd
, buf
, size
, 0);
2504 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2505 } else if (res
== 0) {
2506 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2511 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2512 const char *buf
, int size
, Error
**errp
)
2517 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2519 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2523 if (pwrite(fd
, buf
, size
, 0) == -1) {
2524 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2530 /* Transfer online/offline status between @mem_blk and the guest system.
2532 * On input either @errp or *@errp must be NULL.
2534 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2535 * - R: mem_blk->phys_index
2536 * - W: mem_blk->online
2537 * - W: mem_blk->can_offline
2539 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2540 * - R: mem_blk->phys_index
2541 * - R: mem_blk->online
2542 *- R: mem_blk->can_offline
2543 * Written members remain unmodified on error.
2545 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2546 GuestMemoryBlockResponse
*result
,
2552 Error
*local_err
= NULL
;
2558 error_setg(errp
, "Internal error, 'result' should not be NULL");
2562 dp
= opendir("/sys/devices/system/memory/");
2563 /* if there is no 'memory' directory in sysfs,
2564 * we think this VM does not support online/offline memory block,
2565 * any other solution?
2568 if (errno
== ENOENT
) {
2570 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2577 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2578 mem_blk
->phys_index
);
2579 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2582 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2584 if (errno
== ENOENT
) {
2585 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2588 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2596 status
= g_malloc0(10);
2597 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2599 /* treat with sysfs file that not exist in old kernel */
2600 if (errno
== ENOENT
) {
2601 error_free(local_err
);
2603 mem_blk
->online
= true;
2604 mem_blk
->can_offline
= false;
2605 } else if (!mem_blk
->online
) {
2607 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2611 error_propagate(errp
, local_err
);
2613 error_free(local_err
);
2615 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2622 char removable
= '0';
2624 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2626 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2628 /* if no 'removable' file, it doesn't support offline mem blk */
2629 if (errno
== ENOENT
) {
2630 error_free(local_err
);
2631 mem_blk
->can_offline
= false;
2633 error_propagate(errp
, local_err
);
2636 mem_blk
->can_offline
= (removable
!= '0');
2639 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2640 const char *new_state
= mem_blk
->online
? "online" : "offline";
2642 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2645 error_free(local_err
);
2647 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2651 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2652 result
->has_error_code
= false;
2653 } /* otherwise pretend successful re-(on|off)-lining */
2664 result
->has_error_code
= true;
2665 result
->error_code
= errno
;
2669 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2671 GuestMemoryBlockList
*head
, **tail
;
2672 Error
*local_err
= NULL
;
2679 dp
= opendir("/sys/devices/system/memory/");
2681 /* it's ok if this happens to be a system that doesn't expose
2682 * memory blocks via sysfs, but otherwise we should report
2685 if (errno
!= ENOENT
) {
2686 error_setg_errno(errp
, errno
, "Can't open directory"
2687 "\"/sys/devices/system/memory/\"");
2692 /* Note: the phys_index of memory block may be discontinuous,
2693 * this is because a memblk is the unit of the Sparse Memory design, which
2694 * allows discontinuous memory ranges (ex. NUMA), so here we should
2695 * traverse the memory block directory.
2697 while ((de
= readdir(dp
)) != NULL
) {
2698 GuestMemoryBlock
*mem_blk
;
2700 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2701 !(de
->d_type
& DT_DIR
)) {
2705 mem_blk
= g_malloc0(sizeof *mem_blk
);
2706 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2707 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2708 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2709 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2714 QAPI_LIST_APPEND(tail
, mem_blk
);
2718 if (local_err
== NULL
) {
2719 /* there's no guest with zero memory blocks */
2721 error_setg(errp
, "guest reported zero memory blocks!");
2726 qapi_free_GuestMemoryBlockList(head
);
2727 error_propagate(errp
, local_err
);
2731 GuestMemoryBlockResponseList
*
2732 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2734 GuestMemoryBlockResponseList
*head
, **tail
;
2735 Error
*local_err
= NULL
;
2740 while (mem_blks
!= NULL
) {
2741 GuestMemoryBlockResponse
*result
;
2742 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2744 result
= g_malloc0(sizeof(*result
));
2745 result
->phys_index
= current_mem_blk
->phys_index
;
2746 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2747 if (local_err
) { /* should never happen */
2751 QAPI_LIST_APPEND(tail
, result
);
2752 mem_blks
= mem_blks
->next
;
2757 qapi_free_GuestMemoryBlockResponseList(head
);
2758 error_propagate(errp
, local_err
);
2762 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2764 Error
*local_err
= NULL
;
2768 GuestMemoryBlockInfo
*info
;
2770 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2771 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2773 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2779 buf
= g_malloc0(20);
2780 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2784 error_propagate(errp
, local_err
);
2788 info
= g_new0(GuestMemoryBlockInfo
, 1);
2789 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2796 #define MAX_NAME_LEN 128
2797 static GuestDiskStatsInfoList
*guest_get_diskstats(Error
**errp
)
2800 GuestDiskStatsInfoList
*head
= NULL
, **tail
= &head
;
2801 const char *diskstats
= "/proc/diskstats";
2806 fp
= fopen(diskstats
, "r");
2808 error_setg_errno(errp
, errno
, "open(\"%s\")", diskstats
);
2812 while (getline(&line
, &n
, fp
) != -1) {
2813 g_autofree GuestDiskStatsInfo
*diskstatinfo
= NULL
;
2814 g_autofree GuestDiskStats
*diskstat
= NULL
;
2815 char dev_name
[MAX_NAME_LEN
];
2816 unsigned int ios_pgr
, tot_ticks
, rq_ticks
, wr_ticks
, dc_ticks
, fl_ticks
;
2817 unsigned long rd_ios
, rd_merges_or_rd_sec
, rd_ticks_or_wr_sec
, wr_ios
;
2818 unsigned long wr_merges
, rd_sec_or_wr_ios
, wr_sec
;
2819 unsigned long dc_ios
, dc_merges
, dc_sec
, fl_ios
;
2820 unsigned int major
, minor
;
2823 i
= sscanf(line
, "%u %u %s %lu %lu %lu"
2824 "%lu %lu %lu %lu %u %u %u %u"
2825 "%lu %lu %lu %u %lu %u",
2826 &major
, &minor
, dev_name
,
2827 &rd_ios
, &rd_merges_or_rd_sec
, &rd_sec_or_wr_ios
,
2828 &rd_ticks_or_wr_sec
, &wr_ios
, &wr_merges
, &wr_sec
,
2829 &wr_ticks
, &ios_pgr
, &tot_ticks
, &rq_ticks
,
2830 &dc_ios
, &dc_merges
, &dc_sec
, &dc_ticks
,
2831 &fl_ios
, &fl_ticks
);
2837 diskstatinfo
= g_new0(GuestDiskStatsInfo
, 1);
2838 diskstatinfo
->name
= g_strdup(dev_name
);
2839 diskstatinfo
->major
= major
;
2840 diskstatinfo
->minor
= minor
;
2842 diskstat
= g_new0(GuestDiskStats
, 1);
2844 diskstat
->has_read_ios
= true;
2845 diskstat
->read_ios
= rd_ios
;
2846 diskstat
->has_read_sectors
= true;
2847 diskstat
->read_sectors
= rd_merges_or_rd_sec
;
2848 diskstat
->has_write_ios
= true;
2849 diskstat
->write_ios
= rd_sec_or_wr_ios
;
2850 diskstat
->has_write_sectors
= true;
2851 diskstat
->write_sectors
= rd_ticks_or_wr_sec
;
2854 diskstat
->has_read_ios
= true;
2855 diskstat
->read_ios
= rd_ios
;
2856 diskstat
->has_read_sectors
= true;
2857 diskstat
->read_sectors
= rd_sec_or_wr_ios
;
2858 diskstat
->has_read_merges
= true;
2859 diskstat
->read_merges
= rd_merges_or_rd_sec
;
2860 diskstat
->has_read_ticks
= true;
2861 diskstat
->read_ticks
= rd_ticks_or_wr_sec
;
2862 diskstat
->has_write_ios
= true;
2863 diskstat
->write_ios
= wr_ios
;
2864 diskstat
->has_write_sectors
= true;
2865 diskstat
->write_sectors
= wr_sec
;
2866 diskstat
->has_write_merges
= true;
2867 diskstat
->write_merges
= wr_merges
;
2868 diskstat
->has_write_ticks
= true;
2869 diskstat
->write_ticks
= wr_ticks
;
2870 diskstat
->has_ios_pgr
= true;
2871 diskstat
->ios_pgr
= ios_pgr
;
2872 diskstat
->has_total_ticks
= true;
2873 diskstat
->total_ticks
= tot_ticks
;
2874 diskstat
->has_weight_ticks
= true;
2875 diskstat
->weight_ticks
= rq_ticks
;
2878 diskstat
->has_discard_ios
= true;
2879 diskstat
->discard_ios
= dc_ios
;
2880 diskstat
->has_discard_merges
= true;
2881 diskstat
->discard_merges
= dc_merges
;
2882 diskstat
->has_discard_sectors
= true;
2883 diskstat
->discard_sectors
= dc_sec
;
2884 diskstat
->has_discard_ticks
= true;
2885 diskstat
->discard_ticks
= dc_ticks
;
2888 diskstat
->has_flush_ios
= true;
2889 diskstat
->flush_ios
= fl_ios
;
2890 diskstat
->has_flush_ticks
= true;
2891 diskstat
->flush_ticks
= fl_ticks
;
2894 diskstatinfo
->stats
= g_steal_pointer(&diskstat
);
2895 QAPI_LIST_APPEND(tail
, diskstatinfo
);
2896 diskstatinfo
= NULL
;
2902 g_debug("disk stats reporting available only for Linux");
2907 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
2909 return guest_get_diskstats(errp
);
2912 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
2914 GuestCpuStatsList
*head
= NULL
, **tail
= &head
;
2915 const char *cpustats
= "/proc/stat";
2916 int clk_tck
= sysconf(_SC_CLK_TCK
);
2921 fp
= fopen(cpustats
, "r");
2923 error_setg_errno(errp
, errno
, "open(\"%s\")", cpustats
);
2927 while (getline(&line
, &n
, fp
) != -1) {
2928 GuestCpuStats
*cpustat
= NULL
;
2929 GuestLinuxCpuStats
*linuxcpustat
;
2931 unsigned long user
, system
, idle
, iowait
, irq
, softirq
, steal
, guest
;
2932 unsigned long nice
, guest_nice
;
2935 i
= sscanf(line
, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2936 name
, &user
, &nice
, &system
, &idle
, &iowait
, &irq
, &softirq
,
2937 &steal
, &guest
, &guest_nice
);
2939 /* drop "cpu 1 2 3 ...", get "cpuX 1 2 3 ..." only */
2940 if ((i
== EOF
) || strncmp(name
, "cpu", 3) || (name
[3] == '\0')) {
2945 slog("Parsing cpu stat from %s failed, see \"man proc\"", cpustats
);
2949 cpustat
= g_new0(GuestCpuStats
, 1);
2950 cpustat
->type
= GUEST_CPU_STATS_TYPE_LINUX
;
2952 linuxcpustat
= &cpustat
->u
.q_linux
;
2953 linuxcpustat
->cpu
= atoi(&name
[3]);
2954 linuxcpustat
->user
= user
* 1000 / clk_tck
;
2955 linuxcpustat
->nice
= nice
* 1000 / clk_tck
;
2956 linuxcpustat
->system
= system
* 1000 / clk_tck
;
2957 linuxcpustat
->idle
= idle
* 1000 / clk_tck
;
2960 linuxcpustat
->has_iowait
= true;
2961 linuxcpustat
->iowait
= iowait
* 1000 / clk_tck
;
2965 linuxcpustat
->has_irq
= true;
2966 linuxcpustat
->irq
= irq
* 1000 / clk_tck
;
2967 linuxcpustat
->has_softirq
= true;
2968 linuxcpustat
->softirq
= softirq
* 1000 / clk_tck
;
2972 linuxcpustat
->has_steal
= true;
2973 linuxcpustat
->steal
= steal
* 1000 / clk_tck
;
2977 linuxcpustat
->has_guest
= true;
2978 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2982 linuxcpustat
->has_guest
= true;
2983 linuxcpustat
->guest
= guest
* 1000 / clk_tck
;
2984 linuxcpustat
->has_guestnice
= true;
2985 linuxcpustat
->guestnice
= guest_nice
* 1000 / clk_tck
;
2988 QAPI_LIST_APPEND(tail
, cpustat
);
2996 #else /* defined(__linux__) */
2998 void qmp_guest_suspend_disk(Error
**errp
)
3000 error_setg(errp
, QERR_UNSUPPORTED
);
3003 void qmp_guest_suspend_ram(Error
**errp
)
3005 error_setg(errp
, QERR_UNSUPPORTED
);
3008 void qmp_guest_suspend_hybrid(Error
**errp
)
3010 error_setg(errp
, QERR_UNSUPPORTED
);
3013 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
3015 error_setg(errp
, QERR_UNSUPPORTED
);
3019 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
3021 error_setg(errp
, QERR_UNSUPPORTED
);
3025 void qmp_guest_set_user_password(const char *username
,
3026 const char *password
,
3030 error_setg(errp
, QERR_UNSUPPORTED
);
3033 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
3035 error_setg(errp
, QERR_UNSUPPORTED
);
3039 GuestMemoryBlockResponseList
*
3040 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
3042 error_setg(errp
, QERR_UNSUPPORTED
);
3046 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
3048 error_setg(errp
, QERR_UNSUPPORTED
);
3054 #ifdef HAVE_GETIFADDRS
3055 static GuestNetworkInterface
*
3056 guest_find_interface(GuestNetworkInterfaceList
*head
,
3059 for (; head
; head
= head
->next
) {
3060 if (strcmp(head
->value
->name
, name
) == 0) {
3068 static int guest_get_network_stats(const char *name
,
3069 GuestNetworkInterfaceStat
*stats
)
3073 char const *devinfo
= "/proc/net/dev";
3075 char *line
= NULL
, *colon
;
3077 fp
= fopen(devinfo
, "r");
3079 g_debug("failed to open network stats %s: %s", devinfo
,
3083 name_len
= strlen(name
);
3084 while (getline(&line
, &n
, fp
) != -1) {
3087 long long rx_packets
;
3089 long long rx_dropped
;
3091 long long tx_packets
;
3093 long long tx_dropped
;
3095 trim_line
= g_strchug(line
);
3096 if (trim_line
[0] == '\0') {
3099 colon
= strchr(trim_line
, ':');
3103 if (colon
- name_len
== trim_line
&&
3104 strncmp(trim_line
, name
, name_len
) == 0) {
3105 if (sscanf(colon
+ 1,
3106 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
3107 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
3108 &dummy
, &dummy
, &dummy
, &dummy
,
3109 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
3110 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
3113 stats
->rx_bytes
= rx_bytes
;
3114 stats
->rx_packets
= rx_packets
;
3115 stats
->rx_errs
= rx_errs
;
3116 stats
->rx_dropped
= rx_dropped
;
3117 stats
->tx_bytes
= tx_bytes
;
3118 stats
->tx_packets
= tx_packets
;
3119 stats
->tx_errs
= tx_errs
;
3120 stats
->tx_dropped
= tx_dropped
;
3128 g_debug("/proc/net/dev: Interface '%s' not found", name
);
3129 #else /* !CONFIG_LINUX */
3130 g_debug("Network stats reporting available only for Linux");
3131 #endif /* !CONFIG_LINUX */
3136 * Build information about guest interfaces
3138 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
3140 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
3141 struct ifaddrs
*ifap
, *ifa
;
3143 if (getifaddrs(&ifap
) < 0) {
3144 error_setg_errno(errp
, errno
, "getifaddrs failed");
3148 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
3149 GuestNetworkInterface
*info
;
3150 GuestIpAddressList
**address_tail
;
3151 GuestIpAddress
*address_item
= NULL
;
3152 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
3153 char addr4
[INET_ADDRSTRLEN
];
3154 char addr6
[INET6_ADDRSTRLEN
];
3157 unsigned char *mac_addr
;
3160 g_debug("Processing %s interface", ifa
->ifa_name
);
3162 info
= guest_find_interface(head
, ifa
->ifa_name
);
3165 info
= g_malloc0(sizeof(*info
));
3166 info
->name
= g_strdup(ifa
->ifa_name
);
3168 QAPI_LIST_APPEND(tail
, info
);
3171 if (!info
->has_hardware_address
) {
3172 /* we haven't obtained HW address yet */
3173 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
3175 error_setg_errno(errp
, errno
, "failed to create socket");
3179 memset(&ifr
, 0, sizeof(ifr
));
3180 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->name
);
3181 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
3183 * We can't get the hw addr of this interface, but that's not a
3184 * fatal error. Don't set info->hardware_address, but keep
3187 if (errno
== EADDRNOTAVAIL
) {
3188 /* The interface doesn't have a hw addr (e.g. loopback). */
3189 g_debug("failed to get MAC address of %s: %s",
3190 ifa
->ifa_name
, strerror(errno
));
3192 g_warning("failed to get MAC address of %s: %s",
3193 ifa
->ifa_name
, strerror(errno
));
3197 #ifdef CONFIG_SOLARIS
3198 mac_addr
= (unsigned char *) &ifr
.ifr_addr
.sa_data
;
3200 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
3202 info
->hardware_address
=
3203 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
3204 (int) mac_addr
[0], (int) mac_addr
[1],
3205 (int) mac_addr
[2], (int) mac_addr
[3],
3206 (int) mac_addr
[4], (int) mac_addr
[5]);
3208 info
->has_hardware_address
= true;
3213 if (ifa
->ifa_addr
&&
3214 ifa
->ifa_addr
->sa_family
== AF_INET
) {
3215 /* interface with IPv4 address */
3216 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
3217 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
3218 error_setg_errno(errp
, errno
, "inet_ntop failed");
3222 address_item
= g_malloc0(sizeof(*address_item
));
3223 address_item
->ip_address
= g_strdup(addr4
);
3224 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
3226 if (ifa
->ifa_netmask
) {
3227 /* Count the number of set bits in netmask.
3228 * This is safe as '1' and '0' cannot be shuffled in netmask. */
3229 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
3230 address_item
->prefix
= ctpop32(((uint32_t *) p
)[0]);
3232 } else if (ifa
->ifa_addr
&&
3233 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
3234 /* interface with IPv6 address */
3235 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
3236 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
3237 error_setg_errno(errp
, errno
, "inet_ntop failed");
3241 address_item
= g_malloc0(sizeof(*address_item
));
3242 address_item
->ip_address
= g_strdup(addr6
);
3243 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
3245 if (ifa
->ifa_netmask
) {
3246 /* Count the number of set bits in netmask.
3247 * This is safe as '1' and '0' cannot be shuffled in netmask. */
3248 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
3249 address_item
->prefix
=
3250 ctpop32(((uint32_t *) p
)[0]) +
3251 ctpop32(((uint32_t *) p
)[1]) +
3252 ctpop32(((uint32_t *) p
)[2]) +
3253 ctpop32(((uint32_t *) p
)[3]);
3257 if (!address_item
) {
3261 address_tail
= &info
->ip_addresses
;
3262 while (*address_tail
) {
3263 address_tail
= &(*address_tail
)->next
;
3265 QAPI_LIST_APPEND(address_tail
, address_item
);
3267 info
->has_ip_addresses
= true;
3269 if (!info
->has_statistics
) {
3270 interface_stat
= g_malloc0(sizeof(*interface_stat
));
3271 if (guest_get_network_stats(info
->name
, interface_stat
) == -1) {
3272 info
->has_statistics
= false;
3273 g_free(interface_stat
);
3275 info
->statistics
= interface_stat
;
3276 info
->has_statistics
= true;
3286 qapi_free_GuestNetworkInterfaceList(head
);
3292 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
3294 error_setg(errp
, QERR_UNSUPPORTED
);
3298 #endif /* HAVE_GETIFADDRS */
3300 #if !defined(CONFIG_FSFREEZE)
3302 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
3304 error_setg(errp
, QERR_UNSUPPORTED
);
3308 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
3310 error_setg(errp
, QERR_UNSUPPORTED
);
3315 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
3317 error_setg(errp
, QERR_UNSUPPORTED
);
3322 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
3323 strList
*mountpoints
,
3326 error_setg(errp
, QERR_UNSUPPORTED
);
3331 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
3333 error_setg(errp
, QERR_UNSUPPORTED
);
3338 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
3340 error_setg(errp
, QERR_UNSUPPORTED
);
3344 GuestDiskStatsInfoList
*qmp_guest_get_diskstats(Error
**errp
)
3346 error_setg(errp
, QERR_UNSUPPORTED
);
3350 GuestCpuStatsList
*qmp_guest_get_cpustats(Error
**errp
)
3352 error_setg(errp
, QERR_UNSUPPORTED
);
3356 #endif /* CONFIG_FSFREEZE */
3358 #if !defined(CONFIG_FSTRIM)
3359 GuestFilesystemTrimResponse
*
3360 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
3362 error_setg(errp
, QERR_UNSUPPORTED
);
3367 /* add unsupported commands to the list of blocked RPCs */
3368 GList
*ga_command_init_blockedrpcs(GList
*blockedrpcs
)
3370 #if !defined(__linux__)
3372 const char *list
[] = {
3373 "guest-suspend-disk", "guest-suspend-ram",
3374 "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
3375 "guest-get-memory-blocks", "guest-set-memory-blocks",
3376 "guest-get-memory-block-size", "guest-get-memory-block-info",
3378 char **p
= (char **)list
;
3381 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3386 #if !defined(HAVE_GETIFADDRS)
3387 blockedrpcs
= g_list_append(blockedrpcs
,
3388 g_strdup("guest-network-get-interfaces"));
3391 #if !defined(CONFIG_FSFREEZE)
3393 const char *list
[] = {
3394 "guest-get-fsinfo", "guest-fsfreeze-status",
3395 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3396 "guest-fsfreeze-thaw", "guest-get-fsinfo",
3397 "guest-get-disks", NULL
};
3398 char **p
= (char **)list
;
3401 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup(*p
++));
3406 #if !defined(CONFIG_FSTRIM)
3407 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-fstrim"));
3410 blockedrpcs
= g_list_append(blockedrpcs
, g_strdup("guest-get-devices"));
3415 /* register init/cleanup routines for stateful command groups */
3416 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
3418 #if defined(CONFIG_FSFREEZE)
3419 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
3425 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3427 static double ga_get_login_time(struct utmpx
*user_info
)
3429 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
3430 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
3431 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
3432 return seconds
+ useconds
;
3435 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3437 GHashTable
*cache
= NULL
;
3438 GuestUserList
*head
= NULL
, **tail
= &head
;
3439 struct utmpx
*user_info
= NULL
;
3440 gpointer value
= NULL
;
3441 GuestUser
*user
= NULL
;
3442 double login_time
= 0;
3444 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
3448 user_info
= getutxent();
3449 if (user_info
== NULL
) {
3451 } else if (user_info
->ut_type
!= USER_PROCESS
) {
3453 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
3454 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
3455 user
= (GuestUser
*)value
;
3456 login_time
= ga_get_login_time(user_info
);
3457 /* We're ensuring the earliest login time to be sent */
3458 if (login_time
< user
->login_time
) {
3459 user
->login_time
= login_time
;
3464 user
= g_new0(GuestUser
, 1);
3465 user
->user
= g_strdup(user_info
->ut_user
);
3466 user
->login_time
= ga_get_login_time(user_info
);
3468 g_hash_table_insert(cache
, user
->user
, user
);
3470 QAPI_LIST_APPEND(tail
, user
);
3473 g_hash_table_destroy(cache
);
3479 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3481 error_setg(errp
, QERR_UNSUPPORTED
);
3487 /* Replace escaped special characters with theire real values. The replacement
3488 * is done in place -- returned value is in the original string.
3490 static void ga_osrelease_replace_special(gchar
*value
)
3492 gchar
*p
, *p2
, quote
;
3494 /* Trim the string at first space or semicolon if it is not enclosed in
3495 * single or double quotes. */
3496 if ((value
[0] != '"') || (value
[0] == '\'')) {
3497 p
= strchr(value
, ' ');
3501 p
= strchr(value
, ';');
3522 /* Keep literal backslash followed by whatever is there */
3526 } else if (*p
== quote
) {
3534 static GKeyFile
*ga_parse_osrelease(const char *fname
)
3536 gchar
*content
= NULL
;
3537 gchar
*content2
= NULL
;
3539 GKeyFile
*keys
= g_key_file_new();
3540 const char *group
= "[os-release]\n";
3542 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
3543 slog("failed to read '%s', error: %s", fname
, err
->message
);
3547 if (!g_utf8_validate(content
, -1, NULL
)) {
3548 slog("file is not utf-8 encoded: %s", fname
);
3551 content2
= g_strdup_printf("%s%s", group
, content
);
3553 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
3555 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
3567 g_key_file_free(keys
);
3571 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
3573 GuestOSInfo
*info
= NULL
;
3574 struct utsname kinfo
;
3575 GKeyFile
*osrelease
= NULL
;
3576 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
3578 info
= g_new0(GuestOSInfo
, 1);
3580 if (uname(&kinfo
) != 0) {
3581 error_setg_errno(errp
, errno
, "uname failed");
3583 info
->has_kernel_version
= true;
3584 info
->kernel_version
= g_strdup(kinfo
.version
);
3585 info
->has_kernel_release
= true;
3586 info
->kernel_release
= g_strdup(kinfo
.release
);
3587 info
->has_machine
= true;
3588 info
->machine
= g_strdup(kinfo
.machine
);
3591 if (qga_os_release
!= NULL
) {
3592 osrelease
= ga_parse_osrelease(qga_os_release
);
3594 osrelease
= ga_parse_osrelease("/etc/os-release");
3595 if (osrelease
== NULL
) {
3596 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
3600 if (osrelease
!= NULL
) {
3603 #define GET_FIELD(field, osfield) do { \
3604 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3605 if (value != NULL) { \
3606 ga_osrelease_replace_special(value); \
3607 info->has_ ## field = true; \
3608 info->field = value; \
3611 GET_FIELD(id
, "ID");
3612 GET_FIELD(name
, "NAME");
3613 GET_FIELD(pretty_name
, "PRETTY_NAME");
3614 GET_FIELD(version
, "VERSION");
3615 GET_FIELD(version_id
, "VERSION_ID");
3616 GET_FIELD(variant
, "VARIANT");
3617 GET_FIELD(variant_id
, "VARIANT_ID");
3620 g_key_file_free(osrelease
);
3626 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
3628 error_setg(errp
, QERR_UNSUPPORTED
);
3633 #ifndef HOST_NAME_MAX
3634 # ifdef _POSIX_HOST_NAME_MAX
3635 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
3637 # define HOST_NAME_MAX 255
3641 char *qga_get_host_name(Error
**errp
)
3644 g_autofree
char *hostname
= NULL
;
3646 #ifdef _SC_HOST_NAME_MAX
3647 len
= sysconf(_SC_HOST_NAME_MAX
);
3648 #endif /* _SC_HOST_NAME_MAX */
3651 len
= HOST_NAME_MAX
;
3654 /* Unfortunately, gethostname() below does not guarantee a
3655 * NULL terminated string. Therefore, allocate one byte more
3657 hostname
= g_new0(char, len
+ 1);
3659 if (gethostname(hostname
, len
) < 0) {
3660 error_setg_errno(errp
, errno
,
3661 "cannot get hostname");
3665 return g_steal_pointer(&hostname
);