2 * QEMU Guest Agent POSIX-specific command implementations
4 * Copyright IBM Corp. 2011
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
8 * Michal Privoznik <mprivozn@redhat.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
14 #include "qemu/osdep.h"
16 #include <sys/ioctl.h>
19 #include "qga/guest-agent-core.h"
20 #include "qga-qmp-commands.h"
21 #include "qapi/qmp/qerror.h"
22 #include "qemu/queue.h"
23 #include "qemu/host-utils.h"
24 #include "qemu/sockets.h"
25 #include "qemu/base64.h"
26 #include "qemu/cutils.h"
28 #ifndef CONFIG_HAS_ENVIRON
30 #include <crt_externs.h>
31 #define environ (*_NSGetEnviron())
33 extern char **environ
;
37 #if defined(__linux__)
41 #include <arpa/inet.h>
42 #include <sys/socket.h>
46 #define CONFIG_FSFREEZE
53 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
60 rpid
= waitpid(pid
, status
, 0);
61 } while (rpid
== -1 && errno
== EINTR
);
64 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
69 g_assert(rpid
== pid
);
72 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
74 const char *shutdown_flag
;
75 Error
*local_err
= NULL
;
79 slog("guest-shutdown called, mode: %s", mode
);
80 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
82 } else if (strcmp(mode
, "halt") == 0) {
84 } else if (strcmp(mode
, "reboot") == 0) {
88 "mode is invalid (valid values are: halt|powerdown|reboot");
94 /* child, start the shutdown */
100 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
101 "hypervisor initiated shutdown", (char*)NULL
, environ
);
103 } else if (pid
< 0) {
104 error_setg_errno(errp
, errno
, "failed to create child process");
108 ga_wait_child(pid
, &status
, &local_err
);
110 error_propagate(errp
, local_err
);
114 if (!WIFEXITED(status
)) {
115 error_setg(errp
, "child process has terminated abnormally");
119 if (WEXITSTATUS(status
)) {
120 error_setg(errp
, "child process has failed to shutdown");
127 int64_t qmp_guest_get_time(Error
**errp
)
133 ret
= qemu_gettimeofday(&tq
);
135 error_setg_errno(errp
, errno
, "Failed to get time");
139 time_ns
= tq
.tv_sec
* 1000000000LL + tq
.tv_usec
* 1000;
143 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
148 Error
*local_err
= NULL
;
151 /* If user has passed a time, validate and set it. */
155 /* year-2038 will overflow in case time_t is 32bit */
156 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
157 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
161 tv
.tv_sec
= time_ns
/ 1000000000;
162 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
163 g_date_set_time_t(&date
, tv
.tv_sec
);
164 if (date
.year
< 1970 || date
.year
>= 2070) {
165 error_setg_errno(errp
, errno
, "Invalid time");
169 ret
= settimeofday(&tv
, NULL
);
171 error_setg_errno(errp
, errno
, "Failed to set time to guest");
176 /* Now, if user has passed a time to set and the system time is set, we
177 * just need to synchronize the hardware clock. However, if no time was
178 * passed, user is requesting the opposite: set the system time from the
179 * hardware clock (RTC). */
183 reopen_fd_to_null(0);
184 reopen_fd_to_null(1);
185 reopen_fd_to_null(2);
187 /* Use '/sbin/hwclock -w' to set RTC from the system time,
188 * or '/sbin/hwclock -s' to set the system time from RTC. */
189 execle("/sbin/hwclock", "hwclock", has_time
? "-w" : "-s",
192 } else if (pid
< 0) {
193 error_setg_errno(errp
, errno
, "failed to create child process");
197 ga_wait_child(pid
, &status
, &local_err
);
199 error_propagate(errp
, local_err
);
203 if (!WIFEXITED(status
)) {
204 error_setg(errp
, "child process has terminated abnormally");
208 if (WEXITSTATUS(status
)) {
209 error_setg(errp
, "hwclock failed to set hardware clock to system time");
220 typedef struct GuestFileHandle
{
224 QTAILQ_ENTRY(GuestFileHandle
) next
;
228 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
229 } guest_file_state
= {
230 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
233 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
235 GuestFileHandle
*gfh
;
238 handle
= ga_get_fd_handle(ga_state
, errp
);
243 gfh
= g_new0(GuestFileHandle
, 1);
246 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
251 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
253 GuestFileHandle
*gfh
;
255 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
262 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
266 typedef const char * const ccpc
;
272 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
273 static const struct {
276 } guest_file_open_modes
[] = {
277 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
278 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
279 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
280 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
281 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
282 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
283 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
284 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
285 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
286 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
287 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
288 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
292 find_open_flag(const char *mode_str
, Error
**errp
)
296 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
299 form
= guest_file_open_modes
[mode
].forms
;
300 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
308 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
309 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
312 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
315 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
316 S_IRGRP | S_IWGRP | \
320 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
322 Error
*local_err
= NULL
;
325 oflag
= find_open_flag(mode
, &local_err
);
326 if (local_err
== NULL
) {
329 /* If the caller wants / allows creation of a new file, we implement it
330 * with a two step process: open() + (open() / fchmod()).
332 * First we insist on creating the file exclusively as a new file. If
333 * that succeeds, we're free to set any file-mode bits on it. (The
334 * motivation is that we want to set those file-mode bits independently
335 * of the current umask.)
337 * If the exclusive creation fails because the file already exists
338 * (EEXIST is not possible for any other reason), we just attempt to
339 * open the file, but in this case we won't be allowed to change the
340 * file-mode bits on the preexistent file.
342 * The pathname should never disappear between the two open()s in
343 * practice. If it happens, then someone very likely tried to race us.
344 * In this case just go ahead and report the ENOENT from the second
345 * open() to the caller.
347 * If the caller wants to open a preexistent file, then the first
348 * open() is decisive and its third argument is ignored, and the second
349 * open() and the fchmod() are never called.
351 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
352 if (fd
== -1 && errno
== EEXIST
) {
353 oflag
&= ~(unsigned)O_CREAT
;
354 fd
= open(path
, oflag
);
358 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
359 "(mode: '%s')", path
, mode
);
361 qemu_set_cloexec(fd
);
363 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
364 error_setg_errno(&local_err
, errno
, "failed to set permission "
365 "0%03o on new file '%s' (mode: '%s')",
366 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
370 f
= fdopen(fd
, mode
);
372 error_setg_errno(&local_err
, errno
, "failed to associate "
373 "stdio stream with file descriptor %d, "
374 "file '%s' (mode: '%s')", fd
, path
, mode
);
381 if (oflag
& O_CREAT
) {
387 error_propagate(errp
, local_err
);
391 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
395 Error
*local_err
= NULL
;
401 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
402 fh
= safe_open_or_create(path
, mode
, &local_err
);
403 if (local_err
!= NULL
) {
404 error_propagate(errp
, local_err
);
408 /* set fd non-blocking to avoid common use cases (like reading from a
409 * named pipe) from hanging the agent
411 qemu_set_nonblock(fileno(fh
));
413 handle
= guest_file_handle_add(fh
, errp
);
419 slog("guest-file-open, handle: %" PRId64
, handle
);
423 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
425 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
428 slog("guest-file-close called, handle: %" PRId64
, handle
);
433 ret
= fclose(gfh
->fh
);
435 error_setg_errno(errp
, errno
, "failed to close handle");
439 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
443 struct GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
444 int64_t count
, Error
**errp
)
446 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
447 GuestFileRead
*read_data
= NULL
;
457 count
= QGA_READ_COUNT_DEFAULT
;
458 } else if (count
< 0) {
459 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
466 /* explicitly flush when switching from writing to reading */
467 if (gfh
->state
== RW_STATE_WRITING
) {
468 int ret
= fflush(fh
);
470 error_setg_errno(errp
, errno
, "failed to flush file");
473 gfh
->state
= RW_STATE_NEW
;
476 buf
= g_malloc0(count
+1);
477 read_count
= fread(buf
, 1, count
, fh
);
479 error_setg_errno(errp
, errno
, "failed to read file");
480 slog("guest-file-read failed, handle: %" PRId64
, handle
);
483 read_data
= g_new0(GuestFileRead
, 1);
484 read_data
->count
= read_count
;
485 read_data
->eof
= feof(fh
);
487 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
489 gfh
->state
= RW_STATE_READING
;
497 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
498 bool has_count
, int64_t count
,
501 GuestFileWrite
*write_data
= NULL
;
505 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
514 if (gfh
->state
== RW_STATE_READING
) {
515 int ret
= fseek(fh
, 0, SEEK_CUR
);
517 error_setg_errno(errp
, errno
, "failed to seek file");
520 gfh
->state
= RW_STATE_NEW
;
523 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
530 } else if (count
< 0 || count
> buf_len
) {
531 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
537 write_count
= fwrite(buf
, 1, count
, fh
);
539 error_setg_errno(errp
, errno
, "failed to write to file");
540 slog("guest-file-write failed, handle: %" PRId64
, handle
);
542 write_data
= g_new0(GuestFileWrite
, 1);
543 write_data
->count
= write_count
;
544 write_data
->eof
= feof(fh
);
545 gfh
->state
= RW_STATE_WRITING
;
553 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
554 GuestFileWhence
*whence_code
,
557 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
558 GuestFileSeek
*seek_data
= NULL
;
568 /* We stupidly exposed 'whence':'int' in our qapi */
569 whence
= ga_parse_whence(whence_code
, &err
);
571 error_propagate(errp
, err
);
576 ret
= fseek(fh
, offset
, whence
);
578 error_setg_errno(errp
, errno
, "failed to seek file");
579 if (errno
== ESPIPE
) {
580 /* file is non-seekable, stdio shouldn't be buffering anyways */
581 gfh
->state
= RW_STATE_NEW
;
584 seek_data
= g_new0(GuestFileSeek
, 1);
585 seek_data
->position
= ftell(fh
);
586 seek_data
->eof
= feof(fh
);
587 gfh
->state
= RW_STATE_NEW
;
594 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
596 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
607 error_setg_errno(errp
, errno
, "failed to flush file");
609 gfh
->state
= RW_STATE_NEW
;
613 /* linux-specific implementations. avoid this if at all possible. */
614 #if defined(__linux__)
616 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
617 typedef struct FsMount
{
620 unsigned int devmajor
, devminor
;
621 QTAILQ_ENTRY(FsMount
) next
;
624 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
626 static void free_fs_mount_list(FsMountList
*mounts
)
628 FsMount
*mount
, *temp
;
634 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
635 QTAILQ_REMOVE(mounts
, mount
, next
);
636 g_free(mount
->dirname
);
637 g_free(mount
->devtype
);
642 static int dev_major_minor(const char *devpath
,
643 unsigned int *devmajor
, unsigned int *devminor
)
650 if (stat(devpath
, &st
) < 0) {
651 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
654 if (S_ISDIR(st
.st_mode
)) {
655 /* It is bind mount */
658 if (S_ISBLK(st
.st_mode
)) {
659 *devmajor
= major(st
.st_rdev
);
660 *devminor
= minor(st
.st_rdev
);
667 * Walk the mount table and build a list of local file systems
669 static void build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
673 char const *mtab
= "/proc/self/mounts";
675 unsigned int devmajor
, devminor
;
677 fp
= setmntent(mtab
, "r");
679 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
683 while ((ment
= getmntent(fp
))) {
685 * An entry which device name doesn't start with a '/' is
686 * either a dummy file system or a network file system.
687 * Add special handling for smbfs and cifs as is done by
690 if ((ment
->mnt_fsname
[0] != '/') ||
691 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
692 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
695 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
696 /* Skip bind mounts */
700 mount
= g_new0(FsMount
, 1);
701 mount
->dirname
= g_strdup(ment
->mnt_dir
);
702 mount
->devtype
= g_strdup(ment
->mnt_type
);
703 mount
->devmajor
= devmajor
;
704 mount
->devminor
= devminor
;
706 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
712 static void decode_mntname(char *name
, int len
)
715 for (i
= 0; i
<= len
; i
++) {
716 if (name
[i
] != '\\') {
718 } else if (name
[i
+ 1] == '\\') {
721 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
722 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
723 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
724 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
725 (name
[i
+ 2] - '0') * 8 +
734 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
737 char const *mountinfo
= "/proc/self/mountinfo";
739 char *line
= NULL
, *dash
;
742 unsigned int devmajor
, devminor
;
743 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
745 fp
= fopen(mountinfo
, "r");
747 build_fs_mount_list_from_mtab(mounts
, errp
);
751 while (getline(&line
, &n
, fp
) != -1) {
752 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
753 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
757 dash
= strstr(line
+ dir_e
, " - ");
761 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
762 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
769 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
770 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
772 /* btrfs reports major number = 0 */
773 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
774 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
779 mount
= g_new0(FsMount
, 1);
780 mount
->dirname
= g_strdup(line
+ dir_s
);
781 mount
->devtype
= g_strdup(dash
+ type_s
);
782 mount
->devmajor
= devmajor
;
783 mount
->devminor
= devminor
;
785 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
793 #if defined(CONFIG_FSFREEZE)
795 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
803 path
= g_strndup(syspath
, pathlen
);
804 dpath
= g_strdup_printf("%s/driver", path
);
805 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
808 driver
= g_strdup(basename(buf
));
815 static int compare_uint(const void *_a
, const void *_b
)
817 unsigned int a
= *(unsigned int *)_a
;
818 unsigned int b
= *(unsigned int *)_b
;
820 return a
< b
? -1 : a
> b
? 1 : 0;
823 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
824 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
825 unsigned int *hosts
, int hosts_max
, Error
**errp
)
829 struct dirent
*entry
;
832 path
= g_strndup(syspath
, host
- syspath
);
835 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
840 while (i
< hosts_max
) {
841 entry
= readdir(dir
);
845 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
847 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
852 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
859 /* Store disk device info specified by @sysfs into @fs */
860 static void build_guest_fsinfo_for_real_device(char const *syspath
,
861 GuestFilesystemInfo
*fs
,
864 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
865 int i
, nhosts
= 0, pcilen
;
866 GuestDiskAddress
*disk
;
867 GuestPCIAddress
*pciaddr
;
868 GuestDiskAddressList
*list
= NULL
;
869 bool has_ata
= false, has_host
= false, has_tgt
= false;
870 char *p
, *q
, *driver
= NULL
;
872 p
= strstr(syspath
, "/devices/pci");
873 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
874 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
875 g_debug("only pci device is supported: sysfs path \"%s\"", syspath
);
879 driver
= get_pci_driver(syspath
, (p
+ 12 + pcilen
) - syspath
, errp
);
884 p
= strstr(syspath
, "/target");
885 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
886 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
890 p
= strstr(syspath
, "/ata");
895 p
= strstr(syspath
, "/host");
898 if (p
&& sscanf(q
, "%u", &host
) == 1) {
900 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
901 sizeof(hosts
) / sizeof(hosts
[0]), errp
);
907 pciaddr
= g_malloc0(sizeof(*pciaddr
));
908 pciaddr
->domain
= pci
[0];
909 pciaddr
->bus
= pci
[1];
910 pciaddr
->slot
= pci
[2];
911 pciaddr
->function
= pci
[3];
913 disk
= g_malloc0(sizeof(*disk
));
914 disk
->pci_controller
= pciaddr
;
916 list
= g_malloc0(sizeof(*list
));
919 if (strcmp(driver
, "ata_piix") == 0) {
920 /* a host per ide bus, target*:0:<unit>:0 */
921 if (!has_host
|| !has_tgt
) {
922 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
925 for (i
= 0; i
< nhosts
; i
++) {
926 if (host
== hosts
[i
]) {
927 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
934 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
937 } else if (strcmp(driver
, "sym53c8xx") == 0) {
938 /* scsi(LSI Logic): target*:0:<unit>:0 */
940 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
943 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
945 } else if (strcmp(driver
, "virtio-pci") == 0) {
947 /* virtio-scsi: target*:0:0:<unit> */
948 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
951 /* virtio-blk: 1 disk per 1 device */
952 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
954 } else if (strcmp(driver
, "ahci") == 0) {
955 /* ahci: 1 host per 1 unit */
956 if (!has_host
|| !has_tgt
) {
957 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
960 for (i
= 0; i
< nhosts
; i
++) {
961 if (host
== hosts
[i
]) {
963 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
968 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
972 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
976 list
->next
= fs
->disk
;
983 qapi_free_GuestDiskAddressList(list
);
988 static void build_guest_fsinfo_for_device(char const *devpath
,
989 GuestFilesystemInfo
*fs
,
992 /* Store a list of slave devices of virtual volume specified by @syspath into
994 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
995 GuestFilesystemInfo
*fs
,
1000 struct dirent
*entry
;
1002 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1003 dir
= opendir(dirpath
);
1005 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1012 entry
= readdir(dir
);
1013 if (entry
== NULL
) {
1015 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1020 if (entry
->d_type
== DT_LNK
) {
1023 g_debug(" slave device '%s'", entry
->d_name
);
1024 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1025 build_guest_fsinfo_for_device(path
, fs
, errp
);
1038 /* Dispatch to functions for virtual/real device */
1039 static void build_guest_fsinfo_for_device(char const *devpath
,
1040 GuestFilesystemInfo
*fs
,
1043 char *syspath
= realpath(devpath
, NULL
);
1046 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1051 fs
->name
= g_strdup(basename(syspath
));
1054 g_debug(" parse sysfs path '%s'", syspath
);
1056 if (strstr(syspath
, "/devices/virtual/block/")) {
1057 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1059 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1065 /* Return a list of the disk device(s)' info which @mount lies on */
1066 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1069 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1070 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1071 mount
->devmajor
, mount
->devminor
);
1073 fs
->mountpoint
= g_strdup(mount
->dirname
);
1074 fs
->type
= g_strdup(mount
->devtype
);
1075 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1081 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1084 struct FsMount
*mount
;
1085 GuestFilesystemInfoList
*new, *ret
= NULL
;
1086 Error
*local_err
= NULL
;
1088 QTAILQ_INIT(&mounts
);
1089 build_fs_mount_list(&mounts
, &local_err
);
1091 error_propagate(errp
, local_err
);
1095 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1096 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1098 new = g_malloc0(sizeof(*ret
));
1099 new->value
= build_guest_fsinfo(mount
, &local_err
);
1103 error_propagate(errp
, local_err
);
1104 qapi_free_GuestFilesystemInfoList(ret
);
1110 free_fs_mount_list(&mounts
);
1116 FSFREEZE_HOOK_THAW
= 0,
1117 FSFREEZE_HOOK_FREEZE
,
1120 static const char *fsfreeze_hook_arg_string
[] = {
1125 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1130 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1131 Error
*local_err
= NULL
;
1133 hook
= ga_fsfreeze_hook(ga_state
);
1137 if (access(hook
, X_OK
) != 0) {
1138 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1142 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1146 reopen_fd_to_null(0);
1147 reopen_fd_to_null(1);
1148 reopen_fd_to_null(2);
1150 execle(hook
, hook
, arg_str
, NULL
, environ
);
1151 _exit(EXIT_FAILURE
);
1152 } else if (pid
< 0) {
1153 error_setg_errno(errp
, errno
, "failed to create child process");
1157 ga_wait_child(pid
, &status
, &local_err
);
1159 error_propagate(errp
, local_err
);
1163 if (!WIFEXITED(status
)) {
1164 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1168 status
= WEXITSTATUS(status
);
1170 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1176 * Return status of freeze/thaw
1178 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1180 if (ga_is_frozen(ga_state
)) {
1181 return GUEST_FSFREEZE_STATUS_FROZEN
;
1184 return GUEST_FSFREEZE_STATUS_THAWED
;
1187 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1189 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1193 * Walk list of mounted file systems in the guest, and freeze the ones which
1194 * are real local file systems.
1196 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1197 strList
*mountpoints
,
1203 struct FsMount
*mount
;
1204 Error
*local_err
= NULL
;
1207 slog("guest-fsfreeze called");
1209 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1211 error_propagate(errp
, local_err
);
1215 QTAILQ_INIT(&mounts
);
1216 build_fs_mount_list(&mounts
, &local_err
);
1218 error_propagate(errp
, local_err
);
1222 /* cannot risk guest agent blocking itself on a write in this state */
1223 ga_set_frozen(ga_state
);
1225 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, FsMountList
, next
) {
1226 /* To issue fsfreeze in the reverse order of mounts, check if the
1227 * mount is listed in the list here */
1228 if (has_mountpoints
) {
1229 for (list
= mountpoints
; list
; list
= list
->next
) {
1230 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1239 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1241 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1245 /* we try to cull filesytems we know won't work in advance, but other
1246 * filesytems may not implement fsfreeze for less obvious reasons.
1247 * these will report EOPNOTSUPP. we simply ignore these when tallying
1248 * the number of frozen filesystems.
1250 * any other error means a failure to freeze a filesystem we
1251 * expect to be freezable, so return an error in those cases
1252 * and return system to thawed state.
1254 ret
= ioctl(fd
, FIFREEZE
);
1256 if (errno
!= EOPNOTSUPP
) {
1257 error_setg_errno(errp
, errno
, "failed to freeze %s",
1268 free_fs_mount_list(&mounts
);
1272 free_fs_mount_list(&mounts
);
1273 qmp_guest_fsfreeze_thaw(NULL
);
1278 * Walk list of frozen file systems in the guest, and thaw them.
1280 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1285 int fd
, i
= 0, logged
;
1286 Error
*local_err
= NULL
;
1288 QTAILQ_INIT(&mounts
);
1289 build_fs_mount_list(&mounts
, &local_err
);
1291 error_propagate(errp
, local_err
);
1295 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1297 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1301 /* we have no way of knowing whether a filesystem was actually unfrozen
1302 * as a result of a successful call to FITHAW, only that if an error
1303 * was returned the filesystem was *not* unfrozen by that particular
1306 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1307 * to unfreeze, continuing issuing FITHAW until an error is returned,
1308 * in which case either the filesystem is in an unfreezable state, or,
1309 * more likely, it was thawed previously (and remains so afterward).
1311 * also, since the most recent successful call is the one that did
1312 * the actual unfreeze, we can use this to provide an accurate count
1313 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1314 * may * be useful for determining whether a filesystem was unfrozen
1315 * during the freeze/thaw phase by a process other than qemu-ga.
1318 ret
= ioctl(fd
, FITHAW
);
1319 if (ret
== 0 && !logged
) {
1327 ga_unset_frozen(ga_state
);
1328 free_fs_mount_list(&mounts
);
1330 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1335 static void guest_fsfreeze_cleanup(void)
1339 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1340 qmp_guest_fsfreeze_thaw(&err
);
1342 slog("failed to clean up frozen filesystems: %s",
1343 error_get_pretty(err
));
1348 #endif /* CONFIG_FSFREEZE */
1350 #if defined(CONFIG_FSTRIM)
1352 * Walk list of mounted file systems in the guest, and trim them.
1354 GuestFilesystemTrimResponse
*
1355 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1357 GuestFilesystemTrimResponse
*response
;
1358 GuestFilesystemTrimResultList
*list
;
1359 GuestFilesystemTrimResult
*result
;
1362 struct FsMount
*mount
;
1364 Error
*local_err
= NULL
;
1365 struct fstrim_range r
;
1367 slog("guest-fstrim called");
1369 QTAILQ_INIT(&mounts
);
1370 build_fs_mount_list(&mounts
, &local_err
);
1372 error_propagate(errp
, local_err
);
1376 response
= g_malloc0(sizeof(*response
));
1378 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1379 result
= g_malloc0(sizeof(*result
));
1380 result
->path
= g_strdup(mount
->dirname
);
1382 list
= g_malloc0(sizeof(*list
));
1383 list
->value
= result
;
1384 list
->next
= response
->paths
;
1385 response
->paths
= list
;
1387 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1389 result
->error
= g_strdup_printf("failed to open: %s",
1391 result
->has_error
= true;
1395 /* We try to cull filesytems we know won't work in advance, but other
1396 * filesytems may not implement fstrim for less obvious reasons. These
1397 * will report EOPNOTSUPP; while in some other cases ENOTTY will be
1398 * reported (e.g. CD-ROMs).
1399 * Any other error means an unexpected error.
1403 r
.minlen
= has_minimum
? minimum
: 0;
1404 ret
= ioctl(fd
, FITRIM
, &r
);
1406 result
->has_error
= true;
1407 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1408 result
->error
= g_strdup("trim not supported");
1410 result
->error
= g_strdup_printf("failed to trim: %s",
1417 result
->has_minimum
= true;
1418 result
->minimum
= r
.minlen
;
1419 result
->has_trimmed
= true;
1420 result
->trimmed
= r
.len
;
1424 free_fs_mount_list(&mounts
);
1427 #endif /* CONFIG_FSTRIM */
1430 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1431 #define SUSPEND_SUPPORTED 0
1432 #define SUSPEND_NOT_SUPPORTED 1
1434 static void bios_supports_mode(const char *pmutils_bin
, const char *pmutils_arg
,
1435 const char *sysfile_str
, Error
**errp
)
1437 Error
*local_err
= NULL
;
1442 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1446 char buf
[32]; /* hopefully big enough */
1451 reopen_fd_to_null(0);
1452 reopen_fd_to_null(1);
1453 reopen_fd_to_null(2);
1456 execle(pmutils_path
, pmutils_bin
, pmutils_arg
, NULL
, environ
);
1460 * If we get here either pm-utils is not installed or execle() has
1461 * failed. Let's try the manual method if the caller wants it.
1465 _exit(SUSPEND_NOT_SUPPORTED
);
1468 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1470 _exit(SUSPEND_NOT_SUPPORTED
);
1473 ret
= read(fd
, buf
, sizeof(buf
)-1);
1475 _exit(SUSPEND_NOT_SUPPORTED
);
1479 if (strstr(buf
, sysfile_str
)) {
1480 _exit(SUSPEND_SUPPORTED
);
1483 _exit(SUSPEND_NOT_SUPPORTED
);
1484 } else if (pid
< 0) {
1485 error_setg_errno(errp
, errno
, "failed to create child process");
1489 ga_wait_child(pid
, &status
, &local_err
);
1491 error_propagate(errp
, local_err
);
1495 if (!WIFEXITED(status
)) {
1496 error_setg(errp
, "child process has terminated abnormally");
1500 switch (WEXITSTATUS(status
)) {
1501 case SUSPEND_SUPPORTED
:
1503 case SUSPEND_NOT_SUPPORTED
:
1505 "the requested suspend mode is not supported by the guest");
1509 "the helper program '%s' returned an unexpected exit status"
1510 " code (%d)", pmutils_path
, WEXITSTATUS(status
));
1515 g_free(pmutils_path
);
1518 static void guest_suspend(const char *pmutils_bin
, const char *sysfile_str
,
1521 Error
*local_err
= NULL
;
1526 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1534 reopen_fd_to_null(0);
1535 reopen_fd_to_null(1);
1536 reopen_fd_to_null(2);
1539 execle(pmutils_path
, pmutils_bin
, NULL
, environ
);
1543 * If we get here either pm-utils is not installed or execle() has
1544 * failed. Let's try the manual method if the caller wants it.
1548 _exit(EXIT_FAILURE
);
1551 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1553 _exit(EXIT_FAILURE
);
1556 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1557 _exit(EXIT_FAILURE
);
1560 _exit(EXIT_SUCCESS
);
1561 } else if (pid
< 0) {
1562 error_setg_errno(errp
, errno
, "failed to create child process");
1566 ga_wait_child(pid
, &status
, &local_err
);
1568 error_propagate(errp
, local_err
);
1572 if (!WIFEXITED(status
)) {
1573 error_setg(errp
, "child process has terminated abnormally");
1577 if (WEXITSTATUS(status
)) {
1578 error_setg(errp
, "child process has failed to suspend");
1583 g_free(pmutils_path
);
1586 void qmp_guest_suspend_disk(Error
**errp
)
1588 Error
*local_err
= NULL
;
1590 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err
);
1592 error_propagate(errp
, local_err
);
1596 guest_suspend("pm-hibernate", "disk", errp
);
1599 void qmp_guest_suspend_ram(Error
**errp
)
1601 Error
*local_err
= NULL
;
1603 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err
);
1605 error_propagate(errp
, local_err
);
1609 guest_suspend("pm-suspend", "mem", errp
);
1612 void qmp_guest_suspend_hybrid(Error
**errp
)
1614 Error
*local_err
= NULL
;
1616 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL
,
1619 error_propagate(errp
, local_err
);
1623 guest_suspend("pm-suspend-hybrid", NULL
, errp
);
1626 static GuestNetworkInterfaceList
*
1627 guest_find_interface(GuestNetworkInterfaceList
*head
,
1630 for (; head
; head
= head
->next
) {
1631 if (strcmp(head
->value
->name
, name
) == 0) {
1640 * Build information about guest interfaces
1642 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1644 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1645 struct ifaddrs
*ifap
, *ifa
;
1647 if (getifaddrs(&ifap
) < 0) {
1648 error_setg_errno(errp
, errno
, "getifaddrs failed");
1652 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1653 GuestNetworkInterfaceList
*info
;
1654 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
1655 char addr4
[INET_ADDRSTRLEN
];
1656 char addr6
[INET6_ADDRSTRLEN
];
1659 unsigned char *mac_addr
;
1662 g_debug("Processing %s interface", ifa
->ifa_name
);
1664 info
= guest_find_interface(head
, ifa
->ifa_name
);
1667 info
= g_malloc0(sizeof(*info
));
1668 info
->value
= g_malloc0(sizeof(*info
->value
));
1669 info
->value
->name
= g_strdup(ifa
->ifa_name
);
1672 head
= cur_item
= info
;
1674 cur_item
->next
= info
;
1679 if (!info
->value
->has_hardware_address
&&
1680 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
1681 /* we haven't obtained HW address yet */
1682 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
1684 error_setg_errno(errp
, errno
, "failed to create socket");
1688 memset(&ifr
, 0, sizeof(ifr
));
1689 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
1690 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
1691 error_setg_errno(errp
, errno
,
1692 "failed to get MAC address of %s",
1699 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
1701 info
->value
->hardware_address
=
1702 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1703 (int) mac_addr
[0], (int) mac_addr
[1],
1704 (int) mac_addr
[2], (int) mac_addr
[3],
1705 (int) mac_addr
[4], (int) mac_addr
[5]);
1707 info
->value
->has_hardware_address
= true;
1710 if (ifa
->ifa_addr
&&
1711 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1712 /* interface with IPv4 address */
1713 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1714 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1715 error_setg_errno(errp
, errno
, "inet_ntop failed");
1719 address_item
= g_malloc0(sizeof(*address_item
));
1720 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1721 address_item
->value
->ip_address
= g_strdup(addr4
);
1722 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1724 if (ifa
->ifa_netmask
) {
1725 /* Count the number of set bits in netmask.
1726 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1727 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1728 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1730 } else if (ifa
->ifa_addr
&&
1731 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1732 /* interface with IPv6 address */
1733 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1734 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1735 error_setg_errno(errp
, errno
, "inet_ntop failed");
1739 address_item
= g_malloc0(sizeof(*address_item
));
1740 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1741 address_item
->value
->ip_address
= g_strdup(addr6
);
1742 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1744 if (ifa
->ifa_netmask
) {
1745 /* Count the number of set bits in netmask.
1746 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1747 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1748 address_item
->value
->prefix
=
1749 ctpop32(((uint32_t *) p
)[0]) +
1750 ctpop32(((uint32_t *) p
)[1]) +
1751 ctpop32(((uint32_t *) p
)[2]) +
1752 ctpop32(((uint32_t *) p
)[3]);
1756 if (!address_item
) {
1760 address_list
= &info
->value
->ip_addresses
;
1762 while (*address_list
&& (*address_list
)->next
) {
1763 address_list
= &(*address_list
)->next
;
1766 if (!*address_list
) {
1767 *address_list
= address_item
;
1769 (*address_list
)->next
= address_item
;
1772 info
->value
->has_ip_addresses
= true;
1782 qapi_free_GuestNetworkInterfaceList(head
);
1786 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
1788 static long sysconf_exact(int name
, const char *name_str
, Error
**errp
)
1793 ret
= sysconf(name
);
1796 error_setg(errp
, "sysconf(%s): value indefinite", name_str
);
1798 error_setg_errno(errp
, errno
, "sysconf(%s)", name_str
);
1804 /* Transfer online/offline status between @vcpu and the guest system.
1806 * On input either @errp or *@errp must be NULL.
1808 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1809 * - R: vcpu->logical_id
1811 * - W: vcpu->can_offline
1813 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1814 * - R: vcpu->logical_id
1817 * Written members remain unmodified on error.
1819 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1825 dirpath
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
1827 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
1829 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
1831 static const char fn
[] = "online";
1835 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
1837 if (errno
!= ENOENT
) {
1838 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
1839 } else if (sys2vcpu
) {
1840 vcpu
->online
= true;
1841 vcpu
->can_offline
= false;
1842 } else if (!vcpu
->online
) {
1843 error_setg(errp
, "logical processor #%" PRId64
" can't be "
1844 "offlined", vcpu
->logical_id
);
1845 } /* otherwise pretend successful re-onlining */
1847 unsigned char status
;
1849 res
= pread(fd
, &status
, 1, 0);
1851 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
1852 } else if (res
== 0) {
1853 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
1855 } else if (sys2vcpu
) {
1856 vcpu
->online
= (status
!= '0');
1857 vcpu
->can_offline
= true;
1858 } else if (vcpu
->online
!= (status
!= '0')) {
1859 status
= '0' + vcpu
->online
;
1860 if (pwrite(fd
, &status
, 1, 0) == -1) {
1861 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
1864 } /* otherwise pretend successful re-(on|off)-lining */
1877 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1880 GuestLogicalProcessorList
*head
, **link
;
1882 Error
*local_err
= NULL
;
1887 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
1889 while (local_err
== NULL
&& current
< sc_max
) {
1890 GuestLogicalProcessor
*vcpu
;
1891 GuestLogicalProcessorList
*entry
;
1893 vcpu
= g_malloc0(sizeof *vcpu
);
1894 vcpu
->logical_id
= current
++;
1895 vcpu
->has_can_offline
= true; /* lolspeak ftw */
1896 transfer_vcpu(vcpu
, true, &local_err
);
1898 entry
= g_malloc0(sizeof *entry
);
1899 entry
->value
= vcpu
;
1902 link
= &entry
->next
;
1905 if (local_err
== NULL
) {
1906 /* there's no guest with zero VCPUs */
1907 g_assert(head
!= NULL
);
1911 qapi_free_GuestLogicalProcessorList(head
);
1912 error_propagate(errp
, local_err
);
1916 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1919 Error
*local_err
= NULL
;
1922 while (vcpus
!= NULL
) {
1923 transfer_vcpu(vcpus
->value
, false, &local_err
);
1924 if (local_err
!= NULL
) {
1928 vcpus
= vcpus
->next
;
1931 if (local_err
!= NULL
) {
1932 if (processed
== 0) {
1933 error_propagate(errp
, local_err
);
1935 error_free(local_err
);
1942 void qmp_guest_set_user_password(const char *username
,
1943 const char *password
,
1947 Error
*local_err
= NULL
;
1948 char *passwd_path
= NULL
;
1951 int datafd
[2] = { -1, -1 };
1952 char *rawpasswddata
= NULL
;
1953 size_t rawpasswdlen
;
1954 char *chpasswddata
= NULL
;
1957 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1958 if (!rawpasswddata
) {
1961 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1962 rawpasswddata
[rawpasswdlen
] = '\0';
1964 if (strchr(rawpasswddata
, '\n')) {
1965 error_setg(errp
, "forbidden characters in raw password");
1969 if (strchr(username
, '\n') ||
1970 strchr(username
, ':')) {
1971 error_setg(errp
, "forbidden characters in username");
1975 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
1976 chpasswdlen
= strlen(chpasswddata
);
1978 passwd_path
= g_find_program_in_path("chpasswd");
1981 error_setg(errp
, "cannot find 'passwd' program in PATH");
1985 if (pipe(datafd
) < 0) {
1986 error_setg(errp
, "cannot create pipe FDs");
1996 reopen_fd_to_null(1);
1997 reopen_fd_to_null(2);
2000 execle(passwd_path
, "chpasswd", "-e", NULL
, environ
);
2002 execle(passwd_path
, "chpasswd", NULL
, environ
);
2004 _exit(EXIT_FAILURE
);
2005 } else if (pid
< 0) {
2006 error_setg_errno(errp
, errno
, "failed to create child process");
2012 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2013 error_setg_errno(errp
, errno
, "cannot write new account password");
2019 ga_wait_child(pid
, &status
, &local_err
);
2021 error_propagate(errp
, local_err
);
2025 if (!WIFEXITED(status
)) {
2026 error_setg(errp
, "child process has terminated abnormally");
2030 if (WEXITSTATUS(status
)) {
2031 error_setg(errp
, "child process has failed to set user password");
2036 g_free(chpasswddata
);
2037 g_free(rawpasswddata
);
2038 g_free(passwd_path
);
2039 if (datafd
[0] != -1) {
2042 if (datafd
[1] != -1) {
2047 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2048 int size
, Error
**errp
)
2054 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2056 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2060 res
= pread(fd
, buf
, size
, 0);
2062 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2063 } else if (res
== 0) {
2064 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2069 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2070 const char *buf
, int size
, Error
**errp
)
2075 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2077 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2081 if (pwrite(fd
, buf
, size
, 0) == -1) {
2082 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2088 /* Transfer online/offline status between @mem_blk and the guest system.
2090 * On input either @errp or *@errp must be NULL.
2092 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2093 * - R: mem_blk->phys_index
2094 * - W: mem_blk->online
2095 * - W: mem_blk->can_offline
2097 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2098 * - R: mem_blk->phys_index
2099 * - R: mem_blk->online
2100 *- R: mem_blk->can_offline
2101 * Written members remain unmodified on error.
2103 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2104 GuestMemoryBlockResponse
*result
,
2110 Error
*local_err
= NULL
;
2116 error_setg(errp
, "Internal error, 'result' should not be NULL");
2120 dp
= opendir("/sys/devices/system/memory/");
2121 /* if there is no 'memory' directory in sysfs,
2122 * we think this VM does not support online/offline memory block,
2123 * any other solution?
2125 if (!dp
&& errno
== ENOENT
) {
2127 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2133 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2134 mem_blk
->phys_index
);
2135 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2138 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2140 if (errno
== ENOENT
) {
2141 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2144 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2152 status
= g_malloc0(10);
2153 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2155 /* treat with sysfs file that not exist in old kernel */
2156 if (errno
== ENOENT
) {
2157 error_free(local_err
);
2159 mem_blk
->online
= true;
2160 mem_blk
->can_offline
= false;
2161 } else if (!mem_blk
->online
) {
2163 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2167 error_propagate(errp
, local_err
);
2170 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2177 char removable
= '0';
2179 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2181 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2183 /* if no 'removable' file, it doesn't support offline mem blk */
2184 if (errno
== ENOENT
) {
2185 error_free(local_err
);
2186 mem_blk
->can_offline
= false;
2188 error_propagate(errp
, local_err
);
2191 mem_blk
->can_offline
= (removable
!= '0');
2194 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2195 char *new_state
= mem_blk
->online
? g_strdup("online") :
2196 g_strdup("offline");
2198 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2202 error_free(local_err
);
2204 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2208 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2209 result
->has_error_code
= false;
2210 } /* otherwise pretend successful re-(on|off)-lining */
2221 result
->has_error_code
= true;
2222 result
->error_code
= errno
;
2226 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2228 GuestMemoryBlockList
*head
, **link
;
2229 Error
*local_err
= NULL
;
2236 dp
= opendir("/sys/devices/system/memory/");
2238 /* it's ok if this happens to be a system that doesn't expose
2239 * memory blocks via sysfs, but otherwise we should report
2242 if (errno
!= ENOENT
) {
2243 error_setg_errno(errp
, errno
, "Can't open directory"
2244 "\"/sys/devices/system/memory/\"");
2249 /* Note: the phys_index of memory block may be discontinuous,
2250 * this is because a memblk is the unit of the Sparse Memory design, which
2251 * allows discontinuous memory ranges (ex. NUMA), so here we should
2252 * traverse the memory block directory.
2254 while ((de
= readdir(dp
)) != NULL
) {
2255 GuestMemoryBlock
*mem_blk
;
2256 GuestMemoryBlockList
*entry
;
2258 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2259 !(de
->d_type
& DT_DIR
)) {
2263 mem_blk
= g_malloc0(sizeof *mem_blk
);
2264 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2265 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2266 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2267 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2269 entry
= g_malloc0(sizeof *entry
);
2270 entry
->value
= mem_blk
;
2273 link
= &entry
->next
;
2277 if (local_err
== NULL
) {
2278 /* there's no guest with zero memory blocks */
2280 error_setg(errp
, "guest reported zero memory blocks!");
2285 qapi_free_GuestMemoryBlockList(head
);
2286 error_propagate(errp
, local_err
);
2290 GuestMemoryBlockResponseList
*
2291 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2293 GuestMemoryBlockResponseList
*head
, **link
;
2294 Error
*local_err
= NULL
;
2299 while (mem_blks
!= NULL
) {
2300 GuestMemoryBlockResponse
*result
;
2301 GuestMemoryBlockResponseList
*entry
;
2302 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2304 result
= g_malloc0(sizeof(*result
));
2305 result
->phys_index
= current_mem_blk
->phys_index
;
2306 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2307 if (local_err
) { /* should never happen */
2310 entry
= g_malloc0(sizeof *entry
);
2311 entry
->value
= result
;
2314 link
= &entry
->next
;
2315 mem_blks
= mem_blks
->next
;
2320 qapi_free_GuestMemoryBlockResponseList(head
);
2321 error_propagate(errp
, local_err
);
2325 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2327 Error
*local_err
= NULL
;
2331 GuestMemoryBlockInfo
*info
;
2333 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2334 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2336 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2342 buf
= g_malloc0(20);
2343 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2347 error_propagate(errp
, local_err
);
2351 info
= g_new0(GuestMemoryBlockInfo
, 1);
2352 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2359 #else /* defined(__linux__) */
2361 void qmp_guest_suspend_disk(Error
**errp
)
2363 error_setg(errp
, QERR_UNSUPPORTED
);
2366 void qmp_guest_suspend_ram(Error
**errp
)
2368 error_setg(errp
, QERR_UNSUPPORTED
);
2371 void qmp_guest_suspend_hybrid(Error
**errp
)
2373 error_setg(errp
, QERR_UNSUPPORTED
);
2376 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2378 error_setg(errp
, QERR_UNSUPPORTED
);
2382 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2384 error_setg(errp
, QERR_UNSUPPORTED
);
2388 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2390 error_setg(errp
, QERR_UNSUPPORTED
);
2394 void qmp_guest_set_user_password(const char *username
,
2395 const char *password
,
2399 error_setg(errp
, QERR_UNSUPPORTED
);
2402 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2404 error_setg(errp
, QERR_UNSUPPORTED
);
2408 GuestMemoryBlockResponseList
*
2409 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2411 error_setg(errp
, QERR_UNSUPPORTED
);
2415 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2417 error_setg(errp
, QERR_UNSUPPORTED
);
2423 #if !defined(CONFIG_FSFREEZE)
2425 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
2427 error_setg(errp
, QERR_UNSUPPORTED
);
2431 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
2433 error_setg(errp
, QERR_UNSUPPORTED
);
2438 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
2440 error_setg(errp
, QERR_UNSUPPORTED
);
2445 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
2446 strList
*mountpoints
,
2449 error_setg(errp
, QERR_UNSUPPORTED
);
2454 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
2456 error_setg(errp
, QERR_UNSUPPORTED
);
2460 #endif /* CONFIG_FSFREEZE */
2462 #if !defined(CONFIG_FSTRIM)
2463 GuestFilesystemTrimResponse
*
2464 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
2466 error_setg(errp
, QERR_UNSUPPORTED
);
2471 /* add unsupported commands to the blacklist */
2472 GList
*ga_command_blacklist_init(GList
*blacklist
)
2474 #if !defined(__linux__)
2476 const char *list
[] = {
2477 "guest-suspend-disk", "guest-suspend-ram",
2478 "guest-suspend-hybrid", "guest-network-get-interfaces",
2479 "guest-get-vcpus", "guest-set-vcpus",
2480 "guest-get-memory-blocks", "guest-set-memory-blocks",
2481 "guest-get-memory-block-size", NULL
};
2482 char **p
= (char **)list
;
2485 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2490 #if !defined(CONFIG_FSFREEZE)
2492 const char *list
[] = {
2493 "guest-get-fsinfo", "guest-fsfreeze-status",
2494 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2495 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL
};
2496 char **p
= (char **)list
;
2499 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2504 #if !defined(CONFIG_FSTRIM)
2505 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
2511 /* register init/cleanup routines for stateful command groups */
2512 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2514 #if defined(CONFIG_FSFREEZE)
2515 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);