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 "qemu-common.h"
20 #include "guest-agent-core.h"
21 #include "qga-qapi-commands.h"
22 #include "qapi/error.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qemu/queue.h"
25 #include "qemu/host-utils.h"
26 #include "qemu/sockets.h"
27 #include "qemu/base64.h"
28 #include "qemu/cutils.h"
29 #include "commands-common.h"
35 #ifndef CONFIG_HAS_ENVIRON
37 #include <crt_externs.h>
38 #define environ (*_NSGetEnviron())
40 extern char **environ
;
44 #if defined(__linux__)
48 #include <arpa/inet.h>
49 #include <sys/socket.h>
51 #include <sys/statvfs.h>
58 #define CONFIG_FSFREEZE
65 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
72 rpid
= waitpid(pid
, status
, 0);
73 } while (rpid
== -1 && errno
== EINTR
);
76 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
81 g_assert(rpid
== pid
);
84 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
86 const char *shutdown_flag
;
87 Error
*local_err
= NULL
;
91 slog("guest-shutdown called, mode: %s", mode
);
92 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
94 } else if (strcmp(mode
, "halt") == 0) {
96 } else if (strcmp(mode
, "reboot") == 0) {
100 "mode is invalid (valid values are: halt|powerdown|reboot");
106 /* child, start the shutdown */
108 reopen_fd_to_null(0);
109 reopen_fd_to_null(1);
110 reopen_fd_to_null(2);
112 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
113 "hypervisor initiated shutdown", (char*)NULL
, environ
);
115 } else if (pid
< 0) {
116 error_setg_errno(errp
, errno
, "failed to create child process");
120 ga_wait_child(pid
, &status
, &local_err
);
122 error_propagate(errp
, local_err
);
126 if (!WIFEXITED(status
)) {
127 error_setg(errp
, "child process has terminated abnormally");
131 if (WEXITSTATUS(status
)) {
132 error_setg(errp
, "child process has failed to shutdown");
139 int64_t qmp_guest_get_time(Error
**errp
)
144 ret
= qemu_gettimeofday(&tq
);
146 error_setg_errno(errp
, errno
, "Failed to get time");
150 return tq
.tv_sec
* 1000000000LL + tq
.tv_usec
* 1000;
153 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
158 Error
*local_err
= NULL
;
160 static const char hwclock_path
[] = "/sbin/hwclock";
161 static int hwclock_available
= -1;
163 if (hwclock_available
< 0) {
164 hwclock_available
= (access(hwclock_path
, X_OK
) == 0);
167 if (!hwclock_available
) {
168 error_setg(errp
, QERR_UNSUPPORTED
);
172 /* If user has passed a time, validate and set it. */
176 /* year-2038 will overflow in case time_t is 32bit */
177 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
178 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
182 tv
.tv_sec
= time_ns
/ 1000000000;
183 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
184 g_date_set_time_t(&date
, tv
.tv_sec
);
185 if (date
.year
< 1970 || date
.year
>= 2070) {
186 error_setg_errno(errp
, errno
, "Invalid time");
190 ret
= settimeofday(&tv
, NULL
);
192 error_setg_errno(errp
, errno
, "Failed to set time to guest");
197 /* Now, if user has passed a time to set and the system time is set, we
198 * just need to synchronize the hardware clock. However, if no time was
199 * passed, user is requesting the opposite: set the system time from the
200 * hardware clock (RTC). */
204 reopen_fd_to_null(0);
205 reopen_fd_to_null(1);
206 reopen_fd_to_null(2);
208 /* Use '/sbin/hwclock -w' to set RTC from the system time,
209 * or '/sbin/hwclock -s' to set the system time from RTC. */
210 execle(hwclock_path
, "hwclock", has_time
? "-w" : "-s",
213 } else if (pid
< 0) {
214 error_setg_errno(errp
, errno
, "failed to create child process");
218 ga_wait_child(pid
, &status
, &local_err
);
220 error_propagate(errp
, local_err
);
224 if (!WIFEXITED(status
)) {
225 error_setg(errp
, "child process has terminated abnormally");
229 if (WEXITSTATUS(status
)) {
230 error_setg(errp
, "hwclock failed to set hardware clock to system time");
241 struct GuestFileHandle
{
245 QTAILQ_ENTRY(GuestFileHandle
) next
;
249 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
250 } guest_file_state
= {
251 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
254 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
256 GuestFileHandle
*gfh
;
259 handle
= ga_get_fd_handle(ga_state
, errp
);
264 gfh
= g_new0(GuestFileHandle
, 1);
267 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
272 GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
274 GuestFileHandle
*gfh
;
276 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
283 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
287 typedef const char * const ccpc
;
293 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
294 static const struct {
297 } guest_file_open_modes
[] = {
298 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
299 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
300 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
301 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
302 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
303 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
304 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
305 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
306 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
307 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
308 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
309 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
313 find_open_flag(const char *mode_str
, Error
**errp
)
317 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
320 form
= guest_file_open_modes
[mode
].forms
;
321 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
329 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
330 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
333 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
336 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
337 S_IRGRP | S_IWGRP | \
341 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
343 Error
*local_err
= NULL
;
346 oflag
= find_open_flag(mode
, &local_err
);
347 if (local_err
== NULL
) {
350 /* If the caller wants / allows creation of a new file, we implement it
351 * with a two step process: open() + (open() / fchmod()).
353 * First we insist on creating the file exclusively as a new file. If
354 * that succeeds, we're free to set any file-mode bits on it. (The
355 * motivation is that we want to set those file-mode bits independently
356 * of the current umask.)
358 * If the exclusive creation fails because the file already exists
359 * (EEXIST is not possible for any other reason), we just attempt to
360 * open the file, but in this case we won't be allowed to change the
361 * file-mode bits on the preexistent file.
363 * The pathname should never disappear between the two open()s in
364 * practice. If it happens, then someone very likely tried to race us.
365 * In this case just go ahead and report the ENOENT from the second
366 * open() to the caller.
368 * If the caller wants to open a preexistent file, then the first
369 * open() is decisive and its third argument is ignored, and the second
370 * open() and the fchmod() are never called.
372 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
373 if (fd
== -1 && errno
== EEXIST
) {
374 oflag
&= ~(unsigned)O_CREAT
;
375 fd
= open(path
, oflag
);
379 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
380 "(mode: '%s')", path
, mode
);
382 qemu_set_cloexec(fd
);
384 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
385 error_setg_errno(&local_err
, errno
, "failed to set permission "
386 "0%03o on new file '%s' (mode: '%s')",
387 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
391 f
= fdopen(fd
, mode
);
393 error_setg_errno(&local_err
, errno
, "failed to associate "
394 "stdio stream with file descriptor %d, "
395 "file '%s' (mode: '%s')", fd
, path
, mode
);
402 if (oflag
& O_CREAT
) {
408 error_propagate(errp
, local_err
);
412 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
416 Error
*local_err
= NULL
;
422 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
423 fh
= safe_open_or_create(path
, mode
, &local_err
);
424 if (local_err
!= NULL
) {
425 error_propagate(errp
, local_err
);
429 /* set fd non-blocking to avoid common use cases (like reading from a
430 * named pipe) from hanging the agent
432 qemu_set_nonblock(fileno(fh
));
434 handle
= guest_file_handle_add(fh
, errp
);
440 slog("guest-file-open, handle: %" PRId64
, handle
);
444 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
446 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
449 slog("guest-file-close called, handle: %" PRId64
, handle
);
454 ret
= fclose(gfh
->fh
);
456 error_setg_errno(errp
, errno
, "failed to close handle");
460 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
464 GuestFileRead
*guest_file_read_unsafe(GuestFileHandle
*gfh
,
465 int64_t count
, Error
**errp
)
467 GuestFileRead
*read_data
= NULL
;
472 /* explicitly flush when switching from writing to reading */
473 if (gfh
->state
== RW_STATE_WRITING
) {
474 int ret
= fflush(fh
);
476 error_setg_errno(errp
, errno
, "failed to flush file");
479 gfh
->state
= RW_STATE_NEW
;
482 buf
= g_malloc0(count
+1);
483 read_count
= fread(buf
, 1, count
, fh
);
485 error_setg_errno(errp
, errno
, "failed to read file");
488 read_data
= g_new0(GuestFileRead
, 1);
489 read_data
->count
= read_count
;
490 read_data
->eof
= feof(fh
);
492 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
494 gfh
->state
= RW_STATE_READING
;
502 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
503 bool has_count
, int64_t count
,
506 GuestFileWrite
*write_data
= NULL
;
510 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
519 if (gfh
->state
== RW_STATE_READING
) {
520 int ret
= fseek(fh
, 0, SEEK_CUR
);
522 error_setg_errno(errp
, errno
, "failed to seek file");
525 gfh
->state
= RW_STATE_NEW
;
528 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
535 } else if (count
< 0 || count
> buf_len
) {
536 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
542 write_count
= fwrite(buf
, 1, count
, fh
);
544 error_setg_errno(errp
, errno
, "failed to write to file");
545 slog("guest-file-write failed, handle: %" PRId64
, handle
);
547 write_data
= g_new0(GuestFileWrite
, 1);
548 write_data
->count
= write_count
;
549 write_data
->eof
= feof(fh
);
550 gfh
->state
= RW_STATE_WRITING
;
558 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
559 GuestFileWhence
*whence_code
,
562 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
563 GuestFileSeek
*seek_data
= NULL
;
573 /* We stupidly exposed 'whence':'int' in our qapi */
574 whence
= ga_parse_whence(whence_code
, &err
);
576 error_propagate(errp
, err
);
581 ret
= fseek(fh
, offset
, whence
);
583 error_setg_errno(errp
, errno
, "failed to seek file");
584 if (errno
== ESPIPE
) {
585 /* file is non-seekable, stdio shouldn't be buffering anyways */
586 gfh
->state
= RW_STATE_NEW
;
589 seek_data
= g_new0(GuestFileSeek
, 1);
590 seek_data
->position
= ftell(fh
);
591 seek_data
->eof
= feof(fh
);
592 gfh
->state
= RW_STATE_NEW
;
599 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
601 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
612 error_setg_errno(errp
, errno
, "failed to flush file");
614 gfh
->state
= RW_STATE_NEW
;
618 /* linux-specific implementations. avoid this if at all possible. */
619 #if defined(__linux__)
621 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
622 typedef struct FsMount
{
625 unsigned int devmajor
, devminor
;
626 QTAILQ_ENTRY(FsMount
) next
;
629 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
631 static void free_fs_mount_list(FsMountList
*mounts
)
633 FsMount
*mount
, *temp
;
639 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
640 QTAILQ_REMOVE(mounts
, mount
, next
);
641 g_free(mount
->dirname
);
642 g_free(mount
->devtype
);
647 static int dev_major_minor(const char *devpath
,
648 unsigned int *devmajor
, unsigned int *devminor
)
655 if (stat(devpath
, &st
) < 0) {
656 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
659 if (S_ISDIR(st
.st_mode
)) {
660 /* It is bind mount */
663 if (S_ISBLK(st
.st_mode
)) {
664 *devmajor
= major(st
.st_rdev
);
665 *devminor
= minor(st
.st_rdev
);
672 * Walk the mount table and build a list of local file systems
674 static void build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
678 char const *mtab
= "/proc/self/mounts";
680 unsigned int devmajor
, devminor
;
682 fp
= setmntent(mtab
, "r");
684 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
688 while ((ment
= getmntent(fp
))) {
690 * An entry which device name doesn't start with a '/' is
691 * either a dummy file system or a network file system.
692 * Add special handling for smbfs and cifs as is done by
695 if ((ment
->mnt_fsname
[0] != '/') ||
696 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
697 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
700 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
701 /* Skip bind mounts */
705 mount
= g_new0(FsMount
, 1);
706 mount
->dirname
= g_strdup(ment
->mnt_dir
);
707 mount
->devtype
= g_strdup(ment
->mnt_type
);
708 mount
->devmajor
= devmajor
;
709 mount
->devminor
= devminor
;
711 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
717 static void decode_mntname(char *name
, int len
)
720 for (i
= 0; i
<= len
; i
++) {
721 if (name
[i
] != '\\') {
723 } else if (name
[i
+ 1] == '\\') {
726 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
727 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
728 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
729 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
730 (name
[i
+ 2] - '0') * 8 +
739 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
742 char const *mountinfo
= "/proc/self/mountinfo";
744 char *line
= NULL
, *dash
;
747 unsigned int devmajor
, devminor
;
748 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
750 fp
= fopen(mountinfo
, "r");
752 build_fs_mount_list_from_mtab(mounts
, errp
);
756 while (getline(&line
, &n
, fp
) != -1) {
757 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
758 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
762 dash
= strstr(line
+ dir_e
, " - ");
766 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
767 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
774 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
775 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
777 /* btrfs reports major number = 0 */
778 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
779 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
784 mount
= g_new0(FsMount
, 1);
785 mount
->dirname
= g_strdup(line
+ dir_s
);
786 mount
->devtype
= g_strdup(dash
+ type_s
);
787 mount
->devmajor
= devmajor
;
788 mount
->devminor
= devminor
;
790 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
798 #if defined(CONFIG_FSFREEZE)
800 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
808 path
= g_strndup(syspath
, pathlen
);
809 dpath
= g_strdup_printf("%s/driver", path
);
810 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
813 driver
= g_path_get_basename(buf
);
820 static int compare_uint(const void *_a
, const void *_b
)
822 unsigned int a
= *(unsigned int *)_a
;
823 unsigned int b
= *(unsigned int *)_b
;
825 return a
< b
? -1 : a
> b
? 1 : 0;
828 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
829 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
830 unsigned int *hosts
, int hosts_max
, Error
**errp
)
834 struct dirent
*entry
;
837 path
= g_strndup(syspath
, host
- syspath
);
840 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
845 while (i
< hosts_max
) {
846 entry
= readdir(dir
);
850 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
852 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
857 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
865 * Store disk device info for devices on the PCI bus.
866 * Returns true if information has been stored, or false for failure.
868 static bool build_guest_fsinfo_for_pci_dev(char const *syspath
,
869 GuestDiskAddress
*disk
,
872 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
873 int i
, nhosts
= 0, pcilen
;
874 GuestPCIAddress
*pciaddr
= disk
->pci_controller
;
875 bool has_ata
= false, has_host
= false, has_tgt
= false;
876 char *p
, *q
, *driver
= NULL
;
879 p
= strstr(syspath
, "/devices/pci");
880 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
881 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
882 g_debug("only pci device is supported: sysfs path '%s'", syspath
);
888 driver
= get_pci_driver(syspath
, p
- syspath
, errp
);
889 if (driver
&& (g_str_equal(driver
, "ata_piix") ||
890 g_str_equal(driver
, "sym53c8xx") ||
891 g_str_equal(driver
, "virtio-pci") ||
892 g_str_equal(driver
, "ahci"))) {
897 if (sscanf(p
, "/%x:%x:%x.%x%n",
898 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) == 4) {
903 g_debug("unsupported driver or sysfs path '%s'", syspath
);
907 p
= strstr(syspath
, "/target");
908 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
909 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
913 p
= strstr(syspath
, "/ata");
918 p
= strstr(syspath
, "/host");
921 if (p
&& sscanf(q
, "%u", &host
) == 1) {
923 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
924 ARRAY_SIZE(hosts
), errp
);
930 pciaddr
->domain
= pci
[0];
931 pciaddr
->bus
= pci
[1];
932 pciaddr
->slot
= pci
[2];
933 pciaddr
->function
= pci
[3];
935 if (strcmp(driver
, "ata_piix") == 0) {
936 /* a host per ide bus, target*:0:<unit>:0 */
937 if (!has_host
|| !has_tgt
) {
938 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
941 for (i
= 0; i
< nhosts
; i
++) {
942 if (host
== hosts
[i
]) {
943 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
950 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
953 } else if (strcmp(driver
, "sym53c8xx") == 0) {
954 /* scsi(LSI Logic): target*:0:<unit>:0 */
956 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
959 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
961 } else if (strcmp(driver
, "virtio-pci") == 0) {
963 /* virtio-scsi: target*:0:0:<unit> */
964 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
967 /* virtio-blk: 1 disk per 1 device */
968 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
970 } else if (strcmp(driver
, "ahci") == 0) {
971 /* ahci: 1 host per 1 unit */
972 if (!has_host
|| !has_tgt
) {
973 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
976 for (i
= 0; i
< nhosts
; i
++) {
977 if (host
== hosts
[i
]) {
979 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
984 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
988 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
1000 * Store disk device info for non-PCI virtio devices (for example s390x
1001 * channel I/O devices). Returns true if information has been stored, or
1002 * false for failure.
1004 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath
,
1005 GuestDiskAddress
*disk
,
1008 unsigned int tgt
[3];
1011 if (!strstr(syspath
, "/virtio") || !strstr(syspath
, "/block")) {
1012 g_debug("Unsupported virtio device '%s'", syspath
);
1016 p
= strstr(syspath
, "/target");
1017 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1018 &tgt
[0], &tgt
[1], &tgt
[2]) == 3) {
1019 /* virtio-scsi: target*:0:<target>:<unit> */
1020 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
1022 disk
->target
= tgt
[1];
1023 disk
->unit
= tgt
[2];
1025 /* virtio-blk: 1 disk per 1 device */
1026 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
1032 /* Store disk device info specified by @sysfs into @fs */
1033 static void build_guest_fsinfo_for_real_device(char const *syspath
,
1034 GuestFilesystemInfo
*fs
,
1037 GuestDiskAddress
*disk
;
1038 GuestPCIAddress
*pciaddr
;
1039 GuestDiskAddressList
*list
= NULL
;
1041 #ifdef CONFIG_LIBUDEV
1042 struct udev
*udev
= NULL
;
1043 struct udev_device
*udevice
= NULL
;
1046 pciaddr
= g_new0(GuestPCIAddress
, 1);
1047 pciaddr
->domain
= -1; /* -1 means field is invalid */
1050 pciaddr
->function
= -1;
1052 disk
= g_new0(GuestDiskAddress
, 1);
1053 disk
->pci_controller
= pciaddr
;
1054 disk
->bus_type
= GUEST_DISK_BUS_TYPE_UNKNOWN
;
1056 list
= g_new0(GuestDiskAddressList
, 1);
1059 #ifdef CONFIG_LIBUDEV
1061 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1062 if (udev
== NULL
|| udevice
== NULL
) {
1063 g_debug("failed to query udev");
1065 const char *devnode
, *serial
;
1066 devnode
= udev_device_get_devnode(udevice
);
1067 if (devnode
!= NULL
) {
1068 disk
->dev
= g_strdup(devnode
);
1069 disk
->has_dev
= true;
1071 serial
= udev_device_get_property_value(udevice
, "ID_SERIAL");
1072 if (serial
!= NULL
&& *serial
!= 0) {
1073 disk
->serial
= g_strdup(serial
);
1074 disk
->has_serial
= true;
1079 udev_device_unref(udevice
);
1082 if (strstr(syspath
, "/devices/pci")) {
1083 has_hwinf
= build_guest_fsinfo_for_pci_dev(syspath
, disk
, errp
);
1084 } else if (strstr(syspath
, "/virtio")) {
1085 has_hwinf
= build_guest_fsinfo_for_nonpci_virtio(syspath
, disk
, errp
);
1087 g_debug("Unsupported device type for '%s'", syspath
);
1091 if (has_hwinf
|| disk
->has_dev
|| disk
->has_serial
) {
1092 list
->next
= fs
->disk
;
1095 qapi_free_GuestDiskAddressList(list
);
1099 static void build_guest_fsinfo_for_device(char const *devpath
,
1100 GuestFilesystemInfo
*fs
,
1103 /* Store a list of slave devices of virtual volume specified by @syspath into
1105 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1106 GuestFilesystemInfo
*fs
,
1112 struct dirent
*entry
;
1114 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1115 dir
= opendir(dirpath
);
1117 if (errno
!= ENOENT
) {
1118 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1126 entry
= readdir(dir
);
1127 if (entry
== NULL
) {
1129 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1134 if (entry
->d_type
== DT_LNK
) {
1137 g_debug(" slave device '%s'", entry
->d_name
);
1138 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1139 build_guest_fsinfo_for_device(path
, fs
, &err
);
1143 error_propagate(errp
, err
);
1153 static bool is_disk_virtual(const char *devpath
, Error
**errp
)
1155 g_autofree
char *syspath
= realpath(devpath
, NULL
);
1158 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1161 return strstr(syspath
, "/devices/virtual/block/") != NULL
;
1164 /* Dispatch to functions for virtual/real device */
1165 static void build_guest_fsinfo_for_device(char const *devpath
,
1166 GuestFilesystemInfo
*fs
,
1170 g_autofree
char *syspath
= NULL
;
1171 bool is_virtual
= false;
1173 syspath
= realpath(devpath
, NULL
);
1175 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1180 fs
->name
= g_path_get_basename(syspath
);
1183 g_debug(" parse sysfs path '%s'", syspath
);
1184 is_virtual
= is_disk_virtual(syspath
, errp
);
1185 if (*errp
!= NULL
) {
1189 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1191 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1195 #ifdef CONFIG_LIBUDEV
1198 * Wrapper around build_guest_fsinfo_for_device() for getting just
1201 static GuestDiskAddress
*get_disk_address(const char *syspath
, Error
**errp
)
1203 g_autoptr(GuestFilesystemInfo
) fs
= NULL
;
1205 fs
= g_new0(GuestFilesystemInfo
, 1);
1206 build_guest_fsinfo_for_device(syspath
, fs
, errp
);
1207 if (fs
->disk
!= NULL
) {
1208 return g_steal_pointer(&fs
->disk
->value
);
1213 static char *get_alias_for_syspath(const char *syspath
)
1215 struct udev
*udev
= NULL
;
1216 struct udev_device
*udevice
= NULL
;
1221 g_debug("failed to query udev");
1224 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1225 if (udevice
== NULL
) {
1226 g_debug("failed to query udev for path: %s", syspath
);
1229 const char *alias
= udev_device_get_property_value(
1230 udevice
, "DM_NAME");
1232 * NULL means there was an error and empty string means there is no
1233 * alias. In case of no alias we return NULL instead of empty string.
1235 if (alias
== NULL
) {
1236 g_debug("failed to query udev for device alias for: %s",
1238 } else if (*alias
!= 0) {
1239 ret
= g_strdup(alias
);
1245 udev_device_unref(udevice
);
1249 static char *get_device_for_syspath(const char *syspath
)
1251 struct udev
*udev
= NULL
;
1252 struct udev_device
*udevice
= NULL
;
1257 g_debug("failed to query udev");
1260 udevice
= udev_device_new_from_syspath(udev
, syspath
);
1261 if (udevice
== NULL
) {
1262 g_debug("failed to query udev for path: %s", syspath
);
1265 ret
= g_strdup(udev_device_get_devnode(udevice
));
1270 udev_device_unref(udevice
);
1274 static void get_disk_deps(const char *disk_dir
, GuestDiskInfo
*disk
)
1276 g_autofree
char *deps_dir
= NULL
;
1278 GDir
*dp_deps
= NULL
;
1280 /* List dependent disks */
1281 deps_dir
= g_strdup_printf("%s/slaves", disk_dir
);
1282 g_debug(" listing entries in: %s", deps_dir
);
1283 dp_deps
= g_dir_open(deps_dir
, 0, NULL
);
1284 if (dp_deps
== NULL
) {
1285 g_debug("failed to list entries in %s", deps_dir
);
1288 while ((dep
= g_dir_read_name(dp_deps
)) != NULL
) {
1289 g_autofree
char *dep_dir
= NULL
;
1290 strList
*dep_item
= NULL
;
1293 /* Add dependent disks */
1294 dep_dir
= g_strdup_printf("%s/%s", deps_dir
, dep
);
1295 dev_name
= get_device_for_syspath(dep_dir
);
1296 if (dev_name
!= NULL
) {
1297 g_debug(" adding dependent device: %s", dev_name
);
1298 dep_item
= g_new0(strList
, 1);
1299 dep_item
->value
= dev_name
;
1300 dep_item
->next
= disk
->dependents
;
1301 disk
->dependents
= dep_item
;
1304 g_dir_close(dp_deps
);
1308 * Detect partitions subdirectory, name is "<disk_name><number>" or
1309 * "<disk_name>p<number>"
1311 * @disk_name -- last component of /sys path (e.g. sda)
1312 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1313 * @disk_dev -- device node of the disk (e.g. /dev/sda)
1315 static GuestDiskInfoList
*get_disk_partitions(
1316 GuestDiskInfoList
*list
,
1317 const char *disk_name
, const char *disk_dir
,
1318 const char *disk_dev
)
1320 GuestDiskInfoList
*item
, *ret
= list
;
1321 struct dirent
*de_disk
;
1322 DIR *dp_disk
= NULL
;
1323 size_t len
= strlen(disk_name
);
1325 dp_disk
= opendir(disk_dir
);
1326 while ((de_disk
= readdir(dp_disk
)) != NULL
) {
1327 g_autofree
char *partition_dir
= NULL
;
1329 GuestDiskInfo
*partition
;
1331 if (!(de_disk
->d_type
& DT_DIR
)) {
1335 if (!(strncmp(disk_name
, de_disk
->d_name
, len
) == 0 &&
1336 ((*(de_disk
->d_name
+ len
) == 'p' &&
1337 isdigit(*(de_disk
->d_name
+ len
+ 1))) ||
1338 isdigit(*(de_disk
->d_name
+ len
))))) {
1342 partition_dir
= g_strdup_printf("%s/%s",
1343 disk_dir
, de_disk
->d_name
);
1344 dev_name
= get_device_for_syspath(partition_dir
);
1345 if (dev_name
== NULL
) {
1346 g_debug("Failed to get device name for syspath: %s",
1350 partition
= g_new0(GuestDiskInfo
, 1);
1351 partition
->name
= dev_name
;
1352 partition
->partition
= true;
1353 /* Add parent disk as dependent for easier tracking of hierarchy */
1354 partition
->dependents
= g_new0(strList
, 1);
1355 partition
->dependents
->value
= g_strdup(disk_dev
);
1357 item
= g_new0(GuestDiskInfoList
, 1);
1358 item
->value
= partition
;
1368 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1370 GuestDiskInfoList
*item
, *ret
= NULL
;
1371 GuestDiskInfo
*disk
;
1373 struct dirent
*de
= NULL
;
1375 g_debug("listing /sys/block directory");
1376 dp
= opendir("/sys/block");
1378 error_setg_errno(errp
, errno
, "Can't open directory \"/sys/block\"");
1381 while ((de
= readdir(dp
)) != NULL
) {
1382 g_autofree
char *disk_dir
= NULL
, *line
= NULL
,
1385 Error
*local_err
= NULL
;
1386 if (de
->d_type
!= DT_LNK
) {
1387 g_debug(" skipping entry: %s", de
->d_name
);
1391 /* Check size and skip zero-sized disks */
1392 g_debug(" checking disk size");
1393 size_path
= g_strdup_printf("/sys/block/%s/size", de
->d_name
);
1394 if (!g_file_get_contents(size_path
, &line
, NULL
, NULL
)) {
1395 g_debug(" failed to read disk size");
1398 if (g_strcmp0(line
, "0\n") == 0) {
1399 g_debug(" skipping zero-sized disk");
1403 g_debug(" adding %s", de
->d_name
);
1404 disk_dir
= g_strdup_printf("/sys/block/%s", de
->d_name
);
1405 dev_name
= get_device_for_syspath(disk_dir
);
1406 if (dev_name
== NULL
) {
1407 g_debug("Failed to get device name for syspath: %s",
1411 disk
= g_new0(GuestDiskInfo
, 1);
1412 disk
->name
= dev_name
;
1413 disk
->partition
= false;
1414 disk
->alias
= get_alias_for_syspath(disk_dir
);
1415 disk
->has_alias
= (disk
->alias
!= NULL
);
1416 item
= g_new0(GuestDiskInfoList
, 1);
1421 /* Get address for non-virtual devices */
1422 bool is_virtual
= is_disk_virtual(disk_dir
, &local_err
);
1423 if (local_err
!= NULL
) {
1424 g_debug(" failed to check disk path, ignoring error: %s",
1425 error_get_pretty(local_err
));
1426 error_free(local_err
);
1428 /* Don't try to get the address */
1432 disk
->address
= get_disk_address(disk_dir
, &local_err
);
1433 if (local_err
!= NULL
) {
1434 g_debug(" failed to get device info, ignoring error: %s",
1435 error_get_pretty(local_err
));
1436 error_free(local_err
);
1438 } else if (disk
->address
!= NULL
) {
1439 disk
->has_address
= true;
1443 get_disk_deps(disk_dir
, disk
);
1444 ret
= get_disk_partitions(ret
, de
->d_name
, disk_dir
, dev_name
);
1451 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
1453 error_setg(errp
, QERR_UNSUPPORTED
);
1459 /* Return a list of the disk device(s)' info which @mount lies on */
1460 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1463 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1465 unsigned long used
, nonroot_total
, fr_size
;
1466 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1467 mount
->devmajor
, mount
->devminor
);
1469 fs
->mountpoint
= g_strdup(mount
->dirname
);
1470 fs
->type
= g_strdup(mount
->devtype
);
1471 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1473 if (statvfs(fs
->mountpoint
, &buf
) == 0) {
1474 fr_size
= buf
.f_frsize
;
1475 used
= buf
.f_blocks
- buf
.f_bfree
;
1476 nonroot_total
= used
+ buf
.f_bavail
;
1477 fs
->used_bytes
= used
* fr_size
;
1478 fs
->total_bytes
= nonroot_total
* fr_size
;
1480 fs
->has_total_bytes
= true;
1481 fs
->has_used_bytes
= true;
1489 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1492 struct FsMount
*mount
;
1493 GuestFilesystemInfoList
*new, *ret
= NULL
;
1494 Error
*local_err
= NULL
;
1496 QTAILQ_INIT(&mounts
);
1497 build_fs_mount_list(&mounts
, &local_err
);
1499 error_propagate(errp
, local_err
);
1503 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1504 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1506 new = g_malloc0(sizeof(*ret
));
1507 new->value
= build_guest_fsinfo(mount
, &local_err
);
1511 error_propagate(errp
, local_err
);
1512 qapi_free_GuestFilesystemInfoList(ret
);
1518 free_fs_mount_list(&mounts
);
1524 FSFREEZE_HOOK_THAW
= 0,
1525 FSFREEZE_HOOK_FREEZE
,
1528 static const char *fsfreeze_hook_arg_string
[] = {
1533 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1538 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1539 Error
*local_err
= NULL
;
1541 hook
= ga_fsfreeze_hook(ga_state
);
1545 if (access(hook
, X_OK
) != 0) {
1546 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1550 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1554 reopen_fd_to_null(0);
1555 reopen_fd_to_null(1);
1556 reopen_fd_to_null(2);
1558 execle(hook
, hook
, arg_str
, NULL
, environ
);
1559 _exit(EXIT_FAILURE
);
1560 } else if (pid
< 0) {
1561 error_setg_errno(errp
, errno
, "failed to create child process");
1565 ga_wait_child(pid
, &status
, &local_err
);
1567 error_propagate(errp
, local_err
);
1571 if (!WIFEXITED(status
)) {
1572 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1576 status
= WEXITSTATUS(status
);
1578 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1584 * Return status of freeze/thaw
1586 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1588 if (ga_is_frozen(ga_state
)) {
1589 return GUEST_FSFREEZE_STATUS_FROZEN
;
1592 return GUEST_FSFREEZE_STATUS_THAWED
;
1595 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1597 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1601 * Walk list of mounted file systems in the guest, and freeze the ones which
1602 * are real local file systems.
1604 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1605 strList
*mountpoints
,
1611 struct FsMount
*mount
;
1612 Error
*local_err
= NULL
;
1615 slog("guest-fsfreeze called");
1617 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1619 error_propagate(errp
, local_err
);
1623 QTAILQ_INIT(&mounts
);
1624 build_fs_mount_list(&mounts
, &local_err
);
1626 error_propagate(errp
, local_err
);
1630 /* cannot risk guest agent blocking itself on a write in this state */
1631 ga_set_frozen(ga_state
);
1633 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, next
) {
1634 /* To issue fsfreeze in the reverse order of mounts, check if the
1635 * mount is listed in the list here */
1636 if (has_mountpoints
) {
1637 for (list
= mountpoints
; list
; list
= list
->next
) {
1638 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1647 fd
= qemu_open_old(mount
->dirname
, O_RDONLY
);
1649 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1653 /* we try to cull filesystems we know won't work in advance, but other
1654 * filesystems may not implement fsfreeze for less obvious reasons.
1655 * these will report EOPNOTSUPP. we simply ignore these when tallying
1656 * the number of frozen filesystems.
1657 * if a filesystem is mounted more than once (aka bind mount) a
1658 * consecutive attempt to freeze an already frozen filesystem will
1661 * any other error means a failure to freeze a filesystem we
1662 * expect to be freezable, so return an error in those cases
1663 * and return system to thawed state.
1665 ret
= ioctl(fd
, FIFREEZE
);
1667 if (errno
!= EOPNOTSUPP
&& errno
!= EBUSY
) {
1668 error_setg_errno(errp
, errno
, "failed to freeze %s",
1679 free_fs_mount_list(&mounts
);
1680 /* We may not issue any FIFREEZE here.
1681 * Just unset ga_state here and ready for the next call.
1684 ga_unset_frozen(ga_state
);
1689 free_fs_mount_list(&mounts
);
1690 qmp_guest_fsfreeze_thaw(NULL
);
1695 * Walk list of frozen file systems in the guest, and thaw them.
1697 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1702 int fd
, i
= 0, logged
;
1703 Error
*local_err
= NULL
;
1705 QTAILQ_INIT(&mounts
);
1706 build_fs_mount_list(&mounts
, &local_err
);
1708 error_propagate(errp
, local_err
);
1712 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1714 fd
= qemu_open_old(mount
->dirname
, O_RDONLY
);
1718 /* we have no way of knowing whether a filesystem was actually unfrozen
1719 * as a result of a successful call to FITHAW, only that if an error
1720 * was returned the filesystem was *not* unfrozen by that particular
1723 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1724 * to unfreeze, continuing issuing FITHAW until an error is returned,
1725 * in which case either the filesystem is in an unfreezable state, or,
1726 * more likely, it was thawed previously (and remains so afterward).
1728 * also, since the most recent successful call is the one that did
1729 * the actual unfreeze, we can use this to provide an accurate count
1730 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1731 * may * be useful for determining whether a filesystem was unfrozen
1732 * during the freeze/thaw phase by a process other than qemu-ga.
1735 ret
= ioctl(fd
, FITHAW
);
1736 if (ret
== 0 && !logged
) {
1744 ga_unset_frozen(ga_state
);
1745 free_fs_mount_list(&mounts
);
1747 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1752 static void guest_fsfreeze_cleanup(void)
1756 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1757 qmp_guest_fsfreeze_thaw(&err
);
1759 slog("failed to clean up frozen filesystems: %s",
1760 error_get_pretty(err
));
1765 #endif /* CONFIG_FSFREEZE */
1767 #if defined(CONFIG_FSTRIM)
1769 * Walk list of mounted file systems in the guest, and trim them.
1771 GuestFilesystemTrimResponse
*
1772 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1774 GuestFilesystemTrimResponse
*response
;
1775 GuestFilesystemTrimResultList
*list
;
1776 GuestFilesystemTrimResult
*result
;
1779 struct FsMount
*mount
;
1781 Error
*local_err
= NULL
;
1782 struct fstrim_range r
;
1784 slog("guest-fstrim called");
1786 QTAILQ_INIT(&mounts
);
1787 build_fs_mount_list(&mounts
, &local_err
);
1789 error_propagate(errp
, local_err
);
1793 response
= g_malloc0(sizeof(*response
));
1795 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1796 result
= g_malloc0(sizeof(*result
));
1797 result
->path
= g_strdup(mount
->dirname
);
1799 list
= g_malloc0(sizeof(*list
));
1800 list
->value
= result
;
1801 list
->next
= response
->paths
;
1802 response
->paths
= list
;
1804 fd
= qemu_open_old(mount
->dirname
, O_RDONLY
);
1806 result
->error
= g_strdup_printf("failed to open: %s",
1808 result
->has_error
= true;
1812 /* We try to cull filesystems we know won't work in advance, but other
1813 * filesystems may not implement fstrim for less obvious reasons.
1814 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1815 * will be reported (e.g. CD-ROMs).
1816 * Any other error means an unexpected error.
1820 r
.minlen
= has_minimum
? minimum
: 0;
1821 ret
= ioctl(fd
, FITRIM
, &r
);
1823 result
->has_error
= true;
1824 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1825 result
->error
= g_strdup("trim not supported");
1827 result
->error
= g_strdup_printf("failed to trim: %s",
1834 result
->has_minimum
= true;
1835 result
->minimum
= r
.minlen
;
1836 result
->has_trimmed
= true;
1837 result
->trimmed
= r
.len
;
1841 free_fs_mount_list(&mounts
);
1844 #endif /* CONFIG_FSTRIM */
1847 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1848 #define SUSPEND_SUPPORTED 0
1849 #define SUSPEND_NOT_SUPPORTED 1
1852 SUSPEND_MODE_DISK
= 0,
1853 SUSPEND_MODE_RAM
= 1,
1854 SUSPEND_MODE_HYBRID
= 2,
1858 * Executes a command in a child process using g_spawn_sync,
1859 * returning an int >= 0 representing the exit status of the
1862 * If the program wasn't found in path, returns -1.
1864 * If a problem happened when creating the child process,
1865 * returns -1 and errp is set.
1867 static int run_process_child(const char *command
[], Error
**errp
)
1869 int exit_status
, spawn_flag
;
1870 GError
*g_err
= NULL
;
1873 spawn_flag
= G_SPAWN_SEARCH_PATH
| G_SPAWN_STDOUT_TO_DEV_NULL
|
1874 G_SPAWN_STDERR_TO_DEV_NULL
;
1876 success
= g_spawn_sync(NULL
, (char **)command
, environ
, spawn_flag
,
1877 NULL
, NULL
, NULL
, NULL
,
1878 &exit_status
, &g_err
);
1881 return WEXITSTATUS(exit_status
);
1884 if (g_err
&& (g_err
->code
!= G_SPAWN_ERROR_NOENT
)) {
1885 error_setg(errp
, "failed to create child process, error '%s'",
1889 g_error_free(g_err
);
1893 static bool systemd_supports_mode(SuspendMode mode
, Error
**errp
)
1895 const char *systemctl_args
[3] = {"systemd-hibernate", "systemd-suspend",
1896 "systemd-hybrid-sleep"};
1897 const char *cmd
[4] = {"systemctl", "status", systemctl_args
[mode
], NULL
};
1900 status
= run_process_child(cmd
, errp
);
1903 * systemctl status uses LSB return codes so we can expect
1904 * status > 0 and be ok. To assert if the guest has support
1905 * for the selected suspend mode, status should be < 4. 4 is
1906 * the code for unknown service status, the return value when
1907 * the service does not exist. A common value is status = 3
1908 * (program is not running).
1910 if (status
> 0 && status
< 4) {
1917 static void systemd_suspend(SuspendMode mode
, Error
**errp
)
1919 Error
*local_err
= NULL
;
1920 const char *systemctl_args
[3] = {"hibernate", "suspend", "hybrid-sleep"};
1921 const char *cmd
[3] = {"systemctl", systemctl_args
[mode
], NULL
};
1924 status
= run_process_child(cmd
, &local_err
);
1930 if ((status
== -1) && !local_err
) {
1931 error_setg(errp
, "the helper program 'systemctl %s' was not found",
1932 systemctl_args
[mode
]);
1937 error_propagate(errp
, local_err
);
1939 error_setg(errp
, "the helper program 'systemctl %s' returned an "
1940 "unexpected exit status code (%d)",
1941 systemctl_args
[mode
], status
);
1945 static bool pmutils_supports_mode(SuspendMode mode
, Error
**errp
)
1947 Error
*local_err
= NULL
;
1948 const char *pmutils_args
[3] = {"--hibernate", "--suspend",
1949 "--suspend-hybrid"};
1950 const char *cmd
[3] = {"pm-is-supported", pmutils_args
[mode
], NULL
};
1953 status
= run_process_child(cmd
, &local_err
);
1955 if (status
== SUSPEND_SUPPORTED
) {
1959 if ((status
== -1) && !local_err
) {
1964 error_propagate(errp
, local_err
);
1967 "the helper program '%s' returned an unexpected exit"
1968 " status code (%d)", "pm-is-supported", status
);
1974 static void pmutils_suspend(SuspendMode mode
, Error
**errp
)
1976 Error
*local_err
= NULL
;
1977 const char *pmutils_binaries
[3] = {"pm-hibernate", "pm-suspend",
1978 "pm-suspend-hybrid"};
1979 const char *cmd
[2] = {pmutils_binaries
[mode
], NULL
};
1982 status
= run_process_child(cmd
, &local_err
);
1988 if ((status
== -1) && !local_err
) {
1989 error_setg(errp
, "the helper program '%s' was not found",
1990 pmutils_binaries
[mode
]);
1995 error_propagate(errp
, local_err
);
1998 "the helper program '%s' returned an unexpected exit"
1999 " status code (%d)", pmutils_binaries
[mode
], status
);
2003 static bool linux_sys_state_supports_mode(SuspendMode mode
, Error
**errp
)
2005 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
2006 const char *sysfile_str
= sysfile_strs
[mode
];
2007 char buf
[32]; /* hopefully big enough */
2012 error_setg(errp
, "unknown guest suspend mode");
2016 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
2021 ret
= read(fd
, buf
, sizeof(buf
) - 1);
2028 if (strstr(buf
, sysfile_str
)) {
2034 static void linux_sys_state_suspend(SuspendMode mode
, Error
**errp
)
2036 Error
*local_err
= NULL
;
2037 const char *sysfile_strs
[3] = {"disk", "mem", NULL
};
2038 const char *sysfile_str
= sysfile_strs
[mode
];
2043 error_setg(errp
, "unknown guest suspend mode");
2053 reopen_fd_to_null(0);
2054 reopen_fd_to_null(1);
2055 reopen_fd_to_null(2);
2057 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
2059 _exit(EXIT_FAILURE
);
2062 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
2063 _exit(EXIT_FAILURE
);
2066 _exit(EXIT_SUCCESS
);
2067 } else if (pid
< 0) {
2068 error_setg_errno(errp
, errno
, "failed to create child process");
2072 ga_wait_child(pid
, &status
, &local_err
);
2074 error_propagate(errp
, local_err
);
2078 if (WEXITSTATUS(status
)) {
2079 error_setg(errp
, "child process has failed to suspend");
2084 static void guest_suspend(SuspendMode mode
, Error
**errp
)
2086 Error
*local_err
= NULL
;
2087 bool mode_supported
= false;
2089 if (systemd_supports_mode(mode
, &local_err
)) {
2090 mode_supported
= true;
2091 systemd_suspend(mode
, &local_err
);
2098 error_free(local_err
);
2101 if (pmutils_supports_mode(mode
, &local_err
)) {
2102 mode_supported
= true;
2103 pmutils_suspend(mode
, &local_err
);
2110 error_free(local_err
);
2113 if (linux_sys_state_supports_mode(mode
, &local_err
)) {
2114 mode_supported
= true;
2115 linux_sys_state_suspend(mode
, &local_err
);
2118 if (!mode_supported
) {
2119 error_free(local_err
);
2121 "the requested suspend mode is not supported by the guest");
2123 error_propagate(errp
, local_err
);
2127 void qmp_guest_suspend_disk(Error
**errp
)
2129 guest_suspend(SUSPEND_MODE_DISK
, errp
);
2132 void qmp_guest_suspend_ram(Error
**errp
)
2134 guest_suspend(SUSPEND_MODE_RAM
, errp
);
2137 void qmp_guest_suspend_hybrid(Error
**errp
)
2139 guest_suspend(SUSPEND_MODE_HYBRID
, errp
);
2142 static GuestNetworkInterfaceList
*
2143 guest_find_interface(GuestNetworkInterfaceList
*head
,
2146 for (; head
; head
= head
->next
) {
2147 if (strcmp(head
->value
->name
, name
) == 0) {
2155 static int guest_get_network_stats(const char *name
,
2156 GuestNetworkInterfaceStat
*stats
)
2159 char const *devinfo
= "/proc/net/dev";
2161 char *line
= NULL
, *colon
;
2163 fp
= fopen(devinfo
, "r");
2167 name_len
= strlen(name
);
2168 while (getline(&line
, &n
, fp
) != -1) {
2171 long long rx_packets
;
2173 long long rx_dropped
;
2175 long long tx_packets
;
2177 long long tx_dropped
;
2179 trim_line
= g_strchug(line
);
2180 if (trim_line
[0] == '\0') {
2183 colon
= strchr(trim_line
, ':');
2187 if (colon
- name_len
== trim_line
&&
2188 strncmp(trim_line
, name
, name_len
) == 0) {
2189 if (sscanf(colon
+ 1,
2190 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2191 &rx_bytes
, &rx_packets
, &rx_errs
, &rx_dropped
,
2192 &dummy
, &dummy
, &dummy
, &dummy
,
2193 &tx_bytes
, &tx_packets
, &tx_errs
, &tx_dropped
,
2194 &dummy
, &dummy
, &dummy
, &dummy
) != 16) {
2197 stats
->rx_bytes
= rx_bytes
;
2198 stats
->rx_packets
= rx_packets
;
2199 stats
->rx_errs
= rx_errs
;
2200 stats
->rx_dropped
= rx_dropped
;
2201 stats
->tx_bytes
= tx_bytes
;
2202 stats
->tx_packets
= tx_packets
;
2203 stats
->tx_errs
= tx_errs
;
2204 stats
->tx_dropped
= tx_dropped
;
2212 g_debug("/proc/net/dev: Interface '%s' not found", name
);
2217 * Build information about guest interfaces
2219 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2221 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
2222 struct ifaddrs
*ifap
, *ifa
;
2224 if (getifaddrs(&ifap
) < 0) {
2225 error_setg_errno(errp
, errno
, "getifaddrs failed");
2229 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
2230 GuestNetworkInterfaceList
*info
;
2231 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
2232 GuestNetworkInterfaceStat
*interface_stat
= NULL
;
2233 char addr4
[INET_ADDRSTRLEN
];
2234 char addr6
[INET6_ADDRSTRLEN
];
2237 unsigned char *mac_addr
;
2240 g_debug("Processing %s interface", ifa
->ifa_name
);
2242 info
= guest_find_interface(head
, ifa
->ifa_name
);
2245 info
= g_malloc0(sizeof(*info
));
2246 info
->value
= g_malloc0(sizeof(*info
->value
));
2247 info
->value
->name
= g_strdup(ifa
->ifa_name
);
2250 head
= cur_item
= info
;
2252 cur_item
->next
= info
;
2257 if (!info
->value
->has_hardware_address
&&
2258 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
2259 /* we haven't obtained HW address yet */
2260 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
2262 error_setg_errno(errp
, errno
, "failed to create socket");
2266 memset(&ifr
, 0, sizeof(ifr
));
2267 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
2268 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
2269 error_setg_errno(errp
, errno
,
2270 "failed to get MAC address of %s",
2277 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
2279 info
->value
->hardware_address
=
2280 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2281 (int) mac_addr
[0], (int) mac_addr
[1],
2282 (int) mac_addr
[2], (int) mac_addr
[3],
2283 (int) mac_addr
[4], (int) mac_addr
[5]);
2285 info
->value
->has_hardware_address
= true;
2288 if (ifa
->ifa_addr
&&
2289 ifa
->ifa_addr
->sa_family
== AF_INET
) {
2290 /* interface with IPv4 address */
2291 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
2292 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
2293 error_setg_errno(errp
, errno
, "inet_ntop failed");
2297 address_item
= g_malloc0(sizeof(*address_item
));
2298 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
2299 address_item
->value
->ip_address
= g_strdup(addr4
);
2300 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
2302 if (ifa
->ifa_netmask
) {
2303 /* Count the number of set bits in netmask.
2304 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2305 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
2306 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
2308 } else if (ifa
->ifa_addr
&&
2309 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
2310 /* interface with IPv6 address */
2311 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
2312 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
2313 error_setg_errno(errp
, errno
, "inet_ntop failed");
2317 address_item
= g_malloc0(sizeof(*address_item
));
2318 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
2319 address_item
->value
->ip_address
= g_strdup(addr6
);
2320 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
2322 if (ifa
->ifa_netmask
) {
2323 /* Count the number of set bits in netmask.
2324 * This is safe as '1' and '0' cannot be shuffled in netmask. */
2325 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
2326 address_item
->value
->prefix
=
2327 ctpop32(((uint32_t *) p
)[0]) +
2328 ctpop32(((uint32_t *) p
)[1]) +
2329 ctpop32(((uint32_t *) p
)[2]) +
2330 ctpop32(((uint32_t *) p
)[3]);
2334 if (!address_item
) {
2338 address_list
= &info
->value
->ip_addresses
;
2340 while (*address_list
&& (*address_list
)->next
) {
2341 address_list
= &(*address_list
)->next
;
2344 if (!*address_list
) {
2345 *address_list
= address_item
;
2347 (*address_list
)->next
= address_item
;
2350 info
->value
->has_ip_addresses
= true;
2352 if (!info
->value
->has_statistics
) {
2353 interface_stat
= g_malloc0(sizeof(*interface_stat
));
2354 if (guest_get_network_stats(info
->value
->name
,
2355 interface_stat
) == -1) {
2356 info
->value
->has_statistics
= false;
2357 g_free(interface_stat
);
2359 info
->value
->statistics
= interface_stat
;
2360 info
->value
->has_statistics
= true;
2370 qapi_free_GuestNetworkInterfaceList(head
);
2374 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
2376 static long sysconf_exact(int name
, const char *name_str
, Error
**errp
)
2381 ret
= sysconf(name
);
2384 error_setg(errp
, "sysconf(%s): value indefinite", name_str
);
2386 error_setg_errno(errp
, errno
, "sysconf(%s)", name_str
);
2392 /* Transfer online/offline status between @vcpu and the guest system.
2394 * On input either @errp or *@errp must be NULL.
2396 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
2397 * - R: vcpu->logical_id
2399 * - W: vcpu->can_offline
2401 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
2402 * - R: vcpu->logical_id
2405 * Written members remain unmodified on error.
2407 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
2408 char *dirpath
, Error
**errp
)
2413 static const char fn
[] = "online";
2415 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2417 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2421 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
2423 if (errno
!= ENOENT
) {
2424 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
2425 } else if (sys2vcpu
) {
2426 vcpu
->online
= true;
2427 vcpu
->can_offline
= false;
2428 } else if (!vcpu
->online
) {
2429 error_setg(errp
, "logical processor #%" PRId64
" can't be "
2430 "offlined", vcpu
->logical_id
);
2431 } /* otherwise pretend successful re-onlining */
2433 unsigned char status
;
2435 res
= pread(fd
, &status
, 1, 0);
2437 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
2438 } else if (res
== 0) {
2439 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
2441 } else if (sys2vcpu
) {
2442 vcpu
->online
= (status
!= '0');
2443 vcpu
->can_offline
= true;
2444 } else if (vcpu
->online
!= (status
!= '0')) {
2445 status
= '0' + vcpu
->online
;
2446 if (pwrite(fd
, &status
, 1, 0) == -1) {
2447 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
2450 } /* otherwise pretend successful re-(on|off)-lining */
2460 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2463 GuestLogicalProcessorList
*head
, **link
;
2465 Error
*local_err
= NULL
;
2470 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
2472 while (local_err
== NULL
&& current
< sc_max
) {
2473 GuestLogicalProcessor
*vcpu
;
2474 GuestLogicalProcessorList
*entry
;
2475 int64_t id
= current
++;
2476 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2479 if (g_file_test(path
, G_FILE_TEST_EXISTS
)) {
2480 vcpu
= g_malloc0(sizeof *vcpu
);
2481 vcpu
->logical_id
= id
;
2482 vcpu
->has_can_offline
= true; /* lolspeak ftw */
2483 transfer_vcpu(vcpu
, true, path
, &local_err
);
2484 entry
= g_malloc0(sizeof *entry
);
2485 entry
->value
= vcpu
;
2487 link
= &entry
->next
;
2492 if (local_err
== NULL
) {
2493 /* there's no guest with zero VCPUs */
2494 g_assert(head
!= NULL
);
2498 qapi_free_GuestLogicalProcessorList(head
);
2499 error_propagate(errp
, local_err
);
2503 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2506 Error
*local_err
= NULL
;
2509 while (vcpus
!= NULL
) {
2510 char *path
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
2511 vcpus
->value
->logical_id
);
2513 transfer_vcpu(vcpus
->value
, false, path
, &local_err
);
2515 if (local_err
!= NULL
) {
2519 vcpus
= vcpus
->next
;
2522 if (local_err
!= NULL
) {
2523 if (processed
== 0) {
2524 error_propagate(errp
, local_err
);
2526 error_free(local_err
);
2533 void qmp_guest_set_user_password(const char *username
,
2534 const char *password
,
2538 Error
*local_err
= NULL
;
2539 char *passwd_path
= NULL
;
2542 int datafd
[2] = { -1, -1 };
2543 char *rawpasswddata
= NULL
;
2544 size_t rawpasswdlen
;
2545 char *chpasswddata
= NULL
;
2548 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
2549 if (!rawpasswddata
) {
2552 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
2553 rawpasswddata
[rawpasswdlen
] = '\0';
2555 if (strchr(rawpasswddata
, '\n')) {
2556 error_setg(errp
, "forbidden characters in raw password");
2560 if (strchr(username
, '\n') ||
2561 strchr(username
, ':')) {
2562 error_setg(errp
, "forbidden characters in username");
2566 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
2567 chpasswdlen
= strlen(chpasswddata
);
2569 passwd_path
= g_find_program_in_path("chpasswd");
2572 error_setg(errp
, "cannot find 'passwd' program in PATH");
2576 if (pipe(datafd
) < 0) {
2577 error_setg(errp
, "cannot create pipe FDs");
2587 reopen_fd_to_null(1);
2588 reopen_fd_to_null(2);
2591 execle(passwd_path
, "chpasswd", "-e", NULL
, environ
);
2593 execle(passwd_path
, "chpasswd", NULL
, environ
);
2595 _exit(EXIT_FAILURE
);
2596 } else if (pid
< 0) {
2597 error_setg_errno(errp
, errno
, "failed to create child process");
2603 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2604 error_setg_errno(errp
, errno
, "cannot write new account password");
2610 ga_wait_child(pid
, &status
, &local_err
);
2612 error_propagate(errp
, local_err
);
2616 if (!WIFEXITED(status
)) {
2617 error_setg(errp
, "child process has terminated abnormally");
2621 if (WEXITSTATUS(status
)) {
2622 error_setg(errp
, "child process has failed to set user password");
2627 g_free(chpasswddata
);
2628 g_free(rawpasswddata
);
2629 g_free(passwd_path
);
2630 if (datafd
[0] != -1) {
2633 if (datafd
[1] != -1) {
2638 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2639 int size
, Error
**errp
)
2645 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2647 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2651 res
= pread(fd
, buf
, size
, 0);
2653 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2654 } else if (res
== 0) {
2655 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2660 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2661 const char *buf
, int size
, Error
**errp
)
2666 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2668 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2672 if (pwrite(fd
, buf
, size
, 0) == -1) {
2673 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2679 /* Transfer online/offline status between @mem_blk and the guest system.
2681 * On input either @errp or *@errp must be NULL.
2683 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2684 * - R: mem_blk->phys_index
2685 * - W: mem_blk->online
2686 * - W: mem_blk->can_offline
2688 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2689 * - R: mem_blk->phys_index
2690 * - R: mem_blk->online
2691 *- R: mem_blk->can_offline
2692 * Written members remain unmodified on error.
2694 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2695 GuestMemoryBlockResponse
*result
,
2701 Error
*local_err
= NULL
;
2707 error_setg(errp
, "Internal error, 'result' should not be NULL");
2711 dp
= opendir("/sys/devices/system/memory/");
2712 /* if there is no 'memory' directory in sysfs,
2713 * we think this VM does not support online/offline memory block,
2714 * any other solution?
2717 if (errno
== ENOENT
) {
2719 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2726 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2727 mem_blk
->phys_index
);
2728 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2731 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2733 if (errno
== ENOENT
) {
2734 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2737 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2745 status
= g_malloc0(10);
2746 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2748 /* treat with sysfs file that not exist in old kernel */
2749 if (errno
== ENOENT
) {
2750 error_free(local_err
);
2752 mem_blk
->online
= true;
2753 mem_blk
->can_offline
= false;
2754 } else if (!mem_blk
->online
) {
2756 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2760 error_propagate(errp
, local_err
);
2762 error_free(local_err
);
2764 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2771 char removable
= '0';
2773 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2775 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2777 /* if no 'removable' file, it doesn't support offline mem blk */
2778 if (errno
== ENOENT
) {
2779 error_free(local_err
);
2780 mem_blk
->can_offline
= false;
2782 error_propagate(errp
, local_err
);
2785 mem_blk
->can_offline
= (removable
!= '0');
2788 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2789 const char *new_state
= mem_blk
->online
? "online" : "offline";
2791 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2794 error_free(local_err
);
2796 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2800 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2801 result
->has_error_code
= false;
2802 } /* otherwise pretend successful re-(on|off)-lining */
2813 result
->has_error_code
= true;
2814 result
->error_code
= errno
;
2818 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2820 GuestMemoryBlockList
*head
, **link
;
2821 Error
*local_err
= NULL
;
2828 dp
= opendir("/sys/devices/system/memory/");
2830 /* it's ok if this happens to be a system that doesn't expose
2831 * memory blocks via sysfs, but otherwise we should report
2834 if (errno
!= ENOENT
) {
2835 error_setg_errno(errp
, errno
, "Can't open directory"
2836 "\"/sys/devices/system/memory/\"");
2841 /* Note: the phys_index of memory block may be discontinuous,
2842 * this is because a memblk is the unit of the Sparse Memory design, which
2843 * allows discontinuous memory ranges (ex. NUMA), so here we should
2844 * traverse the memory block directory.
2846 while ((de
= readdir(dp
)) != NULL
) {
2847 GuestMemoryBlock
*mem_blk
;
2848 GuestMemoryBlockList
*entry
;
2850 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2851 !(de
->d_type
& DT_DIR
)) {
2855 mem_blk
= g_malloc0(sizeof *mem_blk
);
2856 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2857 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2858 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2859 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2864 entry
= g_malloc0(sizeof *entry
);
2865 entry
->value
= mem_blk
;
2868 link
= &entry
->next
;
2872 if (local_err
== NULL
) {
2873 /* there's no guest with zero memory blocks */
2875 error_setg(errp
, "guest reported zero memory blocks!");
2880 qapi_free_GuestMemoryBlockList(head
);
2881 error_propagate(errp
, local_err
);
2885 GuestMemoryBlockResponseList
*
2886 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2888 GuestMemoryBlockResponseList
*head
, **link
;
2889 Error
*local_err
= NULL
;
2894 while (mem_blks
!= NULL
) {
2895 GuestMemoryBlockResponse
*result
;
2896 GuestMemoryBlockResponseList
*entry
;
2897 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2899 result
= g_malloc0(sizeof(*result
));
2900 result
->phys_index
= current_mem_blk
->phys_index
;
2901 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2902 if (local_err
) { /* should never happen */
2905 entry
= g_malloc0(sizeof *entry
);
2906 entry
->value
= result
;
2909 link
= &entry
->next
;
2910 mem_blks
= mem_blks
->next
;
2915 qapi_free_GuestMemoryBlockResponseList(head
);
2916 error_propagate(errp
, local_err
);
2920 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2922 Error
*local_err
= NULL
;
2926 GuestMemoryBlockInfo
*info
;
2928 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2929 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2931 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2937 buf
= g_malloc0(20);
2938 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2942 error_propagate(errp
, local_err
);
2946 info
= g_new0(GuestMemoryBlockInfo
, 1);
2947 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2954 #else /* defined(__linux__) */
2956 void qmp_guest_suspend_disk(Error
**errp
)
2958 error_setg(errp
, QERR_UNSUPPORTED
);
2961 void qmp_guest_suspend_ram(Error
**errp
)
2963 error_setg(errp
, QERR_UNSUPPORTED
);
2966 void qmp_guest_suspend_hybrid(Error
**errp
)
2968 error_setg(errp
, QERR_UNSUPPORTED
);
2971 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2973 error_setg(errp
, QERR_UNSUPPORTED
);
2977 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2979 error_setg(errp
, QERR_UNSUPPORTED
);
2983 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2985 error_setg(errp
, QERR_UNSUPPORTED
);
2989 void qmp_guest_set_user_password(const char *username
,
2990 const char *password
,
2994 error_setg(errp
, QERR_UNSUPPORTED
);
2997 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2999 error_setg(errp
, QERR_UNSUPPORTED
);
3003 GuestMemoryBlockResponseList
*
3004 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
3006 error_setg(errp
, QERR_UNSUPPORTED
);
3010 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
3012 error_setg(errp
, QERR_UNSUPPORTED
);
3018 #if !defined(CONFIG_FSFREEZE)
3020 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
3022 error_setg(errp
, QERR_UNSUPPORTED
);
3026 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
3028 error_setg(errp
, QERR_UNSUPPORTED
);
3033 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
3035 error_setg(errp
, QERR_UNSUPPORTED
);
3040 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
3041 strList
*mountpoints
,
3044 error_setg(errp
, QERR_UNSUPPORTED
);
3049 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
3051 error_setg(errp
, QERR_UNSUPPORTED
);
3056 GuestDiskInfoList
*qmp_guest_get_disks(Error
**errp
)
3058 error_setg(errp
, QERR_UNSUPPORTED
);
3062 #endif /* CONFIG_FSFREEZE */
3064 #if !defined(CONFIG_FSTRIM)
3065 GuestFilesystemTrimResponse
*
3066 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
3068 error_setg(errp
, QERR_UNSUPPORTED
);
3073 /* add unsupported commands to the blacklist */
3074 GList
*ga_command_blacklist_init(GList
*blacklist
)
3076 #if !defined(__linux__)
3078 const char *list
[] = {
3079 "guest-suspend-disk", "guest-suspend-ram",
3080 "guest-suspend-hybrid", "guest-network-get-interfaces",
3081 "guest-get-vcpus", "guest-set-vcpus",
3082 "guest-get-memory-blocks", "guest-set-memory-blocks",
3083 "guest-get-memory-block-size", "guest-get-memory-block-info",
3085 char **p
= (char **)list
;
3088 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
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
, *cur_item
= NULL
;
3141 struct utmpx
*user_info
= NULL
;
3142 gpointer value
= NULL
;
3143 GuestUser
*user
= NULL
;
3144 GuestUserList
*item
= NULL
;
3145 double login_time
= 0;
3147 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
3151 user_info
= getutxent();
3152 if (user_info
== NULL
) {
3154 } else if (user_info
->ut_type
!= USER_PROCESS
) {
3156 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
3157 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
3158 user
= (GuestUser
*)value
;
3159 login_time
= ga_get_login_time(user_info
);
3160 /* We're ensuring the earliest login time to be sent */
3161 if (login_time
< user
->login_time
) {
3162 user
->login_time
= login_time
;
3167 item
= g_new0(GuestUserList
, 1);
3168 item
->value
= g_new0(GuestUser
, 1);
3169 item
->value
->user
= g_strdup(user_info
->ut_user
);
3170 item
->value
->login_time
= ga_get_login_time(user_info
);
3172 g_hash_table_insert(cache
, item
->value
->user
, item
->value
);
3175 head
= cur_item
= item
;
3177 cur_item
->next
= item
;
3182 g_hash_table_destroy(cache
);
3188 GuestUserList
*qmp_guest_get_users(Error
**errp
)
3190 error_setg(errp
, QERR_UNSUPPORTED
);
3196 /* Replace escaped special characters with theire real values. The replacement
3197 * is done in place -- returned value is in the original string.
3199 static void ga_osrelease_replace_special(gchar
*value
)
3201 gchar
*p
, *p2
, quote
;
3203 /* Trim the string at first space or semicolon if it is not enclosed in
3204 * single or double quotes. */
3205 if ((value
[0] != '"') || (value
[0] == '\'')) {
3206 p
= strchr(value
, ' ');
3210 p
= strchr(value
, ';');
3231 /* Keep literal backslash followed by whatever is there */
3235 } else if (*p
== quote
) {
3243 static GKeyFile
*ga_parse_osrelease(const char *fname
)
3245 gchar
*content
= NULL
;
3246 gchar
*content2
= NULL
;
3248 GKeyFile
*keys
= g_key_file_new();
3249 const char *group
= "[os-release]\n";
3251 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
3252 slog("failed to read '%s', error: %s", fname
, err
->message
);
3256 if (!g_utf8_validate(content
, -1, NULL
)) {
3257 slog("file is not utf-8 encoded: %s", fname
);
3260 content2
= g_strdup_printf("%s%s", group
, content
);
3262 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
3264 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
3276 g_key_file_free(keys
);
3280 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
3282 GuestOSInfo
*info
= NULL
;
3283 struct utsname kinfo
;
3284 GKeyFile
*osrelease
= NULL
;
3285 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
3287 info
= g_new0(GuestOSInfo
, 1);
3289 if (uname(&kinfo
) != 0) {
3290 error_setg_errno(errp
, errno
, "uname failed");
3292 info
->has_kernel_version
= true;
3293 info
->kernel_version
= g_strdup(kinfo
.version
);
3294 info
->has_kernel_release
= true;
3295 info
->kernel_release
= g_strdup(kinfo
.release
);
3296 info
->has_machine
= true;
3297 info
->machine
= g_strdup(kinfo
.machine
);
3300 if (qga_os_release
!= NULL
) {
3301 osrelease
= ga_parse_osrelease(qga_os_release
);
3303 osrelease
= ga_parse_osrelease("/etc/os-release");
3304 if (osrelease
== NULL
) {
3305 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
3309 if (osrelease
!= NULL
) {
3312 #define GET_FIELD(field, osfield) do { \
3313 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3314 if (value != NULL) { \
3315 ga_osrelease_replace_special(value); \
3316 info->has_ ## field = true; \
3317 info->field = value; \
3320 GET_FIELD(id
, "ID");
3321 GET_FIELD(name
, "NAME");
3322 GET_FIELD(pretty_name
, "PRETTY_NAME");
3323 GET_FIELD(version
, "VERSION");
3324 GET_FIELD(version_id
, "VERSION_ID");
3325 GET_FIELD(variant
, "VARIANT");
3326 GET_FIELD(variant_id
, "VARIANT_ID");
3329 g_key_file_free(osrelease
);
3335 GuestDeviceInfoList
*qmp_guest_get_devices(Error
**errp
)
3337 error_setg(errp
, QERR_UNSUPPORTED
);