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"
31 #include "qemu/sockets.h"
33 #ifndef CONFIG_HAS_ENVIRON
35 #include <crt_externs.h>
36 #define environ (*_NSGetEnviron())
38 extern char **environ
;
42 #if defined(__linux__)
46 #include <arpa/inet.h>
47 #include <sys/socket.h>
51 #define CONFIG_FSFREEZE
58 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
65 rpid
= waitpid(pid
, status
, 0);
66 } while (rpid
== -1 && errno
== EINTR
);
69 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
74 g_assert(rpid
== pid
);
77 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
79 const char *shutdown_flag
;
80 Error
*local_err
= NULL
;
84 slog("guest-shutdown called, mode: %s", mode
);
85 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
87 } else if (strcmp(mode
, "halt") == 0) {
89 } else if (strcmp(mode
, "reboot") == 0) {
93 "mode is invalid (valid values are: halt|powerdown|reboot");
99 /* child, start the shutdown */
101 reopen_fd_to_null(0);
102 reopen_fd_to_null(1);
103 reopen_fd_to_null(2);
105 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
106 "hypervisor initiated shutdown", (char*)NULL
, environ
);
108 } else if (pid
< 0) {
109 error_setg_errno(errp
, errno
, "failed to create child process");
113 ga_wait_child(pid
, &status
, &local_err
);
115 error_propagate(errp
, local_err
);
119 if (!WIFEXITED(status
)) {
120 error_setg(errp
, "child process has terminated abnormally");
124 if (WEXITSTATUS(status
)) {
125 error_setg(errp
, "child process has failed to shutdown");
132 int64_t qmp_guest_get_time(Error
**errp
)
138 ret
= qemu_gettimeofday(&tq
);
140 error_setg_errno(errp
, errno
, "Failed to get time");
144 time_ns
= tq
.tv_sec
* 1000000000LL + tq
.tv_usec
* 1000;
148 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
153 Error
*local_err
= NULL
;
156 /* If user has passed a time, validate and set it. */
160 /* year-2038 will overflow in case time_t is 32bit */
161 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
162 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
166 tv
.tv_sec
= time_ns
/ 1000000000;
167 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
168 g_date_set_time_t(&date
, tv
.tv_sec
);
169 if (date
.year
< 1970 || date
.year
>= 2070) {
170 error_setg_errno(errp
, errno
, "Invalid time");
174 ret
= settimeofday(&tv
, NULL
);
176 error_setg_errno(errp
, errno
, "Failed to set time to guest");
181 /* Now, if user has passed a time to set and the system time is set, we
182 * just need to synchronize the hardware clock. However, if no time was
183 * passed, user is requesting the opposite: set the system time from the
184 * hardware clock (RTC). */
188 reopen_fd_to_null(0);
189 reopen_fd_to_null(1);
190 reopen_fd_to_null(2);
192 /* Use '/sbin/hwclock -w' to set RTC from the system time,
193 * or '/sbin/hwclock -s' to set the system time from RTC. */
194 execle("/sbin/hwclock", "hwclock", has_time
? "-w" : "-s",
197 } else if (pid
< 0) {
198 error_setg_errno(errp
, errno
, "failed to create child process");
202 ga_wait_child(pid
, &status
, &local_err
);
204 error_propagate(errp
, local_err
);
208 if (!WIFEXITED(status
)) {
209 error_setg(errp
, "child process has terminated abnormally");
213 if (WEXITSTATUS(status
)) {
214 error_setg(errp
, "hwclock failed to set hardware clock to system time");
219 typedef struct GuestFileHandle
{
222 QTAILQ_ENTRY(GuestFileHandle
) next
;
226 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
227 } guest_file_state
= {
228 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
231 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
233 GuestFileHandle
*gfh
;
236 handle
= ga_get_fd_handle(ga_state
, errp
);
241 gfh
= g_new0(GuestFileHandle
, 1);
244 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
249 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
251 GuestFileHandle
*gfh
;
253 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
260 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
264 typedef const char * const ccpc
;
270 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
271 static const struct {
274 } guest_file_open_modes
[] = {
275 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
276 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
277 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
278 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
279 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
280 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
281 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
282 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
283 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
284 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
285 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
286 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
290 find_open_flag(const char *mode_str
, Error
**errp
)
294 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
297 form
= guest_file_open_modes
[mode
].forms
;
298 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
306 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
307 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
310 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
313 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
314 S_IRGRP | S_IWGRP | \
318 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
320 Error
*local_err
= NULL
;
323 oflag
= find_open_flag(mode
, &local_err
);
324 if (local_err
== NULL
) {
327 /* If the caller wants / allows creation of a new file, we implement it
328 * with a two step process: open() + (open() / fchmod()).
330 * First we insist on creating the file exclusively as a new file. If
331 * that succeeds, we're free to set any file-mode bits on it. (The
332 * motivation is that we want to set those file-mode bits independently
333 * of the current umask.)
335 * If the exclusive creation fails because the file already exists
336 * (EEXIST is not possible for any other reason), we just attempt to
337 * open the file, but in this case we won't be allowed to change the
338 * file-mode bits on the preexistent file.
340 * The pathname should never disappear between the two open()s in
341 * practice. If it happens, then someone very likely tried to race us.
342 * In this case just go ahead and report the ENOENT from the second
343 * open() to the caller.
345 * If the caller wants to open a preexistent file, then the first
346 * open() is decisive and its third argument is ignored, and the second
347 * open() and the fchmod() are never called.
349 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
350 if (fd
== -1 && errno
== EEXIST
) {
351 oflag
&= ~(unsigned)O_CREAT
;
352 fd
= open(path
, oflag
);
356 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
357 "(mode: '%s')", path
, mode
);
359 qemu_set_cloexec(fd
);
361 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
362 error_setg_errno(&local_err
, errno
, "failed to set permission "
363 "0%03o on new file '%s' (mode: '%s')",
364 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
368 f
= fdopen(fd
, mode
);
370 error_setg_errno(&local_err
, errno
, "failed to associate "
371 "stdio stream with file descriptor %d, "
372 "file '%s' (mode: '%s')", fd
, path
, mode
);
379 if (oflag
& O_CREAT
) {
385 error_propagate(errp
, local_err
);
389 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
393 Error
*local_err
= NULL
;
399 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
400 fh
= safe_open_or_create(path
, mode
, &local_err
);
401 if (local_err
!= NULL
) {
402 error_propagate(errp
, local_err
);
406 /* set fd non-blocking to avoid common use cases (like reading from a
407 * named pipe) from hanging the agent
409 qemu_set_nonblock(fileno(fh
));
411 handle
= guest_file_handle_add(fh
, errp
);
417 slog("guest-file-open, handle: %" PRId64
, handle
);
421 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
423 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
426 slog("guest-file-close called, handle: %" PRId64
, handle
);
431 ret
= fclose(gfh
->fh
);
433 error_setg_errno(errp
, errno
, "failed to close handle");
437 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
441 struct GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
442 int64_t count
, Error
**errp
)
444 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
445 GuestFileRead
*read_data
= NULL
;
455 count
= QGA_READ_COUNT_DEFAULT
;
456 } else if (count
< 0) {
457 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
463 buf
= g_malloc0(count
+1);
464 read_count
= fread(buf
, 1, count
, fh
);
466 error_setg_errno(errp
, errno
, "failed to read file");
467 slog("guest-file-read failed, handle: %" PRId64
, handle
);
470 read_data
= g_new0(GuestFileRead
, 1);
471 read_data
->count
= read_count
;
472 read_data
->eof
= feof(fh
);
474 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
483 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
484 bool has_count
, int64_t count
,
487 GuestFileWrite
*write_data
= NULL
;
491 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
499 buf
= g_base64_decode(buf_b64
, &buf_len
);
503 } else if (count
< 0 || count
> buf_len
) {
504 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
510 write_count
= fwrite(buf
, 1, count
, fh
);
512 error_setg_errno(errp
, errno
, "failed to write to file");
513 slog("guest-file-write failed, handle: %" PRId64
, handle
);
515 write_data
= g_new0(GuestFileWrite
, 1);
516 write_data
->count
= write_count
;
517 write_data
->eof
= feof(fh
);
525 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
526 int64_t whence
, Error
**errp
)
528 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
529 GuestFileSeek
*seek_data
= NULL
;
538 ret
= fseek(fh
, offset
, whence
);
540 error_setg_errno(errp
, errno
, "failed to seek file");
542 seek_data
= g_new0(GuestFileSeek
, 1);
543 seek_data
->position
= ftell(fh
);
544 seek_data
->eof
= feof(fh
);
551 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
553 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
564 error_setg_errno(errp
, errno
, "failed to flush file");
568 /* linux-specific implementations. avoid this if at all possible. */
569 #if defined(__linux__)
571 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
572 typedef struct FsMount
{
575 unsigned int devmajor
, devminor
;
576 QTAILQ_ENTRY(FsMount
) next
;
579 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
581 static void free_fs_mount_list(FsMountList
*mounts
)
583 FsMount
*mount
, *temp
;
589 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
590 QTAILQ_REMOVE(mounts
, mount
, next
);
591 g_free(mount
->dirname
);
592 g_free(mount
->devtype
);
597 static int dev_major_minor(const char *devpath
,
598 unsigned int *devmajor
, unsigned int *devminor
)
605 if (stat(devpath
, &st
) < 0) {
606 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
609 if (S_ISDIR(st
.st_mode
)) {
610 /* It is bind mount */
613 if (S_ISBLK(st
.st_mode
)) {
614 *devmajor
= major(st
.st_rdev
);
615 *devminor
= minor(st
.st_rdev
);
622 * Walk the mount table and build a list of local file systems
624 static void build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
628 char const *mtab
= "/proc/self/mounts";
630 unsigned int devmajor
, devminor
;
632 fp
= setmntent(mtab
, "r");
634 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
638 while ((ment
= getmntent(fp
))) {
640 * An entry which device name doesn't start with a '/' is
641 * either a dummy file system or a network file system.
642 * Add special handling for smbfs and cifs as is done by
645 if ((ment
->mnt_fsname
[0] != '/') ||
646 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
647 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
650 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
651 /* Skip bind mounts */
655 mount
= g_new0(FsMount
, 1);
656 mount
->dirname
= g_strdup(ment
->mnt_dir
);
657 mount
->devtype
= g_strdup(ment
->mnt_type
);
658 mount
->devmajor
= devmajor
;
659 mount
->devminor
= devminor
;
661 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
667 static void decode_mntname(char *name
, int len
)
670 for (i
= 0; i
<= len
; i
++) {
671 if (name
[i
] != '\\') {
673 } else if (name
[i
+ 1] == '\\') {
676 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
677 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
678 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
679 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
680 (name
[i
+ 2] - '0') * 8 +
689 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
692 char const *mountinfo
= "/proc/self/mountinfo";
694 char *line
= NULL
, *dash
;
697 unsigned int devmajor
, devminor
;
698 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
700 fp
= fopen(mountinfo
, "r");
702 build_fs_mount_list_from_mtab(mounts
, errp
);
706 while (getline(&line
, &n
, fp
) != -1) {
707 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
708 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
712 dash
= strstr(line
+ dir_e
, " - ");
716 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
717 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
724 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
725 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
727 /* btrfs reports major number = 0 */
728 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
729 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
734 mount
= g_new0(FsMount
, 1);
735 mount
->dirname
= g_strdup(line
+ dir_s
);
736 mount
->devtype
= g_strdup(dash
+ type_s
);
737 mount
->devmajor
= devmajor
;
738 mount
->devminor
= devminor
;
740 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
748 #if defined(CONFIG_FSFREEZE)
750 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
758 path
= g_strndup(syspath
, pathlen
);
759 dpath
= g_strdup_printf("%s/driver", path
);
760 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
763 driver
= g_strdup(basename(buf
));
770 static int compare_uint(const void *_a
, const void *_b
)
772 unsigned int a
= *(unsigned int *)_a
;
773 unsigned int b
= *(unsigned int *)_b
;
775 return a
< b
? -1 : a
> b
? 1 : 0;
778 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
779 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
780 unsigned int *hosts
, int hosts_max
, Error
**errp
)
784 struct dirent
*entry
;
787 path
= g_strndup(syspath
, host
- syspath
);
790 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
795 while (i
< hosts_max
) {
796 entry
= readdir(dir
);
800 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
802 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
807 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
814 /* Store disk device info specified by @sysfs into @fs */
815 static void build_guest_fsinfo_for_real_device(char const *syspath
,
816 GuestFilesystemInfo
*fs
,
819 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
820 int i
, nhosts
= 0, pcilen
;
821 GuestDiskAddress
*disk
;
822 GuestPCIAddress
*pciaddr
;
823 GuestDiskAddressList
*list
= NULL
;
824 bool has_ata
= false, has_host
= false, has_tgt
= false;
825 char *p
, *q
, *driver
= NULL
;
827 p
= strstr(syspath
, "/devices/pci");
828 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
829 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
830 g_debug("only pci device is supported: sysfs path \"%s\"", syspath
);
834 driver
= get_pci_driver(syspath
, (p
+ 12 + pcilen
) - syspath
, errp
);
839 p
= strstr(syspath
, "/target");
840 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
841 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
845 p
= strstr(syspath
, "/ata");
850 p
= strstr(syspath
, "/host");
853 if (p
&& sscanf(q
, "%u", &host
) == 1) {
855 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
856 sizeof(hosts
) / sizeof(hosts
[0]), errp
);
862 pciaddr
= g_malloc0(sizeof(*pciaddr
));
863 pciaddr
->domain
= pci
[0];
864 pciaddr
->bus
= pci
[1];
865 pciaddr
->slot
= pci
[2];
866 pciaddr
->function
= pci
[3];
868 disk
= g_malloc0(sizeof(*disk
));
869 disk
->pci_controller
= pciaddr
;
871 list
= g_malloc0(sizeof(*list
));
874 if (strcmp(driver
, "ata_piix") == 0) {
875 /* a host per ide bus, target*:0:<unit>:0 */
876 if (!has_host
|| !has_tgt
) {
877 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
880 for (i
= 0; i
< nhosts
; i
++) {
881 if (host
== hosts
[i
]) {
882 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
889 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
892 } else if (strcmp(driver
, "sym53c8xx") == 0) {
893 /* scsi(LSI Logic): target*:0:<unit>:0 */
895 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
898 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
900 } else if (strcmp(driver
, "virtio-pci") == 0) {
902 /* virtio-scsi: target*:0:0:<unit> */
903 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
906 /* virtio-blk: 1 disk per 1 device */
907 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
909 } else if (strcmp(driver
, "ahci") == 0) {
910 /* ahci: 1 host per 1 unit */
911 if (!has_host
|| !has_tgt
) {
912 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
915 for (i
= 0; i
< nhosts
; i
++) {
916 if (host
== hosts
[i
]) {
918 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
923 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
927 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
931 list
->next
= fs
->disk
;
938 qapi_free_GuestDiskAddressList(list
);
943 static void build_guest_fsinfo_for_device(char const *devpath
,
944 GuestFilesystemInfo
*fs
,
947 /* Store a list of slave devices of virtual volume specified by @syspath into
949 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
950 GuestFilesystemInfo
*fs
,
955 struct dirent
*entry
;
957 dirpath
= g_strdup_printf("%s/slaves", syspath
);
958 dir
= opendir(dirpath
);
960 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
967 entry
= readdir(dir
);
970 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
975 if (entry
->d_type
== DT_LNK
) {
978 g_debug(" slave device '%s'", entry
->d_name
);
979 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
980 build_guest_fsinfo_for_device(path
, fs
, errp
);
993 /* Dispatch to functions for virtual/real device */
994 static void build_guest_fsinfo_for_device(char const *devpath
,
995 GuestFilesystemInfo
*fs
,
998 char *syspath
= realpath(devpath
, NULL
);
1001 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1006 fs
->name
= g_strdup(basename(syspath
));
1009 g_debug(" parse sysfs path '%s'", syspath
);
1011 if (strstr(syspath
, "/devices/virtual/block/")) {
1012 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1014 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1020 /* Return a list of the disk device(s)' info which @mount lies on */
1021 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1024 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1025 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1026 mount
->devmajor
, mount
->devminor
);
1028 fs
->mountpoint
= g_strdup(mount
->dirname
);
1029 fs
->type
= g_strdup(mount
->devtype
);
1030 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1036 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1039 struct FsMount
*mount
;
1040 GuestFilesystemInfoList
*new, *ret
= NULL
;
1041 Error
*local_err
= NULL
;
1043 QTAILQ_INIT(&mounts
);
1044 build_fs_mount_list(&mounts
, &local_err
);
1046 error_propagate(errp
, local_err
);
1050 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1051 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1053 new = g_malloc0(sizeof(*ret
));
1054 new->value
= build_guest_fsinfo(mount
, &local_err
);
1058 error_propagate(errp
, local_err
);
1059 qapi_free_GuestFilesystemInfoList(ret
);
1065 free_fs_mount_list(&mounts
);
1071 FSFREEZE_HOOK_THAW
= 0,
1072 FSFREEZE_HOOK_FREEZE
,
1075 static const char *fsfreeze_hook_arg_string
[] = {
1080 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1085 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1086 Error
*local_err
= NULL
;
1088 hook
= ga_fsfreeze_hook(ga_state
);
1092 if (access(hook
, X_OK
) != 0) {
1093 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1097 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1101 reopen_fd_to_null(0);
1102 reopen_fd_to_null(1);
1103 reopen_fd_to_null(2);
1105 execle(hook
, hook
, arg_str
, NULL
, environ
);
1106 _exit(EXIT_FAILURE
);
1107 } else if (pid
< 0) {
1108 error_setg_errno(errp
, errno
, "failed to create child process");
1112 ga_wait_child(pid
, &status
, &local_err
);
1114 error_propagate(errp
, local_err
);
1118 if (!WIFEXITED(status
)) {
1119 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1123 status
= WEXITSTATUS(status
);
1125 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1131 * Return status of freeze/thaw
1133 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1135 if (ga_is_frozen(ga_state
)) {
1136 return GUEST_FSFREEZE_STATUS_FROZEN
;
1139 return GUEST_FSFREEZE_STATUS_THAWED
;
1142 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1144 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1148 * Walk list of mounted file systems in the guest, and freeze the ones which
1149 * are real local file systems.
1151 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1152 strList
*mountpoints
,
1158 struct FsMount
*mount
;
1159 Error
*local_err
= NULL
;
1162 slog("guest-fsfreeze called");
1164 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1166 error_propagate(errp
, local_err
);
1170 QTAILQ_INIT(&mounts
);
1171 build_fs_mount_list(&mounts
, &local_err
);
1173 error_propagate(errp
, local_err
);
1177 /* cannot risk guest agent blocking itself on a write in this state */
1178 ga_set_frozen(ga_state
);
1180 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, FsMountList
, next
) {
1181 /* To issue fsfreeze in the reverse order of mounts, check if the
1182 * mount is listed in the list here */
1183 if (has_mountpoints
) {
1184 for (list
= mountpoints
; list
; list
= list
->next
) {
1185 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1194 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1196 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1200 /* we try to cull filesytems we know won't work in advance, but other
1201 * filesytems may not implement fsfreeze for less obvious reasons.
1202 * these will report EOPNOTSUPP. we simply ignore these when tallying
1203 * the number of frozen filesystems.
1205 * any other error means a failure to freeze a filesystem we
1206 * expect to be freezable, so return an error in those cases
1207 * and return system to thawed state.
1209 ret
= ioctl(fd
, FIFREEZE
);
1211 if (errno
!= EOPNOTSUPP
) {
1212 error_setg_errno(errp
, errno
, "failed to freeze %s",
1223 free_fs_mount_list(&mounts
);
1227 free_fs_mount_list(&mounts
);
1228 qmp_guest_fsfreeze_thaw(NULL
);
1233 * Walk list of frozen file systems in the guest, and thaw them.
1235 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1240 int fd
, i
= 0, logged
;
1241 Error
*local_err
= NULL
;
1243 QTAILQ_INIT(&mounts
);
1244 build_fs_mount_list(&mounts
, &local_err
);
1246 error_propagate(errp
, local_err
);
1250 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1252 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1256 /* we have no way of knowing whether a filesystem was actually unfrozen
1257 * as a result of a successful call to FITHAW, only that if an error
1258 * was returned the filesystem was *not* unfrozen by that particular
1261 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1262 * to unfreeze, continuing issuing FITHAW until an error is returned,
1263 * in which case either the filesystem is in an unfreezable state, or,
1264 * more likely, it was thawed previously (and remains so afterward).
1266 * also, since the most recent successful call is the one that did
1267 * the actual unfreeze, we can use this to provide an accurate count
1268 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1269 * may * be useful for determining whether a filesystem was unfrozen
1270 * during the freeze/thaw phase by a process other than qemu-ga.
1273 ret
= ioctl(fd
, FITHAW
);
1274 if (ret
== 0 && !logged
) {
1282 ga_unset_frozen(ga_state
);
1283 free_fs_mount_list(&mounts
);
1285 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1290 static void guest_fsfreeze_cleanup(void)
1294 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1295 qmp_guest_fsfreeze_thaw(&err
);
1297 slog("failed to clean up frozen filesystems: %s",
1298 error_get_pretty(err
));
1303 #endif /* CONFIG_FSFREEZE */
1305 #if defined(CONFIG_FSTRIM)
1307 * Walk list of mounted file systems in the guest, and trim them.
1309 GuestFilesystemTrimResponse
*
1310 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1312 GuestFilesystemTrimResponse
*response
;
1313 GuestFilesystemTrimResultList
*list
;
1314 GuestFilesystemTrimResult
*result
;
1317 struct FsMount
*mount
;
1319 Error
*local_err
= NULL
;
1320 struct fstrim_range r
;
1322 slog("guest-fstrim called");
1324 QTAILQ_INIT(&mounts
);
1325 build_fs_mount_list(&mounts
, &local_err
);
1327 error_propagate(errp
, local_err
);
1331 response
= g_malloc0(sizeof(*response
));
1333 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1334 result
= g_malloc0(sizeof(*result
));
1335 result
->path
= g_strdup(mount
->dirname
);
1337 list
= g_malloc0(sizeof(*list
));
1338 list
->value
= result
;
1339 list
->next
= response
->paths
;
1340 response
->paths
= list
;
1342 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1344 result
->error
= g_strdup_printf("failed to open: %s",
1346 result
->has_error
= true;
1350 /* We try to cull filesytems we know won't work in advance, but other
1351 * filesytems may not implement fstrim for less obvious reasons. These
1352 * will report EOPNOTSUPP; while in some other cases ENOTTY will be
1353 * reported (e.g. CD-ROMs).
1354 * Any other error means an unexpected error.
1358 r
.minlen
= has_minimum
? minimum
: 0;
1359 ret
= ioctl(fd
, FITRIM
, &r
);
1361 result
->has_error
= true;
1362 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1363 result
->error
= g_strdup("trim not supported");
1365 result
->error
= g_strdup_printf("failed to trim: %s",
1372 result
->has_minimum
= true;
1373 result
->minimum
= r
.minlen
;
1374 result
->has_trimmed
= true;
1375 result
->trimmed
= r
.len
;
1379 free_fs_mount_list(&mounts
);
1382 #endif /* CONFIG_FSTRIM */
1385 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1386 #define SUSPEND_SUPPORTED 0
1387 #define SUSPEND_NOT_SUPPORTED 1
1389 static void bios_supports_mode(const char *pmutils_bin
, const char *pmutils_arg
,
1390 const char *sysfile_str
, Error
**errp
)
1392 Error
*local_err
= NULL
;
1397 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1401 char buf
[32]; /* hopefully big enough */
1406 reopen_fd_to_null(0);
1407 reopen_fd_to_null(1);
1408 reopen_fd_to_null(2);
1411 execle(pmutils_path
, pmutils_bin
, pmutils_arg
, NULL
, environ
);
1415 * If we get here either pm-utils is not installed or execle() has
1416 * failed. Let's try the manual method if the caller wants it.
1420 _exit(SUSPEND_NOT_SUPPORTED
);
1423 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1425 _exit(SUSPEND_NOT_SUPPORTED
);
1428 ret
= read(fd
, buf
, sizeof(buf
)-1);
1430 _exit(SUSPEND_NOT_SUPPORTED
);
1434 if (strstr(buf
, sysfile_str
)) {
1435 _exit(SUSPEND_SUPPORTED
);
1438 _exit(SUSPEND_NOT_SUPPORTED
);
1439 } else if (pid
< 0) {
1440 error_setg_errno(errp
, errno
, "failed to create child process");
1444 ga_wait_child(pid
, &status
, &local_err
);
1446 error_propagate(errp
, local_err
);
1450 if (!WIFEXITED(status
)) {
1451 error_setg(errp
, "child process has terminated abnormally");
1455 switch (WEXITSTATUS(status
)) {
1456 case SUSPEND_SUPPORTED
:
1458 case SUSPEND_NOT_SUPPORTED
:
1460 "the requested suspend mode is not supported by the guest");
1464 "the helper program '%s' returned an unexpected exit status"
1465 " code (%d)", pmutils_path
, WEXITSTATUS(status
));
1470 g_free(pmutils_path
);
1473 static void guest_suspend(const char *pmutils_bin
, const char *sysfile_str
,
1476 Error
*local_err
= NULL
;
1481 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1489 reopen_fd_to_null(0);
1490 reopen_fd_to_null(1);
1491 reopen_fd_to_null(2);
1494 execle(pmutils_path
, pmutils_bin
, NULL
, environ
);
1498 * If we get here either pm-utils is not installed or execle() has
1499 * failed. Let's try the manual method if the caller wants it.
1503 _exit(EXIT_FAILURE
);
1506 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1508 _exit(EXIT_FAILURE
);
1511 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1512 _exit(EXIT_FAILURE
);
1515 _exit(EXIT_SUCCESS
);
1516 } else if (pid
< 0) {
1517 error_setg_errno(errp
, errno
, "failed to create child process");
1521 ga_wait_child(pid
, &status
, &local_err
);
1523 error_propagate(errp
, local_err
);
1527 if (!WIFEXITED(status
)) {
1528 error_setg(errp
, "child process has terminated abnormally");
1532 if (WEXITSTATUS(status
)) {
1533 error_setg(errp
, "child process has failed to suspend");
1538 g_free(pmutils_path
);
1541 void qmp_guest_suspend_disk(Error
**errp
)
1543 Error
*local_err
= NULL
;
1545 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err
);
1547 error_propagate(errp
, local_err
);
1551 guest_suspend("pm-hibernate", "disk", errp
);
1554 void qmp_guest_suspend_ram(Error
**errp
)
1556 Error
*local_err
= NULL
;
1558 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err
);
1560 error_propagate(errp
, local_err
);
1564 guest_suspend("pm-suspend", "mem", errp
);
1567 void qmp_guest_suspend_hybrid(Error
**errp
)
1569 Error
*local_err
= NULL
;
1571 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL
,
1574 error_propagate(errp
, local_err
);
1578 guest_suspend("pm-suspend-hybrid", NULL
, errp
);
1581 static GuestNetworkInterfaceList
*
1582 guest_find_interface(GuestNetworkInterfaceList
*head
,
1585 for (; head
; head
= head
->next
) {
1586 if (strcmp(head
->value
->name
, name
) == 0) {
1595 * Build information about guest interfaces
1597 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1599 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1600 struct ifaddrs
*ifap
, *ifa
;
1602 if (getifaddrs(&ifap
) < 0) {
1603 error_setg_errno(errp
, errno
, "getifaddrs failed");
1607 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1608 GuestNetworkInterfaceList
*info
;
1609 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
1610 char addr4
[INET_ADDRSTRLEN
];
1611 char addr6
[INET6_ADDRSTRLEN
];
1614 unsigned char *mac_addr
;
1617 g_debug("Processing %s interface", ifa
->ifa_name
);
1619 info
= guest_find_interface(head
, ifa
->ifa_name
);
1622 info
= g_malloc0(sizeof(*info
));
1623 info
->value
= g_malloc0(sizeof(*info
->value
));
1624 info
->value
->name
= g_strdup(ifa
->ifa_name
);
1627 head
= cur_item
= info
;
1629 cur_item
->next
= info
;
1634 if (!info
->value
->has_hardware_address
&&
1635 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
1636 /* we haven't obtained HW address yet */
1637 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
1639 error_setg_errno(errp
, errno
, "failed to create socket");
1643 memset(&ifr
, 0, sizeof(ifr
));
1644 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
1645 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
1646 error_setg_errno(errp
, errno
,
1647 "failed to get MAC address of %s",
1654 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
1656 info
->value
->hardware_address
=
1657 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1658 (int) mac_addr
[0], (int) mac_addr
[1],
1659 (int) mac_addr
[2], (int) mac_addr
[3],
1660 (int) mac_addr
[4], (int) mac_addr
[5]);
1662 info
->value
->has_hardware_address
= true;
1665 if (ifa
->ifa_addr
&&
1666 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1667 /* interface with IPv4 address */
1668 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1669 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1670 error_setg_errno(errp
, errno
, "inet_ntop failed");
1674 address_item
= g_malloc0(sizeof(*address_item
));
1675 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1676 address_item
->value
->ip_address
= g_strdup(addr4
);
1677 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1679 if (ifa
->ifa_netmask
) {
1680 /* Count the number of set bits in netmask.
1681 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1682 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1683 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1685 } else if (ifa
->ifa_addr
&&
1686 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1687 /* interface with IPv6 address */
1688 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1689 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1690 error_setg_errno(errp
, errno
, "inet_ntop failed");
1694 address_item
= g_malloc0(sizeof(*address_item
));
1695 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1696 address_item
->value
->ip_address
= g_strdup(addr6
);
1697 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1699 if (ifa
->ifa_netmask
) {
1700 /* Count the number of set bits in netmask.
1701 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1702 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1703 address_item
->value
->prefix
=
1704 ctpop32(((uint32_t *) p
)[0]) +
1705 ctpop32(((uint32_t *) p
)[1]) +
1706 ctpop32(((uint32_t *) p
)[2]) +
1707 ctpop32(((uint32_t *) p
)[3]);
1711 if (!address_item
) {
1715 address_list
= &info
->value
->ip_addresses
;
1717 while (*address_list
&& (*address_list
)->next
) {
1718 address_list
= &(*address_list
)->next
;
1721 if (!*address_list
) {
1722 *address_list
= address_item
;
1724 (*address_list
)->next
= address_item
;
1727 info
->value
->has_ip_addresses
= true;
1737 qapi_free_GuestNetworkInterfaceList(head
);
1741 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
1743 static long sysconf_exact(int name
, const char *name_str
, Error
**errp
)
1748 ret
= sysconf(name
);
1751 error_setg(errp
, "sysconf(%s): value indefinite", name_str
);
1753 error_setg_errno(errp
, errno
, "sysconf(%s)", name_str
);
1759 /* Transfer online/offline status between @vcpu and the guest system.
1761 * On input either @errp or *@errp must be NULL.
1763 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1764 * - R: vcpu->logical_id
1766 * - W: vcpu->can_offline
1768 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1769 * - R: vcpu->logical_id
1772 * Written members remain unmodified on error.
1774 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1780 dirpath
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
1782 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
1784 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
1786 static const char fn
[] = "online";
1790 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
1792 if (errno
!= ENOENT
) {
1793 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
1794 } else if (sys2vcpu
) {
1795 vcpu
->online
= true;
1796 vcpu
->can_offline
= false;
1797 } else if (!vcpu
->online
) {
1798 error_setg(errp
, "logical processor #%" PRId64
" can't be "
1799 "offlined", vcpu
->logical_id
);
1800 } /* otherwise pretend successful re-onlining */
1802 unsigned char status
;
1804 res
= pread(fd
, &status
, 1, 0);
1806 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
1807 } else if (res
== 0) {
1808 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
1810 } else if (sys2vcpu
) {
1811 vcpu
->online
= (status
!= '0');
1812 vcpu
->can_offline
= true;
1813 } else if (vcpu
->online
!= (status
!= '0')) {
1814 status
= '0' + vcpu
->online
;
1815 if (pwrite(fd
, &status
, 1, 0) == -1) {
1816 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
1819 } /* otherwise pretend successful re-(on|off)-lining */
1832 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1835 GuestLogicalProcessorList
*head
, **link
;
1837 Error
*local_err
= NULL
;
1842 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
1844 while (local_err
== NULL
&& current
< sc_max
) {
1845 GuestLogicalProcessor
*vcpu
;
1846 GuestLogicalProcessorList
*entry
;
1848 vcpu
= g_malloc0(sizeof *vcpu
);
1849 vcpu
->logical_id
= current
++;
1850 vcpu
->has_can_offline
= true; /* lolspeak ftw */
1851 transfer_vcpu(vcpu
, true, &local_err
);
1853 entry
= g_malloc0(sizeof *entry
);
1854 entry
->value
= vcpu
;
1857 link
= &entry
->next
;
1860 if (local_err
== NULL
) {
1861 /* there's no guest with zero VCPUs */
1862 g_assert(head
!= NULL
);
1866 qapi_free_GuestLogicalProcessorList(head
);
1867 error_propagate(errp
, local_err
);
1871 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1874 Error
*local_err
= NULL
;
1877 while (vcpus
!= NULL
) {
1878 transfer_vcpu(vcpus
->value
, false, &local_err
);
1879 if (local_err
!= NULL
) {
1883 vcpus
= vcpus
->next
;
1886 if (local_err
!= NULL
) {
1887 if (processed
== 0) {
1888 error_propagate(errp
, local_err
);
1890 error_free(local_err
);
1897 void qmp_guest_set_user_password(const char *username
,
1898 const char *password
,
1902 Error
*local_err
= NULL
;
1903 char *passwd_path
= NULL
;
1906 int datafd
[2] = { -1, -1 };
1907 char *rawpasswddata
= NULL
;
1908 size_t rawpasswdlen
;
1909 char *chpasswddata
= NULL
;
1912 rawpasswddata
= (char *)g_base64_decode(password
, &rawpasswdlen
);
1913 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1914 rawpasswddata
[rawpasswdlen
] = '\0';
1916 if (strchr(rawpasswddata
, '\n')) {
1917 error_setg(errp
, "forbidden characters in raw password");
1921 if (strchr(username
, '\n') ||
1922 strchr(username
, ':')) {
1923 error_setg(errp
, "forbidden characters in username");
1927 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
1928 chpasswdlen
= strlen(chpasswddata
);
1930 passwd_path
= g_find_program_in_path("chpasswd");
1933 error_setg(errp
, "cannot find 'passwd' program in PATH");
1937 if (pipe(datafd
) < 0) {
1938 error_setg(errp
, "cannot create pipe FDs");
1948 reopen_fd_to_null(1);
1949 reopen_fd_to_null(2);
1952 execle(passwd_path
, "chpasswd", "-e", NULL
, environ
);
1954 execle(passwd_path
, "chpasswd", NULL
, environ
);
1956 _exit(EXIT_FAILURE
);
1957 } else if (pid
< 0) {
1958 error_setg_errno(errp
, errno
, "failed to create child process");
1964 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
1965 error_setg_errno(errp
, errno
, "cannot write new account password");
1971 ga_wait_child(pid
, &status
, &local_err
);
1973 error_propagate(errp
, local_err
);
1977 if (!WIFEXITED(status
)) {
1978 error_setg(errp
, "child process has terminated abnormally");
1982 if (WEXITSTATUS(status
)) {
1983 error_setg(errp
, "child process has failed to set user password");
1988 g_free(chpasswddata
);
1989 g_free(rawpasswddata
);
1990 g_free(passwd_path
);
1991 if (datafd
[0] != -1) {
1994 if (datafd
[1] != -1) {
1999 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2000 int size
, Error
**errp
)
2006 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2008 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2012 res
= pread(fd
, buf
, size
, 0);
2014 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2015 } else if (res
== 0) {
2016 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2021 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2022 const char *buf
, int size
, Error
**errp
)
2027 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2029 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2033 if (pwrite(fd
, buf
, size
, 0) == -1) {
2034 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2040 /* Transfer online/offline status between @mem_blk and the guest system.
2042 * On input either @errp or *@errp must be NULL.
2044 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2045 * - R: mem_blk->phys_index
2046 * - W: mem_blk->online
2047 * - W: mem_blk->can_offline
2049 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2050 * - R: mem_blk->phys_index
2051 * - R: mem_blk->online
2052 *- R: mem_blk->can_offline
2053 * Written members remain unmodified on error.
2055 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2056 GuestMemoryBlockResponse
*result
,
2062 Error
*local_err
= NULL
;
2068 error_setg(errp
, "Internal error, 'result' should not be NULL");
2072 dp
= opendir("/sys/devices/system/memory/");
2073 /* if there is no 'memory' directory in sysfs,
2074 * we think this VM does not support online/offline memory block,
2075 * any other solution?
2077 if (!dp
&& errno
== ENOENT
) {
2079 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2085 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2086 mem_blk
->phys_index
);
2087 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2090 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2092 if (errno
== ENOENT
) {
2093 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2096 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2104 status
= g_malloc0(10);
2105 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2107 /* treat with sysfs file that not exist in old kernel */
2108 if (errno
== ENOENT
) {
2109 error_free(local_err
);
2111 mem_blk
->online
= true;
2112 mem_blk
->can_offline
= false;
2113 } else if (!mem_blk
->online
) {
2115 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2119 error_propagate(errp
, local_err
);
2122 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2129 char removable
= '0';
2131 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2133 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2135 /* if no 'removable' file, it doesn't support offline mem blk */
2136 if (errno
== ENOENT
) {
2137 error_free(local_err
);
2138 mem_blk
->can_offline
= false;
2140 error_propagate(errp
, local_err
);
2143 mem_blk
->can_offline
= (removable
!= '0');
2146 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2147 char *new_state
= mem_blk
->online
? g_strdup("online") :
2148 g_strdup("offline");
2150 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2154 error_free(local_err
);
2156 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2160 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2161 result
->has_error_code
= false;
2162 } /* otherwise pretend successful re-(on|off)-lining */
2173 result
->has_error_code
= true;
2174 result
->error_code
= errno
;
2178 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2180 GuestMemoryBlockList
*head
, **link
;
2181 Error
*local_err
= NULL
;
2188 dp
= opendir("/sys/devices/system/memory/");
2190 /* it's ok if this happens to be a system that doesn't expose
2191 * memory blocks via sysfs, but otherwise we should report
2194 if (errno
!= ENOENT
) {
2195 error_setg_errno(errp
, errno
, "Can't open directory"
2196 "\"/sys/devices/system/memory/\"\n");
2201 /* Note: the phys_index of memory block may be discontinuous,
2202 * this is because a memblk is the unit of the Sparse Memory design, which
2203 * allows discontinuous memory ranges (ex. NUMA), so here we should
2204 * traverse the memory block directory.
2206 while ((de
= readdir(dp
)) != NULL
) {
2207 GuestMemoryBlock
*mem_blk
;
2208 GuestMemoryBlockList
*entry
;
2210 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2211 !(de
->d_type
& DT_DIR
)) {
2215 mem_blk
= g_malloc0(sizeof *mem_blk
);
2216 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2217 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2218 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2219 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2221 entry
= g_malloc0(sizeof *entry
);
2222 entry
->value
= mem_blk
;
2225 link
= &entry
->next
;
2229 if (local_err
== NULL
) {
2230 /* there's no guest with zero memory blocks */
2232 error_setg(errp
, "guest reported zero memory blocks!");
2237 qapi_free_GuestMemoryBlockList(head
);
2238 error_propagate(errp
, local_err
);
2242 GuestMemoryBlockResponseList
*
2243 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2245 GuestMemoryBlockResponseList
*head
, **link
;
2246 Error
*local_err
= NULL
;
2251 while (mem_blks
!= NULL
) {
2252 GuestMemoryBlockResponse
*result
;
2253 GuestMemoryBlockResponseList
*entry
;
2254 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2256 result
= g_malloc0(sizeof(*result
));
2257 result
->phys_index
= current_mem_blk
->phys_index
;
2258 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2259 if (local_err
) { /* should never happen */
2262 entry
= g_malloc0(sizeof *entry
);
2263 entry
->value
= result
;
2266 link
= &entry
->next
;
2267 mem_blks
= mem_blks
->next
;
2272 qapi_free_GuestMemoryBlockResponseList(head
);
2273 error_propagate(errp
, local_err
);
2277 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2279 Error
*local_err
= NULL
;
2283 GuestMemoryBlockInfo
*info
;
2285 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2286 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2288 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2294 buf
= g_malloc0(20);
2295 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2299 error_propagate(errp
, local_err
);
2303 info
= g_new0(GuestMemoryBlockInfo
, 1);
2304 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2311 #else /* defined(__linux__) */
2313 void qmp_guest_suspend_disk(Error
**errp
)
2315 error_setg(errp
, QERR_UNSUPPORTED
);
2318 void qmp_guest_suspend_ram(Error
**errp
)
2320 error_setg(errp
, QERR_UNSUPPORTED
);
2323 void qmp_guest_suspend_hybrid(Error
**errp
)
2325 error_setg(errp
, QERR_UNSUPPORTED
);
2328 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2330 error_setg(errp
, QERR_UNSUPPORTED
);
2334 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2336 error_setg(errp
, QERR_UNSUPPORTED
);
2340 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2342 error_setg(errp
, QERR_UNSUPPORTED
);
2346 void qmp_guest_set_user_password(const char *username
,
2347 const char *password
,
2351 error_setg(errp
, QERR_UNSUPPORTED
);
2354 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2356 error_setg(errp
, QERR_UNSUPPORTED
);
2360 GuestMemoryBlockResponseList
*
2361 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2363 error_setg(errp
, QERR_UNSUPPORTED
);
2367 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2369 error_setg(errp
, QERR_UNSUPPORTED
);
2375 #if !defined(CONFIG_FSFREEZE)
2377 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
2379 error_setg(errp
, QERR_UNSUPPORTED
);
2383 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
2385 error_setg(errp
, QERR_UNSUPPORTED
);
2390 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
2392 error_setg(errp
, QERR_UNSUPPORTED
);
2397 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
2398 strList
*mountpoints
,
2401 error_setg(errp
, QERR_UNSUPPORTED
);
2406 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
2408 error_setg(errp
, QERR_UNSUPPORTED
);
2412 #endif /* CONFIG_FSFREEZE */
2414 #if !defined(CONFIG_FSTRIM)
2415 GuestFilesystemTrimResponse
*
2416 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
2418 error_setg(errp
, QERR_UNSUPPORTED
);
2423 /* add unsupported commands to the blacklist */
2424 GList
*ga_command_blacklist_init(GList
*blacklist
)
2426 #if !defined(__linux__)
2428 const char *list
[] = {
2429 "guest-suspend-disk", "guest-suspend-ram",
2430 "guest-suspend-hybrid", "guest-network-get-interfaces",
2431 "guest-get-vcpus", "guest-set-vcpus",
2432 "guest-get-memory-blocks", "guest-set-memory-blocks",
2433 "guest-get-memory-block-size", NULL
};
2434 char **p
= (char **)list
;
2437 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2442 #if !defined(CONFIG_FSFREEZE)
2444 const char *list
[] = {
2445 "guest-get-fsinfo", "guest-fsfreeze-status",
2446 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2447 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL
};
2448 char **p
= (char **)list
;
2451 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2456 #if !defined(CONFIG_FSTRIM)
2457 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
2463 /* register init/cleanup routines for stateful command groups */
2464 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2466 #if defined(CONFIG_FSFREEZE)
2467 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);