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");
225 typedef struct GuestFileHandle
{
229 QTAILQ_ENTRY(GuestFileHandle
) next
;
233 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
234 } guest_file_state
= {
235 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
238 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
240 GuestFileHandle
*gfh
;
243 handle
= ga_get_fd_handle(ga_state
, errp
);
248 gfh
= g_new0(GuestFileHandle
, 1);
251 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
256 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
258 GuestFileHandle
*gfh
;
260 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
267 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
271 typedef const char * const ccpc
;
277 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
278 static const struct {
281 } guest_file_open_modes
[] = {
282 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
283 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
284 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
285 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
286 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
287 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
288 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
289 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
290 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
291 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
292 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
293 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
297 find_open_flag(const char *mode_str
, Error
**errp
)
301 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
304 form
= guest_file_open_modes
[mode
].forms
;
305 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
313 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
314 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
317 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
320 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
321 S_IRGRP | S_IWGRP | \
325 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
327 Error
*local_err
= NULL
;
330 oflag
= find_open_flag(mode
, &local_err
);
331 if (local_err
== NULL
) {
334 /* If the caller wants / allows creation of a new file, we implement it
335 * with a two step process: open() + (open() / fchmod()).
337 * First we insist on creating the file exclusively as a new file. If
338 * that succeeds, we're free to set any file-mode bits on it. (The
339 * motivation is that we want to set those file-mode bits independently
340 * of the current umask.)
342 * If the exclusive creation fails because the file already exists
343 * (EEXIST is not possible for any other reason), we just attempt to
344 * open the file, but in this case we won't be allowed to change the
345 * file-mode bits on the preexistent file.
347 * The pathname should never disappear between the two open()s in
348 * practice. If it happens, then someone very likely tried to race us.
349 * In this case just go ahead and report the ENOENT from the second
350 * open() to the caller.
352 * If the caller wants to open a preexistent file, then the first
353 * open() is decisive and its third argument is ignored, and the second
354 * open() and the fchmod() are never called.
356 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
357 if (fd
== -1 && errno
== EEXIST
) {
358 oflag
&= ~(unsigned)O_CREAT
;
359 fd
= open(path
, oflag
);
363 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
364 "(mode: '%s')", path
, mode
);
366 qemu_set_cloexec(fd
);
368 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
369 error_setg_errno(&local_err
, errno
, "failed to set permission "
370 "0%03o on new file '%s' (mode: '%s')",
371 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
375 f
= fdopen(fd
, mode
);
377 error_setg_errno(&local_err
, errno
, "failed to associate "
378 "stdio stream with file descriptor %d, "
379 "file '%s' (mode: '%s')", fd
, path
, mode
);
386 if (oflag
& O_CREAT
) {
392 error_propagate(errp
, local_err
);
396 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
400 Error
*local_err
= NULL
;
406 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
407 fh
= safe_open_or_create(path
, mode
, &local_err
);
408 if (local_err
!= NULL
) {
409 error_propagate(errp
, local_err
);
413 /* set fd non-blocking to avoid common use cases (like reading from a
414 * named pipe) from hanging the agent
416 qemu_set_nonblock(fileno(fh
));
418 handle
= guest_file_handle_add(fh
, errp
);
424 slog("guest-file-open, handle: %" PRId64
, handle
);
428 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
430 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
433 slog("guest-file-close called, handle: %" PRId64
, handle
);
438 ret
= fclose(gfh
->fh
);
440 error_setg_errno(errp
, errno
, "failed to close handle");
444 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
448 struct GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
449 int64_t count
, Error
**errp
)
451 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
452 GuestFileRead
*read_data
= NULL
;
462 count
= QGA_READ_COUNT_DEFAULT
;
463 } else if (count
< 0) {
464 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
471 /* explicitly flush when switching from writing to reading */
472 if (gfh
->state
== RW_STATE_WRITING
) {
473 int ret
= fflush(fh
);
475 error_setg_errno(errp
, errno
, "failed to flush file");
478 gfh
->state
= RW_STATE_NEW
;
481 buf
= g_malloc0(count
+1);
482 read_count
= fread(buf
, 1, count
, fh
);
484 error_setg_errno(errp
, errno
, "failed to read file");
485 slog("guest-file-read failed, handle: %" PRId64
, handle
);
488 read_data
= g_new0(GuestFileRead
, 1);
489 read_data
->count
= read_count
;
490 read_data
->eof
= feof(fh
);
492 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
494 gfh
->state
= RW_STATE_READING
;
502 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
503 bool has_count
, int64_t count
,
506 GuestFileWrite
*write_data
= NULL
;
510 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
519 if (gfh
->state
== RW_STATE_READING
) {
520 int ret
= fseek(fh
, 0, SEEK_CUR
);
522 error_setg_errno(errp
, errno
, "failed to seek file");
525 gfh
->state
= RW_STATE_NEW
;
528 buf
= g_base64_decode(buf_b64
, &buf_len
);
532 } else if (count
< 0 || count
> buf_len
) {
533 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
539 write_count
= fwrite(buf
, 1, count
, fh
);
541 error_setg_errno(errp
, errno
, "failed to write to file");
542 slog("guest-file-write failed, handle: %" PRId64
, handle
);
544 write_data
= g_new0(GuestFileWrite
, 1);
545 write_data
->count
= write_count
;
546 write_data
->eof
= feof(fh
);
547 gfh
->state
= RW_STATE_WRITING
;
555 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
556 int64_t whence
, Error
**errp
)
558 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
559 GuestFileSeek
*seek_data
= NULL
;
568 ret
= fseek(fh
, offset
, whence
);
570 error_setg_errno(errp
, errno
, "failed to seek file");
571 if (errno
== ESPIPE
) {
572 /* file is non-seekable, stdio shouldn't be buffering anyways */
573 gfh
->state
= RW_STATE_NEW
;
576 seek_data
= g_new0(GuestFileSeek
, 1);
577 seek_data
->position
= ftell(fh
);
578 seek_data
->eof
= feof(fh
);
579 gfh
->state
= RW_STATE_NEW
;
586 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
588 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
599 error_setg_errno(errp
, errno
, "failed to flush file");
601 gfh
->state
= RW_STATE_NEW
;
605 /* linux-specific implementations. avoid this if at all possible. */
606 #if defined(__linux__)
608 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
609 typedef struct FsMount
{
612 unsigned int devmajor
, devminor
;
613 QTAILQ_ENTRY(FsMount
) next
;
616 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
618 static void free_fs_mount_list(FsMountList
*mounts
)
620 FsMount
*mount
, *temp
;
626 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
627 QTAILQ_REMOVE(mounts
, mount
, next
);
628 g_free(mount
->dirname
);
629 g_free(mount
->devtype
);
634 static int dev_major_minor(const char *devpath
,
635 unsigned int *devmajor
, unsigned int *devminor
)
642 if (stat(devpath
, &st
) < 0) {
643 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
646 if (S_ISDIR(st
.st_mode
)) {
647 /* It is bind mount */
650 if (S_ISBLK(st
.st_mode
)) {
651 *devmajor
= major(st
.st_rdev
);
652 *devminor
= minor(st
.st_rdev
);
659 * Walk the mount table and build a list of local file systems
661 static void build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
665 char const *mtab
= "/proc/self/mounts";
667 unsigned int devmajor
, devminor
;
669 fp
= setmntent(mtab
, "r");
671 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
675 while ((ment
= getmntent(fp
))) {
677 * An entry which device name doesn't start with a '/' is
678 * either a dummy file system or a network file system.
679 * Add special handling for smbfs and cifs as is done by
682 if ((ment
->mnt_fsname
[0] != '/') ||
683 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
684 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
687 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
688 /* Skip bind mounts */
692 mount
= g_new0(FsMount
, 1);
693 mount
->dirname
= g_strdup(ment
->mnt_dir
);
694 mount
->devtype
= g_strdup(ment
->mnt_type
);
695 mount
->devmajor
= devmajor
;
696 mount
->devminor
= devminor
;
698 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
704 static void decode_mntname(char *name
, int len
)
707 for (i
= 0; i
<= len
; i
++) {
708 if (name
[i
] != '\\') {
710 } else if (name
[i
+ 1] == '\\') {
713 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
714 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
715 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
716 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
717 (name
[i
+ 2] - '0') * 8 +
726 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
729 char const *mountinfo
= "/proc/self/mountinfo";
731 char *line
= NULL
, *dash
;
734 unsigned int devmajor
, devminor
;
735 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
737 fp
= fopen(mountinfo
, "r");
739 build_fs_mount_list_from_mtab(mounts
, errp
);
743 while (getline(&line
, &n
, fp
) != -1) {
744 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
745 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
749 dash
= strstr(line
+ dir_e
, " - ");
753 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
754 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
761 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
762 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
764 /* btrfs reports major number = 0 */
765 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
766 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
771 mount
= g_new0(FsMount
, 1);
772 mount
->dirname
= g_strdup(line
+ dir_s
);
773 mount
->devtype
= g_strdup(dash
+ type_s
);
774 mount
->devmajor
= devmajor
;
775 mount
->devminor
= devminor
;
777 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
785 #if defined(CONFIG_FSFREEZE)
787 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
795 path
= g_strndup(syspath
, pathlen
);
796 dpath
= g_strdup_printf("%s/driver", path
);
797 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
800 driver
= g_strdup(basename(buf
));
807 static int compare_uint(const void *_a
, const void *_b
)
809 unsigned int a
= *(unsigned int *)_a
;
810 unsigned int b
= *(unsigned int *)_b
;
812 return a
< b
? -1 : a
> b
? 1 : 0;
815 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
816 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
817 unsigned int *hosts
, int hosts_max
, Error
**errp
)
821 struct dirent
*entry
;
824 path
= g_strndup(syspath
, host
- syspath
);
827 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
832 while (i
< hosts_max
) {
833 entry
= readdir(dir
);
837 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
839 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
844 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
851 /* Store disk device info specified by @sysfs into @fs */
852 static void build_guest_fsinfo_for_real_device(char const *syspath
,
853 GuestFilesystemInfo
*fs
,
856 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
857 int i
, nhosts
= 0, pcilen
;
858 GuestDiskAddress
*disk
;
859 GuestPCIAddress
*pciaddr
;
860 GuestDiskAddressList
*list
= NULL
;
861 bool has_ata
= false, has_host
= false, has_tgt
= false;
862 char *p
, *q
, *driver
= NULL
;
864 p
= strstr(syspath
, "/devices/pci");
865 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
866 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
867 g_debug("only pci device is supported: sysfs path \"%s\"", syspath
);
871 driver
= get_pci_driver(syspath
, (p
+ 12 + pcilen
) - syspath
, errp
);
876 p
= strstr(syspath
, "/target");
877 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
878 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
882 p
= strstr(syspath
, "/ata");
887 p
= strstr(syspath
, "/host");
890 if (p
&& sscanf(q
, "%u", &host
) == 1) {
892 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
893 sizeof(hosts
) / sizeof(hosts
[0]), errp
);
899 pciaddr
= g_malloc0(sizeof(*pciaddr
));
900 pciaddr
->domain
= pci
[0];
901 pciaddr
->bus
= pci
[1];
902 pciaddr
->slot
= pci
[2];
903 pciaddr
->function
= pci
[3];
905 disk
= g_malloc0(sizeof(*disk
));
906 disk
->pci_controller
= pciaddr
;
908 list
= g_malloc0(sizeof(*list
));
911 if (strcmp(driver
, "ata_piix") == 0) {
912 /* a host per ide bus, target*:0:<unit>:0 */
913 if (!has_host
|| !has_tgt
) {
914 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
917 for (i
= 0; i
< nhosts
; i
++) {
918 if (host
== hosts
[i
]) {
919 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
926 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
929 } else if (strcmp(driver
, "sym53c8xx") == 0) {
930 /* scsi(LSI Logic): target*:0:<unit>:0 */
932 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
935 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
937 } else if (strcmp(driver
, "virtio-pci") == 0) {
939 /* virtio-scsi: target*:0:0:<unit> */
940 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
943 /* virtio-blk: 1 disk per 1 device */
944 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
946 } else if (strcmp(driver
, "ahci") == 0) {
947 /* ahci: 1 host per 1 unit */
948 if (!has_host
|| !has_tgt
) {
949 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
952 for (i
= 0; i
< nhosts
; i
++) {
953 if (host
== hosts
[i
]) {
955 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
960 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
964 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
968 list
->next
= fs
->disk
;
975 qapi_free_GuestDiskAddressList(list
);
980 static void build_guest_fsinfo_for_device(char const *devpath
,
981 GuestFilesystemInfo
*fs
,
984 /* Store a list of slave devices of virtual volume specified by @syspath into
986 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
987 GuestFilesystemInfo
*fs
,
992 struct dirent
*entry
;
994 dirpath
= g_strdup_printf("%s/slaves", syspath
);
995 dir
= opendir(dirpath
);
997 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1004 entry
= readdir(dir
);
1005 if (entry
== NULL
) {
1007 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1012 if (entry
->d_type
== DT_LNK
) {
1015 g_debug(" slave device '%s'", entry
->d_name
);
1016 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1017 build_guest_fsinfo_for_device(path
, fs
, errp
);
1030 /* Dispatch to functions for virtual/real device */
1031 static void build_guest_fsinfo_for_device(char const *devpath
,
1032 GuestFilesystemInfo
*fs
,
1035 char *syspath
= realpath(devpath
, NULL
);
1038 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1043 fs
->name
= g_strdup(basename(syspath
));
1046 g_debug(" parse sysfs path '%s'", syspath
);
1048 if (strstr(syspath
, "/devices/virtual/block/")) {
1049 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1051 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1057 /* Return a list of the disk device(s)' info which @mount lies on */
1058 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1061 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1062 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1063 mount
->devmajor
, mount
->devminor
);
1065 fs
->mountpoint
= g_strdup(mount
->dirname
);
1066 fs
->type
= g_strdup(mount
->devtype
);
1067 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1073 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1076 struct FsMount
*mount
;
1077 GuestFilesystemInfoList
*new, *ret
= NULL
;
1078 Error
*local_err
= NULL
;
1080 QTAILQ_INIT(&mounts
);
1081 build_fs_mount_list(&mounts
, &local_err
);
1083 error_propagate(errp
, local_err
);
1087 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1088 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1090 new = g_malloc0(sizeof(*ret
));
1091 new->value
= build_guest_fsinfo(mount
, &local_err
);
1095 error_propagate(errp
, local_err
);
1096 qapi_free_GuestFilesystemInfoList(ret
);
1102 free_fs_mount_list(&mounts
);
1108 FSFREEZE_HOOK_THAW
= 0,
1109 FSFREEZE_HOOK_FREEZE
,
1112 static const char *fsfreeze_hook_arg_string
[] = {
1117 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1122 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1123 Error
*local_err
= NULL
;
1125 hook
= ga_fsfreeze_hook(ga_state
);
1129 if (access(hook
, X_OK
) != 0) {
1130 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1134 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1138 reopen_fd_to_null(0);
1139 reopen_fd_to_null(1);
1140 reopen_fd_to_null(2);
1142 execle(hook
, hook
, arg_str
, NULL
, environ
);
1143 _exit(EXIT_FAILURE
);
1144 } else if (pid
< 0) {
1145 error_setg_errno(errp
, errno
, "failed to create child process");
1149 ga_wait_child(pid
, &status
, &local_err
);
1151 error_propagate(errp
, local_err
);
1155 if (!WIFEXITED(status
)) {
1156 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1160 status
= WEXITSTATUS(status
);
1162 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1168 * Return status of freeze/thaw
1170 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1172 if (ga_is_frozen(ga_state
)) {
1173 return GUEST_FSFREEZE_STATUS_FROZEN
;
1176 return GUEST_FSFREEZE_STATUS_THAWED
;
1179 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1181 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1185 * Walk list of mounted file systems in the guest, and freeze the ones which
1186 * are real local file systems.
1188 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1189 strList
*mountpoints
,
1195 struct FsMount
*mount
;
1196 Error
*local_err
= NULL
;
1199 slog("guest-fsfreeze called");
1201 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1203 error_propagate(errp
, local_err
);
1207 QTAILQ_INIT(&mounts
);
1208 build_fs_mount_list(&mounts
, &local_err
);
1210 error_propagate(errp
, local_err
);
1214 /* cannot risk guest agent blocking itself on a write in this state */
1215 ga_set_frozen(ga_state
);
1217 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, FsMountList
, next
) {
1218 /* To issue fsfreeze in the reverse order of mounts, check if the
1219 * mount is listed in the list here */
1220 if (has_mountpoints
) {
1221 for (list
= mountpoints
; list
; list
= list
->next
) {
1222 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1231 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1233 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1237 /* we try to cull filesytems we know won't work in advance, but other
1238 * filesytems may not implement fsfreeze for less obvious reasons.
1239 * these will report EOPNOTSUPP. we simply ignore these when tallying
1240 * the number of frozen filesystems.
1242 * any other error means a failure to freeze a filesystem we
1243 * expect to be freezable, so return an error in those cases
1244 * and return system to thawed state.
1246 ret
= ioctl(fd
, FIFREEZE
);
1248 if (errno
!= EOPNOTSUPP
) {
1249 error_setg_errno(errp
, errno
, "failed to freeze %s",
1260 free_fs_mount_list(&mounts
);
1264 free_fs_mount_list(&mounts
);
1265 qmp_guest_fsfreeze_thaw(NULL
);
1270 * Walk list of frozen file systems in the guest, and thaw them.
1272 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1277 int fd
, i
= 0, logged
;
1278 Error
*local_err
= NULL
;
1280 QTAILQ_INIT(&mounts
);
1281 build_fs_mount_list(&mounts
, &local_err
);
1283 error_propagate(errp
, local_err
);
1287 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1289 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1293 /* we have no way of knowing whether a filesystem was actually unfrozen
1294 * as a result of a successful call to FITHAW, only that if an error
1295 * was returned the filesystem was *not* unfrozen by that particular
1298 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1299 * to unfreeze, continuing issuing FITHAW until an error is returned,
1300 * in which case either the filesystem is in an unfreezable state, or,
1301 * more likely, it was thawed previously (and remains so afterward).
1303 * also, since the most recent successful call is the one that did
1304 * the actual unfreeze, we can use this to provide an accurate count
1305 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1306 * may * be useful for determining whether a filesystem was unfrozen
1307 * during the freeze/thaw phase by a process other than qemu-ga.
1310 ret
= ioctl(fd
, FITHAW
);
1311 if (ret
== 0 && !logged
) {
1319 ga_unset_frozen(ga_state
);
1320 free_fs_mount_list(&mounts
);
1322 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1327 static void guest_fsfreeze_cleanup(void)
1331 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1332 qmp_guest_fsfreeze_thaw(&err
);
1334 slog("failed to clean up frozen filesystems: %s",
1335 error_get_pretty(err
));
1340 #endif /* CONFIG_FSFREEZE */
1342 #if defined(CONFIG_FSTRIM)
1344 * Walk list of mounted file systems in the guest, and trim them.
1346 GuestFilesystemTrimResponse
*
1347 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1349 GuestFilesystemTrimResponse
*response
;
1350 GuestFilesystemTrimResultList
*list
;
1351 GuestFilesystemTrimResult
*result
;
1354 struct FsMount
*mount
;
1356 Error
*local_err
= NULL
;
1357 struct fstrim_range r
;
1359 slog("guest-fstrim called");
1361 QTAILQ_INIT(&mounts
);
1362 build_fs_mount_list(&mounts
, &local_err
);
1364 error_propagate(errp
, local_err
);
1368 response
= g_malloc0(sizeof(*response
));
1370 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1371 result
= g_malloc0(sizeof(*result
));
1372 result
->path
= g_strdup(mount
->dirname
);
1374 list
= g_malloc0(sizeof(*list
));
1375 list
->value
= result
;
1376 list
->next
= response
->paths
;
1377 response
->paths
= list
;
1379 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1381 result
->error
= g_strdup_printf("failed to open: %s",
1383 result
->has_error
= true;
1387 /* We try to cull filesytems we know won't work in advance, but other
1388 * filesytems may not implement fstrim for less obvious reasons. These
1389 * will report EOPNOTSUPP; while in some other cases ENOTTY will be
1390 * reported (e.g. CD-ROMs).
1391 * Any other error means an unexpected error.
1395 r
.minlen
= has_minimum
? minimum
: 0;
1396 ret
= ioctl(fd
, FITRIM
, &r
);
1398 result
->has_error
= true;
1399 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1400 result
->error
= g_strdup("trim not supported");
1402 result
->error
= g_strdup_printf("failed to trim: %s",
1409 result
->has_minimum
= true;
1410 result
->minimum
= r
.minlen
;
1411 result
->has_trimmed
= true;
1412 result
->trimmed
= r
.len
;
1416 free_fs_mount_list(&mounts
);
1419 #endif /* CONFIG_FSTRIM */
1422 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1423 #define SUSPEND_SUPPORTED 0
1424 #define SUSPEND_NOT_SUPPORTED 1
1426 static void bios_supports_mode(const char *pmutils_bin
, const char *pmutils_arg
,
1427 const char *sysfile_str
, Error
**errp
)
1429 Error
*local_err
= NULL
;
1434 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1438 char buf
[32]; /* hopefully big enough */
1443 reopen_fd_to_null(0);
1444 reopen_fd_to_null(1);
1445 reopen_fd_to_null(2);
1448 execle(pmutils_path
, pmutils_bin
, pmutils_arg
, NULL
, environ
);
1452 * If we get here either pm-utils is not installed or execle() has
1453 * failed. Let's try the manual method if the caller wants it.
1457 _exit(SUSPEND_NOT_SUPPORTED
);
1460 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1462 _exit(SUSPEND_NOT_SUPPORTED
);
1465 ret
= read(fd
, buf
, sizeof(buf
)-1);
1467 _exit(SUSPEND_NOT_SUPPORTED
);
1471 if (strstr(buf
, sysfile_str
)) {
1472 _exit(SUSPEND_SUPPORTED
);
1475 _exit(SUSPEND_NOT_SUPPORTED
);
1476 } else if (pid
< 0) {
1477 error_setg_errno(errp
, errno
, "failed to create child process");
1481 ga_wait_child(pid
, &status
, &local_err
);
1483 error_propagate(errp
, local_err
);
1487 if (!WIFEXITED(status
)) {
1488 error_setg(errp
, "child process has terminated abnormally");
1492 switch (WEXITSTATUS(status
)) {
1493 case SUSPEND_SUPPORTED
:
1495 case SUSPEND_NOT_SUPPORTED
:
1497 "the requested suspend mode is not supported by the guest");
1501 "the helper program '%s' returned an unexpected exit status"
1502 " code (%d)", pmutils_path
, WEXITSTATUS(status
));
1507 g_free(pmutils_path
);
1510 static void guest_suspend(const char *pmutils_bin
, const char *sysfile_str
,
1513 Error
*local_err
= NULL
;
1518 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1526 reopen_fd_to_null(0);
1527 reopen_fd_to_null(1);
1528 reopen_fd_to_null(2);
1531 execle(pmutils_path
, pmutils_bin
, NULL
, environ
);
1535 * If we get here either pm-utils is not installed or execle() has
1536 * failed. Let's try the manual method if the caller wants it.
1540 _exit(EXIT_FAILURE
);
1543 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1545 _exit(EXIT_FAILURE
);
1548 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1549 _exit(EXIT_FAILURE
);
1552 _exit(EXIT_SUCCESS
);
1553 } else if (pid
< 0) {
1554 error_setg_errno(errp
, errno
, "failed to create child process");
1558 ga_wait_child(pid
, &status
, &local_err
);
1560 error_propagate(errp
, local_err
);
1564 if (!WIFEXITED(status
)) {
1565 error_setg(errp
, "child process has terminated abnormally");
1569 if (WEXITSTATUS(status
)) {
1570 error_setg(errp
, "child process has failed to suspend");
1575 g_free(pmutils_path
);
1578 void qmp_guest_suspend_disk(Error
**errp
)
1580 Error
*local_err
= NULL
;
1582 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err
);
1584 error_propagate(errp
, local_err
);
1588 guest_suspend("pm-hibernate", "disk", errp
);
1591 void qmp_guest_suspend_ram(Error
**errp
)
1593 Error
*local_err
= NULL
;
1595 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err
);
1597 error_propagate(errp
, local_err
);
1601 guest_suspend("pm-suspend", "mem", errp
);
1604 void qmp_guest_suspend_hybrid(Error
**errp
)
1606 Error
*local_err
= NULL
;
1608 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL
,
1611 error_propagate(errp
, local_err
);
1615 guest_suspend("pm-suspend-hybrid", NULL
, errp
);
1618 static GuestNetworkInterfaceList
*
1619 guest_find_interface(GuestNetworkInterfaceList
*head
,
1622 for (; head
; head
= head
->next
) {
1623 if (strcmp(head
->value
->name
, name
) == 0) {
1632 * Build information about guest interfaces
1634 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1636 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1637 struct ifaddrs
*ifap
, *ifa
;
1639 if (getifaddrs(&ifap
) < 0) {
1640 error_setg_errno(errp
, errno
, "getifaddrs failed");
1644 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1645 GuestNetworkInterfaceList
*info
;
1646 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
1647 char addr4
[INET_ADDRSTRLEN
];
1648 char addr6
[INET6_ADDRSTRLEN
];
1651 unsigned char *mac_addr
;
1654 g_debug("Processing %s interface", ifa
->ifa_name
);
1656 info
= guest_find_interface(head
, ifa
->ifa_name
);
1659 info
= g_malloc0(sizeof(*info
));
1660 info
->value
= g_malloc0(sizeof(*info
->value
));
1661 info
->value
->name
= g_strdup(ifa
->ifa_name
);
1664 head
= cur_item
= info
;
1666 cur_item
->next
= info
;
1671 if (!info
->value
->has_hardware_address
&&
1672 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
1673 /* we haven't obtained HW address yet */
1674 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
1676 error_setg_errno(errp
, errno
, "failed to create socket");
1680 memset(&ifr
, 0, sizeof(ifr
));
1681 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
1682 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
1683 error_setg_errno(errp
, errno
,
1684 "failed to get MAC address of %s",
1691 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
1693 info
->value
->hardware_address
=
1694 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1695 (int) mac_addr
[0], (int) mac_addr
[1],
1696 (int) mac_addr
[2], (int) mac_addr
[3],
1697 (int) mac_addr
[4], (int) mac_addr
[5]);
1699 info
->value
->has_hardware_address
= true;
1702 if (ifa
->ifa_addr
&&
1703 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1704 /* interface with IPv4 address */
1705 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1706 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1707 error_setg_errno(errp
, errno
, "inet_ntop failed");
1711 address_item
= g_malloc0(sizeof(*address_item
));
1712 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1713 address_item
->value
->ip_address
= g_strdup(addr4
);
1714 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1716 if (ifa
->ifa_netmask
) {
1717 /* Count the number of set bits in netmask.
1718 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1719 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1720 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1722 } else if (ifa
->ifa_addr
&&
1723 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1724 /* interface with IPv6 address */
1725 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1726 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1727 error_setg_errno(errp
, errno
, "inet_ntop failed");
1731 address_item
= g_malloc0(sizeof(*address_item
));
1732 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1733 address_item
->value
->ip_address
= g_strdup(addr6
);
1734 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1736 if (ifa
->ifa_netmask
) {
1737 /* Count the number of set bits in netmask.
1738 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1739 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1740 address_item
->value
->prefix
=
1741 ctpop32(((uint32_t *) p
)[0]) +
1742 ctpop32(((uint32_t *) p
)[1]) +
1743 ctpop32(((uint32_t *) p
)[2]) +
1744 ctpop32(((uint32_t *) p
)[3]);
1748 if (!address_item
) {
1752 address_list
= &info
->value
->ip_addresses
;
1754 while (*address_list
&& (*address_list
)->next
) {
1755 address_list
= &(*address_list
)->next
;
1758 if (!*address_list
) {
1759 *address_list
= address_item
;
1761 (*address_list
)->next
= address_item
;
1764 info
->value
->has_ip_addresses
= true;
1774 qapi_free_GuestNetworkInterfaceList(head
);
1778 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
1780 static long sysconf_exact(int name
, const char *name_str
, Error
**errp
)
1785 ret
= sysconf(name
);
1788 error_setg(errp
, "sysconf(%s): value indefinite", name_str
);
1790 error_setg_errno(errp
, errno
, "sysconf(%s)", name_str
);
1796 /* Transfer online/offline status between @vcpu and the guest system.
1798 * On input either @errp or *@errp must be NULL.
1800 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1801 * - R: vcpu->logical_id
1803 * - W: vcpu->can_offline
1805 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1806 * - R: vcpu->logical_id
1809 * Written members remain unmodified on error.
1811 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1817 dirpath
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
1819 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
1821 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
1823 static const char fn
[] = "online";
1827 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
1829 if (errno
!= ENOENT
) {
1830 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
1831 } else if (sys2vcpu
) {
1832 vcpu
->online
= true;
1833 vcpu
->can_offline
= false;
1834 } else if (!vcpu
->online
) {
1835 error_setg(errp
, "logical processor #%" PRId64
" can't be "
1836 "offlined", vcpu
->logical_id
);
1837 } /* otherwise pretend successful re-onlining */
1839 unsigned char status
;
1841 res
= pread(fd
, &status
, 1, 0);
1843 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
1844 } else if (res
== 0) {
1845 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
1847 } else if (sys2vcpu
) {
1848 vcpu
->online
= (status
!= '0');
1849 vcpu
->can_offline
= true;
1850 } else if (vcpu
->online
!= (status
!= '0')) {
1851 status
= '0' + vcpu
->online
;
1852 if (pwrite(fd
, &status
, 1, 0) == -1) {
1853 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
1856 } /* otherwise pretend successful re-(on|off)-lining */
1869 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1872 GuestLogicalProcessorList
*head
, **link
;
1874 Error
*local_err
= NULL
;
1879 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
1881 while (local_err
== NULL
&& current
< sc_max
) {
1882 GuestLogicalProcessor
*vcpu
;
1883 GuestLogicalProcessorList
*entry
;
1885 vcpu
= g_malloc0(sizeof *vcpu
);
1886 vcpu
->logical_id
= current
++;
1887 vcpu
->has_can_offline
= true; /* lolspeak ftw */
1888 transfer_vcpu(vcpu
, true, &local_err
);
1890 entry
= g_malloc0(sizeof *entry
);
1891 entry
->value
= vcpu
;
1894 link
= &entry
->next
;
1897 if (local_err
== NULL
) {
1898 /* there's no guest with zero VCPUs */
1899 g_assert(head
!= NULL
);
1903 qapi_free_GuestLogicalProcessorList(head
);
1904 error_propagate(errp
, local_err
);
1908 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1911 Error
*local_err
= NULL
;
1914 while (vcpus
!= NULL
) {
1915 transfer_vcpu(vcpus
->value
, false, &local_err
);
1916 if (local_err
!= NULL
) {
1920 vcpus
= vcpus
->next
;
1923 if (local_err
!= NULL
) {
1924 if (processed
== 0) {
1925 error_propagate(errp
, local_err
);
1927 error_free(local_err
);
1934 void qmp_guest_set_user_password(const char *username
,
1935 const char *password
,
1939 Error
*local_err
= NULL
;
1940 char *passwd_path
= NULL
;
1943 int datafd
[2] = { -1, -1 };
1944 char *rawpasswddata
= NULL
;
1945 size_t rawpasswdlen
;
1946 char *chpasswddata
= NULL
;
1949 rawpasswddata
= (char *)g_base64_decode(password
, &rawpasswdlen
);
1950 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1951 rawpasswddata
[rawpasswdlen
] = '\0';
1953 if (strchr(rawpasswddata
, '\n')) {
1954 error_setg(errp
, "forbidden characters in raw password");
1958 if (strchr(username
, '\n') ||
1959 strchr(username
, ':')) {
1960 error_setg(errp
, "forbidden characters in username");
1964 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
1965 chpasswdlen
= strlen(chpasswddata
);
1967 passwd_path
= g_find_program_in_path("chpasswd");
1970 error_setg(errp
, "cannot find 'passwd' program in PATH");
1974 if (pipe(datafd
) < 0) {
1975 error_setg(errp
, "cannot create pipe FDs");
1985 reopen_fd_to_null(1);
1986 reopen_fd_to_null(2);
1989 execle(passwd_path
, "chpasswd", "-e", NULL
, environ
);
1991 execle(passwd_path
, "chpasswd", NULL
, environ
);
1993 _exit(EXIT_FAILURE
);
1994 } else if (pid
< 0) {
1995 error_setg_errno(errp
, errno
, "failed to create child process");
2001 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2002 error_setg_errno(errp
, errno
, "cannot write new account password");
2008 ga_wait_child(pid
, &status
, &local_err
);
2010 error_propagate(errp
, local_err
);
2014 if (!WIFEXITED(status
)) {
2015 error_setg(errp
, "child process has terminated abnormally");
2019 if (WEXITSTATUS(status
)) {
2020 error_setg(errp
, "child process has failed to set user password");
2025 g_free(chpasswddata
);
2026 g_free(rawpasswddata
);
2027 g_free(passwd_path
);
2028 if (datafd
[0] != -1) {
2031 if (datafd
[1] != -1) {
2036 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2037 int size
, Error
**errp
)
2043 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2045 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2049 res
= pread(fd
, buf
, size
, 0);
2051 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2052 } else if (res
== 0) {
2053 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2058 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2059 const char *buf
, int size
, Error
**errp
)
2064 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2066 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2070 if (pwrite(fd
, buf
, size
, 0) == -1) {
2071 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2077 /* Transfer online/offline status between @mem_blk and the guest system.
2079 * On input either @errp or *@errp must be NULL.
2081 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2082 * - R: mem_blk->phys_index
2083 * - W: mem_blk->online
2084 * - W: mem_blk->can_offline
2086 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2087 * - R: mem_blk->phys_index
2088 * - R: mem_blk->online
2089 *- R: mem_blk->can_offline
2090 * Written members remain unmodified on error.
2092 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2093 GuestMemoryBlockResponse
*result
,
2099 Error
*local_err
= NULL
;
2105 error_setg(errp
, "Internal error, 'result' should not be NULL");
2109 dp
= opendir("/sys/devices/system/memory/");
2110 /* if there is no 'memory' directory in sysfs,
2111 * we think this VM does not support online/offline memory block,
2112 * any other solution?
2114 if (!dp
&& errno
== ENOENT
) {
2116 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2122 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2123 mem_blk
->phys_index
);
2124 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2127 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2129 if (errno
== ENOENT
) {
2130 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2133 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2141 status
= g_malloc0(10);
2142 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2144 /* treat with sysfs file that not exist in old kernel */
2145 if (errno
== ENOENT
) {
2146 error_free(local_err
);
2148 mem_blk
->online
= true;
2149 mem_blk
->can_offline
= false;
2150 } else if (!mem_blk
->online
) {
2152 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2156 error_propagate(errp
, local_err
);
2159 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2166 char removable
= '0';
2168 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2170 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2172 /* if no 'removable' file, it doesn't support offline mem blk */
2173 if (errno
== ENOENT
) {
2174 error_free(local_err
);
2175 mem_blk
->can_offline
= false;
2177 error_propagate(errp
, local_err
);
2180 mem_blk
->can_offline
= (removable
!= '0');
2183 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2184 char *new_state
= mem_blk
->online
? g_strdup("online") :
2185 g_strdup("offline");
2187 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2191 error_free(local_err
);
2193 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2197 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2198 result
->has_error_code
= false;
2199 } /* otherwise pretend successful re-(on|off)-lining */
2210 result
->has_error_code
= true;
2211 result
->error_code
= errno
;
2215 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2217 GuestMemoryBlockList
*head
, **link
;
2218 Error
*local_err
= NULL
;
2225 dp
= opendir("/sys/devices/system/memory/");
2227 /* it's ok if this happens to be a system that doesn't expose
2228 * memory blocks via sysfs, but otherwise we should report
2231 if (errno
!= ENOENT
) {
2232 error_setg_errno(errp
, errno
, "Can't open directory"
2233 "\"/sys/devices/system/memory/\"\n");
2238 /* Note: the phys_index of memory block may be discontinuous,
2239 * this is because a memblk is the unit of the Sparse Memory design, which
2240 * allows discontinuous memory ranges (ex. NUMA), so here we should
2241 * traverse the memory block directory.
2243 while ((de
= readdir(dp
)) != NULL
) {
2244 GuestMemoryBlock
*mem_blk
;
2245 GuestMemoryBlockList
*entry
;
2247 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2248 !(de
->d_type
& DT_DIR
)) {
2252 mem_blk
= g_malloc0(sizeof *mem_blk
);
2253 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2254 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2255 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2256 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2258 entry
= g_malloc0(sizeof *entry
);
2259 entry
->value
= mem_blk
;
2262 link
= &entry
->next
;
2266 if (local_err
== NULL
) {
2267 /* there's no guest with zero memory blocks */
2269 error_setg(errp
, "guest reported zero memory blocks!");
2274 qapi_free_GuestMemoryBlockList(head
);
2275 error_propagate(errp
, local_err
);
2279 GuestMemoryBlockResponseList
*
2280 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2282 GuestMemoryBlockResponseList
*head
, **link
;
2283 Error
*local_err
= NULL
;
2288 while (mem_blks
!= NULL
) {
2289 GuestMemoryBlockResponse
*result
;
2290 GuestMemoryBlockResponseList
*entry
;
2291 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2293 result
= g_malloc0(sizeof(*result
));
2294 result
->phys_index
= current_mem_blk
->phys_index
;
2295 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2296 if (local_err
) { /* should never happen */
2299 entry
= g_malloc0(sizeof *entry
);
2300 entry
->value
= result
;
2303 link
= &entry
->next
;
2304 mem_blks
= mem_blks
->next
;
2309 qapi_free_GuestMemoryBlockResponseList(head
);
2310 error_propagate(errp
, local_err
);
2314 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2316 Error
*local_err
= NULL
;
2320 GuestMemoryBlockInfo
*info
;
2322 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2323 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2325 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2331 buf
= g_malloc0(20);
2332 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2336 error_propagate(errp
, local_err
);
2340 info
= g_new0(GuestMemoryBlockInfo
, 1);
2341 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2348 #else /* defined(__linux__) */
2350 void qmp_guest_suspend_disk(Error
**errp
)
2352 error_setg(errp
, QERR_UNSUPPORTED
);
2355 void qmp_guest_suspend_ram(Error
**errp
)
2357 error_setg(errp
, QERR_UNSUPPORTED
);
2360 void qmp_guest_suspend_hybrid(Error
**errp
)
2362 error_setg(errp
, QERR_UNSUPPORTED
);
2365 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2367 error_setg(errp
, QERR_UNSUPPORTED
);
2371 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2373 error_setg(errp
, QERR_UNSUPPORTED
);
2377 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2379 error_setg(errp
, QERR_UNSUPPORTED
);
2383 void qmp_guest_set_user_password(const char *username
,
2384 const char *password
,
2388 error_setg(errp
, QERR_UNSUPPORTED
);
2391 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2393 error_setg(errp
, QERR_UNSUPPORTED
);
2397 GuestMemoryBlockResponseList
*
2398 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2400 error_setg(errp
, QERR_UNSUPPORTED
);
2404 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2406 error_setg(errp
, QERR_UNSUPPORTED
);
2412 #if !defined(CONFIG_FSFREEZE)
2414 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
2416 error_setg(errp
, QERR_UNSUPPORTED
);
2420 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
2422 error_setg(errp
, QERR_UNSUPPORTED
);
2427 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
2429 error_setg(errp
, QERR_UNSUPPORTED
);
2434 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
2435 strList
*mountpoints
,
2438 error_setg(errp
, QERR_UNSUPPORTED
);
2443 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
2445 error_setg(errp
, QERR_UNSUPPORTED
);
2449 #endif /* CONFIG_FSFREEZE */
2451 #if !defined(CONFIG_FSTRIM)
2452 GuestFilesystemTrimResponse
*
2453 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
2455 error_setg(errp
, QERR_UNSUPPORTED
);
2460 /* add unsupported commands to the blacklist */
2461 GList
*ga_command_blacklist_init(GList
*blacklist
)
2463 #if !defined(__linux__)
2465 const char *list
[] = {
2466 "guest-suspend-disk", "guest-suspend-ram",
2467 "guest-suspend-hybrid", "guest-network-get-interfaces",
2468 "guest-get-vcpus", "guest-set-vcpus",
2469 "guest-get-memory-blocks", "guest-set-memory-blocks",
2470 "guest-get-memory-block-size", NULL
};
2471 char **p
= (char **)list
;
2474 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2479 #if !defined(CONFIG_FSFREEZE)
2481 const char *list
[] = {
2482 "guest-get-fsinfo", "guest-fsfreeze-status",
2483 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2484 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL
};
2485 char **p
= (char **)list
;
2488 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2493 #if !defined(CONFIG_FSTRIM)
2494 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
2500 /* register init/cleanup routines for stateful command groups */
2501 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2503 #if defined(CONFIG_FSFREEZE)
2504 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);