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"
34 #if defined(__linux__)
37 #include <sys/statvfs.h>
44 #define CONFIG_FSFREEZE
51 #ifdef HAVE_GETIFADDRS
52 #include <arpa/inet.h>
53 #include <sys/socket.h>
55 #include <sys/types.h>
58 #include <sys/sockio.h>
62 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
69 rpid
= waitpid(pid
, status
, 0);
70 } while (rpid
== -1 && errno
== EINTR
);
73 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
78 g_assert(rpid
== pid
);
81 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
83 const char *shutdown_flag
;
84 Error
*local_err
= NULL
;
89 const char *powerdown_flag
= "-i5";
90 const char *halt_flag
= "-i0";
91 const char *reboot_flag
= "-i6";
93 const char *powerdown_flag
= "-P";
94 const char *halt_flag
= "-H";
95 const char *reboot_flag
= "-r";
98 slog("guest-shutdown called, mode: %s", mode
);
99 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
100 shutdown_flag
= powerdown_flag
;
101 } else if (strcmp(mode
, "halt") == 0) {
102 shutdown_flag
= halt_flag
;
103 } else if (strcmp(mode
, "reboot") == 0) {
104 shutdown_flag
= reboot_flag
;
107 "mode is invalid (valid values are: halt|powerdown|reboot");
113 /* child, start the shutdown */
115 reopen_fd_to_null(0);
116 reopen_fd_to_null(1);
117 reopen_fd_to_null(2);
119 #ifdef CONFIG_SOLARIS
120 execl("/sbin/shutdown", "shutdown", shutdown_flag
, "-g0", "-y",
121 "hypervisor initiated shutdown", (char *)NULL
);
123 execl("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
124 "hypervisor initiated shutdown", (char *)NULL
);
127 } else if (pid
< 0) {
128 error_setg_errno(errp
, errno
, "failed to create child process");
132 ga_wait_child(pid
, &status
, &local_err
);
134 error_propagate(errp
, local_err
);
138 if (!WIFEXITED(status
)) {
139 error_setg(errp
, "child process has terminated abnormally");
143 if (WEXITSTATUS(status
)) {
144 error_setg(errp
, "child process has failed to shutdown");
151 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
156 Error
*local_err
= NULL
;
158 static const char hwclock_path
[] = "/sbin/hwclock";
159 static int hwclock_available
= -1;
161 if (hwclock_available
< 0) {
162 hwclock_available
= (access(hwclock_path
, X_OK
) == 0);
165 if (!hwclock_available
) {
166 error_setg(errp
, QERR_UNSUPPORTED
);
170 /* If user has passed a time, validate and set it. */
174 /* year-2038 will overflow in case time_t is 32bit */
175 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
176 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
180 tv
.tv_sec
= time_ns
/ 1000000000;
181 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
182 g_date_set_time_t(&date
, tv
.tv_sec
);
183 if (date
.year
< 1970 || date
.year
>= 2070) {
184 error_setg_errno(errp
, errno
, "Invalid time");
188 ret
= settimeofday(&tv
, NULL
);
190 error_setg_errno(errp
, errno
, "Failed to set time to guest");
195 /* Now, if user has passed a time to set and the system time is set, we
196 * just need to synchronize the hardware clock. However, if no time was
197 * passed, user is requesting the opposite: set the system time from the
198 * hardware clock (RTC). */
202 reopen_fd_to_null(0);
203 reopen_fd_to_null(1);
204 reopen_fd_to_null(2);
206 /* Use '/sbin/hwclock -w' to set RTC from the system time,
207 * or '/sbin/hwclock -s' to set the system time from RTC. */
208 execl(hwclock_path
, "hwclock", has_time
? "-w" : "-s", NULL
);
210 } else if (pid
< 0) {
211 error_setg_errno(errp
, errno
, "failed to create child process");
215 ga_wait_child(pid
, &status
, &local_err
);
217 error_propagate(errp
, local_err
);
221 if (!WIFEXITED(status
)) {
222 error_setg(errp
, "child process has terminated abnormally");
226 if (WEXITSTATUS(status
)) {
227 error_setg(errp
, "hwclock failed to set hardware clock to system time");
238 struct GuestFileHandle
{
242 QTAILQ_ENTRY(GuestFileHandle
) next
;
246 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
247 } guest_file_state
= {
248 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
251 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
253 GuestFileHandle
*gfh
;
256 handle
= ga_get_fd_handle(ga_state
, errp
);
261 gfh
= g_new0(GuestFileHandle
, 1);
264 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
269 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
271 GuestFileHandle
*gfh
;
273 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
280 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
284 typedef const char * const ccpc
;
290 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
291 static const struct {
294 } guest_file_open_modes
[] = {
295 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
296 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
297 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
298 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
299 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
300 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
301 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
302 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
303 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
304 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
305 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
306 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
310 find_open_flag(const char *mode_str
, Error
**errp
)
314 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
317 form
= guest_file_open_modes
[mode
].forms
;
318 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
326 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
327 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
330 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
333 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
334 S_IRGRP | S_IWGRP | \
338 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
340 Error
*local_err
= NULL
;
343 oflag
= find_open_flag(mode
, &local_err
);
344 if (local_err
== NULL
) {
347 /* If the caller wants / allows creation of a new file, we implement it
348 * with a two step process: open() + (open() / fchmod()).
350 * First we insist on creating the file exclusively as a new file. If
351 * that succeeds, we're free to set any file-mode bits on it. (The
352 * motivation is that we want to set those file-mode bits independently
353 * of the current umask.)
355 * If the exclusive creation fails because the file already exists
356 * (EEXIST is not possible for any other reason), we just attempt to
357 * open the file, but in this case we won't be allowed to change the
358 * file-mode bits on the preexistent file.
360 * The pathname should never disappear between the two open()s in
361 * practice. If it happens, then someone very likely tried to race us.
362 * In this case just go ahead and report the ENOENT from the second
363 * open() to the caller.
365 * If the caller wants to open a preexistent file, then the first
366 * open() is decisive and its third argument is ignored, and the second
367 * open() and the fchmod() are never called.
369 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
370 if (fd
== -1 && errno
== EEXIST
) {
371 oflag
&= ~(unsigned)O_CREAT
;
372 fd
= open(path
, oflag
);
376 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
377 "(mode: '%s')", path
, mode
);
379 qemu_set_cloexec(fd
);
381 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
382 error_setg_errno(&local_err
, errno
, "failed to set permission "
383 "0%03o on new file '%s' (mode: '%s')",
384 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
388 f
= fdopen(fd
, mode
);
390 error_setg_errno(&local_err
, errno
, "failed to associate "
391 "stdio stream with file descriptor %d, "
392 "file '%s' (mode: '%s')", fd
, path
, mode
);
399 if (oflag
& O_CREAT
) {
405 error_propagate(errp
, local_err
);
409 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
413 Error
*local_err
= NULL
;
419 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
420 fh
= safe_open_or_create(path
, mode
, &local_err
);
421 if (local_err
!= NULL
) {
422 error_propagate(errp
, local_err
);
426 /* set fd non-blocking to avoid common use cases (like reading from a
427 * named pipe) from hanging the agent
429 if (!g_unix_set_fd_nonblocking(fileno(fh
), true, NULL
)) {
431 error_setg_errno(errp
, errno
, "Failed to set FD nonblocking");
435 handle
= guest_file_handle_add(fh
, errp
);
441 slog("guest-file-open, handle: %" PRId64
, handle
);
445 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
447 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
450 slog("guest-file-close called, handle: %" PRId64
, handle
);
455 ret
= fclose(gfh
->fh
);
457 error_setg_errno(errp
, errno
, "failed to close handle");
461 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
465 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
466 int64_t count
, Error
**errp
)
468 GuestFileRead
*read_data
= NULL
;
473 /* explicitly flush when switching from writing to reading */
474 if (gfh
->state
== RW_STATE_WRITING
) {
475 int ret
= fflush(fh
);
477 error_setg_errno(errp
, errno
, "failed to flush file");
480 gfh
->state
= RW_STATE_NEW
;
483 buf
= g_malloc0(count
+ 1);
484 read_count
= fread(buf
, 1, count
, fh
);
486 error_setg_errno(errp
, errno
, "failed to read file");
489 read_data
= g_new0(GuestFileRead
, 1);
490 read_data
->count
= read_count
;
491 read_data
->eof
= feof(fh
);
493 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
495 gfh
->state
= RW_STATE_READING
;
503 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
504 bool has_count
, int64_t count
,
507 GuestFileWrite
*write_data
= NULL
;
511 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
520 if (gfh
->state
== RW_STATE_READING
) {
521 int ret
= fseek(fh
, 0, SEEK_CUR
);
523 error_setg_errno(errp
, errno
, "failed to seek file");
526 gfh
->state
= RW_STATE_NEW
;
529 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
536 } else if (count
< 0 || count
> buf_len
) {
537 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
543 write_count
= fwrite(buf
, 1, count
, fh
);
545 error_setg_errno(errp
, errno
, "failed to write to file");
546 slog("guest-file-write failed, handle: %" PRId64
, handle
);
548 write_data
= g_new0(GuestFileWrite
, 1);
549 write_data
->count
= write_count
;
550 write_data
->eof
= feof(fh
);
551 gfh
->state
= RW_STATE_WRITING
;
559 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
560 GuestFileWhence
*whence_code
,
563 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
564 GuestFileSeek
*seek_data
= NULL
;
574 /* We stupidly exposed 'whence':'int' in our qapi */
575 whence
= ga_parse_whence(whence_code
, &err
);
577 error_propagate(errp
, err
);
582 ret
= fseek(fh
, offset
, whence
);
584 error_setg_errno(errp
, errno
, "failed to seek file");
585 if (errno
== ESPIPE
) {
586 /* file is non-seekable, stdio shouldn't be buffering anyways */
587 gfh
->state
= RW_STATE_NEW
;
590 seek_data
= g_new0(GuestFileSeek
, 1);
591 seek_data
->position
= ftell(fh
);
592 seek_data
->eof
= feof(fh
);
593 gfh
->state
= RW_STATE_NEW
;
600 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
602 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
613 error_setg_errno(errp
, errno
, "failed to flush file");
615 gfh
->state
= RW_STATE_NEW
;
619 /* linux-specific implementations. avoid this if at all possible. */
620 #if defined(__linux__)
622 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
623 typedef struct FsMount
{
626 unsigned int devmajor
, devminor
;
627 QTAILQ_ENTRY(FsMount
) next
;
630 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
632 static void free_fs_mount_list(FsMountList
*mounts
)
634 FsMount
*mount
, *temp
;
640 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
641 QTAILQ_REMOVE(mounts
, mount
, next
);
642 g_free(mount
->dirname
);
643 g_free(mount
->devtype
);
648 static int dev_major_minor(const char *devpath
,
649 unsigned int *devmajor
, unsigned int *devminor
)
656 if (stat(devpath
, &st
) < 0) {
657 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
660 if (S_ISDIR(st
.st_mode
)) {
661 /* It is bind mount */
664 if (S_ISBLK(st
.st_mode
)) {
665 *devmajor
= major(st
.st_rdev
);
666 *devminor
= minor(st
.st_rdev
);
673 * Walk the mount table and build a list of local file systems
675 static void build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
679 char const *mtab
= "/proc/self/mounts";
681 unsigned int devmajor
, devminor
;
683 fp
= setmntent(mtab
, "r");
685 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
689 while ((ment
= getmntent(fp
))) {
691 * An entry which device name doesn't start with a '/' is
692 * either a dummy file system or a network file system.
693 * Add special handling for smbfs and cifs as is done by
696 if ((ment
->mnt_fsname
[0] != '/') ||
697 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
698 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
701 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
702 /* Skip bind mounts */
706 mount
= g_new0(FsMount
, 1);
707 mount
->dirname
= g_strdup(ment
->mnt_dir
);
708 mount
->devtype
= g_strdup(ment
->mnt_type
);
709 mount
->devmajor
= devmajor
;
710 mount
->devminor
= devminor
;
712 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
718 static void decode_mntname(char *name
, int len
)
721 for (i
= 0; i
<= len
; i
++) {
722 if (name
[i
] != '\\') {
724 } else if (name
[i
+ 1] == '\\') {
727 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
728 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
729 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
730 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
731 (name
[i
+ 2] - '0') * 8 +
740 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
743 char const *mountinfo
= "/proc/self/mountinfo";
745 char *line
= NULL
, *dash
;
748 unsigned int devmajor
, devminor
;
749 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
751 fp
= fopen(mountinfo
, "r");
753 build_fs_mount_list_from_mtab(mounts
, errp
);
757 while (getline(&line
, &n
, fp
) != -1) {
758 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
759 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
763 dash
= strstr(line
+ dir_e
, " - ");
767 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
768 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
775 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
776 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
778 /* btrfs reports major number = 0 */
779 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
780 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
785 mount
= g_new0(FsMount
, 1);
786 mount
->dirname
= g_strdup(line
+ dir_s
);
787 mount
->devtype
= g_strdup(dash
+ type_s
);
788 mount
->devmajor
= devmajor
;
789 mount
->devminor
= devminor
;
791 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
799 #if defined(CONFIG_FSFREEZE)
801 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
809 path
= g_strndup(syspath
, pathlen
);
810 dpath
= g_strdup_printf("%s/driver", path
);
811 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
814 driver
= g_path_get_basename(buf
);
821 static int compare_uint(const void *_a
, const void *_b
)
823 unsigned int a
= *(unsigned int *)_a
;
824 unsigned int b
= *(unsigned int *)_b
;
826 return a
< b
? -1 : a
> b
? 1 : 0;
829 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
830 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
831 unsigned int *hosts
, int hosts_max
, Error
**errp
)
835 struct dirent
*entry
;
838 path
= g_strndup(syspath
, host
- syspath
);
841 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
846 while (i
< hosts_max
) {
847 entry
= readdir(dir
);
851 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
853 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
858 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
866 * Store disk device info for devices on the PCI bus.
867 * Returns true if information has been stored, or false for failure.
869 static bool build_guest_fsinfo_for_pci_dev(char const *syspath
,
870 GuestDiskAddress
*disk
,
873 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
874 int i
, nhosts
= 0, pcilen
;
875 GuestPCIAddress
*pciaddr
= disk
->pci_controller
;
876 bool has_ata
= false, has_host
= false, has_tgt
= false;
877 char *p
, *q
, *driver
= NULL
;
880 p
= strstr(syspath
, "/devices/pci");
881 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
882 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
883 g_debug("only pci device is supported: sysfs path '%s'", syspath
);
889 driver
= get_pci_driver(syspath
, p
- syspath
, errp
);
890 if (driver
&& (g_str_equal(driver
, "ata_piix") ||
891 g_str_equal(driver
, "sym53c8xx") ||
892 g_str_equal(driver
, "virtio-pci") ||
893 g_str_equal(driver
, "ahci") ||
894 g_str_equal(driver
, "nvme"))) {
899 if (sscanf(p
, "/%x:%x:%x.%x%n",
900 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
905 g_debug("unsupported driver or sysfs path '%s'", syspath
);
909 p
= strstr(syspath
, "/target");
910 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
911 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
915 p
= strstr(syspath
, "/ata");
920 p
= strstr(syspath
, "/host");
923 if (p
&& sscanf(q
, "%u", &host
) == 1) {
925 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
926 ARRAY_SIZE(hosts
), errp
);
932 pciaddr
->domain
= pci
[0];
933 pciaddr
->bus
= pci
[1];
934 pciaddr
->slot
= pci
[2];
935 pciaddr
->function
= pci
[3];
937 if (strcmp(driver
, "ata_piix") == 0) {
938 /* a host per ide bus, target*:0:<unit>:0 */
939 if (!has_host
|| !has_tgt
) {
940 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
943 for (i
= 0; i
< nhosts
; i
++) {
944 if (host
== hosts
[i
]) {
945 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
952 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
955 } else if (strcmp(driver
, "sym53c8xx") == 0) {
956 /* scsi(LSI Logic): target*:0:<unit>:0 */
958 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
961 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
963 } else if (strcmp(driver
, "virtio-pci") == 0) {
965 /* virtio-scsi: target*:0:0:<unit> */
966 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
969 /* virtio-blk: 1 disk per 1 device */
970 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
972 } else if (strcmp(driver
, "ahci") == 0) {
973 /* ahci: 1 host per 1 unit */
974 if (!has_host
|| !has_tgt
) {
975 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
978 for (i
= 0; i
< nhosts
; i
++) {
979 if (host
== hosts
[i
]) {
981 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
986 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
989 } else if (strcmp(driver
, "nvme") == 0) {
990 disk
->bus_type
= GUEST_DISK_BUS_TYPE_NVME
;
992 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
1004 * Store disk device info for non-PCI virtio devices (for example s390x
1005 * channel I/O devices). Returns true if information has been stored, or
1006 * false for failure.
1008 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath
,
1009 GuestDiskAddress
*disk
,
1012 unsigned int tgt
[3];
1015 if (!strstr(syspath
, "/virtio") || !strstr(syspath
, "/block")) {
1016 g_debug("Unsupported virtio device '%s'", syspath
);
1020 p
= strstr(syspath
, "/target");
1021 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1022 &tgt
[0], &tgt
[1], &tgt
[2]) == 3) {
1023 /* virtio-scsi: target*:0:<target>:<unit> */
1024 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1026 disk
->target
= tgt
[1];
1027 disk
->unit
= tgt
[2];
1029 /* virtio-blk: 1 disk per 1 device */
1030 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
1037 * Store disk device info for CCW devices (s390x channel I/O devices).
1038 * Returns true if information has been stored, or false for failure.
1040 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath
,
1041 GuestDiskAddress
*disk
,
1044 unsigned int cssid
, ssid
, subchno
, devno
;
1047 p
= strstr(syspath
, "/devices/css");
1048 if (!p
|| sscanf(p
+ 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1049 &cssid
, &ssid
, &subchno
, &devno
) < 4) {
1050 g_debug("could not parse ccw device sysfs path: %s", syspath
);
1054 disk
->has_ccw_address
= true;
1055 disk
->ccw_address
= g_new0(GuestCCWAddress
, 1);
1056 disk
->ccw_address
->cssid
= cssid
;
1057 disk
->ccw_address
->ssid
= ssid
;
1058 disk
->ccw_address
->subchno
= subchno
;
1059 disk
->ccw_address
->devno
= devno
;
1061 if (strstr(p
, "/virtio")) {
1062 build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1068 /* Store disk device info specified by @sysfs into @fs */
1069 static void build_guest_fsinfo_for_real_device(char const *syspath
,
1070 GuestFilesystemInfo
*fs
,
1073 GuestDiskAddress
*disk
;
1074 GuestPCIAddress
*pciaddr
;
1076 #ifdef CONFIG_LIBUDEV
1077 struct udev
*udev
= NULL
;
1078 struct udev_device
*udevice
= NULL
;
1081 pciaddr
= g_new0(GuestPCIAddress
, 1);
1082 pciaddr
->domain
= -1; /* -1 means field is invalid */
1085 pciaddr
->function
= -1;
1087 disk
= g_new0(GuestDiskAddress
, 1);
1088 disk
->pci_controller
= pciaddr
;
1089 disk
->bus_type
= GUEST_DISK_BUS_TYPE_UNKNOWN
;
1091 #ifdef CONFIG_LIBUDEV
1093 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1094 if (udev
== NULL
|| udevice
== NULL
) {
1095 g_debug("failed to query udev");
1097 const char *devnode
, *serial
;
1098 devnode
= udev_device_get_devnode(udevice
);
1099 if (devnode
!= NULL
) {
1100 disk
->dev
= g_strdup(devnode
);
1101 disk
->has_dev
= true;
1103 serial
= udev_device_get_property_value(udevice
, "ID_SERIAL");
1104 if (serial
!= NULL
&& *serial
!= 0) {
1105 disk
->serial
= g_strdup(serial
);
1106 disk
->has_serial
= true;
1111 udev_device_unref(udevice
);
1114 if (strstr(syspath
, "/devices/pci")) {
1115 has_hwinf
= build_guest_fsinfo_for_pci_dev(syspath
, disk
, errp
);
1116 } else if (strstr(syspath
, "/devices/css")) {
1117 has_hwinf
= build_guest_fsinfo_for_ccw_dev(syspath
, disk
, errp
);
1118 } else if (strstr(syspath
, "/virtio")) {
1119 has_hwinf
= build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1121 g_debug("Unsupported device type for '%s'", syspath
);
1125 if (has_hwinf
|| disk
->has_dev
|| disk
->has_serial
) {
1126 QAPI_LIST_PREPEND(fs
->disk
, disk
);
1128 qapi_free_GuestDiskAddress(disk
);
1132 static void build_guest_fsinfo_for_device(char const *devpath
,
1133 GuestFilesystemInfo
*fs
,
1136 /* Store a list of slave devices of virtual volume specified by @syspath into
1138 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1139 GuestFilesystemInfo
*fs
,
1145 struct dirent
*entry
;
1147 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1148 dir
= opendir(dirpath
);
1150 if (errno
!= ENOENT
) {
1151 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1159 entry
= readdir(dir
);
1160 if (entry
== NULL
) {
1162 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1167 if (entry
->d_type
== DT_LNK
) {
1170 g_debug(" slave device '%s'", entry
->d_name
);
1171 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1172 build_guest_fsinfo_for_device(path
, fs
, &err
);
1176 error_propagate(errp
, err
);
1186 static bool is_disk_virtual(const char *devpath
, Error
**errp
)
1188 g_autofree
char *syspath
= realpath(devpath
, NULL
);
1191 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1194 return strstr(syspath
, "/devices/virtual/block/") != NULL
;
1197 /* Dispatch to functions for virtual/real device */
1198 static void build_guest_fsinfo_for_device(char const *devpath
,
1199 GuestFilesystemInfo
*fs
,
1203 g_autofree
char *syspath
= NULL
;
1204 bool is_virtual
= false;
1206 syspath
= realpath(devpath
, NULL
);
1208 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1213 fs
->name
= g_path_get_basename(syspath
);
1216 g_debug(" parse sysfs path '%s'", syspath
);
1217 is_virtual
= is_disk_virtual(syspath
, errp
);
1218 if (*errp
!= NULL
) {
1222 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1224 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1228 #ifdef CONFIG_LIBUDEV
1231 * Wrapper around build_guest_fsinfo_for_device() for getting just
1234 static GuestDiskAddress
*get_disk_address(const char *syspath
, Error
**errp
)
1236 g_autoptr(GuestFilesystemInfo
) fs
= NULL
;
1238 fs
= g_new0(GuestFilesystemInfo
, 1);
1239 build_guest_fsinfo_for_device(syspath
, fs
, errp
);
1240 if (fs
->disk
!= NULL
) {
1241 return g_steal_pointer(&fs
->disk
->value
);
1246 static char *get_alias_for_syspath(const char *syspath
)
1248 struct udev
*udev
= NULL
;
1249 struct udev_device
*udevice
= NULL
;
1254 g_debug("failed to query udev");
1257 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1258 if (udevice
== NULL
) {
1259 g_debug("failed to query udev for path: %s", syspath
);
1262 const char *alias
= udev_device_get_property_value(
1263 udevice
, "DM_NAME");
1265 * NULL means there was an error and empty string means there is no
1266 * alias. In case of no alias we return NULL instead of empty string.
1268 if (alias
== NULL
) {
1269 g_debug("failed to query udev for device alias for: %s",
1271 } else if (*alias
!= 0) {
1272 ret
= g_strdup(alias
);
1278 udev_device_unref(udevice
);
1282 static char *get_device_for_syspath(const char *syspath
)
1284 struct udev
*udev
= NULL
;
1285 struct udev_device
*udevice
= NULL
;
1290 g_debug("failed to query udev");
1293 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1294 if (udevice
== NULL
) {
1295 g_debug("failed to query udev for path: %s", syspath
);
1298 ret
= g_strdup(udev_device_get_devnode(udevice
));
1303 udev_device_unref(udevice
);
1307 static void get_disk_deps(const char *disk_dir
, GuestDiskInfo
*disk
)
1309 g_autofree
char *deps_dir
= NULL
;
1311 GDir
*dp_deps
= NULL
;
1313 /* List dependent disks */
1314 deps_dir
= g_strdup_printf("%s/slaves", disk_dir
);
1315 g_debug(" listing entries in: %s", deps_dir
);
1316 dp_deps
= g_dir_open(deps_dir
, 0, NULL
);
1317 if (dp_deps
== NULL
) {
1318 g_debug("failed to list entries in %s", deps_dir
);
1321 disk
->has_dependencies
= true;
1322 while ((dep
= g_dir_read_name(dp_deps
)) != NULL
) {
1323 g_autofree
char *dep_dir
= NULL
;
1326 /* Add dependent disks */
1327 dep_dir
= g_strdup_printf("%s/%s", deps_dir
, dep
);
1328 dev_name
= get_device_for_syspath(dep_dir
);
1329 if (dev_name
!= NULL
) {
1330 g_debug(" adding dependent device: %s", dev_name
);
1331 QAPI_LIST_PREPEND(disk
->dependencies
, dev_name
);
1334 g_dir_close(dp_deps
);
1338 * Detect partitions subdirectory, name is "<disk_name><number>" or
1339 * "<disk_name>p<number>"
1341 * @disk_name -- last component of /sys path (e.g. sda)
1342 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1343 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1345 static GuestDiskInfoList
*get_disk_partitions(
1346 GuestDiskInfoList
*list
,
1347 const char *disk_name
, const char *disk_dir
,
1348 const char *disk_dev
)
1350 GuestDiskInfoList
*ret
= list
;
1351 struct dirent
*de_disk
;
1352 DIR *dp_disk
= NULL
;
1353 size_t len
= strlen(disk_name
);
1355 dp_disk
= opendir(disk_dir
);
1356 while ((de_disk
= readdir(dp_disk
)) != NULL
) {
1357 g_autofree
char *partition_dir
= NULL
;
1359 GuestDiskInfo
*partition
;
1361 if (!(de_disk
->d_type
& DT_DIR
)) {
1365 if (!(strncmp(disk_name
, de_disk
->d_name
, len
) == 0 &&
1366 ((*(de_disk
->d_name
+ len
) == 'p' &&
1367 isdigit(*(de_disk
->d_name
+ len
+ 1))) ||
1368 isdigit(*(de_disk
->d_name
+ len
))))) {
1372 partition_dir
= g_strdup_printf("%s/%s",
1373 disk_dir
, de_disk
->d_name
);
1374 dev_name
= get_device_for_syspath(partition_dir
);
1375 if (dev_name
== NULL
) {
1376 g_debug("Failed to get device name for syspath: %s",
1380 partition
= g_new0(GuestDiskInfo
, 1);
1381 partition
->name
= dev_name
;
1382 partition
->partition
= true;
1383 partition
->has_dependencies
= true;
1384 /* Add parent disk as dependent for easier tracking of hierarchy */
1385 QAPI_LIST_PREPEND(partition
->dependencies
, g_strdup(disk_dev
));
1387 QAPI_LIST_PREPEND(ret
, partition
);
1394 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1396 GuestDiskInfoList
*ret
= NULL
;
1397 GuestDiskInfo
*disk
;
1399 struct dirent
*de
= NULL
;
1401 g_debug("listing /sys/block directory");
1402 dp
= opendir("/sys/block");
1404 error_setg_errno(errp
, errno
, "Can't open directory \"/sys/block\"");
1407 while ((de
= readdir(dp
)) != NULL
) {
1408 g_autofree
char *disk_dir
= NULL
, *line
= NULL
,
1411 Error
*local_err
= NULL
;
1412 if (de
->d_type
!= DT_LNK
) {
1413 g_debug(" skipping entry: %s", de
->d_name
);
1417 /* Check size and skip zero-sized disks */
1418 g_debug(" checking disk size");
1419 size_path
= g_strdup_printf("/sys/block/%s/size", de
->d_name
);
1420 if (!g_file_get_contents(size_path
, &line
, NULL
, NULL
)) {
1421 g_debug(" failed to read disk size");
1424 if (g_strcmp0(line
, "0\n") == 0) {
1425 g_debug(" skipping zero-sized disk");
1429 g_debug(" adding %s", de
->d_name
);
1430 disk_dir
= g_strdup_printf("/sys/block/%s", de
->d_name
);
1431 dev_name
= get_device_for_syspath(disk_dir
);
1432 if (dev_name
== NULL
) {
1433 g_debug("Failed to get device name for syspath: %s",
1437 disk
= g_new0(GuestDiskInfo
, 1);
1438 disk
->name
= dev_name
;
1439 disk
->partition
= false;
1440 disk
->alias
= get_alias_for_syspath(disk_dir
);
1441 disk
->has_alias
= (disk
->alias
!= NULL
);
1442 QAPI_LIST_PREPEND(ret
, disk
);
1444 /* Get address for non-virtual devices */
1445 bool is_virtual
= is_disk_virtual(disk_dir
, &local_err
);
1446 if (local_err
!= NULL
) {
1447 g_debug(" failed to check disk path, ignoring error: %s",
1448 error_get_pretty(local_err
));
1449 error_free(local_err
);
1451 /* Don't try to get the address */
1455 disk
->address
= get_disk_address(disk_dir
, &local_err
);
1456 if (local_err
!= NULL
) {
1457 g_debug(" failed to get device info, ignoring error: %s",
1458 error_get_pretty(local_err
));
1459 error_free(local_err
);
1461 } else if (disk
->address
!= NULL
) {
1462 disk
->has_address
= true;
1466 get_disk_deps(disk_dir
, disk
);
1467 ret
= get_disk_partitions(ret
, de
->d_name
, disk_dir
, dev_name
);
1477 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1479 error_setg(errp
, QERR_UNSUPPORTED
);
1485 /* Return a list of the disk device(s)' info which @mount lies on */
1486 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1489 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1491 unsigned long used
, nonroot_total
, fr_size
;
1492 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1493 mount
->devmajor
, mount
->devminor
);
1495 fs
->mountpoint
= g_strdup(mount
->dirname
);
1496 fs
->type
= g_strdup(mount
->devtype
);
1497 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1499 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1500 fr_size
= buf
.f_frsize
;
1501 used
= buf
.f_blocks
- buf
.f_bfree
;
1502 nonroot_total
= used
+ buf
.f_bavail
;
1503 fs
->used_bytes
= used
* fr_size
;
1504 fs
->total_bytes
= nonroot_total
* fr_size
;
1506 fs
->has_total_bytes
= true;
1507 fs
->has_used_bytes
= true;
1515 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1518 struct FsMount
*mount
;
1519 GuestFilesystemInfoList
*ret
= NULL
;
1520 Error
*local_err
= NULL
;
1522 QTAILQ_INIT(&mounts
);
1523 build_fs_mount_list(&mounts
, &local_err
);
1525 error_propagate(errp
, local_err
);
1529 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1530 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1532 QAPI_LIST_PREPEND(ret
, build_guest_fsinfo(mount
, &local_err
));
1534 error_propagate(errp
, local_err
);
1535 qapi_free_GuestFilesystemInfoList(ret
);
1541 free_fs_mount_list(&mounts
);
1547 FSFREEZE_HOOK_THAW
= 0,
1548 FSFREEZE_HOOK_FREEZE
,
1551 static const char *fsfreeze_hook_arg_string
[] = {
1556 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1561 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1562 Error
*local_err
= NULL
;
1564 hook
= ga_fsfreeze_hook(ga_state
);
1568 if (access(hook
, X_OK
) != 0) {
1569 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1573 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1577 reopen_fd_to_null(0);
1578 reopen_fd_to_null(1);
1579 reopen_fd_to_null(2);
1581 execl(hook
, hook
, arg_str
, NULL
);
1582 _exit(EXIT_FAILURE
);
1583 } else if (pid
< 0) {
1584 error_setg_errno(errp
, errno
, "failed to create child process");
1588 ga_wait_child(pid
, &status
, &local_err
);
1590 error_propagate(errp
, local_err
);
1594 if (!WIFEXITED(status
)) {
1595 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1599 status
= WEXITSTATUS(status
);
1601 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1607 * Return status of freeze/thaw
1609 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1611 if (ga_is_frozen(ga_state
)) {
1612 return GUEST_FSFREEZE_STATUS_FROZEN
;
1615 return GUEST_FSFREEZE_STATUS_THAWED
;
1618 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1620 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1624 * Walk list of mounted file systems in the guest, and freeze the ones which
1625 * are real local file systems.
1627 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1628 strList
*mountpoints
,
1634 struct FsMount
*mount
;
1635 Error
*local_err
= NULL
;
1638 slog("guest-fsfreeze called");
1640 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1642 error_propagate(errp
, local_err
);
1646 QTAILQ_INIT(&mounts
);
1647 build_fs_mount_list(&mounts
, &local_err
);
1649 error_propagate(errp
, local_err
);
1653 /* cannot risk guest agent blocking itself on a write in this state */
1654 ga_set_frozen(ga_state
);
1656 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, next
) {
1657 /* To issue fsfreeze in the reverse order of mounts, check if the
1658 * mount is listed in the list here */
1659 if (has_mountpoints
) {
1660 for (list
= mountpoints
; list
; list
= list
->next
) {
1661 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1670 fd
= qemu_open_old(mount
->dirname
, O_RDONLY
);
1672 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1676 /* we try to cull filesystems we know won't work in advance, but other
1677 * filesystems may not implement fsfreeze for less obvious reasons.
1678 * these will report EOPNOTSUPP. we simply ignore these when tallying
1679 * the number of frozen filesystems.
1680 * if a filesystem is mounted more than once (aka bind mount) a
1681 * consecutive attempt to freeze an already frozen filesystem will
1684 * any other error means a failure to freeze a filesystem we
1685 * expect to be freezable, so return an error in those cases
1686 * and return system to thawed state.
1688 ret
= ioctl(fd
, FIFREEZE
);
1690 if (errno
!= EOPNOTSUPP
&& errno
!= EBUSY
) {
1691 error_setg_errno(errp
, errno
, "failed to freeze %s",
1702 free_fs_mount_list(&mounts
);
1703 /* We may not issue any FIFREEZE here.
1704 * Just unset ga_state here and ready for the next call.
1707 ga_unset_frozen(ga_state
);
1712 free_fs_mount_list(&mounts
);
1713 qmp_guest_fsfreeze_thaw(NULL
);
1718 * Walk list of frozen file systems in the guest, and thaw them.
1720 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1725 int fd
, i
= 0, logged
;
1726 Error
*local_err
= NULL
;
1728 QTAILQ_INIT(&mounts
);
1729 build_fs_mount_list(&mounts
, &local_err
);
1731 error_propagate(errp
, local_err
);
1735 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1737 fd
= qemu_open_old(mount
->dirname
, O_RDONLY
);
1741 /* we have no way of knowing whether a filesystem was actually unfrozen
1742 * as a result of a successful call to FITHAW, only that if an error
1743 * was returned the filesystem was *not* unfrozen by that particular
1746 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1747 * to unfreeze, continuing issuing FITHAW until an error is returned,
1748 * in which case either the filesystem is in an unfreezable state, or,
1749 * more likely, it was thawed previously (and remains so afterward).
1751 * also, since the most recent successful call is the one that did
1752 * the actual unfreeze, we can use this to provide an accurate count
1753 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1754 * may * be useful for determining whether a filesystem was unfrozen
1755 * during the freeze/thaw phase by a process other than qemu-ga.
1758 ret
= ioctl(fd
, FITHAW
);
1759 if (ret
== 0 && !logged
) {
1767 ga_unset_frozen(ga_state
);
1768 free_fs_mount_list(&mounts
);
1770 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1775 static void guest_fsfreeze_cleanup(void)
1779 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1780 qmp_guest_fsfreeze_thaw(&err
);
1782 slog("failed to clean up frozen filesystems: %s",
1783 error_get_pretty(err
));
1788 #endif /* CONFIG_FSFREEZE */
1790 #if defined(CONFIG_FSTRIM)
1792 * Walk list of mounted file systems in the guest, and trim them.
1794 GuestFilesystemTrimResponse
*
1795 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1797 GuestFilesystemTrimResponse
*response
;
1798 GuestFilesystemTrimResult
*result
;
1801 struct FsMount
*mount
;
1803 Error
*local_err
= NULL
;
1804 struct fstrim_range r
;
1806 slog("guest-fstrim called");
1808 QTAILQ_INIT(&mounts
);
1809 build_fs_mount_list(&mounts
, &local_err
);
1811 error_propagate(errp
, local_err
);
1815 response
= g_malloc0(sizeof(*response
));
1817 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1818 result
= g_malloc0(sizeof(*result
));
1819 result
->path
= g_strdup(mount
->dirname
);
1821 QAPI_LIST_PREPEND(response
->paths
, result
);
1823 fd
= qemu_open_old(mount
->dirname
, O_RDONLY
);
1825 result
->error
= g_strdup_printf("failed to open: %s",
1827 result
->has_error
= true;
1831 /* We try to cull filesystems we know won't work in advance, but other
1832 * filesystems may not implement fstrim for less obvious reasons.
1833 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1834 * will be reported (e.g. CD-ROMs).
1835 * Any other error means an unexpected error.
1839 r
.minlen
= has_minimum
? minimum
: 0;
1840 ret
= ioctl(fd
, FITRIM
, &r
);
1842 result
->has_error
= true;
1843 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1844 result
->error
= g_strdup("trim not supported");
1846 result
->error
= g_strdup_printf("failed to trim: %s",
1853 result
->has_minimum
= true;
1854 result
->minimum
= r
.minlen
;
1855 result
->has_trimmed
= true;
1856 result
->trimmed
= r
.len
;
1860 free_fs_mount_list(&mounts
);
1863 #endif /* CONFIG_FSTRIM */
1866 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1867 #define SUSPEND_SUPPORTED 0
1868 #define SUSPEND_NOT_SUPPORTED 1
1871 SUSPEND_MODE_DISK
= 0,
1872 SUSPEND_MODE_RAM
= 1,
1873 SUSPEND_MODE_HYBRID
= 2,
1877 * Executes a command in a child process using g_spawn_sync,
1878 * returning an int >= 0 representing the exit status of the
1881 * If the program wasn't found in path, returns -1.
1883 * If a problem happened when creating the child process,
1884 * returns -1 and errp is set.
1886 static int run_process_child(const char *command
[], Error
**errp
)
1888 int exit_status
, spawn_flag
;
1889 GError
*g_err
= NULL
;
1892 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1893 G_SPAWN_STDERR_TO_DEV_NULL
;
1895 success
= g_spawn_sync(NULL
, (char **)command
, NULL
, spawn_flag
,
1896 NULL
, NULL
, NULL
, NULL
,
1897 &exit_status
, &g_err
);
1900 return WEXITSTATUS(exit_status
);
1903 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1904 error_setg(errp
, "failed to create child process, error '%s'",
1908 g_error_free(g_err
);
1912 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1914 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1915 "systemd-hybrid-sleep"};
1916 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
1919 status
= run_process_child(cmd
, errp
);
1922 * systemctl status uses LSB return codes so we can expect
1923 * status > 0 and be ok. To assert if the guest has support
1924 * for the selected suspend mode, status should be < 4. 4 is
1925 * the code for unknown service status, the return value when
1926 * the service does not exist. A common value is status = 3
1927 * (program is not running).
1929 if (status
> 0 && status
< 4) {
1936 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
1938 Error
*local_err
= NULL
;
1939 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
1940 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
1943 status
= run_process_child(cmd
, &local_err
);
1949 if ((status
== -1) && !local_err
) {
1950 error_setg(errp
, "the helper program 'systemctl %s' was not found",
1951 systemctl_args
[mode
]);
1956 error_propagate(errp
, local_err
);
1958 error_setg(errp
, "the helper program 'systemctl %s' returned an "
1959 "unexpected exit status code (%d)",
1960 systemctl_args
[mode
], status
);
1964 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
1966 Error
*local_err
= NULL
;
1967 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
1968 "--suspend-hybrid"};
1969 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
1972 status
= run_process_child(cmd
, &local_err
);
1974 if (status
== SUSPEND_SUPPORTED
) {
1978 if ((status
== -1) && !local_err
) {
1983 error_propagate(errp
, local_err
);
1986 "the helper program '%s' returned an unexpected exit"
1987 " status code (%d)", "pm-is-supported", status
);
1993 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
1995 Error
*local_err
= NULL
;
1996 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
1997 "pm-suspend-hybrid"};
1998 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
2001 status
= run_process_child(cmd
, &local_err
);
2007 if ((status
== -1) && !local_err
) {
2008 error_setg(errp
, "the helper program '%s' was not found",
2009 pmutils_binaries
[mode
]);
2014 error_propagate(errp
, local_err
);
2017 "the helper program '%s' returned an unexpected exit"
2018 " status code (%d)", pmutils_binaries
[mode
], status
);
2022 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
2024 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
2025 const char *sysfile_str
= sysfile_strs
[mode
];
2026 char buf
[32]; /* hopefully big enough */
2031 error_setg(errp
, "unknown guest suspend mode");
2035 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
2040 ret
= read(fd
, buf
, sizeof(buf
) - 1);
2047 if (strstr(buf
, sysfile_str
)) {
2053 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
2055 Error
*local_err
= NULL
;
2056 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
2057 const char *sysfile_str
= sysfile_strs
[mode
];
2062 error_setg(errp
, "unknown guest suspend mode");
2072 reopen_fd_to_null(0);
2073 reopen_fd_to_null(1);
2074 reopen_fd_to_null(2);
2076 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
2078 _exit(EXIT_FAILURE
);
2081 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
2082 _exit(EXIT_FAILURE
);
2085 _exit(EXIT_SUCCESS
);
2086 } else if (pid
< 0) {
2087 error_setg_errno(errp
, errno
, "failed to create child process");
2091 ga_wait_child(pid
, &status
, &local_err
);
2093 error_propagate(errp
, local_err
);
2097 if (WEXITSTATUS(status
)) {
2098 error_setg(errp
, "child process has failed to suspend");
2103 static void guest_suspend(SuspendMode mode
, Error
**errp
)
2105 Error
*local_err
= NULL
;
2106 bool mode_supported
= false;
2108 if (systemd_supports_mode(mode
, &local_err
)) {
2109 mode_supported
= true;
2110 systemd_suspend(mode
, &local_err
);
2117 error_free(local_err
);
2120 if (pmutils_supports_mode(mode
, &local_err
)) {
2121 mode_supported
= true;
2122 pmutils_suspend(mode
, &local_err
);
2129 error_free(local_err
);
2132 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
2133 mode_supported
= true;
2134 linux_sys_state_suspend(mode
, &local_err
);
2137 if (!mode_supported
) {
2138 error_free(local_err
);
2140 "the requested suspend mode is not supported by the guest");
2142 error_propagate(errp
, local_err
);
2146 void qmp_guest_suspend_disk(Error
**errp
)
2148 guest_suspend(SUSPEND_MODE_DISK
, errp
);
2151 void qmp_guest_suspend_ram(Error
**errp
)
2153 guest_suspend(SUSPEND_MODE_RAM
, errp
);
2156 void qmp_guest_suspend_hybrid(Error
**errp
)
2158 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
2161 /* Transfer online/offline status between @vcpu and the guest system.
2163 * On input either @errp or *@errp must be NULL.
2165 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2166 * - R: vcpu->logical_id
2168 * - W: vcpu->can_offline
2170 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2171 * - R: vcpu->logical_id
2174 * Written members remain unmodified on error.
2176 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
2177 char *dirpath
, Error
**errp
)
2182 static const char fn
[] = "online";
2184 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2186 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2190 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2192 if (errno
!= ENOENT
) {
2193 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2194 } else if (sys2vcpu
) {
2195 vcpu
->online
= true;
2196 vcpu
->can_offline
= false;
2197 } else if (!vcpu
->online
) {
2198 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2199 "offlined", vcpu
->logical_id
);
2200 } /* otherwise pretend successful re-onlining */
2202 unsigned char status
;
2204 res
= pread(fd
, &status
, 1, 0);
2206 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2207 } else if (res
== 0) {
2208 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2210 } else if (sys2vcpu
) {
2211 vcpu
->online
= (status
!= '0');
2212 vcpu
->can_offline
= true;
2213 } else if (vcpu
->online
!= (status
!= '0')) {
2214 status
= '0' + vcpu
->online
;
2215 if (pwrite(fd
, &status
, 1, 0) == -1) {
2216 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2219 } /* otherwise pretend successful re-(on|off)-lining */
2229 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2231 GuestLogicalProcessorList
*head
, **tail
;
2232 const char *cpu_dir
= "/sys/devices/system/cpu";
2234 g_autoptr(GDir
) cpu_gdir
= NULL
;
2235 Error
*local_err
= NULL
;
2239 cpu_gdir
= g_dir_open(cpu_dir
, 0, NULL
);
2241 if (cpu_gdir
== NULL
) {
2242 error_setg_errno(errp
, errno
, "failed to list entries: %s", cpu_dir
);
2246 while (local_err
== NULL
&& (line
= g_dir_read_name(cpu_gdir
)) != NULL
) {
2247 GuestLogicalProcessor
*vcpu
;
2249 if (sscanf(line
, "cpu%" PRId64
, &id
)) {
2250 g_autofree
char *path
= g_strdup_printf("/sys/devices/system/cpu/"
2251 "cpu%" PRId64
"/", id
);
2252 vcpu
= g_malloc0(sizeof *vcpu
);
2253 vcpu
->logical_id
= id
;
2254 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2255 transfer_vcpu(vcpu
, true, path
, &local_err
);
2256 QAPI_LIST_APPEND(tail
, vcpu
);
2260 if (local_err
== NULL
) {
2261 /* there's no guest with zero VCPUs */
2262 g_assert(head
!= NULL
);
2266 qapi_free_GuestLogicalProcessorList(head
);
2267 error_propagate(errp
, local_err
);
2271 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2274 Error
*local_err
= NULL
;
2277 while (vcpus
!= NULL
) {
2278 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2279 vcpus
->value
->logical_id
);
2281 transfer_vcpu(vcpus
->value
, false, path
, &local_err
);
2283 if (local_err
!= NULL
) {
2287 vcpus
= vcpus
->next
;
2290 if (local_err
!= NULL
) {
2291 if (processed
== 0) {
2292 error_propagate(errp
, local_err
);
2294 error_free(local_err
);
2301 void qmp_guest_set_user_password(const char *username
,
2302 const char *password
,
2306 Error
*local_err
= NULL
;
2307 char *passwd_path
= NULL
;
2310 int datafd
[2] = { -1, -1 };
2311 char *rawpasswddata
= NULL
;
2312 size_t rawpasswdlen
;
2313 char *chpasswddata
= NULL
;
2316 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2317 if (!rawpasswddata
) {
2320 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2321 rawpasswddata
[rawpasswdlen
] = '\0';
2323 if (strchr(rawpasswddata
, '\n')) {
2324 error_setg(errp
, "forbidden characters in raw password");
2328 if (strchr(username
, '\n') ||
2329 strchr(username
, ':')) {
2330 error_setg(errp
, "forbidden characters in username");
2334 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
2335 chpasswdlen
= strlen(chpasswddata
);
2337 passwd_path
= g_find_program_in_path("chpasswd");
2340 error_setg(errp
, "cannot find 'passwd' program in PATH");
2344 if (!g_unix_open_pipe(datafd
, FD_CLOEXEC
, NULL
)) {
2345 error_setg(errp
, "cannot create pipe FDs");
2355 reopen_fd_to_null(1);
2356 reopen_fd_to_null(2);
2359 execl(passwd_path
, "chpasswd", "-e", NULL
);
2361 execl(passwd_path
, "chpasswd", NULL
);
2363 _exit(EXIT_FAILURE
);
2364 } else if (pid
< 0) {
2365 error_setg_errno(errp
, errno
, "failed to create child process");
2371 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2372 error_setg_errno(errp
, errno
, "cannot write new account password");
2378 ga_wait_child(pid
, &status
, &local_err
);
2380 error_propagate(errp
, local_err
);
2384 if (!WIFEXITED(status
)) {
2385 error_setg(errp
, "child process has terminated abnormally");
2389 if (WEXITSTATUS(status
)) {
2390 error_setg(errp
, "child process has failed to set user password");
2395 g_free(chpasswddata
);
2396 g_free(rawpasswddata
);
2397 g_free(passwd_path
);
2398 if (datafd
[0] != -1) {
2401 if (datafd
[1] != -1) {
2406 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2407 int size
, Error
**errp
)
2413 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2415 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2419 res
= pread(fd
, buf
, size
, 0);
2421 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2422 } else if (res
== 0) {
2423 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2428 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2429 const char *buf
, int size
, Error
**errp
)
2434 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2436 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2440 if (pwrite(fd
, buf
, size
, 0) == -1) {
2441 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2447 /* Transfer online/offline status between @mem_blk and the guest system.
2449 * On input either @errp or *@errp must be NULL.
2451 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2452 * - R: mem_blk->phys_index
2453 * - W: mem_blk->online
2454 * - W: mem_blk->can_offline
2456 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2457 * - R: mem_blk->phys_index
2458 * - R: mem_blk->online
2459 *- R: mem_blk->can_offline
2460 * Written members remain unmodified on error.
2462 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2463 GuestMemoryBlockResponse
*result
,
2469 Error
*local_err
= NULL
;
2475 error_setg(errp
, "Internal error, 'result' should not be NULL");
2479 dp
= opendir("/sys/devices/system/memory/");
2480 /* if there is no 'memory' directory in sysfs,
2481 * we think this VM does not support online/offline memory block,
2482 * any other solution?
2485 if (errno
== ENOENT
) {
2487 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2494 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2495 mem_blk
->phys_index
);
2496 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2499 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2501 if (errno
== ENOENT
) {
2502 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2505 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2513 status
= g_malloc0(10);
2514 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2516 /* treat with sysfs file that not exist in old kernel */
2517 if (errno
== ENOENT
) {
2518 error_free(local_err
);
2520 mem_blk
->online
= true;
2521 mem_blk
->can_offline
= false;
2522 } else if (!mem_blk
->online
) {
2524 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2528 error_propagate(errp
, local_err
);
2530 error_free(local_err
);
2532 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2539 char removable
= '0';
2541 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2543 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2545 /* if no 'removable' file, it doesn't support offline mem blk */
2546 if (errno
== ENOENT
) {
2547 error_free(local_err
);
2548 mem_blk
->can_offline
= false;
2550 error_propagate(errp
, local_err
);
2553 mem_blk
->can_offline
= (removable
!= '0');
2556 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2557 const char *new_state
= mem_blk
->online
? "online" : "offline";
2559 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2562 error_free(local_err
);
2564 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2568 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2569 result
->has_error_code
= false;
2570 } /* otherwise pretend successful re-(on|off)-lining */
2581 result
->has_error_code
= true;
2582 result
->error_code
= errno
;
2586 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2588 GuestMemoryBlockList
*head
, **tail
;
2589 Error
*local_err
= NULL
;
2596 dp
= opendir("/sys/devices/system/memory/");
2598 /* it's ok if this happens to be a system that doesn't expose
2599 * memory blocks via sysfs, but otherwise we should report
2602 if (errno
!= ENOENT
) {
2603 error_setg_errno(errp
, errno
, "Can't open directory"
2604 "\"/sys/devices/system/memory/\"");
2609 /* Note: the phys_index of memory block may be discontinuous,
2610 * this is because a memblk is the unit of the Sparse Memory design, which
2611 * allows discontinuous memory ranges (ex. NUMA), so here we should
2612 * traverse the memory block directory.
2614 while ((de
= readdir(dp
)) != NULL
) {
2615 GuestMemoryBlock
*mem_blk
;
2617 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2618 !(de
->d_type
& DT_DIR
)) {
2622 mem_blk
= g_malloc0(sizeof *mem_blk
);
2623 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2624 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2625 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2626 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2631 QAPI_LIST_APPEND(tail
, mem_blk
);
2635 if (local_err
== NULL
) {
2636 /* there's no guest with zero memory blocks */
2638 error_setg(errp
, "guest reported zero memory blocks!");
2643 qapi_free_GuestMemoryBlockList(head
);
2644 error_propagate(errp
, local_err
);
2648 GuestMemoryBlockResponseList
*
2649 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2651 GuestMemoryBlockResponseList
*head
, **tail
;
2652 Error
*local_err
= NULL
;
2657 while (mem_blks
!= NULL
) {
2658 GuestMemoryBlockResponse
*result
;
2659 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2661 result
= g_malloc0(sizeof(*result
));
2662 result
->phys_index
= current_mem_blk
->phys_index
;
2663 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2664 if (local_err
) { /* should never happen */
2668 QAPI_LIST_APPEND(tail
, result
);
2669 mem_blks
= mem_blks
->next
;
2674 qapi_free_GuestMemoryBlockResponseList(head
);
2675 error_propagate(errp
, local_err
);
2679 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2681 Error
*local_err
= NULL
;
2685 GuestMemoryBlockInfo
*info
;
2687 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2688 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2690 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2696 buf
= g_malloc0(20);
2697 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2701 error_propagate(errp
, local_err
);
2705 info
= g_new0(GuestMemoryBlockInfo
, 1);
2706 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2713 #else /* defined(__linux__) */
2715 void qmp_guest_suspend_disk(Error
**errp
)
2717 error_setg(errp
, QERR_UNSUPPORTED
);
2720 void qmp_guest_suspend_ram(Error
**errp
)
2722 error_setg(errp
, QERR_UNSUPPORTED
);
2725 void qmp_guest_suspend_hybrid(Error
**errp
)
2727 error_setg(errp
, QERR_UNSUPPORTED
);
2730 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2732 error_setg(errp
, QERR_UNSUPPORTED
);
2736 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2738 error_setg(errp
, QERR_UNSUPPORTED
);
2742 void qmp_guest_set_user_password(const char *username
,
2743 const char *password
,
2747 error_setg(errp
, QERR_UNSUPPORTED
);
2750 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2752 error_setg(errp
, QERR_UNSUPPORTED
);
2756 GuestMemoryBlockResponseList
*
2757 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2759 error_setg(errp
, QERR_UNSUPPORTED
);
2763 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2765 error_setg(errp
, QERR_UNSUPPORTED
);
2771 #ifdef HAVE_GETIFADDRS
2772 static GuestNetworkInterface
*
2773 guest_find_interface(GuestNetworkInterfaceList
*head
,
2776 for (; head
; head
= head
->next
) {
2777 if (strcmp(head
->value
->name
, name
) == 0) {
2785 static int guest_get_network_stats(const char *name
,
2786 GuestNetworkInterfaceStat
*stats
)
2790 char const *devinfo
= "/proc/net/dev";
2792 char *line
= NULL
, *colon
;
2794 fp
= fopen(devinfo
, "r");
2796 g_debug("failed to open network stats %s: %s", devinfo
,
2800 name_len
= strlen(name
);
2801 while (getline(&line
, &n
, fp
) != -1) {
2804 long long rx_packets
;
2806 long long rx_dropped
;
2808 long long tx_packets
;
2810 long long tx_dropped
;
2812 trim_line
= g_strchug(line
);
2813 if (trim_line
[0] == '\0') {
2816 colon
= strchr(trim_line
, ':');
2820 if (colon
- name_len
== trim_line
&&
2821 strncmp(trim_line
, name
, name_len
) == 0) {
2822 if (sscanf(colon
+ 1,
2823 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2824 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
2825 &dummy
, &dummy
, &dummy
, &dummy
,
2826 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
2827 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
2830 stats
->rx_bytes
= rx_bytes
;
2831 stats
->rx_packets
= rx_packets
;
2832 stats
->rx_errs
= rx_errs
;
2833 stats
->rx_dropped
= rx_dropped
;
2834 stats
->tx_bytes
= tx_bytes
;
2835 stats
->tx_packets
= tx_packets
;
2836 stats
->tx_errs
= tx_errs
;
2837 stats
->tx_dropped
= tx_dropped
;
2845 g_debug("/proc/net/dev: Interface '%s' not found", name
);
2846 #else /* !CONFIG_LINUX */
2847 g_debug("Network stats reporting available only for Linux");
2848 #endif /* !CONFIG_LINUX */
2853 * Build information about guest interfaces
2855 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2857 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
2858 struct ifaddrs
*ifap
, *ifa
;
2860 if (getifaddrs(&ifap
) < 0) {
2861 error_setg_errno(errp
, errno
, "getifaddrs failed");
2865 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
2866 GuestNetworkInterface
*info
;
2867 GuestIpAddressList
**address_tail
;
2868 GuestIpAddress
*address_item
= NULL
;
2869 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
2870 char addr4
[INET_ADDRSTRLEN
];
2871 char addr6
[INET6_ADDRSTRLEN
];
2874 unsigned char *mac_addr
;
2877 g_debug("Processing %s interface", ifa
->ifa_name
);
2879 info
= guest_find_interface(head
, ifa
->ifa_name
);
2882 info
= g_malloc0(sizeof(*info
));
2883 info
->name
= g_strdup(ifa
->ifa_name
);
2885 QAPI_LIST_APPEND(tail
, info
);
2888 if (!info
->has_hardware_address
) {
2889 /* we haven't obtained HW address yet */
2890 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
2892 error_setg_errno(errp
, errno
, "failed to create socket");
2896 memset(&ifr
, 0, sizeof(ifr
));
2897 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->name
);
2898 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
2900 * We can't get the hw addr of this interface, but that's not a
2901 * fatal error. Don't set info->hardware_address, but keep
2904 if (errno
== EADDRNOTAVAIL
) {
2905 /* The interface doesn't have a hw addr (e.g. loopback). */
2906 g_debug("failed to get MAC address of %s: %s",
2907 ifa
->ifa_name
, strerror(errno
));
2909 g_warning("failed to get MAC address of %s: %s",
2910 ifa
->ifa_name
, strerror(errno
));
2914 #ifdef CONFIG_SOLARIS
2915 mac_addr
= (unsigned char *) &ifr
.ifr_addr
.sa_data
;
2917 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
2919 info
->hardware_address
=
2920 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2921 (int) mac_addr
[0], (int) mac_addr
[1],
2922 (int) mac_addr
[2], (int) mac_addr
[3],
2923 (int) mac_addr
[4], (int) mac_addr
[5]);
2925 info
->has_hardware_address
= true;
2930 if (ifa
->ifa_addr
&&
2931 ifa
->ifa_addr
->sa_family
== AF_INET
) {
2932 /* interface with IPv4 address */
2933 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
2934 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
2935 error_setg_errno(errp
, errno
, "inet_ntop failed");
2939 address_item
= g_malloc0(sizeof(*address_item
));
2940 address_item
->ip_address
= g_strdup(addr4
);
2941 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
2943 if (ifa
->ifa_netmask
) {
2944 /* Count the number of set bits in netmask.
2945 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2946 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
2947 address_item
->prefix
= ctpop32(((uint32_t *) p
)[0]);
2949 } else if (ifa
->ifa_addr
&&
2950 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
2951 /* interface with IPv6 address */
2952 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
2953 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
2954 error_setg_errno(errp
, errno
, "inet_ntop failed");
2958 address_item
= g_malloc0(sizeof(*address_item
));
2959 address_item
->ip_address
= g_strdup(addr6
);
2960 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
2962 if (ifa
->ifa_netmask
) {
2963 /* Count the number of set bits in netmask.
2964 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2965 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
2966 address_item
->prefix
=
2967 ctpop32(((uint32_t *) p
)[0]) +
2968 ctpop32(((uint32_t *) p
)[1]) +
2969 ctpop32(((uint32_t *) p
)[2]) +
2970 ctpop32(((uint32_t *) p
)[3]);
2974 if (!address_item
) {
2978 address_tail
= &info
->ip_addresses
;
2979 while (*address_tail
) {
2980 address_tail
= &(*address_tail
)->next
;
2982 QAPI_LIST_APPEND(address_tail
, address_item
);
2984 info
->has_ip_addresses
= true;
2986 if (!info
->has_statistics
) {
2987 interface_stat
= g_malloc0(sizeof(*interface_stat
));
2988 if (guest_get_network_stats(info
->name
, interface_stat
) == -1) {
2989 info
->has_statistics
= false;
2990 g_free(interface_stat
);
2992 info
->statistics
= interface_stat
;
2993 info
->has_statistics
= true;
3003 qapi_free_GuestNetworkInterfaceList(head
);
3009 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
3011 error_setg(errp
, QERR_UNSUPPORTED
);
3015 #endif /* HAVE_GETIFADDRS */
3017 #if !defined(CONFIG_FSFREEZE)
3019 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
3021 error_setg(errp
, QERR_UNSUPPORTED
);
3025 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
3027 error_setg(errp
, QERR_UNSUPPORTED
);
3032 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
3034 error_setg(errp
, QERR_UNSUPPORTED
);
3039 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
3040 strList
*mountpoints
,
3043 error_setg(errp
, QERR_UNSUPPORTED
);
3048 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
3050 error_setg(errp
, QERR_UNSUPPORTED
);
3055 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
3057 error_setg(errp
, QERR_UNSUPPORTED
);
3061 #endif /* CONFIG_FSFREEZE */
3063 #if !defined(CONFIG_FSTRIM)
3064 GuestFilesystemTrimResponse
*
3065 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
3067 error_setg(errp
, QERR_UNSUPPORTED
);
3072 /* add unsupported commands to the blacklist */
3073 GList
*ga_command_blacklist_init(GList
*blacklist
)
3075 #if !defined(__linux__)
3077 const char *list
[] = {
3078 "guest-suspend-disk", "guest-suspend-ram",
3079 "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
3080 "guest-get-memory-blocks", "guest-set-memory-blocks",
3081 "guest-get-memory-block-size", "guest-get-memory-block-info",
3083 char **p
= (char **)list
;
3086 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
3091 #if !defined(HAVE_GETIFADDRS)
3092 blacklist
= g_list_append(blacklist
,
3093 g_strdup("guest-network-get-interfaces"));
3096 #if !defined(CONFIG_FSFREEZE)
3098 const char *list
[] = {
3099 "guest-get-fsinfo", "guest-fsfreeze-status",
3100 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3101 "guest-fsfreeze-thaw", "guest-get-fsinfo",
3102 "guest-get-disks", NULL
};
3103 char **p
= (char **)list
;
3106 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
3111 #if !defined(CONFIG_FSTRIM)
3112 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
3115 blacklist
= g_list_append(blacklist
, g_strdup("guest-get-devices"));
3120 /* register init/cleanup routines for stateful command groups */
3121 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
3123 #if defined(CONFIG_FSFREEZE)
3124 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
3130 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3132 static double ga_get_login_time(struct utmpx
*user_info
)
3134 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
3135 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
3136 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
3137 return seconds
+ useconds
;
3140 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3142 GHashTable
*cache
= NULL
;
3143 GuestUserList
*head
= NULL
, **tail
= &head
;
3144 struct utmpx
*user_info
= NULL
;
3145 gpointer value
= NULL
;
3146 GuestUser
*user
= NULL
;
3147 double login_time
= 0;
3149 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
3153 user_info
= getutxent();
3154 if (user_info
== NULL
) {
3156 } else if (user_info
->ut_type
!= USER_PROCESS
) {
3158 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
3159 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
3160 user
= (GuestUser
*)value
;
3161 login_time
= ga_get_login_time(user_info
);
3162 /* We're ensuring the earliest login time to be sent */
3163 if (login_time
< user
->login_time
) {
3164 user
->login_time
= login_time
;
3169 user
= g_new0(GuestUser
, 1);
3170 user
->user
= g_strdup(user_info
->ut_user
);
3171 user
->login_time
= ga_get_login_time(user_info
);
3173 g_hash_table_insert(cache
, user
->user
, user
);
3175 QAPI_LIST_APPEND(tail
, user
);
3178 g_hash_table_destroy(cache
);
3184 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3186 error_setg(errp
, QERR_UNSUPPORTED
);
3192 /* Replace escaped special characters with theire real values. The replacement
3193 * is done in place -- returned value is in the original string.
3195 static void ga_osrelease_replace_special(gchar
*value
)
3197 gchar
*p
, *p2
, quote
;
3199 /* Trim the string at first space or semicolon if it is not enclosed in
3200 * single or double quotes. */
3201 if ((value
[0] != '"') || (value
[0] == '\'')) {
3202 p
= strchr(value
, ' ');
3206 p
= strchr(value
, ';');
3227 /* Keep literal backslash followed by whatever is there */
3231 } else if (*p
== quote
) {
3239 static GKeyFile
*ga_parse_osrelease(const char *fname
)
3241 gchar
*content
= NULL
;
3242 gchar
*content2
= NULL
;
3244 GKeyFile
*keys
= g_key_file_new();
3245 const char *group
= "[os-release]\n";
3247 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
3248 slog("failed to read '%s', error: %s", fname
, err
->message
);
3252 if (!g_utf8_validate(content
, -1, NULL
)) {
3253 slog("file is not utf-8 encoded: %s", fname
);
3256 content2
= g_strdup_printf("%s%s", group
, content
);
3258 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
3260 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
3272 g_key_file_free(keys
);
3276 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
3278 GuestOSInfo
*info
= NULL
;
3279 struct utsname kinfo
;
3280 GKeyFile
*osrelease
= NULL
;
3281 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
3283 info
= g_new0(GuestOSInfo
, 1);
3285 if (uname(&kinfo
) != 0) {
3286 error_setg_errno(errp
, errno
, "uname failed");
3288 info
->has_kernel_version
= true;
3289 info
->kernel_version
= g_strdup(kinfo
.version
);
3290 info
->has_kernel_release
= true;
3291 info
->kernel_release
= g_strdup(kinfo
.release
);
3292 info
->has_machine
= true;
3293 info
->machine
= g_strdup(kinfo
.machine
);
3296 if (qga_os_release
!= NULL
) {
3297 osrelease
= ga_parse_osrelease(qga_os_release
);
3299 osrelease
= ga_parse_osrelease("/etc/os-release");
3300 if (osrelease
== NULL
) {
3301 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
3305 if (osrelease
!= NULL
) {
3308 #define GET_FIELD(field, osfield) do { \
3309 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3310 if (value != NULL) { \
3311 ga_osrelease_replace_special(value); \
3312 info->has_ ## field = true; \
3313 info->field = value; \
3316 GET_FIELD(id
, "ID");
3317 GET_FIELD(name
, "NAME");
3318 GET_FIELD(pretty_name
, "PRETTY_NAME");
3319 GET_FIELD(version
, "VERSION");
3320 GET_FIELD(version_id
, "VERSION_ID");
3321 GET_FIELD(variant
, "VARIANT");
3322 GET_FIELD(variant_id
, "VARIANT_ID");
3325 g_key_file_free(osrelease
);
3331 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
3333 error_setg(errp
, QERR_UNSUPPORTED
);
3338 #ifndef HOST_NAME_MAX
3339 # ifdef _POSIX_HOST_NAME_MAX
3340 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
3342 # define HOST_NAME_MAX 255
3346 char *qga_get_host_name(Error
**errp
)
3349 g_autofree
char *hostname
= NULL
;
3351 #ifdef _SC_HOST_NAME_MAX
3352 len
= sysconf(_SC_HOST_NAME_MAX
);
3353 #endif /* _SC_HOST_NAME_MAX */
3356 len
= HOST_NAME_MAX
;
3359 /* Unfortunately, gethostname() below does not guarantee a
3360 * NULL terminated string. Therefore, allocate one byte more
3362 hostname
= g_new0(char, len
+ 1);
3364 if (gethostname(hostname
, len
) < 0) {
3365 error_setg_errno(errp
, errno
,
3366 "cannot get hostname");
3370 return g_steal_pointer(&hostname
);