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.
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
26 #include "qga/guest-agent-core.h"
27 #include "qga-qmp-commands.h"
28 #include "qapi/qmp/qerror.h"
29 #include "qemu/queue.h"
30 #include "qemu/host-utils.h"
32 #ifndef CONFIG_HAS_ENVIRON
34 #include <crt_externs.h>
35 #define environ (*_NSGetEnviron())
37 extern char **environ
;
41 #if defined(__linux__)
45 #include <arpa/inet.h>
46 #include <sys/socket.h>
50 #define CONFIG_FSFREEZE
57 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
64 rpid
= waitpid(pid
, status
, 0);
65 } while (rpid
== -1 && errno
== EINTR
);
68 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
73 g_assert(rpid
== pid
);
76 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
78 const char *shutdown_flag
;
79 Error
*local_err
= NULL
;
83 slog("guest-shutdown called, mode: %s", mode
);
84 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
86 } else if (strcmp(mode
, "halt") == 0) {
88 } else if (strcmp(mode
, "reboot") == 0) {
92 "mode is invalid (valid values are: halt|powerdown|reboot");
98 /* child, start the shutdown */
100 reopen_fd_to_null(0);
101 reopen_fd_to_null(1);
102 reopen_fd_to_null(2);
104 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
105 "hypervisor initiated shutdown", (char*)NULL
, environ
);
107 } else if (pid
< 0) {
108 error_setg_errno(errp
, errno
, "failed to create child process");
112 ga_wait_child(pid
, &status
, &local_err
);
114 error_propagate(errp
, local_err
);
118 if (!WIFEXITED(status
)) {
119 error_setg(errp
, "child process has terminated abnormally");
123 if (WEXITSTATUS(status
)) {
124 error_setg(errp
, "child process has failed to shutdown");
131 int64_t qmp_guest_get_time(Error
**errp
)
137 ret
= qemu_gettimeofday(&tq
);
139 error_setg_errno(errp
, errno
, "Failed to get time");
143 time_ns
= tq
.tv_sec
* 1000000000LL + tq
.tv_usec
* 1000;
147 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
152 Error
*local_err
= NULL
;
155 /* If user has passed a time, validate and set it. */
159 /* year-2038 will overflow in case time_t is 32bit */
160 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
161 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
165 tv
.tv_sec
= time_ns
/ 1000000000;
166 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
167 g_date_set_time_t(&date
, tv
.tv_sec
);
168 if (date
.year
< 1970 || date
.year
>= 2070) {
169 error_setg_errno(errp
, errno
, "Invalid time");
173 ret
= settimeofday(&tv
, NULL
);
175 error_setg_errno(errp
, errno
, "Failed to set time to guest");
180 /* Now, if user has passed a time to set and the system time is set, we
181 * just need to synchronize the hardware clock. However, if no time was
182 * passed, user is requesting the opposite: set the system time from the
183 * hardware clock (RTC). */
187 reopen_fd_to_null(0);
188 reopen_fd_to_null(1);
189 reopen_fd_to_null(2);
191 /* Use '/sbin/hwclock -w' to set RTC from the system time,
192 * or '/sbin/hwclock -s' to set the system time from RTC. */
193 execle("/sbin/hwclock", "hwclock", has_time
? "-w" : "-s",
196 } else if (pid
< 0) {
197 error_setg_errno(errp
, errno
, "failed to create child process");
201 ga_wait_child(pid
, &status
, &local_err
);
203 error_propagate(errp
, local_err
);
207 if (!WIFEXITED(status
)) {
208 error_setg(errp
, "child process has terminated abnormally");
212 if (WEXITSTATUS(status
)) {
213 error_setg(errp
, "hwclock failed to set hardware clock to system time");
218 typedef struct GuestFileHandle
{
221 QTAILQ_ENTRY(GuestFileHandle
) next
;
225 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
226 } guest_file_state
= {
227 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
230 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
232 GuestFileHandle
*gfh
;
235 handle
= ga_get_fd_handle(ga_state
, errp
);
240 gfh
= g_new0(GuestFileHandle
, 1);
243 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
248 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
250 GuestFileHandle
*gfh
;
252 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
259 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
263 typedef const char * const ccpc
;
269 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
270 static const struct {
273 } guest_file_open_modes
[] = {
274 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
275 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
276 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
277 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
278 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
279 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
280 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
281 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
282 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
283 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
284 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
285 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
289 find_open_flag(const char *mode_str
, Error
**errp
)
293 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
296 form
= guest_file_open_modes
[mode
].forms
;
297 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
305 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
306 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
309 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
312 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
313 S_IRGRP | S_IWGRP | \
317 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
319 Error
*local_err
= NULL
;
322 oflag
= find_open_flag(mode
, &local_err
);
323 if (local_err
== NULL
) {
326 /* If the caller wants / allows creation of a new file, we implement it
327 * with a two step process: open() + (open() / fchmod()).
329 * First we insist on creating the file exclusively as a new file. If
330 * that succeeds, we're free to set any file-mode bits on it. (The
331 * motivation is that we want to set those file-mode bits independently
332 * of the current umask.)
334 * If the exclusive creation fails because the file already exists
335 * (EEXIST is not possible for any other reason), we just attempt to
336 * open the file, but in this case we won't be allowed to change the
337 * file-mode bits on the preexistent file.
339 * The pathname should never disappear between the two open()s in
340 * practice. If it happens, then someone very likely tried to race us.
341 * In this case just go ahead and report the ENOENT from the second
342 * open() to the caller.
344 * If the caller wants to open a preexistent file, then the first
345 * open() is decisive and its third argument is ignored, and the second
346 * open() and the fchmod() are never called.
348 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
349 if (fd
== -1 && errno
== EEXIST
) {
350 oflag
&= ~(unsigned)O_CREAT
;
351 fd
= open(path
, oflag
);
355 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
356 "(mode: '%s')", path
, mode
);
358 qemu_set_cloexec(fd
);
360 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
361 error_setg_errno(&local_err
, errno
, "failed to set permission "
362 "0%03o on new file '%s' (mode: '%s')",
363 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
367 f
= fdopen(fd
, mode
);
369 error_setg_errno(&local_err
, errno
, "failed to associate "
370 "stdio stream with file descriptor %d, "
371 "file '%s' (mode: '%s')", fd
, path
, mode
);
378 if (oflag
& O_CREAT
) {
384 error_propagate(errp
, local_err
);
388 static int guest_file_toggle_flags(int fd
, int flags
, bool set
, Error
**err
)
392 old_flags
= fcntl(fd
, F_GETFL
);
393 if (old_flags
== -1) {
394 error_setg_errno(err
, errno
, QERR_QGA_COMMAND_FAILED
,
395 "failed to fetch filehandle flags");
399 ret
= fcntl(fd
, F_SETFL
, set
? (old_flags
| flags
) : (old_flags
& ~flags
));
401 error_setg_errno(err
, errno
, QERR_QGA_COMMAND_FAILED
,
402 "failed to set filehandle flags");
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 (guest_file_toggle_flags(fileno(fh
), O_NONBLOCK
, true, errp
) < 0) {
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 struct GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
465 int64_t count
, Error
**errp
)
467 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
468 GuestFileRead
*read_data
= NULL
;
478 count
= QGA_READ_COUNT_DEFAULT
;
479 } else if (count
< 0) {
480 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
486 buf
= g_malloc0(count
+1);
487 read_count
= fread(buf
, 1, count
, fh
);
489 error_setg_errno(errp
, errno
, "failed to read file");
490 slog("guest-file-read failed, handle: %" PRId64
, handle
);
493 read_data
= g_new0(GuestFileRead
, 1);
494 read_data
->count
= read_count
;
495 read_data
->eof
= feof(fh
);
497 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
506 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
507 bool has_count
, int64_t count
,
510 GuestFileWrite
*write_data
= NULL
;
514 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
522 buf
= g_base64_decode(buf_b64
, &buf_len
);
526 } else if (count
< 0 || count
> buf_len
) {
527 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
533 write_count
= fwrite(buf
, 1, count
, fh
);
535 error_setg_errno(errp
, errno
, "failed to write to file");
536 slog("guest-file-write failed, handle: %" PRId64
, handle
);
538 write_data
= g_new0(GuestFileWrite
, 1);
539 write_data
->count
= write_count
;
540 write_data
->eof
= feof(fh
);
548 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
549 int64_t whence
, Error
**errp
)
551 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
552 GuestFileSeek
*seek_data
= NULL
;
561 ret
= fseek(fh
, offset
, whence
);
563 error_setg_errno(errp
, errno
, "failed to seek file");
565 seek_data
= g_new0(GuestFileSeek
, 1);
566 seek_data
->position
= ftell(fh
);
567 seek_data
->eof
= feof(fh
);
574 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
576 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
587 error_setg_errno(errp
, errno
, "failed to flush file");
591 /* linux-specific implementations. avoid this if at all possible. */
592 #if defined(__linux__)
594 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
595 typedef struct FsMount
{
598 unsigned int devmajor
, devminor
;
599 QTAILQ_ENTRY(FsMount
) next
;
602 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
604 static void free_fs_mount_list(FsMountList
*mounts
)
606 FsMount
*mount
, *temp
;
612 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
613 QTAILQ_REMOVE(mounts
, mount
, next
);
614 g_free(mount
->dirname
);
615 g_free(mount
->devtype
);
620 static int dev_major_minor(const char *devpath
,
621 unsigned int *devmajor
, unsigned int *devminor
)
628 if (stat(devpath
, &st
) < 0) {
629 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
632 if (S_ISDIR(st
.st_mode
)) {
633 /* It is bind mount */
636 if (S_ISBLK(st
.st_mode
)) {
637 *devmajor
= major(st
.st_rdev
);
638 *devminor
= minor(st
.st_rdev
);
645 * Walk the mount table and build a list of local file systems
647 static void build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
651 char const *mtab
= "/proc/self/mounts";
653 unsigned int devmajor
, devminor
;
655 fp
= setmntent(mtab
, "r");
657 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
661 while ((ment
= getmntent(fp
))) {
663 * An entry which device name doesn't start with a '/' is
664 * either a dummy file system or a network file system.
665 * Add special handling for smbfs and cifs as is done by
668 if ((ment
->mnt_fsname
[0] != '/') ||
669 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
670 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
673 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
674 /* Skip bind mounts */
678 mount
= g_new0(FsMount
, 1);
679 mount
->dirname
= g_strdup(ment
->mnt_dir
);
680 mount
->devtype
= g_strdup(ment
->mnt_type
);
681 mount
->devmajor
= devmajor
;
682 mount
->devminor
= devminor
;
684 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
690 static void decode_mntname(char *name
, int len
)
693 for (i
= 0; i
<= len
; i
++) {
694 if (name
[i
] != '\\') {
696 } else if (name
[i
+ 1] == '\\') {
699 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
700 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
701 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
702 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
703 (name
[i
+ 2] - '0') * 8 +
712 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
715 char const *mountinfo
= "/proc/self/mountinfo";
717 char *line
= NULL
, *dash
;
720 unsigned int devmajor
, devminor
;
721 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
723 fp
= fopen(mountinfo
, "r");
725 build_fs_mount_list_from_mtab(mounts
, errp
);
729 while (getline(&line
, &n
, fp
) != -1) {
730 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
731 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
735 dash
= strstr(line
+ dir_e
, " - ");
739 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
740 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
747 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
748 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
750 /* btrfs reports major number = 0 */
751 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
752 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
757 mount
= g_new0(FsMount
, 1);
758 mount
->dirname
= g_strdup(line
+ dir_s
);
759 mount
->devtype
= g_strdup(dash
+ type_s
);
760 mount
->devmajor
= devmajor
;
761 mount
->devminor
= devminor
;
763 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
771 #if defined(CONFIG_FSFREEZE)
773 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
781 path
= g_strndup(syspath
, pathlen
);
782 dpath
= g_strdup_printf("%s/driver", path
);
783 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
786 driver
= g_strdup(basename(buf
));
793 static int compare_uint(const void *_a
, const void *_b
)
795 unsigned int a
= *(unsigned int *)_a
;
796 unsigned int b
= *(unsigned int *)_b
;
798 return a
< b
? -1 : a
> b
? 1 : 0;
801 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
802 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
803 unsigned int *hosts
, int hosts_max
, Error
**errp
)
807 struct dirent
*entry
;
810 path
= g_strndup(syspath
, host
- syspath
);
813 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
818 while (i
< hosts_max
) {
819 entry
= readdir(dir
);
823 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
825 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
830 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
837 /* Store disk device info specified by @sysfs into @fs */
838 static void build_guest_fsinfo_for_real_device(char const *syspath
,
839 GuestFilesystemInfo
*fs
,
842 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
843 int i
, nhosts
= 0, pcilen
;
844 GuestDiskAddress
*disk
;
845 GuestPCIAddress
*pciaddr
;
846 GuestDiskAddressList
*list
= NULL
;
847 bool has_ata
= false, has_host
= false, has_tgt
= false;
848 char *p
, *q
, *driver
= NULL
;
850 p
= strstr(syspath
, "/devices/pci");
851 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
852 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
853 g_debug("only pci device is supported: sysfs path \"%s\"", syspath
);
857 driver
= get_pci_driver(syspath
, (p
+ 12 + pcilen
) - syspath
, errp
);
862 p
= strstr(syspath
, "/target");
863 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
864 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
868 p
= strstr(syspath
, "/ata");
873 p
= strstr(syspath
, "/host");
876 if (p
&& sscanf(q
, "%u", &host
) == 1) {
878 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
879 sizeof(hosts
) / sizeof(hosts
[0]), errp
);
885 pciaddr
= g_malloc0(sizeof(*pciaddr
));
886 pciaddr
->domain
= pci
[0];
887 pciaddr
->bus
= pci
[1];
888 pciaddr
->slot
= pci
[2];
889 pciaddr
->function
= pci
[3];
891 disk
= g_malloc0(sizeof(*disk
));
892 disk
->pci_controller
= pciaddr
;
894 list
= g_malloc0(sizeof(*list
));
897 if (strcmp(driver
, "ata_piix") == 0) {
898 /* a host per ide bus, target*:0:<unit>:0 */
899 if (!has_host
|| !has_tgt
) {
900 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
903 for (i
= 0; i
< nhosts
; i
++) {
904 if (host
== hosts
[i
]) {
905 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
912 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
915 } else if (strcmp(driver
, "sym53c8xx") == 0) {
916 /* scsi(LSI Logic): target*:0:<unit>:0 */
918 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
921 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
923 } else if (strcmp(driver
, "virtio-pci") == 0) {
925 /* virtio-scsi: target*:0:0:<unit> */
926 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
929 /* virtio-blk: 1 disk per 1 device */
930 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
932 } else if (strcmp(driver
, "ahci") == 0) {
933 /* ahci: 1 host per 1 unit */
934 if (!has_host
|| !has_tgt
) {
935 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
938 for (i
= 0; i
< nhosts
; i
++) {
939 if (host
== hosts
[i
]) {
941 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
946 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
950 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
954 list
->next
= fs
->disk
;
961 qapi_free_GuestDiskAddressList(list
);
966 static void build_guest_fsinfo_for_device(char const *devpath
,
967 GuestFilesystemInfo
*fs
,
970 /* Store a list of slave devices of virtual volume specified by @syspath into
972 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
973 GuestFilesystemInfo
*fs
,
978 struct dirent
*entry
;
980 dirpath
= g_strdup_printf("%s/slaves", syspath
);
981 dir
= opendir(dirpath
);
983 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
990 entry
= readdir(dir
);
993 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
998 if (entry
->d_type
== DT_LNK
) {
1001 g_debug(" slave device '%s'", entry
->d_name
);
1002 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1003 build_guest_fsinfo_for_device(path
, fs
, errp
);
1016 /* Dispatch to functions for virtual/real device */
1017 static void build_guest_fsinfo_for_device(char const *devpath
,
1018 GuestFilesystemInfo
*fs
,
1021 char *syspath
= realpath(devpath
, NULL
);
1024 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1029 fs
->name
= g_strdup(basename(syspath
));
1032 g_debug(" parse sysfs path '%s'", syspath
);
1034 if (strstr(syspath
, "/devices/virtual/block/")) {
1035 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1037 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1043 /* Return a list of the disk device(s)' info which @mount lies on */
1044 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1047 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1048 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1049 mount
->devmajor
, mount
->devminor
);
1051 fs
->mountpoint
= g_strdup(mount
->dirname
);
1052 fs
->type
= g_strdup(mount
->devtype
);
1053 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1059 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1062 struct FsMount
*mount
;
1063 GuestFilesystemInfoList
*new, *ret
= NULL
;
1064 Error
*local_err
= NULL
;
1066 QTAILQ_INIT(&mounts
);
1067 build_fs_mount_list(&mounts
, &local_err
);
1069 error_propagate(errp
, local_err
);
1073 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1074 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1076 new = g_malloc0(sizeof(*ret
));
1077 new->value
= build_guest_fsinfo(mount
, &local_err
);
1081 error_propagate(errp
, local_err
);
1082 qapi_free_GuestFilesystemInfoList(ret
);
1088 free_fs_mount_list(&mounts
);
1094 FSFREEZE_HOOK_THAW
= 0,
1095 FSFREEZE_HOOK_FREEZE
,
1098 static const char *fsfreeze_hook_arg_string
[] = {
1103 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1108 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1109 Error
*local_err
= NULL
;
1111 hook
= ga_fsfreeze_hook(ga_state
);
1115 if (access(hook
, X_OK
) != 0) {
1116 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1120 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1124 reopen_fd_to_null(0);
1125 reopen_fd_to_null(1);
1126 reopen_fd_to_null(2);
1128 execle(hook
, hook
, arg_str
, NULL
, environ
);
1129 _exit(EXIT_FAILURE
);
1130 } else if (pid
< 0) {
1131 error_setg_errno(errp
, errno
, "failed to create child process");
1135 ga_wait_child(pid
, &status
, &local_err
);
1137 error_propagate(errp
, local_err
);
1141 if (!WIFEXITED(status
)) {
1142 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1146 status
= WEXITSTATUS(status
);
1148 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1154 * Return status of freeze/thaw
1156 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1158 if (ga_is_frozen(ga_state
)) {
1159 return GUEST_FSFREEZE_STATUS_FROZEN
;
1162 return GUEST_FSFREEZE_STATUS_THAWED
;
1165 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1167 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1171 * Walk list of mounted file systems in the guest, and freeze the ones which
1172 * are real local file systems.
1174 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1175 strList
*mountpoints
,
1181 struct FsMount
*mount
;
1182 Error
*local_err
= NULL
;
1185 slog("guest-fsfreeze called");
1187 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1189 error_propagate(errp
, local_err
);
1193 QTAILQ_INIT(&mounts
);
1194 build_fs_mount_list(&mounts
, &local_err
);
1196 error_propagate(errp
, local_err
);
1200 /* cannot risk guest agent blocking itself on a write in this state */
1201 ga_set_frozen(ga_state
);
1203 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, FsMountList
, next
) {
1204 /* To issue fsfreeze in the reverse order of mounts, check if the
1205 * mount is listed in the list here */
1206 if (has_mountpoints
) {
1207 for (list
= mountpoints
; list
; list
= list
->next
) {
1208 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1217 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1219 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1223 /* we try to cull filesytems we know won't work in advance, but other
1224 * filesytems may not implement fsfreeze for less obvious reasons.
1225 * these will report EOPNOTSUPP. we simply ignore these when tallying
1226 * the number of frozen filesystems.
1228 * any other error means a failure to freeze a filesystem we
1229 * expect to be freezable, so return an error in those cases
1230 * and return system to thawed state.
1232 ret
= ioctl(fd
, FIFREEZE
);
1234 if (errno
!= EOPNOTSUPP
) {
1235 error_setg_errno(errp
, errno
, "failed to freeze %s",
1246 free_fs_mount_list(&mounts
);
1250 free_fs_mount_list(&mounts
);
1251 qmp_guest_fsfreeze_thaw(NULL
);
1256 * Walk list of frozen file systems in the guest, and thaw them.
1258 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1263 int fd
, i
= 0, logged
;
1264 Error
*local_err
= NULL
;
1266 QTAILQ_INIT(&mounts
);
1267 build_fs_mount_list(&mounts
, &local_err
);
1269 error_propagate(errp
, local_err
);
1273 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1275 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1279 /* we have no way of knowing whether a filesystem was actually unfrozen
1280 * as a result of a successful call to FITHAW, only that if an error
1281 * was returned the filesystem was *not* unfrozen by that particular
1284 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1285 * to unfreeze, continuing issuing FITHAW until an error is returned,
1286 * in which case either the filesystem is in an unfreezable state, or,
1287 * more likely, it was thawed previously (and remains so afterward).
1289 * also, since the most recent successful call is the one that did
1290 * the actual unfreeze, we can use this to provide an accurate count
1291 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1292 * may * be useful for determining whether a filesystem was unfrozen
1293 * during the freeze/thaw phase by a process other than qemu-ga.
1296 ret
= ioctl(fd
, FITHAW
);
1297 if (ret
== 0 && !logged
) {
1305 ga_unset_frozen(ga_state
);
1306 free_fs_mount_list(&mounts
);
1308 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1313 static void guest_fsfreeze_cleanup(void)
1317 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1318 qmp_guest_fsfreeze_thaw(&err
);
1320 slog("failed to clean up frozen filesystems: %s",
1321 error_get_pretty(err
));
1326 #endif /* CONFIG_FSFREEZE */
1328 #if defined(CONFIG_FSTRIM)
1330 * Walk list of mounted file systems in the guest, and trim them.
1332 GuestFilesystemTrimResponse
*
1333 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1335 GuestFilesystemTrimResponse
*response
;
1336 GuestFilesystemTrimResultList
*list
;
1337 GuestFilesystemTrimResult
*result
;
1340 struct FsMount
*mount
;
1342 Error
*local_err
= NULL
;
1343 struct fstrim_range r
;
1345 slog("guest-fstrim called");
1347 QTAILQ_INIT(&mounts
);
1348 build_fs_mount_list(&mounts
, &local_err
);
1350 error_propagate(errp
, local_err
);
1354 response
= g_malloc0(sizeof(*response
));
1356 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1357 result
= g_malloc0(sizeof(*result
));
1358 result
->path
= g_strdup(mount
->dirname
);
1360 list
= g_malloc0(sizeof(*list
));
1361 list
->value
= result
;
1362 list
->next
= response
->paths
;
1363 response
->paths
= list
;
1365 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1367 result
->error
= g_strdup_printf("failed to open: %s",
1369 result
->has_error
= true;
1373 /* We try to cull filesytems we know won't work in advance, but other
1374 * filesytems may not implement fstrim for less obvious reasons. These
1375 * will report EOPNOTSUPP; while in some other cases ENOTTY will be
1376 * reported (e.g. CD-ROMs).
1377 * Any other error means an unexpected error.
1381 r
.minlen
= has_minimum
? minimum
: 0;
1382 ret
= ioctl(fd
, FITRIM
, &r
);
1384 result
->has_error
= true;
1385 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1386 result
->error
= g_strdup("trim not supported");
1388 result
->error
= g_strdup_printf("failed to trim: %s",
1395 result
->has_minimum
= true;
1396 result
->minimum
= r
.minlen
;
1397 result
->has_trimmed
= true;
1398 result
->trimmed
= r
.len
;
1402 free_fs_mount_list(&mounts
);
1405 #endif /* CONFIG_FSTRIM */
1408 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1409 #define SUSPEND_SUPPORTED 0
1410 #define SUSPEND_NOT_SUPPORTED 1
1412 static void bios_supports_mode(const char *pmutils_bin
, const char *pmutils_arg
,
1413 const char *sysfile_str
, Error
**errp
)
1415 Error
*local_err
= NULL
;
1420 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1424 char buf
[32]; /* hopefully big enough */
1429 reopen_fd_to_null(0);
1430 reopen_fd_to_null(1);
1431 reopen_fd_to_null(2);
1434 execle(pmutils_path
, pmutils_bin
, pmutils_arg
, NULL
, environ
);
1438 * If we get here either pm-utils is not installed or execle() has
1439 * failed. Let's try the manual method if the caller wants it.
1443 _exit(SUSPEND_NOT_SUPPORTED
);
1446 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1448 _exit(SUSPEND_NOT_SUPPORTED
);
1451 ret
= read(fd
, buf
, sizeof(buf
)-1);
1453 _exit(SUSPEND_NOT_SUPPORTED
);
1457 if (strstr(buf
, sysfile_str
)) {
1458 _exit(SUSPEND_SUPPORTED
);
1461 _exit(SUSPEND_NOT_SUPPORTED
);
1462 } else if (pid
< 0) {
1463 error_setg_errno(errp
, errno
, "failed to create child process");
1467 ga_wait_child(pid
, &status
, &local_err
);
1469 error_propagate(errp
, local_err
);
1473 if (!WIFEXITED(status
)) {
1474 error_setg(errp
, "child process has terminated abnormally");
1478 switch (WEXITSTATUS(status
)) {
1479 case SUSPEND_SUPPORTED
:
1481 case SUSPEND_NOT_SUPPORTED
:
1483 "the requested suspend mode is not supported by the guest");
1487 "the helper program '%s' returned an unexpected exit status"
1488 " code (%d)", pmutils_path
, WEXITSTATUS(status
));
1493 g_free(pmutils_path
);
1496 static void guest_suspend(const char *pmutils_bin
, const char *sysfile_str
,
1499 Error
*local_err
= NULL
;
1504 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1512 reopen_fd_to_null(0);
1513 reopen_fd_to_null(1);
1514 reopen_fd_to_null(2);
1517 execle(pmutils_path
, pmutils_bin
, NULL
, environ
);
1521 * If we get here either pm-utils is not installed or execle() has
1522 * failed. Let's try the manual method if the caller wants it.
1526 _exit(EXIT_FAILURE
);
1529 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1531 _exit(EXIT_FAILURE
);
1534 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1535 _exit(EXIT_FAILURE
);
1538 _exit(EXIT_SUCCESS
);
1539 } else if (pid
< 0) {
1540 error_setg_errno(errp
, errno
, "failed to create child process");
1544 ga_wait_child(pid
, &status
, &local_err
);
1546 error_propagate(errp
, local_err
);
1550 if (!WIFEXITED(status
)) {
1551 error_setg(errp
, "child process has terminated abnormally");
1555 if (WEXITSTATUS(status
)) {
1556 error_setg(errp
, "child process has failed to suspend");
1561 g_free(pmutils_path
);
1564 void qmp_guest_suspend_disk(Error
**errp
)
1566 Error
*local_err
= NULL
;
1568 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err
);
1570 error_propagate(errp
, local_err
);
1574 guest_suspend("pm-hibernate", "disk", errp
);
1577 void qmp_guest_suspend_ram(Error
**errp
)
1579 Error
*local_err
= NULL
;
1581 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err
);
1583 error_propagate(errp
, local_err
);
1587 guest_suspend("pm-suspend", "mem", errp
);
1590 void qmp_guest_suspend_hybrid(Error
**errp
)
1592 Error
*local_err
= NULL
;
1594 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL
,
1597 error_propagate(errp
, local_err
);
1601 guest_suspend("pm-suspend-hybrid", NULL
, errp
);
1604 static GuestNetworkInterfaceList
*
1605 guest_find_interface(GuestNetworkInterfaceList
*head
,
1608 for (; head
; head
= head
->next
) {
1609 if (strcmp(head
->value
->name
, name
) == 0) {
1618 * Build information about guest interfaces
1620 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1622 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1623 struct ifaddrs
*ifap
, *ifa
;
1625 if (getifaddrs(&ifap
) < 0) {
1626 error_setg_errno(errp
, errno
, "getifaddrs failed");
1630 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1631 GuestNetworkInterfaceList
*info
;
1632 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
1633 char addr4
[INET_ADDRSTRLEN
];
1634 char addr6
[INET6_ADDRSTRLEN
];
1637 unsigned char *mac_addr
;
1640 g_debug("Processing %s interface", ifa
->ifa_name
);
1642 info
= guest_find_interface(head
, ifa
->ifa_name
);
1645 info
= g_malloc0(sizeof(*info
));
1646 info
->value
= g_malloc0(sizeof(*info
->value
));
1647 info
->value
->name
= g_strdup(ifa
->ifa_name
);
1650 head
= cur_item
= info
;
1652 cur_item
->next
= info
;
1657 if (!info
->value
->has_hardware_address
&&
1658 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
1659 /* we haven't obtained HW address yet */
1660 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
1662 error_setg_errno(errp
, errno
, "failed to create socket");
1666 memset(&ifr
, 0, sizeof(ifr
));
1667 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
1668 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
1669 error_setg_errno(errp
, errno
,
1670 "failed to get MAC address of %s",
1677 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
1679 info
->value
->hardware_address
=
1680 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1681 (int) mac_addr
[0], (int) mac_addr
[1],
1682 (int) mac_addr
[2], (int) mac_addr
[3],
1683 (int) mac_addr
[4], (int) mac_addr
[5]);
1685 info
->value
->has_hardware_address
= true;
1688 if (ifa
->ifa_addr
&&
1689 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1690 /* interface with IPv4 address */
1691 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1692 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1693 error_setg_errno(errp
, errno
, "inet_ntop failed");
1697 address_item
= g_malloc0(sizeof(*address_item
));
1698 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1699 address_item
->value
->ip_address
= g_strdup(addr4
);
1700 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1702 if (ifa
->ifa_netmask
) {
1703 /* Count the number of set bits in netmask.
1704 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1705 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1706 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1708 } else if (ifa
->ifa_addr
&&
1709 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1710 /* interface with IPv6 address */
1711 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1712 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1713 error_setg_errno(errp
, errno
, "inet_ntop failed");
1717 address_item
= g_malloc0(sizeof(*address_item
));
1718 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1719 address_item
->value
->ip_address
= g_strdup(addr6
);
1720 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1722 if (ifa
->ifa_netmask
) {
1723 /* Count the number of set bits in netmask.
1724 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1725 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1726 address_item
->value
->prefix
=
1727 ctpop32(((uint32_t *) p
)[0]) +
1728 ctpop32(((uint32_t *) p
)[1]) +
1729 ctpop32(((uint32_t *) p
)[2]) +
1730 ctpop32(((uint32_t *) p
)[3]);
1734 if (!address_item
) {
1738 address_list
= &info
->value
->ip_addresses
;
1740 while (*address_list
&& (*address_list
)->next
) {
1741 address_list
= &(*address_list
)->next
;
1744 if (!*address_list
) {
1745 *address_list
= address_item
;
1747 (*address_list
)->next
= address_item
;
1750 info
->value
->has_ip_addresses
= true;
1760 qapi_free_GuestNetworkInterfaceList(head
);
1764 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
1766 static long sysconf_exact(int name
, const char *name_str
, Error
**errp
)
1771 ret
= sysconf(name
);
1774 error_setg(errp
, "sysconf(%s): value indefinite", name_str
);
1776 error_setg_errno(errp
, errno
, "sysconf(%s)", name_str
);
1782 /* Transfer online/offline status between @vcpu and the guest system.
1784 * On input either @errp or *@errp must be NULL.
1786 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1787 * - R: vcpu->logical_id
1789 * - W: vcpu->can_offline
1791 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1792 * - R: vcpu->logical_id
1795 * Written members remain unmodified on error.
1797 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1803 dirpath
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
1805 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
1807 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
1809 static const char fn
[] = "online";
1813 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
1815 if (errno
!= ENOENT
) {
1816 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
1817 } else if (sys2vcpu
) {
1818 vcpu
->online
= true;
1819 vcpu
->can_offline
= false;
1820 } else if (!vcpu
->online
) {
1821 error_setg(errp
, "logical processor #%" PRId64
" can't be "
1822 "offlined", vcpu
->logical_id
);
1823 } /* otherwise pretend successful re-onlining */
1825 unsigned char status
;
1827 res
= pread(fd
, &status
, 1, 0);
1829 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
1830 } else if (res
== 0) {
1831 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
1833 } else if (sys2vcpu
) {
1834 vcpu
->online
= (status
!= '0');
1835 vcpu
->can_offline
= true;
1836 } else if (vcpu
->online
!= (status
!= '0')) {
1837 status
= '0' + vcpu
->online
;
1838 if (pwrite(fd
, &status
, 1, 0) == -1) {
1839 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
1842 } /* otherwise pretend successful re-(on|off)-lining */
1855 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1858 GuestLogicalProcessorList
*head
, **link
;
1860 Error
*local_err
= NULL
;
1865 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
1867 while (local_err
== NULL
&& current
< sc_max
) {
1868 GuestLogicalProcessor
*vcpu
;
1869 GuestLogicalProcessorList
*entry
;
1871 vcpu
= g_malloc0(sizeof *vcpu
);
1872 vcpu
->logical_id
= current
++;
1873 vcpu
->has_can_offline
= true; /* lolspeak ftw */
1874 transfer_vcpu(vcpu
, true, &local_err
);
1876 entry
= g_malloc0(sizeof *entry
);
1877 entry
->value
= vcpu
;
1880 link
= &entry
->next
;
1883 if (local_err
== NULL
) {
1884 /* there's no guest with zero VCPUs */
1885 g_assert(head
!= NULL
);
1889 qapi_free_GuestLogicalProcessorList(head
);
1890 error_propagate(errp
, local_err
);
1894 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1897 Error
*local_err
= NULL
;
1900 while (vcpus
!= NULL
) {
1901 transfer_vcpu(vcpus
->value
, false, &local_err
);
1902 if (local_err
!= NULL
) {
1906 vcpus
= vcpus
->next
;
1909 if (local_err
!= NULL
) {
1910 if (processed
== 0) {
1911 error_propagate(errp
, local_err
);
1913 error_free(local_err
);
1920 void qmp_guest_set_user_password(const char *username
,
1921 const char *password
,
1925 Error
*local_err
= NULL
;
1926 char *passwd_path
= NULL
;
1929 int datafd
[2] = { -1, -1 };
1930 char *rawpasswddata
= NULL
;
1931 size_t rawpasswdlen
;
1932 char *chpasswddata
= NULL
;
1935 rawpasswddata
= (char *)g_base64_decode(password
, &rawpasswdlen
);
1936 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1937 rawpasswddata
[rawpasswdlen
] = '\0';
1939 if (strchr(rawpasswddata
, '\n')) {
1940 error_setg(errp
, "forbidden characters in raw password");
1944 if (strchr(username
, '\n') ||
1945 strchr(username
, ':')) {
1946 error_setg(errp
, "forbidden characters in username");
1950 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
1951 chpasswdlen
= strlen(chpasswddata
);
1953 passwd_path
= g_find_program_in_path("chpasswd");
1956 error_setg(errp
, "cannot find 'passwd' program in PATH");
1960 if (pipe(datafd
) < 0) {
1961 error_setg(errp
, "cannot create pipe FDs");
1971 reopen_fd_to_null(1);
1972 reopen_fd_to_null(2);
1975 execle(passwd_path
, "chpasswd", "-e", NULL
, environ
);
1977 execle(passwd_path
, "chpasswd", NULL
, environ
);
1979 _exit(EXIT_FAILURE
);
1980 } else if (pid
< 0) {
1981 error_setg_errno(errp
, errno
, "failed to create child process");
1987 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
1988 error_setg_errno(errp
, errno
, "cannot write new account password");
1994 ga_wait_child(pid
, &status
, &local_err
);
1996 error_propagate(errp
, local_err
);
2000 if (!WIFEXITED(status
)) {
2001 error_setg(errp
, "child process has terminated abnormally");
2005 if (WEXITSTATUS(status
)) {
2006 error_setg(errp
, "child process has failed to set user password");
2011 g_free(chpasswddata
);
2012 g_free(rawpasswddata
);
2013 g_free(passwd_path
);
2014 if (datafd
[0] != -1) {
2017 if (datafd
[1] != -1) {
2022 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2023 int size
, Error
**errp
)
2029 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2031 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2035 res
= pread(fd
, buf
, size
, 0);
2037 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2038 } else if (res
== 0) {
2039 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2044 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2045 const char *buf
, int size
, Error
**errp
)
2050 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2052 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2056 if (pwrite(fd
, buf
, size
, 0) == -1) {
2057 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2063 /* Transfer online/offline status between @mem_blk and the guest system.
2065 * On input either @errp or *@errp must be NULL.
2067 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2068 * - R: mem_blk->phys_index
2069 * - W: mem_blk->online
2070 * - W: mem_blk->can_offline
2072 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2073 * - R: mem_blk->phys_index
2074 * - R: mem_blk->online
2075 *- R: mem_blk->can_offline
2076 * Written members remain unmodified on error.
2078 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2079 GuestMemoryBlockResponse
*result
,
2085 Error
*local_err
= NULL
;
2091 error_setg(errp
, "Internal error, 'result' should not be NULL");
2095 dp
= opendir("/sys/devices/system/memory/");
2096 /* if there is no 'memory' directory in sysfs,
2097 * we think this VM does not support online/offline memory block,
2098 * any other solution?
2100 if (!dp
&& errno
== ENOENT
) {
2102 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2108 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2109 mem_blk
->phys_index
);
2110 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2113 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2115 if (errno
== ENOENT
) {
2116 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2119 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2127 status
= g_malloc0(10);
2128 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2130 /* treat with sysfs file that not exist in old kernel */
2131 if (errno
== ENOENT
) {
2132 error_free(local_err
);
2134 mem_blk
->online
= true;
2135 mem_blk
->can_offline
= false;
2136 } else if (!mem_blk
->online
) {
2138 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2142 error_propagate(errp
, local_err
);
2145 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2152 char removable
= '0';
2154 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2156 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2158 /* if no 'removable' file, it doesn't support offline mem blk */
2159 if (errno
== ENOENT
) {
2160 error_free(local_err
);
2161 mem_blk
->can_offline
= false;
2163 error_propagate(errp
, local_err
);
2166 mem_blk
->can_offline
= (removable
!= '0');
2169 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2170 char *new_state
= mem_blk
->online
? g_strdup("online") :
2171 g_strdup("offline");
2173 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2177 error_free(local_err
);
2179 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2183 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2184 result
->has_error_code
= false;
2185 } /* otherwise pretend successful re-(on|off)-lining */
2196 result
->has_error_code
= true;
2197 result
->error_code
= errno
;
2201 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2203 GuestMemoryBlockList
*head
, **link
;
2204 Error
*local_err
= NULL
;
2211 dp
= opendir("/sys/devices/system/memory/");
2213 /* it's ok if this happens to be a system that doesn't expose
2214 * memory blocks via sysfs, but otherwise we should report
2217 if (errno
!= ENOENT
) {
2218 error_setg_errno(errp
, errno
, "Can't open directory"
2219 "\"/sys/devices/system/memory/\"\n");
2224 /* Note: the phys_index of memory block may be discontinuous,
2225 * this is because a memblk is the unit of the Sparse Memory design, which
2226 * allows discontinuous memory ranges (ex. NUMA), so here we should
2227 * traverse the memory block directory.
2229 while ((de
= readdir(dp
)) != NULL
) {
2230 GuestMemoryBlock
*mem_blk
;
2231 GuestMemoryBlockList
*entry
;
2233 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2234 !(de
->d_type
& DT_DIR
)) {
2238 mem_blk
= g_malloc0(sizeof *mem_blk
);
2239 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2240 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2241 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2242 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2244 entry
= g_malloc0(sizeof *entry
);
2245 entry
->value
= mem_blk
;
2248 link
= &entry
->next
;
2252 if (local_err
== NULL
) {
2253 /* there's no guest with zero memory blocks */
2255 error_setg(errp
, "guest reported zero memory blocks!");
2260 qapi_free_GuestMemoryBlockList(head
);
2261 error_propagate(errp
, local_err
);
2265 GuestMemoryBlockResponseList
*
2266 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2268 GuestMemoryBlockResponseList
*head
, **link
;
2269 Error
*local_err
= NULL
;
2274 while (mem_blks
!= NULL
) {
2275 GuestMemoryBlockResponse
*result
;
2276 GuestMemoryBlockResponseList
*entry
;
2277 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2279 result
= g_malloc0(sizeof(*result
));
2280 result
->phys_index
= current_mem_blk
->phys_index
;
2281 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2282 if (local_err
) { /* should never happen */
2285 entry
= g_malloc0(sizeof *entry
);
2286 entry
->value
= result
;
2289 link
= &entry
->next
;
2290 mem_blks
= mem_blks
->next
;
2295 qapi_free_GuestMemoryBlockResponseList(head
);
2296 error_propagate(errp
, local_err
);
2300 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2302 Error
*local_err
= NULL
;
2306 GuestMemoryBlockInfo
*info
;
2308 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2309 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2311 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2317 buf
= g_malloc0(20);
2318 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2322 error_propagate(errp
, local_err
);
2326 info
= g_new0(GuestMemoryBlockInfo
, 1);
2327 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2334 #else /* defined(__linux__) */
2336 void qmp_guest_suspend_disk(Error
**errp
)
2338 error_setg(errp
, QERR_UNSUPPORTED
);
2341 void qmp_guest_suspend_ram(Error
**errp
)
2343 error_setg(errp
, QERR_UNSUPPORTED
);
2346 void qmp_guest_suspend_hybrid(Error
**errp
)
2348 error_setg(errp
, QERR_UNSUPPORTED
);
2351 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2353 error_setg(errp
, QERR_UNSUPPORTED
);
2357 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2359 error_setg(errp
, QERR_UNSUPPORTED
);
2363 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2365 error_setg(errp
, QERR_UNSUPPORTED
);
2369 void qmp_guest_set_user_password(const char *username
,
2370 const char *password
,
2374 error_setg(errp
, QERR_UNSUPPORTED
);
2377 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2379 error_setg(errp
, QERR_UNSUPPORTED
);
2383 GuestMemoryBlockResponseList
*
2384 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2386 error_setg(errp
, QERR_UNSUPPORTED
);
2390 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2392 error_setg(errp
, QERR_UNSUPPORTED
);
2398 #if !defined(CONFIG_FSFREEZE)
2400 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
2402 error_setg(errp
, QERR_UNSUPPORTED
);
2406 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
2408 error_setg(errp
, QERR_UNSUPPORTED
);
2413 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
2415 error_setg(errp
, QERR_UNSUPPORTED
);
2420 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
2421 strList
*mountpoints
,
2424 error_setg(errp
, QERR_UNSUPPORTED
);
2429 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
2431 error_setg(errp
, QERR_UNSUPPORTED
);
2435 #endif /* CONFIG_FSFREEZE */
2437 #if !defined(CONFIG_FSTRIM)
2438 GuestFilesystemTrimResponse
*
2439 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
2441 error_setg(errp
, QERR_UNSUPPORTED
);
2446 /* add unsupported commands to the blacklist */
2447 GList
*ga_command_blacklist_init(GList
*blacklist
)
2449 #if !defined(__linux__)
2451 const char *list
[] = {
2452 "guest-suspend-disk", "guest-suspend-ram",
2453 "guest-suspend-hybrid", "guest-network-get-interfaces",
2454 "guest-get-vcpus", "guest-set-vcpus",
2455 "guest-get-memory-blocks", "guest-set-memory-blocks",
2456 "guest-get-memory-block-size", NULL
};
2457 char **p
= (char **)list
;
2460 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2465 #if !defined(CONFIG_FSFREEZE)
2467 const char *list
[] = {
2468 "guest-get-fsinfo", "guest-fsfreeze-status",
2469 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2470 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL
};
2471 char **p
= (char **)list
;
2474 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2479 #if !defined(CONFIG_FSTRIM)
2480 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
2486 /* register init/cleanup routines for stateful command groups */
2487 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2489 #if defined(CONFIG_FSFREEZE)
2490 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);