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"))) {
898 if (sscanf(p
, "/%x:%x:%x.%x%n",
899 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
904 g_debug("unsupported driver or sysfs path '%s'", syspath
);
908 p
= strstr(syspath
, "/target");
909 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
910 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
914 p
= strstr(syspath
, "/ata");
919 p
= strstr(syspath
, "/host");
922 if (p
&& sscanf(q
, "%u", &host
) == 1) {
924 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
925 ARRAY_SIZE(hosts
), errp
);
931 pciaddr
->domain
= pci
[0];
932 pciaddr
->bus
= pci
[1];
933 pciaddr
->slot
= pci
[2];
934 pciaddr
->function
= pci
[3];
936 if (strcmp(driver
, "ata_piix") == 0) {
937 /* a host per ide bus, target*:0:<unit>:0 */
938 if (!has_host
|| !has_tgt
) {
939 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
942 for (i
= 0; i
< nhosts
; i
++) {
943 if (host
== hosts
[i
]) {
944 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
951 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
954 } else if (strcmp(driver
, "sym53c8xx") == 0) {
955 /* scsi(LSI Logic): target*:0:<unit>:0 */
957 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
960 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
962 } else if (strcmp(driver
, "virtio-pci") == 0) {
964 /* virtio-scsi: target*:0:0:<unit> */
965 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
968 /* virtio-blk: 1 disk per 1 device */
969 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
971 } else if (strcmp(driver
, "ahci") == 0) {
972 /* ahci: 1 host per 1 unit */
973 if (!has_host
|| !has_tgt
) {
974 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
977 for (i
= 0; i
< nhosts
; i
++) {
978 if (host
== hosts
[i
]) {
980 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
985 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
989 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
1001 * Store disk device info for non-PCI virtio devices (for example s390x
1002 * channel I/O devices). Returns true if information has been stored, or
1003 * false for failure.
1005 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath
,
1006 GuestDiskAddress
*disk
,
1009 unsigned int tgt
[3];
1012 if (!strstr(syspath
, "/virtio") || !strstr(syspath
, "/block")) {
1013 g_debug("Unsupported virtio device '%s'", syspath
);
1017 p
= strstr(syspath
, "/target");
1018 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1019 &tgt
[0], &tgt
[1], &tgt
[2]) == 3) {
1020 /* virtio-scsi: target*:0:<target>:<unit> */
1021 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1023 disk
->target
= tgt
[1];
1024 disk
->unit
= tgt
[2];
1026 /* virtio-blk: 1 disk per 1 device */
1027 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
1034 * Store disk device info for CCW devices (s390x channel I/O devices).
1035 * Returns true if information has been stored, or false for failure.
1037 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath
,
1038 GuestDiskAddress
*disk
,
1041 unsigned int cssid
, ssid
, subchno
, devno
;
1044 p
= strstr(syspath
, "/devices/css");
1045 if (!p
|| sscanf(p
+ 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1046 &cssid
, &ssid
, &subchno
, &devno
) < 4) {
1047 g_debug("could not parse ccw device sysfs path: %s", syspath
);
1051 disk
->has_ccw_address
= true;
1052 disk
->ccw_address
= g_new0(GuestCCWAddress
, 1);
1053 disk
->ccw_address
->cssid
= cssid
;
1054 disk
->ccw_address
->ssid
= ssid
;
1055 disk
->ccw_address
->subchno
= subchno
;
1056 disk
->ccw_address
->devno
= devno
;
1058 if (strstr(p
, "/virtio")) {
1059 build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1065 /* Store disk device info specified by @sysfs into @fs */
1066 static void build_guest_fsinfo_for_real_device(char const *syspath
,
1067 GuestFilesystemInfo
*fs
,
1070 GuestDiskAddress
*disk
;
1071 GuestPCIAddress
*pciaddr
;
1073 #ifdef CONFIG_LIBUDEV
1074 struct udev
*udev
= NULL
;
1075 struct udev_device
*udevice
= NULL
;
1078 pciaddr
= g_new0(GuestPCIAddress
, 1);
1079 pciaddr
->domain
= -1; /* -1 means field is invalid */
1082 pciaddr
->function
= -1;
1084 disk
= g_new0(GuestDiskAddress
, 1);
1085 disk
->pci_controller
= pciaddr
;
1086 disk
->bus_type
= GUEST_DISK_BUS_TYPE_UNKNOWN
;
1088 #ifdef CONFIG_LIBUDEV
1090 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1091 if (udev
== NULL
|| udevice
== NULL
) {
1092 g_debug("failed to query udev");
1094 const char *devnode
, *serial
;
1095 devnode
= udev_device_get_devnode(udevice
);
1096 if (devnode
!= NULL
) {
1097 disk
->dev
= g_strdup(devnode
);
1098 disk
->has_dev
= true;
1100 serial
= udev_device_get_property_value(udevice
, "ID_SERIAL");
1101 if (serial
!= NULL
&& *serial
!= 0) {
1102 disk
->serial
= g_strdup(serial
);
1103 disk
->has_serial
= true;
1108 udev_device_unref(udevice
);
1111 if (strstr(syspath
, "/devices/pci")) {
1112 has_hwinf
= build_guest_fsinfo_for_pci_dev(syspath
, disk
, errp
);
1113 } else if (strstr(syspath
, "/devices/css")) {
1114 has_hwinf
= build_guest_fsinfo_for_ccw_dev(syspath
, disk
, errp
);
1115 } else if (strstr(syspath
, "/virtio")) {
1116 has_hwinf
= build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1118 g_debug("Unsupported device type for '%s'", syspath
);
1122 if (has_hwinf
|| disk
->has_dev
|| disk
->has_serial
) {
1123 QAPI_LIST_PREPEND(fs
->disk
, disk
);
1125 qapi_free_GuestDiskAddress(disk
);
1129 static void build_guest_fsinfo_for_device(char const *devpath
,
1130 GuestFilesystemInfo
*fs
,
1133 /* Store a list of slave devices of virtual volume specified by @syspath into
1135 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1136 GuestFilesystemInfo
*fs
,
1142 struct dirent
*entry
;
1144 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1145 dir
= opendir(dirpath
);
1147 if (errno
!= ENOENT
) {
1148 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1156 entry
= readdir(dir
);
1157 if (entry
== NULL
) {
1159 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1164 if (entry
->d_type
== DT_LNK
) {
1167 g_debug(" slave device '%s'", entry
->d_name
);
1168 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1169 build_guest_fsinfo_for_device(path
, fs
, &err
);
1173 error_propagate(errp
, err
);
1183 static bool is_disk_virtual(const char *devpath
, Error
**errp
)
1185 g_autofree
char *syspath
= realpath(devpath
, NULL
);
1188 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1191 return strstr(syspath
, "/devices/virtual/block/") != NULL
;
1194 /* Dispatch to functions for virtual/real device */
1195 static void build_guest_fsinfo_for_device(char const *devpath
,
1196 GuestFilesystemInfo
*fs
,
1200 g_autofree
char *syspath
= NULL
;
1201 bool is_virtual
= false;
1203 syspath
= realpath(devpath
, NULL
);
1205 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1210 fs
->name
= g_path_get_basename(syspath
);
1213 g_debug(" parse sysfs path '%s'", syspath
);
1214 is_virtual
= is_disk_virtual(syspath
, errp
);
1215 if (*errp
!= NULL
) {
1219 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1221 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1225 #ifdef CONFIG_LIBUDEV
1228 * Wrapper around build_guest_fsinfo_for_device() for getting just
1231 static GuestDiskAddress
*get_disk_address(const char *syspath
, Error
**errp
)
1233 g_autoptr(GuestFilesystemInfo
) fs
= NULL
;
1235 fs
= g_new0(GuestFilesystemInfo
, 1);
1236 build_guest_fsinfo_for_device(syspath
, fs
, errp
);
1237 if (fs
->disk
!= NULL
) {
1238 return g_steal_pointer(&fs
->disk
->value
);
1243 static char *get_alias_for_syspath(const char *syspath
)
1245 struct udev
*udev
= NULL
;
1246 struct udev_device
*udevice
= NULL
;
1251 g_debug("failed to query udev");
1254 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1255 if (udevice
== NULL
) {
1256 g_debug("failed to query udev for path: %s", syspath
);
1259 const char *alias
= udev_device_get_property_value(
1260 udevice
, "DM_NAME");
1262 * NULL means there was an error and empty string means there is no
1263 * alias. In case of no alias we return NULL instead of empty string.
1265 if (alias
== NULL
) {
1266 g_debug("failed to query udev for device alias for: %s",
1268 } else if (*alias
!= 0) {
1269 ret
= g_strdup(alias
);
1275 udev_device_unref(udevice
);
1279 static char *get_device_for_syspath(const char *syspath
)
1281 struct udev
*udev
= NULL
;
1282 struct udev_device
*udevice
= NULL
;
1287 g_debug("failed to query udev");
1290 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1291 if (udevice
== NULL
) {
1292 g_debug("failed to query udev for path: %s", syspath
);
1295 ret
= g_strdup(udev_device_get_devnode(udevice
));
1300 udev_device_unref(udevice
);
1304 static void get_disk_deps(const char *disk_dir
, GuestDiskInfo
*disk
)
1306 g_autofree
char *deps_dir
= NULL
;
1308 GDir
*dp_deps
= NULL
;
1310 /* List dependent disks */
1311 deps_dir
= g_strdup_printf("%s/slaves", disk_dir
);
1312 g_debug(" listing entries in: %s", deps_dir
);
1313 dp_deps
= g_dir_open(deps_dir
, 0, NULL
);
1314 if (dp_deps
== NULL
) {
1315 g_debug("failed to list entries in %s", deps_dir
);
1318 disk
->has_dependencies
= true;
1319 while ((dep
= g_dir_read_name(dp_deps
)) != NULL
) {
1320 g_autofree
char *dep_dir
= NULL
;
1323 /* Add dependent disks */
1324 dep_dir
= g_strdup_printf("%s/%s", deps_dir
, dep
);
1325 dev_name
= get_device_for_syspath(dep_dir
);
1326 if (dev_name
!= NULL
) {
1327 g_debug(" adding dependent device: %s", dev_name
);
1328 QAPI_LIST_PREPEND(disk
->dependencies
, dev_name
);
1331 g_dir_close(dp_deps
);
1335 * Detect partitions subdirectory, name is "<disk_name><number>" or
1336 * "<disk_name>p<number>"
1338 * @disk_name -- last component of /sys path (e.g. sda)
1339 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1340 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1342 static GuestDiskInfoList
*get_disk_partitions(
1343 GuestDiskInfoList
*list
,
1344 const char *disk_name
, const char *disk_dir
,
1345 const char *disk_dev
)
1347 GuestDiskInfoList
*ret
= list
;
1348 struct dirent
*de_disk
;
1349 DIR *dp_disk
= NULL
;
1350 size_t len
= strlen(disk_name
);
1352 dp_disk
= opendir(disk_dir
);
1353 while ((de_disk
= readdir(dp_disk
)) != NULL
) {
1354 g_autofree
char *partition_dir
= NULL
;
1356 GuestDiskInfo
*partition
;
1358 if (!(de_disk
->d_type
& DT_DIR
)) {
1362 if (!(strncmp(disk_name
, de_disk
->d_name
, len
) == 0 &&
1363 ((*(de_disk
->d_name
+ len
) == 'p' &&
1364 isdigit(*(de_disk
->d_name
+ len
+ 1))) ||
1365 isdigit(*(de_disk
->d_name
+ len
))))) {
1369 partition_dir
= g_strdup_printf("%s/%s",
1370 disk_dir
, de_disk
->d_name
);
1371 dev_name
= get_device_for_syspath(partition_dir
);
1372 if (dev_name
== NULL
) {
1373 g_debug("Failed to get device name for syspath: %s",
1377 partition
= g_new0(GuestDiskInfo
, 1);
1378 partition
->name
= dev_name
;
1379 partition
->partition
= true;
1380 partition
->has_dependencies
= true;
1381 /* Add parent disk as dependent for easier tracking of hierarchy */
1382 QAPI_LIST_PREPEND(partition
->dependencies
, g_strdup(disk_dev
));
1384 QAPI_LIST_PREPEND(ret
, partition
);
1391 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1393 GuestDiskInfoList
*ret
= NULL
;
1394 GuestDiskInfo
*disk
;
1396 struct dirent
*de
= NULL
;
1398 g_debug("listing /sys/block directory");
1399 dp
= opendir("/sys/block");
1401 error_setg_errno(errp
, errno
, "Can't open directory \"/sys/block\"");
1404 while ((de
= readdir(dp
)) != NULL
) {
1405 g_autofree
char *disk_dir
= NULL
, *line
= NULL
,
1408 Error
*local_err
= NULL
;
1409 if (de
->d_type
!= DT_LNK
) {
1410 g_debug(" skipping entry: %s", de
->d_name
);
1414 /* Check size and skip zero-sized disks */
1415 g_debug(" checking disk size");
1416 size_path
= g_strdup_printf("/sys/block/%s/size", de
->d_name
);
1417 if (!g_file_get_contents(size_path
, &line
, NULL
, NULL
)) {
1418 g_debug(" failed to read disk size");
1421 if (g_strcmp0(line
, "0\n") == 0) {
1422 g_debug(" skipping zero-sized disk");
1426 g_debug(" adding %s", de
->d_name
);
1427 disk_dir
= g_strdup_printf("/sys/block/%s", de
->d_name
);
1428 dev_name
= get_device_for_syspath(disk_dir
);
1429 if (dev_name
== NULL
) {
1430 g_debug("Failed to get device name for syspath: %s",
1434 disk
= g_new0(GuestDiskInfo
, 1);
1435 disk
->name
= dev_name
;
1436 disk
->partition
= false;
1437 disk
->alias
= get_alias_for_syspath(disk_dir
);
1438 disk
->has_alias
= (disk
->alias
!= NULL
);
1439 QAPI_LIST_PREPEND(ret
, disk
);
1441 /* Get address for non-virtual devices */
1442 bool is_virtual
= is_disk_virtual(disk_dir
, &local_err
);
1443 if (local_err
!= NULL
) {
1444 g_debug(" failed to check disk path, ignoring error: %s",
1445 error_get_pretty(local_err
));
1446 error_free(local_err
);
1448 /* Don't try to get the address */
1452 disk
->address
= get_disk_address(disk_dir
, &local_err
);
1453 if (local_err
!= NULL
) {
1454 g_debug(" failed to get device info, ignoring error: %s",
1455 error_get_pretty(local_err
));
1456 error_free(local_err
);
1458 } else if (disk
->address
!= NULL
) {
1459 disk
->has_address
= true;
1463 get_disk_deps(disk_dir
, disk
);
1464 ret
= get_disk_partitions(ret
, de
->d_name
, disk_dir
, dev_name
);
1474 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1476 error_setg(errp
, QERR_UNSUPPORTED
);
1482 /* Return a list of the disk device(s)' info which @mount lies on */
1483 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1486 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1488 unsigned long used
, nonroot_total
, fr_size
;
1489 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1490 mount
->devmajor
, mount
->devminor
);
1492 fs
->mountpoint
= g_strdup(mount
->dirname
);
1493 fs
->type
= g_strdup(mount
->devtype
);
1494 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1496 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1497 fr_size
= buf
.f_frsize
;
1498 used
= buf
.f_blocks
- buf
.f_bfree
;
1499 nonroot_total
= used
+ buf
.f_bavail
;
1500 fs
->used_bytes
= used
* fr_size
;
1501 fs
->total_bytes
= nonroot_total
* fr_size
;
1503 fs
->has_total_bytes
= true;
1504 fs
->has_used_bytes
= true;
1512 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1515 struct FsMount
*mount
;
1516 GuestFilesystemInfoList
*ret
= NULL
;
1517 Error
*local_err
= NULL
;
1519 QTAILQ_INIT(&mounts
);
1520 build_fs_mount_list(&mounts
, &local_err
);
1522 error_propagate(errp
, local_err
);
1526 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1527 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1529 QAPI_LIST_PREPEND(ret
, build_guest_fsinfo(mount
, &local_err
));
1531 error_propagate(errp
, local_err
);
1532 qapi_free_GuestFilesystemInfoList(ret
);
1538 free_fs_mount_list(&mounts
);
1544 FSFREEZE_HOOK_THAW
= 0,
1545 FSFREEZE_HOOK_FREEZE
,
1548 static const char *fsfreeze_hook_arg_string
[] = {
1553 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1558 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1559 Error
*local_err
= NULL
;
1561 hook
= ga_fsfreeze_hook(ga_state
);
1565 if (access(hook
, X_OK
) != 0) {
1566 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1570 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1574 reopen_fd_to_null(0);
1575 reopen_fd_to_null(1);
1576 reopen_fd_to_null(2);
1578 execl(hook
, hook
, arg_str
, NULL
);
1579 _exit(EXIT_FAILURE
);
1580 } else if (pid
< 0) {
1581 error_setg_errno(errp
, errno
, "failed to create child process");
1585 ga_wait_child(pid
, &status
, &local_err
);
1587 error_propagate(errp
, local_err
);
1591 if (!WIFEXITED(status
)) {
1592 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1596 status
= WEXITSTATUS(status
);
1598 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1604 * Return status of freeze/thaw
1606 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1608 if (ga_is_frozen(ga_state
)) {
1609 return GUEST_FSFREEZE_STATUS_FROZEN
;
1612 return GUEST_FSFREEZE_STATUS_THAWED
;
1615 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1617 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1621 * Walk list of mounted file systems in the guest, and freeze the ones which
1622 * are real local file systems.
1624 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1625 strList
*mountpoints
,
1631 struct FsMount
*mount
;
1632 Error
*local_err
= NULL
;
1635 slog("guest-fsfreeze called");
1637 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1639 error_propagate(errp
, local_err
);
1643 QTAILQ_INIT(&mounts
);
1644 build_fs_mount_list(&mounts
, &local_err
);
1646 error_propagate(errp
, local_err
);
1650 /* cannot risk guest agent blocking itself on a write in this state */
1651 ga_set_frozen(ga_state
);
1653 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, next
) {
1654 /* To issue fsfreeze in the reverse order of mounts, check if the
1655 * mount is listed in the list here */
1656 if (has_mountpoints
) {
1657 for (list
= mountpoints
; list
; list
= list
->next
) {
1658 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1667 fd
= qemu_open_old(mount
->dirname
, O_RDONLY
);
1669 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1673 /* we try to cull filesystems we know won't work in advance, but other
1674 * filesystems may not implement fsfreeze for less obvious reasons.
1675 * these will report EOPNOTSUPP. we simply ignore these when tallying
1676 * the number of frozen filesystems.
1677 * if a filesystem is mounted more than once (aka bind mount) a
1678 * consecutive attempt to freeze an already frozen filesystem will
1681 * any other error means a failure to freeze a filesystem we
1682 * expect to be freezable, so return an error in those cases
1683 * and return system to thawed state.
1685 ret
= ioctl(fd
, FIFREEZE
);
1687 if (errno
!= EOPNOTSUPP
&& errno
!= EBUSY
) {
1688 error_setg_errno(errp
, errno
, "failed to freeze %s",
1699 free_fs_mount_list(&mounts
);
1700 /* We may not issue any FIFREEZE here.
1701 * Just unset ga_state here and ready for the next call.
1704 ga_unset_frozen(ga_state
);
1709 free_fs_mount_list(&mounts
);
1710 qmp_guest_fsfreeze_thaw(NULL
);
1715 * Walk list of frozen file systems in the guest, and thaw them.
1717 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1722 int fd
, i
= 0, logged
;
1723 Error
*local_err
= NULL
;
1725 QTAILQ_INIT(&mounts
);
1726 build_fs_mount_list(&mounts
, &local_err
);
1728 error_propagate(errp
, local_err
);
1732 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1734 fd
= qemu_open_old(mount
->dirname
, O_RDONLY
);
1738 /* we have no way of knowing whether a filesystem was actually unfrozen
1739 * as a result of a successful call to FITHAW, only that if an error
1740 * was returned the filesystem was *not* unfrozen by that particular
1743 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1744 * to unfreeze, continuing issuing FITHAW until an error is returned,
1745 * in which case either the filesystem is in an unfreezable state, or,
1746 * more likely, it was thawed previously (and remains so afterward).
1748 * also, since the most recent successful call is the one that did
1749 * the actual unfreeze, we can use this to provide an accurate count
1750 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1751 * may * be useful for determining whether a filesystem was unfrozen
1752 * during the freeze/thaw phase by a process other than qemu-ga.
1755 ret
= ioctl(fd
, FITHAW
);
1756 if (ret
== 0 && !logged
) {
1764 ga_unset_frozen(ga_state
);
1765 free_fs_mount_list(&mounts
);
1767 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1772 static void guest_fsfreeze_cleanup(void)
1776 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1777 qmp_guest_fsfreeze_thaw(&err
);
1779 slog("failed to clean up frozen filesystems: %s",
1780 error_get_pretty(err
));
1785 #endif /* CONFIG_FSFREEZE */
1787 #if defined(CONFIG_FSTRIM)
1789 * Walk list of mounted file systems in the guest, and trim them.
1791 GuestFilesystemTrimResponse
*
1792 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1794 GuestFilesystemTrimResponse
*response
;
1795 GuestFilesystemTrimResult
*result
;
1798 struct FsMount
*mount
;
1800 Error
*local_err
= NULL
;
1801 struct fstrim_range r
;
1803 slog("guest-fstrim called");
1805 QTAILQ_INIT(&mounts
);
1806 build_fs_mount_list(&mounts
, &local_err
);
1808 error_propagate(errp
, local_err
);
1812 response
= g_malloc0(sizeof(*response
));
1814 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1815 result
= g_malloc0(sizeof(*result
));
1816 result
->path
= g_strdup(mount
->dirname
);
1818 QAPI_LIST_PREPEND(response
->paths
, result
);
1820 fd
= qemu_open_old(mount
->dirname
, O_RDONLY
);
1822 result
->error
= g_strdup_printf("failed to open: %s",
1824 result
->has_error
= true;
1828 /* We try to cull filesystems we know won't work in advance, but other
1829 * filesystems may not implement fstrim for less obvious reasons.
1830 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1831 * will be reported (e.g. CD-ROMs).
1832 * Any other error means an unexpected error.
1836 r
.minlen
= has_minimum
? minimum
: 0;
1837 ret
= ioctl(fd
, FITRIM
, &r
);
1839 result
->has_error
= true;
1840 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1841 result
->error
= g_strdup("trim not supported");
1843 result
->error
= g_strdup_printf("failed to trim: %s",
1850 result
->has_minimum
= true;
1851 result
->minimum
= r
.minlen
;
1852 result
->has_trimmed
= true;
1853 result
->trimmed
= r
.len
;
1857 free_fs_mount_list(&mounts
);
1860 #endif /* CONFIG_FSTRIM */
1863 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1864 #define SUSPEND_SUPPORTED 0
1865 #define SUSPEND_NOT_SUPPORTED 1
1868 SUSPEND_MODE_DISK
= 0,
1869 SUSPEND_MODE_RAM
= 1,
1870 SUSPEND_MODE_HYBRID
= 2,
1874 * Executes a command in a child process using g_spawn_sync,
1875 * returning an int >= 0 representing the exit status of the
1878 * If the program wasn't found in path, returns -1.
1880 * If a problem happened when creating the child process,
1881 * returns -1 and errp is set.
1883 static int run_process_child(const char *command
[], Error
**errp
)
1885 int exit_status
, spawn_flag
;
1886 GError
*g_err
= NULL
;
1889 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1890 G_SPAWN_STDERR_TO_DEV_NULL
;
1892 success
= g_spawn_sync(NULL
, (char **)command
, NULL
, spawn_flag
,
1893 NULL
, NULL
, NULL
, NULL
,
1894 &exit_status
, &g_err
);
1897 return WEXITSTATUS(exit_status
);
1900 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1901 error_setg(errp
, "failed to create child process, error '%s'",
1905 g_error_free(g_err
);
1909 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1911 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1912 "systemd-hybrid-sleep"};
1913 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
1916 status
= run_process_child(cmd
, errp
);
1919 * systemctl status uses LSB return codes so we can expect
1920 * status > 0 and be ok. To assert if the guest has support
1921 * for the selected suspend mode, status should be < 4. 4 is
1922 * the code for unknown service status, the return value when
1923 * the service does not exist. A common value is status = 3
1924 * (program is not running).
1926 if (status
> 0 && status
< 4) {
1933 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
1935 Error
*local_err
= NULL
;
1936 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
1937 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
1940 status
= run_process_child(cmd
, &local_err
);
1946 if ((status
== -1) && !local_err
) {
1947 error_setg(errp
, "the helper program 'systemctl %s' was not found",
1948 systemctl_args
[mode
]);
1953 error_propagate(errp
, local_err
);
1955 error_setg(errp
, "the helper program 'systemctl %s' returned an "
1956 "unexpected exit status code (%d)",
1957 systemctl_args
[mode
], status
);
1961 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
1963 Error
*local_err
= NULL
;
1964 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
1965 "--suspend-hybrid"};
1966 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
1969 status
= run_process_child(cmd
, &local_err
);
1971 if (status
== SUSPEND_SUPPORTED
) {
1975 if ((status
== -1) && !local_err
) {
1980 error_propagate(errp
, local_err
);
1983 "the helper program '%s' returned an unexpected exit"
1984 " status code (%d)", "pm-is-supported", status
);
1990 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
1992 Error
*local_err
= NULL
;
1993 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
1994 "pm-suspend-hybrid"};
1995 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
1998 status
= run_process_child(cmd
, &local_err
);
2004 if ((status
== -1) && !local_err
) {
2005 error_setg(errp
, "the helper program '%s' was not found",
2006 pmutils_binaries
[mode
]);
2011 error_propagate(errp
, local_err
);
2014 "the helper program '%s' returned an unexpected exit"
2015 " status code (%d)", pmutils_binaries
[mode
], status
);
2019 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
2021 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
2022 const char *sysfile_str
= sysfile_strs
[mode
];
2023 char buf
[32]; /* hopefully big enough */
2028 error_setg(errp
, "unknown guest suspend mode");
2032 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
2037 ret
= read(fd
, buf
, sizeof(buf
) - 1);
2044 if (strstr(buf
, sysfile_str
)) {
2050 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
2052 Error
*local_err
= NULL
;
2053 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
2054 const char *sysfile_str
= sysfile_strs
[mode
];
2059 error_setg(errp
, "unknown guest suspend mode");
2069 reopen_fd_to_null(0);
2070 reopen_fd_to_null(1);
2071 reopen_fd_to_null(2);
2073 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
2075 _exit(EXIT_FAILURE
);
2078 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
2079 _exit(EXIT_FAILURE
);
2082 _exit(EXIT_SUCCESS
);
2083 } else if (pid
< 0) {
2084 error_setg_errno(errp
, errno
, "failed to create child process");
2088 ga_wait_child(pid
, &status
, &local_err
);
2090 error_propagate(errp
, local_err
);
2094 if (WEXITSTATUS(status
)) {
2095 error_setg(errp
, "child process has failed to suspend");
2100 static void guest_suspend(SuspendMode mode
, Error
**errp
)
2102 Error
*local_err
= NULL
;
2103 bool mode_supported
= false;
2105 if (systemd_supports_mode(mode
, &local_err
)) {
2106 mode_supported
= true;
2107 systemd_suspend(mode
, &local_err
);
2114 error_free(local_err
);
2117 if (pmutils_supports_mode(mode
, &local_err
)) {
2118 mode_supported
= true;
2119 pmutils_suspend(mode
, &local_err
);
2126 error_free(local_err
);
2129 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
2130 mode_supported
= true;
2131 linux_sys_state_suspend(mode
, &local_err
);
2134 if (!mode_supported
) {
2135 error_free(local_err
);
2137 "the requested suspend mode is not supported by the guest");
2139 error_propagate(errp
, local_err
);
2143 void qmp_guest_suspend_disk(Error
**errp
)
2145 guest_suspend(SUSPEND_MODE_DISK
, errp
);
2148 void qmp_guest_suspend_ram(Error
**errp
)
2150 guest_suspend(SUSPEND_MODE_RAM
, errp
);
2153 void qmp_guest_suspend_hybrid(Error
**errp
)
2155 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
2158 /* Transfer online/offline status between @vcpu and the guest system.
2160 * On input either @errp or *@errp must be NULL.
2162 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2163 * - R: vcpu->logical_id
2165 * - W: vcpu->can_offline
2167 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2168 * - R: vcpu->logical_id
2171 * Written members remain unmodified on error.
2173 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
2174 char *dirpath
, Error
**errp
)
2179 static const char fn
[] = "online";
2181 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2183 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2187 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2189 if (errno
!= ENOENT
) {
2190 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2191 } else if (sys2vcpu
) {
2192 vcpu
->online
= true;
2193 vcpu
->can_offline
= false;
2194 } else if (!vcpu
->online
) {
2195 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2196 "offlined", vcpu
->logical_id
);
2197 } /* otherwise pretend successful re-onlining */
2199 unsigned char status
;
2201 res
= pread(fd
, &status
, 1, 0);
2203 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2204 } else if (res
== 0) {
2205 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2207 } else if (sys2vcpu
) {
2208 vcpu
->online
= (status
!= '0');
2209 vcpu
->can_offline
= true;
2210 } else if (vcpu
->online
!= (status
!= '0')) {
2211 status
= '0' + vcpu
->online
;
2212 if (pwrite(fd
, &status
, 1, 0) == -1) {
2213 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2216 } /* otherwise pretend successful re-(on|off)-lining */
2226 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2228 GuestLogicalProcessorList
*head
, **tail
;
2229 const char *cpu_dir
= "/sys/devices/system/cpu";
2231 g_autoptr(GDir
) cpu_gdir
= NULL
;
2232 Error
*local_err
= NULL
;
2236 cpu_gdir
= g_dir_open(cpu_dir
, 0, NULL
);
2238 if (cpu_gdir
== NULL
) {
2239 error_setg_errno(errp
, errno
, "failed to list entries: %s", cpu_dir
);
2243 while (local_err
== NULL
&& (line
= g_dir_read_name(cpu_gdir
)) != NULL
) {
2244 GuestLogicalProcessor
*vcpu
;
2246 if (sscanf(line
, "cpu%" PRId64
, &id
)) {
2247 g_autofree
char *path
= g_strdup_printf("/sys/devices/system/cpu/"
2248 "cpu%" PRId64
"/", id
);
2249 vcpu
= g_malloc0(sizeof *vcpu
);
2250 vcpu
->logical_id
= id
;
2251 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2252 transfer_vcpu(vcpu
, true, path
, &local_err
);
2253 QAPI_LIST_APPEND(tail
, vcpu
);
2257 if (local_err
== NULL
) {
2258 /* there's no guest with zero VCPUs */
2259 g_assert(head
!= NULL
);
2263 qapi_free_GuestLogicalProcessorList(head
);
2264 error_propagate(errp
, local_err
);
2268 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2271 Error
*local_err
= NULL
;
2274 while (vcpus
!= NULL
) {
2275 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2276 vcpus
->value
->logical_id
);
2278 transfer_vcpu(vcpus
->value
, false, path
, &local_err
);
2280 if (local_err
!= NULL
) {
2284 vcpus
= vcpus
->next
;
2287 if (local_err
!= NULL
) {
2288 if (processed
== 0) {
2289 error_propagate(errp
, local_err
);
2291 error_free(local_err
);
2298 void qmp_guest_set_user_password(const char *username
,
2299 const char *password
,
2303 Error
*local_err
= NULL
;
2304 char *passwd_path
= NULL
;
2307 int datafd
[2] = { -1, -1 };
2308 char *rawpasswddata
= NULL
;
2309 size_t rawpasswdlen
;
2310 char *chpasswddata
= NULL
;
2313 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2314 if (!rawpasswddata
) {
2317 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2318 rawpasswddata
[rawpasswdlen
] = '\0';
2320 if (strchr(rawpasswddata
, '\n')) {
2321 error_setg(errp
, "forbidden characters in raw password");
2325 if (strchr(username
, '\n') ||
2326 strchr(username
, ':')) {
2327 error_setg(errp
, "forbidden characters in username");
2331 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
2332 chpasswdlen
= strlen(chpasswddata
);
2334 passwd_path
= g_find_program_in_path("chpasswd");
2337 error_setg(errp
, "cannot find 'passwd' program in PATH");
2341 if (!g_unix_open_pipe(datafd
, FD_CLOEXEC
, NULL
)) {
2342 error_setg(errp
, "cannot create pipe FDs");
2352 reopen_fd_to_null(1);
2353 reopen_fd_to_null(2);
2356 execl(passwd_path
, "chpasswd", "-e", NULL
);
2358 execl(passwd_path
, "chpasswd", NULL
);
2360 _exit(EXIT_FAILURE
);
2361 } else if (pid
< 0) {
2362 error_setg_errno(errp
, errno
, "failed to create child process");
2368 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2369 error_setg_errno(errp
, errno
, "cannot write new account password");
2375 ga_wait_child(pid
, &status
, &local_err
);
2377 error_propagate(errp
, local_err
);
2381 if (!WIFEXITED(status
)) {
2382 error_setg(errp
, "child process has terminated abnormally");
2386 if (WEXITSTATUS(status
)) {
2387 error_setg(errp
, "child process has failed to set user password");
2392 g_free(chpasswddata
);
2393 g_free(rawpasswddata
);
2394 g_free(passwd_path
);
2395 if (datafd
[0] != -1) {
2398 if (datafd
[1] != -1) {
2403 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2404 int size
, Error
**errp
)
2410 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2412 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2416 res
= pread(fd
, buf
, size
, 0);
2418 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2419 } else if (res
== 0) {
2420 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2425 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2426 const char *buf
, int size
, Error
**errp
)
2431 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2433 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2437 if (pwrite(fd
, buf
, size
, 0) == -1) {
2438 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2444 /* Transfer online/offline status between @mem_blk and the guest system.
2446 * On input either @errp or *@errp must be NULL.
2448 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2449 * - R: mem_blk->phys_index
2450 * - W: mem_blk->online
2451 * - W: mem_blk->can_offline
2453 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2454 * - R: mem_blk->phys_index
2455 * - R: mem_blk->online
2456 *- R: mem_blk->can_offline
2457 * Written members remain unmodified on error.
2459 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2460 GuestMemoryBlockResponse
*result
,
2466 Error
*local_err
= NULL
;
2472 error_setg(errp
, "Internal error, 'result' should not be NULL");
2476 dp
= opendir("/sys/devices/system/memory/");
2477 /* if there is no 'memory' directory in sysfs,
2478 * we think this VM does not support online/offline memory block,
2479 * any other solution?
2482 if (errno
== ENOENT
) {
2484 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2491 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2492 mem_blk
->phys_index
);
2493 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2496 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2498 if (errno
== ENOENT
) {
2499 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2502 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2510 status
= g_malloc0(10);
2511 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2513 /* treat with sysfs file that not exist in old kernel */
2514 if (errno
== ENOENT
) {
2515 error_free(local_err
);
2517 mem_blk
->online
= true;
2518 mem_blk
->can_offline
= false;
2519 } else if (!mem_blk
->online
) {
2521 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2525 error_propagate(errp
, local_err
);
2527 error_free(local_err
);
2529 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2536 char removable
= '0';
2538 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2540 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2542 /* if no 'removable' file, it doesn't support offline mem blk */
2543 if (errno
== ENOENT
) {
2544 error_free(local_err
);
2545 mem_blk
->can_offline
= false;
2547 error_propagate(errp
, local_err
);
2550 mem_blk
->can_offline
= (removable
!= '0');
2553 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2554 const char *new_state
= mem_blk
->online
? "online" : "offline";
2556 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2559 error_free(local_err
);
2561 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2565 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2566 result
->has_error_code
= false;
2567 } /* otherwise pretend successful re-(on|off)-lining */
2578 result
->has_error_code
= true;
2579 result
->error_code
= errno
;
2583 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2585 GuestMemoryBlockList
*head
, **tail
;
2586 Error
*local_err
= NULL
;
2593 dp
= opendir("/sys/devices/system/memory/");
2595 /* it's ok if this happens to be a system that doesn't expose
2596 * memory blocks via sysfs, but otherwise we should report
2599 if (errno
!= ENOENT
) {
2600 error_setg_errno(errp
, errno
, "Can't open directory"
2601 "\"/sys/devices/system/memory/\"");
2606 /* Note: the phys_index of memory block may be discontinuous,
2607 * this is because a memblk is the unit of the Sparse Memory design, which
2608 * allows discontinuous memory ranges (ex. NUMA), so here we should
2609 * traverse the memory block directory.
2611 while ((de
= readdir(dp
)) != NULL
) {
2612 GuestMemoryBlock
*mem_blk
;
2614 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2615 !(de
->d_type
& DT_DIR
)) {
2619 mem_blk
= g_malloc0(sizeof *mem_blk
);
2620 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2621 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2622 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2623 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2628 QAPI_LIST_APPEND(tail
, mem_blk
);
2632 if (local_err
== NULL
) {
2633 /* there's no guest with zero memory blocks */
2635 error_setg(errp
, "guest reported zero memory blocks!");
2640 qapi_free_GuestMemoryBlockList(head
);
2641 error_propagate(errp
, local_err
);
2645 GuestMemoryBlockResponseList
*
2646 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2648 GuestMemoryBlockResponseList
*head
, **tail
;
2649 Error
*local_err
= NULL
;
2654 while (mem_blks
!= NULL
) {
2655 GuestMemoryBlockResponse
*result
;
2656 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2658 result
= g_malloc0(sizeof(*result
));
2659 result
->phys_index
= current_mem_blk
->phys_index
;
2660 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2661 if (local_err
) { /* should never happen */
2665 QAPI_LIST_APPEND(tail
, result
);
2666 mem_blks
= mem_blks
->next
;
2671 qapi_free_GuestMemoryBlockResponseList(head
);
2672 error_propagate(errp
, local_err
);
2676 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2678 Error
*local_err
= NULL
;
2682 GuestMemoryBlockInfo
*info
;
2684 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2685 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2687 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2693 buf
= g_malloc0(20);
2694 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2698 error_propagate(errp
, local_err
);
2702 info
= g_new0(GuestMemoryBlockInfo
, 1);
2703 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2710 #else /* defined(__linux__) */
2712 void qmp_guest_suspend_disk(Error
**errp
)
2714 error_setg(errp
, QERR_UNSUPPORTED
);
2717 void qmp_guest_suspend_ram(Error
**errp
)
2719 error_setg(errp
, QERR_UNSUPPORTED
);
2722 void qmp_guest_suspend_hybrid(Error
**errp
)
2724 error_setg(errp
, QERR_UNSUPPORTED
);
2727 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2729 error_setg(errp
, QERR_UNSUPPORTED
);
2733 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2735 error_setg(errp
, QERR_UNSUPPORTED
);
2739 void qmp_guest_set_user_password(const char *username
,
2740 const char *password
,
2744 error_setg(errp
, QERR_UNSUPPORTED
);
2747 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2749 error_setg(errp
, QERR_UNSUPPORTED
);
2753 GuestMemoryBlockResponseList
*
2754 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2756 error_setg(errp
, QERR_UNSUPPORTED
);
2760 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2762 error_setg(errp
, QERR_UNSUPPORTED
);
2768 #ifdef HAVE_GETIFADDRS
2769 static GuestNetworkInterface
*
2770 guest_find_interface(GuestNetworkInterfaceList
*head
,
2773 for (; head
; head
= head
->next
) {
2774 if (strcmp(head
->value
->name
, name
) == 0) {
2782 static int guest_get_network_stats(const char *name
,
2783 GuestNetworkInterfaceStat
*stats
)
2787 char const *devinfo
= "/proc/net/dev";
2789 char *line
= NULL
, *colon
;
2791 fp
= fopen(devinfo
, "r");
2793 g_debug("failed to open network stats %s: %s", devinfo
,
2797 name_len
= strlen(name
);
2798 while (getline(&line
, &n
, fp
) != -1) {
2801 long long rx_packets
;
2803 long long rx_dropped
;
2805 long long tx_packets
;
2807 long long tx_dropped
;
2809 trim_line
= g_strchug(line
);
2810 if (trim_line
[0] == '\0') {
2813 colon
= strchr(trim_line
, ':');
2817 if (colon
- name_len
== trim_line
&&
2818 strncmp(trim_line
, name
, name_len
) == 0) {
2819 if (sscanf(colon
+ 1,
2820 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2821 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
2822 &dummy
, &dummy
, &dummy
, &dummy
,
2823 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
2824 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
2827 stats
->rx_bytes
= rx_bytes
;
2828 stats
->rx_packets
= rx_packets
;
2829 stats
->rx_errs
= rx_errs
;
2830 stats
->rx_dropped
= rx_dropped
;
2831 stats
->tx_bytes
= tx_bytes
;
2832 stats
->tx_packets
= tx_packets
;
2833 stats
->tx_errs
= tx_errs
;
2834 stats
->tx_dropped
= tx_dropped
;
2842 g_debug("/proc/net/dev: Interface '%s' not found", name
);
2843 #else /* !CONFIG_LINUX */
2844 g_debug("Network stats reporting available only for Linux");
2845 #endif /* !CONFIG_LINUX */
2850 * Build information about guest interfaces
2852 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2854 GuestNetworkInterfaceList
*head
= NULL
, **tail
= &head
;
2855 struct ifaddrs
*ifap
, *ifa
;
2857 if (getifaddrs(&ifap
) < 0) {
2858 error_setg_errno(errp
, errno
, "getifaddrs failed");
2862 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
2863 GuestNetworkInterface
*info
;
2864 GuestIpAddressList
**address_tail
;
2865 GuestIpAddress
*address_item
= NULL
;
2866 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
2867 char addr4
[INET_ADDRSTRLEN
];
2868 char addr6
[INET6_ADDRSTRLEN
];
2871 unsigned char *mac_addr
;
2874 g_debug("Processing %s interface", ifa
->ifa_name
);
2876 info
= guest_find_interface(head
, ifa
->ifa_name
);
2879 info
= g_malloc0(sizeof(*info
));
2880 info
->name
= g_strdup(ifa
->ifa_name
);
2882 QAPI_LIST_APPEND(tail
, info
);
2885 if (!info
->has_hardware_address
) {
2886 /* we haven't obtained HW address yet */
2887 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
2889 error_setg_errno(errp
, errno
, "failed to create socket");
2893 memset(&ifr
, 0, sizeof(ifr
));
2894 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->name
);
2895 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
2897 * We can't get the hw addr of this interface, but that's not a
2898 * fatal error. Don't set info->hardware_address, but keep
2901 if (errno
== EADDRNOTAVAIL
) {
2902 /* The interface doesn't have a hw addr (e.g. loopback). */
2903 g_debug("failed to get MAC address of %s: %s",
2904 ifa
->ifa_name
, strerror(errno
));
2906 g_warning("failed to get MAC address of %s: %s",
2907 ifa
->ifa_name
, strerror(errno
));
2911 #ifdef CONFIG_SOLARIS
2912 mac_addr
= (unsigned char *) &ifr
.ifr_addr
.sa_data
;
2914 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
2916 info
->hardware_address
=
2917 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2918 (int) mac_addr
[0], (int) mac_addr
[1],
2919 (int) mac_addr
[2], (int) mac_addr
[3],
2920 (int) mac_addr
[4], (int) mac_addr
[5]);
2922 info
->has_hardware_address
= true;
2927 if (ifa
->ifa_addr
&&
2928 ifa
->ifa_addr
->sa_family
== AF_INET
) {
2929 /* interface with IPv4 address */
2930 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
2931 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
2932 error_setg_errno(errp
, errno
, "inet_ntop failed");
2936 address_item
= g_malloc0(sizeof(*address_item
));
2937 address_item
->ip_address
= g_strdup(addr4
);
2938 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
2940 if (ifa
->ifa_netmask
) {
2941 /* Count the number of set bits in netmask.
2942 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2943 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
2944 address_item
->prefix
= ctpop32(((uint32_t *) p
)[0]);
2946 } else if (ifa
->ifa_addr
&&
2947 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
2948 /* interface with IPv6 address */
2949 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
2950 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
2951 error_setg_errno(errp
, errno
, "inet_ntop failed");
2955 address_item
= g_malloc0(sizeof(*address_item
));
2956 address_item
->ip_address
= g_strdup(addr6
);
2957 address_item
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
2959 if (ifa
->ifa_netmask
) {
2960 /* Count the number of set bits in netmask.
2961 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2962 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
2963 address_item
->prefix
=
2964 ctpop32(((uint32_t *) p
)[0]) +
2965 ctpop32(((uint32_t *) p
)[1]) +
2966 ctpop32(((uint32_t *) p
)[2]) +
2967 ctpop32(((uint32_t *) p
)[3]);
2971 if (!address_item
) {
2975 address_tail
= &info
->ip_addresses
;
2976 while (*address_tail
) {
2977 address_tail
= &(*address_tail
)->next
;
2979 QAPI_LIST_APPEND(address_tail
, address_item
);
2981 info
->has_ip_addresses
= true;
2983 if (!info
->has_statistics
) {
2984 interface_stat
= g_malloc0(sizeof(*interface_stat
));
2985 if (guest_get_network_stats(info
->name
, interface_stat
) == -1) {
2986 info
->has_statistics
= false;
2987 g_free(interface_stat
);
2989 info
->statistics
= interface_stat
;
2990 info
->has_statistics
= true;
3000 qapi_free_GuestNetworkInterfaceList(head
);
3006 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
3008 error_setg(errp
, QERR_UNSUPPORTED
);
3012 #endif /* HAVE_GETIFADDRS */
3014 #if !defined(CONFIG_FSFREEZE)
3016 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
3018 error_setg(errp
, QERR_UNSUPPORTED
);
3022 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
3024 error_setg(errp
, QERR_UNSUPPORTED
);
3029 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
3031 error_setg(errp
, QERR_UNSUPPORTED
);
3036 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
3037 strList
*mountpoints
,
3040 error_setg(errp
, QERR_UNSUPPORTED
);
3045 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
3047 error_setg(errp
, QERR_UNSUPPORTED
);
3052 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
3054 error_setg(errp
, QERR_UNSUPPORTED
);
3058 #endif /* CONFIG_FSFREEZE */
3060 #if !defined(CONFIG_FSTRIM)
3061 GuestFilesystemTrimResponse
*
3062 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
3064 error_setg(errp
, QERR_UNSUPPORTED
);
3069 /* add unsupported commands to the blacklist */
3070 GList
*ga_command_blacklist_init(GList
*blacklist
)
3072 #if !defined(__linux__)
3074 const char *list
[] = {
3075 "guest-suspend-disk", "guest-suspend-ram",
3076 "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
3077 "guest-get-memory-blocks", "guest-set-memory-blocks",
3078 "guest-get-memory-block-size", "guest-get-memory-block-info",
3080 char **p
= (char **)list
;
3083 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
3088 #if !defined(HAVE_GETIFADDRS)
3089 blacklist
= g_list_append(blacklist
,
3090 g_strdup("guest-network-get-interfaces"));
3093 #if !defined(CONFIG_FSFREEZE)
3095 const char *list
[] = {
3096 "guest-get-fsinfo", "guest-fsfreeze-status",
3097 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3098 "guest-fsfreeze-thaw", "guest-get-fsinfo",
3099 "guest-get-disks", NULL
};
3100 char **p
= (char **)list
;
3103 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
3108 #if !defined(CONFIG_FSTRIM)
3109 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
3112 blacklist
= g_list_append(blacklist
, g_strdup("guest-get-devices"));
3117 /* register init/cleanup routines for stateful command groups */
3118 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
3120 #if defined(CONFIG_FSFREEZE)
3121 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
3127 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3129 static double ga_get_login_time(struct utmpx
*user_info
)
3131 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
3132 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
3133 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
3134 return seconds
+ useconds
;
3137 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3139 GHashTable
*cache
= NULL
;
3140 GuestUserList
*head
= NULL
, **tail
= &head
;
3141 struct utmpx
*user_info
= NULL
;
3142 gpointer value
= NULL
;
3143 GuestUser
*user
= NULL
;
3144 double login_time
= 0;
3146 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
3150 user_info
= getutxent();
3151 if (user_info
== NULL
) {
3153 } else if (user_info
->ut_type
!= USER_PROCESS
) {
3155 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
3156 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
3157 user
= (GuestUser
*)value
;
3158 login_time
= ga_get_login_time(user_info
);
3159 /* We're ensuring the earliest login time to be sent */
3160 if (login_time
< user
->login_time
) {
3161 user
->login_time
= login_time
;
3166 user
= g_new0(GuestUser
, 1);
3167 user
->user
= g_strdup(user_info
->ut_user
);
3168 user
->login_time
= ga_get_login_time(user_info
);
3170 g_hash_table_insert(cache
, user
->user
, user
);
3172 QAPI_LIST_APPEND(tail
, user
);
3175 g_hash_table_destroy(cache
);
3181 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3183 error_setg(errp
, QERR_UNSUPPORTED
);
3189 /* Replace escaped special characters with theire real values. The replacement
3190 * is done in place -- returned value is in the original string.
3192 static void ga_osrelease_replace_special(gchar
*value
)
3194 gchar
*p
, *p2
, quote
;
3196 /* Trim the string at first space or semicolon if it is not enclosed in
3197 * single or double quotes. */
3198 if ((value
[0] != '"') || (value
[0] == '\'')) {
3199 p
= strchr(value
, ' ');
3203 p
= strchr(value
, ';');
3224 /* Keep literal backslash followed by whatever is there */
3228 } else if (*p
== quote
) {
3236 static GKeyFile
*ga_parse_osrelease(const char *fname
)
3238 gchar
*content
= NULL
;
3239 gchar
*content2
= NULL
;
3241 GKeyFile
*keys
= g_key_file_new();
3242 const char *group
= "[os-release]\n";
3244 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
3245 slog("failed to read '%s', error: %s", fname
, err
->message
);
3249 if (!g_utf8_validate(content
, -1, NULL
)) {
3250 slog("file is not utf-8 encoded: %s", fname
);
3253 content2
= g_strdup_printf("%s%s", group
, content
);
3255 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
3257 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
3269 g_key_file_free(keys
);
3273 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
3275 GuestOSInfo
*info
= NULL
;
3276 struct utsname kinfo
;
3277 GKeyFile
*osrelease
= NULL
;
3278 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
3280 info
= g_new0(GuestOSInfo
, 1);
3282 if (uname(&kinfo
) != 0) {
3283 error_setg_errno(errp
, errno
, "uname failed");
3285 info
->has_kernel_version
= true;
3286 info
->kernel_version
= g_strdup(kinfo
.version
);
3287 info
->has_kernel_release
= true;
3288 info
->kernel_release
= g_strdup(kinfo
.release
);
3289 info
->has_machine
= true;
3290 info
->machine
= g_strdup(kinfo
.machine
);
3293 if (qga_os_release
!= NULL
) {
3294 osrelease
= ga_parse_osrelease(qga_os_release
);
3296 osrelease
= ga_parse_osrelease("/etc/os-release");
3297 if (osrelease
== NULL
) {
3298 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
3302 if (osrelease
!= NULL
) {
3305 #define GET_FIELD(field, osfield) do { \
3306 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3307 if (value != NULL) { \
3308 ga_osrelease_replace_special(value); \
3309 info->has_ ## field = true; \
3310 info->field = value; \
3313 GET_FIELD(id
, "ID");
3314 GET_FIELD(name
, "NAME");
3315 GET_FIELD(pretty_name
, "PRETTY_NAME");
3316 GET_FIELD(version
, "VERSION");
3317 GET_FIELD(version_id
, "VERSION_ID");
3318 GET_FIELD(variant
, "VARIANT");
3319 GET_FIELD(variant_id
, "VARIANT_ID");
3322 g_key_file_free(osrelease
);
3328 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
3330 error_setg(errp
, QERR_UNSUPPORTED
);
3335 #ifndef HOST_NAME_MAX
3336 # ifdef _POSIX_HOST_NAME_MAX
3337 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
3339 # define HOST_NAME_MAX 255
3343 char *qga_get_host_name(Error
**errp
)
3346 g_autofree
char *hostname
= NULL
;
3348 #ifdef _SC_HOST_NAME_MAX
3349 len
= sysconf(_SC_HOST_NAME_MAX
);
3350 #endif /* _SC_HOST_NAME_MAX */
3353 len
= HOST_NAME_MAX
;
3356 /* Unfortunately, gethostname() below does not guarantee a
3357 * NULL terminated string. Therefore, allocate one byte more
3359 hostname
= g_new0(char, len
+ 1);
3361 if (gethostname(hostname
, len
) < 0) {
3362 error_setg_errno(errp
, errno
,
3363 "cannot get hostname");
3367 return g_steal_pointer(&hostname
);