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"
32 #include "qemu/base64.h"
34 #ifndef CONFIG_HAS_ENVIRON
36 #include <crt_externs.h>
37 #define environ (*_NSGetEnviron())
39 extern char **environ
;
43 #if defined(__linux__)
47 #include <arpa/inet.h>
48 #include <sys/socket.h>
52 #define CONFIG_FSFREEZE
59 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
66 rpid
= waitpid(pid
, status
, 0);
67 } while (rpid
== -1 && errno
== EINTR
);
70 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
75 g_assert(rpid
== pid
);
78 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
80 const char *shutdown_flag
;
81 Error
*local_err
= NULL
;
85 slog("guest-shutdown called, mode: %s", mode
);
86 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
88 } else if (strcmp(mode
, "halt") == 0) {
90 } else if (strcmp(mode
, "reboot") == 0) {
94 "mode is invalid (valid values are: halt|powerdown|reboot");
100 /* child, start the shutdown */
102 reopen_fd_to_null(0);
103 reopen_fd_to_null(1);
104 reopen_fd_to_null(2);
106 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
107 "hypervisor initiated shutdown", (char*)NULL
, environ
);
109 } else if (pid
< 0) {
110 error_setg_errno(errp
, errno
, "failed to create child process");
114 ga_wait_child(pid
, &status
, &local_err
);
116 error_propagate(errp
, local_err
);
120 if (!WIFEXITED(status
)) {
121 error_setg(errp
, "child process has terminated abnormally");
125 if (WEXITSTATUS(status
)) {
126 error_setg(errp
, "child process has failed to shutdown");
133 int64_t qmp_guest_get_time(Error
**errp
)
139 ret
= qemu_gettimeofday(&tq
);
141 error_setg_errno(errp
, errno
, "Failed to get time");
145 time_ns
= tq
.tv_sec
* 1000000000LL + tq
.tv_usec
* 1000;
149 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
154 Error
*local_err
= NULL
;
157 /* If user has passed a time, validate and set it. */
161 /* year-2038 will overflow in case time_t is 32bit */
162 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
163 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
167 tv
.tv_sec
= time_ns
/ 1000000000;
168 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
169 g_date_set_time_t(&date
, tv
.tv_sec
);
170 if (date
.year
< 1970 || date
.year
>= 2070) {
171 error_setg_errno(errp
, errno
, "Invalid time");
175 ret
= settimeofday(&tv
, NULL
);
177 error_setg_errno(errp
, errno
, "Failed to set time to guest");
182 /* Now, if user has passed a time to set and the system time is set, we
183 * just need to synchronize the hardware clock. However, if no time was
184 * passed, user is requesting the opposite: set the system time from the
185 * hardware clock (RTC). */
189 reopen_fd_to_null(0);
190 reopen_fd_to_null(1);
191 reopen_fd_to_null(2);
193 /* Use '/sbin/hwclock -w' to set RTC from the system time,
194 * or '/sbin/hwclock -s' to set the system time from RTC. */
195 execle("/sbin/hwclock", "hwclock", has_time
? "-w" : "-s",
198 } else if (pid
< 0) {
199 error_setg_errno(errp
, errno
, "failed to create child process");
203 ga_wait_child(pid
, &status
, &local_err
);
205 error_propagate(errp
, local_err
);
209 if (!WIFEXITED(status
)) {
210 error_setg(errp
, "child process has terminated abnormally");
214 if (WEXITSTATUS(status
)) {
215 error_setg(errp
, "hwclock failed to set hardware clock to system time");
226 typedef struct GuestFileHandle
{
230 QTAILQ_ENTRY(GuestFileHandle
) next
;
234 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
235 } guest_file_state
= {
236 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
239 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
241 GuestFileHandle
*gfh
;
244 handle
= ga_get_fd_handle(ga_state
, errp
);
249 gfh
= g_new0(GuestFileHandle
, 1);
252 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
257 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
259 GuestFileHandle
*gfh
;
261 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
268 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
272 typedef const char * const ccpc
;
278 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
279 static const struct {
282 } guest_file_open_modes
[] = {
283 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
284 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
285 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
286 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
287 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
288 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
289 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
290 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
291 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
292 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
293 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
294 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
298 find_open_flag(const char *mode_str
, Error
**errp
)
302 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
305 form
= guest_file_open_modes
[mode
].forms
;
306 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
314 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
315 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
318 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
321 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
322 S_IRGRP | S_IWGRP | \
326 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
328 Error
*local_err
= NULL
;
331 oflag
= find_open_flag(mode
, &local_err
);
332 if (local_err
== NULL
) {
335 /* If the caller wants / allows creation of a new file, we implement it
336 * with a two step process: open() + (open() / fchmod()).
338 * First we insist on creating the file exclusively as a new file. If
339 * that succeeds, we're free to set any file-mode bits on it. (The
340 * motivation is that we want to set those file-mode bits independently
341 * of the current umask.)
343 * If the exclusive creation fails because the file already exists
344 * (EEXIST is not possible for any other reason), we just attempt to
345 * open the file, but in this case we won't be allowed to change the
346 * file-mode bits on the preexistent file.
348 * The pathname should never disappear between the two open()s in
349 * practice. If it happens, then someone very likely tried to race us.
350 * In this case just go ahead and report the ENOENT from the second
351 * open() to the caller.
353 * If the caller wants to open a preexistent file, then the first
354 * open() is decisive and its third argument is ignored, and the second
355 * open() and the fchmod() are never called.
357 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
358 if (fd
== -1 && errno
== EEXIST
) {
359 oflag
&= ~(unsigned)O_CREAT
;
360 fd
= open(path
, oflag
);
364 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
365 "(mode: '%s')", path
, mode
);
367 qemu_set_cloexec(fd
);
369 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
370 error_setg_errno(&local_err
, errno
, "failed to set permission "
371 "0%03o on new file '%s' (mode: '%s')",
372 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
376 f
= fdopen(fd
, mode
);
378 error_setg_errno(&local_err
, errno
, "failed to associate "
379 "stdio stream with file descriptor %d, "
380 "file '%s' (mode: '%s')", fd
, path
, mode
);
387 if (oflag
& O_CREAT
) {
393 error_propagate(errp
, local_err
);
397 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
401 Error
*local_err
= NULL
;
407 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
408 fh
= safe_open_or_create(path
, mode
, &local_err
);
409 if (local_err
!= NULL
) {
410 error_propagate(errp
, local_err
);
414 /* set fd non-blocking to avoid common use cases (like reading from a
415 * named pipe) from hanging the agent
417 qemu_set_nonblock(fileno(fh
));
419 handle
= guest_file_handle_add(fh
, errp
);
425 slog("guest-file-open, handle: %" PRId64
, handle
);
429 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
431 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
434 slog("guest-file-close called, handle: %" PRId64
, handle
);
439 ret
= fclose(gfh
->fh
);
441 error_setg_errno(errp
, errno
, "failed to close handle");
445 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
449 struct GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
450 int64_t count
, Error
**errp
)
452 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
453 GuestFileRead
*read_data
= NULL
;
463 count
= QGA_READ_COUNT_DEFAULT
;
464 } else if (count
< 0) {
465 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
472 /* explicitly flush when switching from writing to reading */
473 if (gfh
->state
== RW_STATE_WRITING
) {
474 int ret
= fflush(fh
);
476 error_setg_errno(errp
, errno
, "failed to flush file");
479 gfh
->state
= RW_STATE_NEW
;
482 buf
= g_malloc0(count
+1);
483 read_count
= fread(buf
, 1, count
, fh
);
485 error_setg_errno(errp
, errno
, "failed to read file");
486 slog("guest-file-read failed, handle: %" PRId64
, handle
);
489 read_data
= g_new0(GuestFileRead
, 1);
490 read_data
->count
= read_count
;
491 read_data
->eof
= feof(fh
);
493 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
495 gfh
->state
= RW_STATE_READING
;
503 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
504 bool has_count
, int64_t count
,
507 GuestFileWrite
*write_data
= NULL
;
511 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
520 if (gfh
->state
== RW_STATE_READING
) {
521 int ret
= fseek(fh
, 0, SEEK_CUR
);
523 error_setg_errno(errp
, errno
, "failed to seek file");
526 gfh
->state
= RW_STATE_NEW
;
529 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
536 } else if (count
< 0 || count
> buf_len
) {
537 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
543 write_count
= fwrite(buf
, 1, count
, fh
);
545 error_setg_errno(errp
, errno
, "failed to write to file");
546 slog("guest-file-write failed, handle: %" PRId64
, handle
);
548 write_data
= g_new0(GuestFileWrite
, 1);
549 write_data
->count
= write_count
;
550 write_data
->eof
= feof(fh
);
551 gfh
->state
= RW_STATE_WRITING
;
559 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
560 int64_t whence_code
, Error
**errp
)
562 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
563 GuestFileSeek
*seek_data
= NULL
;
572 /* We stupidly exposed 'whence':'int' in our qapi */
573 switch (whence_code
) {
584 error_setg(errp
, "invalid whence code %"PRId64
, whence_code
);
589 ret
= fseek(fh
, offset
, whence
);
591 error_setg_errno(errp
, errno
, "failed to seek file");
592 if (errno
== ESPIPE
) {
593 /* file is non-seekable, stdio shouldn't be buffering anyways */
594 gfh
->state
= RW_STATE_NEW
;
597 seek_data
= g_new0(GuestFileSeek
, 1);
598 seek_data
->position
= ftell(fh
);
599 seek_data
->eof
= feof(fh
);
600 gfh
->state
= RW_STATE_NEW
;
607 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
609 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
620 error_setg_errno(errp
, errno
, "failed to flush file");
622 gfh
->state
= RW_STATE_NEW
;
626 /* linux-specific implementations. avoid this if at all possible. */
627 #if defined(__linux__)
629 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
630 typedef struct FsMount
{
633 unsigned int devmajor
, devminor
;
634 QTAILQ_ENTRY(FsMount
) next
;
637 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
639 static void free_fs_mount_list(FsMountList
*mounts
)
641 FsMount
*mount
, *temp
;
647 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
648 QTAILQ_REMOVE(mounts
, mount
, next
);
649 g_free(mount
->dirname
);
650 g_free(mount
->devtype
);
655 static int dev_major_minor(const char *devpath
,
656 unsigned int *devmajor
, unsigned int *devminor
)
663 if (stat(devpath
, &st
) < 0) {
664 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
667 if (S_ISDIR(st
.st_mode
)) {
668 /* It is bind mount */
671 if (S_ISBLK(st
.st_mode
)) {
672 *devmajor
= major(st
.st_rdev
);
673 *devminor
= minor(st
.st_rdev
);
680 * Walk the mount table and build a list of local file systems
682 static void build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
686 char const *mtab
= "/proc/self/mounts";
688 unsigned int devmajor
, devminor
;
690 fp
= setmntent(mtab
, "r");
692 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
696 while ((ment
= getmntent(fp
))) {
698 * An entry which device name doesn't start with a '/' is
699 * either a dummy file system or a network file system.
700 * Add special handling for smbfs and cifs as is done by
703 if ((ment
->mnt_fsname
[0] != '/') ||
704 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
705 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
708 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
709 /* Skip bind mounts */
713 mount
= g_new0(FsMount
, 1);
714 mount
->dirname
= g_strdup(ment
->mnt_dir
);
715 mount
->devtype
= g_strdup(ment
->mnt_type
);
716 mount
->devmajor
= devmajor
;
717 mount
->devminor
= devminor
;
719 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
725 static void decode_mntname(char *name
, int len
)
728 for (i
= 0; i
<= len
; i
++) {
729 if (name
[i
] != '\\') {
731 } else if (name
[i
+ 1] == '\\') {
734 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
735 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
736 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
737 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
738 (name
[i
+ 2] - '0') * 8 +
747 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
750 char const *mountinfo
= "/proc/self/mountinfo";
752 char *line
= NULL
, *dash
;
755 unsigned int devmajor
, devminor
;
756 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
758 fp
= fopen(mountinfo
, "r");
760 build_fs_mount_list_from_mtab(mounts
, errp
);
764 while (getline(&line
, &n
, fp
) != -1) {
765 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
766 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
770 dash
= strstr(line
+ dir_e
, " - ");
774 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
775 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
782 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
783 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
785 /* btrfs reports major number = 0 */
786 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
787 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
792 mount
= g_new0(FsMount
, 1);
793 mount
->dirname
= g_strdup(line
+ dir_s
);
794 mount
->devtype
= g_strdup(dash
+ type_s
);
795 mount
->devmajor
= devmajor
;
796 mount
->devminor
= devminor
;
798 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
806 #if defined(CONFIG_FSFREEZE)
808 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
816 path
= g_strndup(syspath
, pathlen
);
817 dpath
= g_strdup_printf("%s/driver", path
);
818 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
821 driver
= g_strdup(basename(buf
));
828 static int compare_uint(const void *_a
, const void *_b
)
830 unsigned int a
= *(unsigned int *)_a
;
831 unsigned int b
= *(unsigned int *)_b
;
833 return a
< b
? -1 : a
> b
? 1 : 0;
836 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
837 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
838 unsigned int *hosts
, int hosts_max
, Error
**errp
)
842 struct dirent
*entry
;
845 path
= g_strndup(syspath
, host
- syspath
);
848 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
853 while (i
< hosts_max
) {
854 entry
= readdir(dir
);
858 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
860 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
865 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
872 /* Store disk device info specified by @sysfs into @fs */
873 static void build_guest_fsinfo_for_real_device(char const *syspath
,
874 GuestFilesystemInfo
*fs
,
877 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
878 int i
, nhosts
= 0, pcilen
;
879 GuestDiskAddress
*disk
;
880 GuestPCIAddress
*pciaddr
;
881 GuestDiskAddressList
*list
= NULL
;
882 bool has_ata
= false, has_host
= false, has_tgt
= false;
883 char *p
, *q
, *driver
= NULL
;
885 p
= strstr(syspath
, "/devices/pci");
886 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
887 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
888 g_debug("only pci device is supported: sysfs path \"%s\"", syspath
);
892 driver
= get_pci_driver(syspath
, (p
+ 12 + pcilen
) - syspath
, errp
);
897 p
= strstr(syspath
, "/target");
898 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
899 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
903 p
= strstr(syspath
, "/ata");
908 p
= strstr(syspath
, "/host");
911 if (p
&& sscanf(q
, "%u", &host
) == 1) {
913 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
914 sizeof(hosts
) / sizeof(hosts
[0]), errp
);
920 pciaddr
= g_malloc0(sizeof(*pciaddr
));
921 pciaddr
->domain
= pci
[0];
922 pciaddr
->bus
= pci
[1];
923 pciaddr
->slot
= pci
[2];
924 pciaddr
->function
= pci
[3];
926 disk
= g_malloc0(sizeof(*disk
));
927 disk
->pci_controller
= pciaddr
;
929 list
= g_malloc0(sizeof(*list
));
932 if (strcmp(driver
, "ata_piix") == 0) {
933 /* a host per ide bus, target*:0:<unit>:0 */
934 if (!has_host
|| !has_tgt
) {
935 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
938 for (i
= 0; i
< nhosts
; i
++) {
939 if (host
== hosts
[i
]) {
940 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
947 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
950 } else if (strcmp(driver
, "sym53c8xx") == 0) {
951 /* scsi(LSI Logic): target*:0:<unit>:0 */
953 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
956 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
958 } else if (strcmp(driver
, "virtio-pci") == 0) {
960 /* virtio-scsi: target*:0:0:<unit> */
961 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
964 /* virtio-blk: 1 disk per 1 device */
965 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
967 } else if (strcmp(driver
, "ahci") == 0) {
968 /* ahci: 1 host per 1 unit */
969 if (!has_host
|| !has_tgt
) {
970 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
973 for (i
= 0; i
< nhosts
; i
++) {
974 if (host
== hosts
[i
]) {
976 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
981 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
985 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
989 list
->next
= fs
->disk
;
996 qapi_free_GuestDiskAddressList(list
);
1001 static void build_guest_fsinfo_for_device(char const *devpath
,
1002 GuestFilesystemInfo
*fs
,
1005 /* Store a list of slave devices of virtual volume specified by @syspath into
1007 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
1008 GuestFilesystemInfo
*fs
,
1013 struct dirent
*entry
;
1015 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1016 dir
= opendir(dirpath
);
1018 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1025 entry
= readdir(dir
);
1026 if (entry
== NULL
) {
1028 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1033 if (entry
->d_type
== DT_LNK
) {
1036 g_debug(" slave device '%s'", entry
->d_name
);
1037 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1038 build_guest_fsinfo_for_device(path
, fs
, errp
);
1051 /* Dispatch to functions for virtual/real device */
1052 static void build_guest_fsinfo_for_device(char const *devpath
,
1053 GuestFilesystemInfo
*fs
,
1056 char *syspath
= realpath(devpath
, NULL
);
1059 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1064 fs
->name
= g_strdup(basename(syspath
));
1067 g_debug(" parse sysfs path '%s'", syspath
);
1069 if (strstr(syspath
, "/devices/virtual/block/")) {
1070 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1072 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1078 /* Return a list of the disk device(s)' info which @mount lies on */
1079 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1082 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1083 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1084 mount
->devmajor
, mount
->devminor
);
1086 fs
->mountpoint
= g_strdup(mount
->dirname
);
1087 fs
->type
= g_strdup(mount
->devtype
);
1088 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1094 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1097 struct FsMount
*mount
;
1098 GuestFilesystemInfoList
*new, *ret
= NULL
;
1099 Error
*local_err
= NULL
;
1101 QTAILQ_INIT(&mounts
);
1102 build_fs_mount_list(&mounts
, &local_err
);
1104 error_propagate(errp
, local_err
);
1108 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1109 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1111 new = g_malloc0(sizeof(*ret
));
1112 new->value
= build_guest_fsinfo(mount
, &local_err
);
1116 error_propagate(errp
, local_err
);
1117 qapi_free_GuestFilesystemInfoList(ret
);
1123 free_fs_mount_list(&mounts
);
1129 FSFREEZE_HOOK_THAW
= 0,
1130 FSFREEZE_HOOK_FREEZE
,
1133 static const char *fsfreeze_hook_arg_string
[] = {
1138 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1143 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1144 Error
*local_err
= NULL
;
1146 hook
= ga_fsfreeze_hook(ga_state
);
1150 if (access(hook
, X_OK
) != 0) {
1151 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1155 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1159 reopen_fd_to_null(0);
1160 reopen_fd_to_null(1);
1161 reopen_fd_to_null(2);
1163 execle(hook
, hook
, arg_str
, NULL
, environ
);
1164 _exit(EXIT_FAILURE
);
1165 } else if (pid
< 0) {
1166 error_setg_errno(errp
, errno
, "failed to create child process");
1170 ga_wait_child(pid
, &status
, &local_err
);
1172 error_propagate(errp
, local_err
);
1176 if (!WIFEXITED(status
)) {
1177 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1181 status
= WEXITSTATUS(status
);
1183 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1189 * Return status of freeze/thaw
1191 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1193 if (ga_is_frozen(ga_state
)) {
1194 return GUEST_FSFREEZE_STATUS_FROZEN
;
1197 return GUEST_FSFREEZE_STATUS_THAWED
;
1200 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1202 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1206 * Walk list of mounted file systems in the guest, and freeze the ones which
1207 * are real local file systems.
1209 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1210 strList
*mountpoints
,
1216 struct FsMount
*mount
;
1217 Error
*local_err
= NULL
;
1220 slog("guest-fsfreeze called");
1222 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1224 error_propagate(errp
, local_err
);
1228 QTAILQ_INIT(&mounts
);
1229 build_fs_mount_list(&mounts
, &local_err
);
1231 error_propagate(errp
, local_err
);
1235 /* cannot risk guest agent blocking itself on a write in this state */
1236 ga_set_frozen(ga_state
);
1238 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, FsMountList
, next
) {
1239 /* To issue fsfreeze in the reverse order of mounts, check if the
1240 * mount is listed in the list here */
1241 if (has_mountpoints
) {
1242 for (list
= mountpoints
; list
; list
= list
->next
) {
1243 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1252 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1254 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1258 /* we try to cull filesytems we know won't work in advance, but other
1259 * filesytems may not implement fsfreeze for less obvious reasons.
1260 * these will report EOPNOTSUPP. we simply ignore these when tallying
1261 * the number of frozen filesystems.
1263 * any other error means a failure to freeze a filesystem we
1264 * expect to be freezable, so return an error in those cases
1265 * and return system to thawed state.
1267 ret
= ioctl(fd
, FIFREEZE
);
1269 if (errno
!= EOPNOTSUPP
) {
1270 error_setg_errno(errp
, errno
, "failed to freeze %s",
1281 free_fs_mount_list(&mounts
);
1285 free_fs_mount_list(&mounts
);
1286 qmp_guest_fsfreeze_thaw(NULL
);
1291 * Walk list of frozen file systems in the guest, and thaw them.
1293 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1298 int fd
, i
= 0, logged
;
1299 Error
*local_err
= NULL
;
1301 QTAILQ_INIT(&mounts
);
1302 build_fs_mount_list(&mounts
, &local_err
);
1304 error_propagate(errp
, local_err
);
1308 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1310 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1314 /* we have no way of knowing whether a filesystem was actually unfrozen
1315 * as a result of a successful call to FITHAW, only that if an error
1316 * was returned the filesystem was *not* unfrozen by that particular
1319 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1320 * to unfreeze, continuing issuing FITHAW until an error is returned,
1321 * in which case either the filesystem is in an unfreezable state, or,
1322 * more likely, it was thawed previously (and remains so afterward).
1324 * also, since the most recent successful call is the one that did
1325 * the actual unfreeze, we can use this to provide an accurate count
1326 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1327 * may * be useful for determining whether a filesystem was unfrozen
1328 * during the freeze/thaw phase by a process other than qemu-ga.
1331 ret
= ioctl(fd
, FITHAW
);
1332 if (ret
== 0 && !logged
) {
1340 ga_unset_frozen(ga_state
);
1341 free_fs_mount_list(&mounts
);
1343 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1348 static void guest_fsfreeze_cleanup(void)
1352 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1353 qmp_guest_fsfreeze_thaw(&err
);
1355 slog("failed to clean up frozen filesystems: %s",
1356 error_get_pretty(err
));
1361 #endif /* CONFIG_FSFREEZE */
1363 #if defined(CONFIG_FSTRIM)
1365 * Walk list of mounted file systems in the guest, and trim them.
1367 GuestFilesystemTrimResponse
*
1368 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1370 GuestFilesystemTrimResponse
*response
;
1371 GuestFilesystemTrimResultList
*list
;
1372 GuestFilesystemTrimResult
*result
;
1375 struct FsMount
*mount
;
1377 Error
*local_err
= NULL
;
1378 struct fstrim_range r
;
1380 slog("guest-fstrim called");
1382 QTAILQ_INIT(&mounts
);
1383 build_fs_mount_list(&mounts
, &local_err
);
1385 error_propagate(errp
, local_err
);
1389 response
= g_malloc0(sizeof(*response
));
1391 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1392 result
= g_malloc0(sizeof(*result
));
1393 result
->path
= g_strdup(mount
->dirname
);
1395 list
= g_malloc0(sizeof(*list
));
1396 list
->value
= result
;
1397 list
->next
= response
->paths
;
1398 response
->paths
= list
;
1400 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1402 result
->error
= g_strdup_printf("failed to open: %s",
1404 result
->has_error
= true;
1408 /* We try to cull filesytems we know won't work in advance, but other
1409 * filesytems may not implement fstrim for less obvious reasons. These
1410 * will report EOPNOTSUPP; while in some other cases ENOTTY will be
1411 * reported (e.g. CD-ROMs).
1412 * Any other error means an unexpected error.
1416 r
.minlen
= has_minimum
? minimum
: 0;
1417 ret
= ioctl(fd
, FITRIM
, &r
);
1419 result
->has_error
= true;
1420 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1421 result
->error
= g_strdup("trim not supported");
1423 result
->error
= g_strdup_printf("failed to trim: %s",
1430 result
->has_minimum
= true;
1431 result
->minimum
= r
.minlen
;
1432 result
->has_trimmed
= true;
1433 result
->trimmed
= r
.len
;
1437 free_fs_mount_list(&mounts
);
1440 #endif /* CONFIG_FSTRIM */
1443 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1444 #define SUSPEND_SUPPORTED 0
1445 #define SUSPEND_NOT_SUPPORTED 1
1447 static void bios_supports_mode(const char *pmutils_bin
, const char *pmutils_arg
,
1448 const char *sysfile_str
, Error
**errp
)
1450 Error
*local_err
= NULL
;
1455 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1459 char buf
[32]; /* hopefully big enough */
1464 reopen_fd_to_null(0);
1465 reopen_fd_to_null(1);
1466 reopen_fd_to_null(2);
1469 execle(pmutils_path
, pmutils_bin
, pmutils_arg
, NULL
, environ
);
1473 * If we get here either pm-utils is not installed or execle() has
1474 * failed. Let's try the manual method if the caller wants it.
1478 _exit(SUSPEND_NOT_SUPPORTED
);
1481 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1483 _exit(SUSPEND_NOT_SUPPORTED
);
1486 ret
= read(fd
, buf
, sizeof(buf
)-1);
1488 _exit(SUSPEND_NOT_SUPPORTED
);
1492 if (strstr(buf
, sysfile_str
)) {
1493 _exit(SUSPEND_SUPPORTED
);
1496 _exit(SUSPEND_NOT_SUPPORTED
);
1497 } else if (pid
< 0) {
1498 error_setg_errno(errp
, errno
, "failed to create child process");
1502 ga_wait_child(pid
, &status
, &local_err
);
1504 error_propagate(errp
, local_err
);
1508 if (!WIFEXITED(status
)) {
1509 error_setg(errp
, "child process has terminated abnormally");
1513 switch (WEXITSTATUS(status
)) {
1514 case SUSPEND_SUPPORTED
:
1516 case SUSPEND_NOT_SUPPORTED
:
1518 "the requested suspend mode is not supported by the guest");
1522 "the helper program '%s' returned an unexpected exit status"
1523 " code (%d)", pmutils_path
, WEXITSTATUS(status
));
1528 g_free(pmutils_path
);
1531 static void guest_suspend(const char *pmutils_bin
, const char *sysfile_str
,
1534 Error
*local_err
= NULL
;
1539 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1547 reopen_fd_to_null(0);
1548 reopen_fd_to_null(1);
1549 reopen_fd_to_null(2);
1552 execle(pmutils_path
, pmutils_bin
, NULL
, environ
);
1556 * If we get here either pm-utils is not installed or execle() has
1557 * failed. Let's try the manual method if the caller wants it.
1561 _exit(EXIT_FAILURE
);
1564 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1566 _exit(EXIT_FAILURE
);
1569 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1570 _exit(EXIT_FAILURE
);
1573 _exit(EXIT_SUCCESS
);
1574 } else if (pid
< 0) {
1575 error_setg_errno(errp
, errno
, "failed to create child process");
1579 ga_wait_child(pid
, &status
, &local_err
);
1581 error_propagate(errp
, local_err
);
1585 if (!WIFEXITED(status
)) {
1586 error_setg(errp
, "child process has terminated abnormally");
1590 if (WEXITSTATUS(status
)) {
1591 error_setg(errp
, "child process has failed to suspend");
1596 g_free(pmutils_path
);
1599 void qmp_guest_suspend_disk(Error
**errp
)
1601 Error
*local_err
= NULL
;
1603 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err
);
1605 error_propagate(errp
, local_err
);
1609 guest_suspend("pm-hibernate", "disk", errp
);
1612 void qmp_guest_suspend_ram(Error
**errp
)
1614 Error
*local_err
= NULL
;
1616 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err
);
1618 error_propagate(errp
, local_err
);
1622 guest_suspend("pm-suspend", "mem", errp
);
1625 void qmp_guest_suspend_hybrid(Error
**errp
)
1627 Error
*local_err
= NULL
;
1629 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL
,
1632 error_propagate(errp
, local_err
);
1636 guest_suspend("pm-suspend-hybrid", NULL
, errp
);
1639 static GuestNetworkInterfaceList
*
1640 guest_find_interface(GuestNetworkInterfaceList
*head
,
1643 for (; head
; head
= head
->next
) {
1644 if (strcmp(head
->value
->name
, name
) == 0) {
1653 * Build information about guest interfaces
1655 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1657 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1658 struct ifaddrs
*ifap
, *ifa
;
1660 if (getifaddrs(&ifap
) < 0) {
1661 error_setg_errno(errp
, errno
, "getifaddrs failed");
1665 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1666 GuestNetworkInterfaceList
*info
;
1667 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
1668 char addr4
[INET_ADDRSTRLEN
];
1669 char addr6
[INET6_ADDRSTRLEN
];
1672 unsigned char *mac_addr
;
1675 g_debug("Processing %s interface", ifa
->ifa_name
);
1677 info
= guest_find_interface(head
, ifa
->ifa_name
);
1680 info
= g_malloc0(sizeof(*info
));
1681 info
->value
= g_malloc0(sizeof(*info
->value
));
1682 info
->value
->name
= g_strdup(ifa
->ifa_name
);
1685 head
= cur_item
= info
;
1687 cur_item
->next
= info
;
1692 if (!info
->value
->has_hardware_address
&&
1693 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
1694 /* we haven't obtained HW address yet */
1695 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
1697 error_setg_errno(errp
, errno
, "failed to create socket");
1701 memset(&ifr
, 0, sizeof(ifr
));
1702 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
1703 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
1704 error_setg_errno(errp
, errno
,
1705 "failed to get MAC address of %s",
1712 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
1714 info
->value
->hardware_address
=
1715 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1716 (int) mac_addr
[0], (int) mac_addr
[1],
1717 (int) mac_addr
[2], (int) mac_addr
[3],
1718 (int) mac_addr
[4], (int) mac_addr
[5]);
1720 info
->value
->has_hardware_address
= true;
1723 if (ifa
->ifa_addr
&&
1724 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1725 /* interface with IPv4 address */
1726 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1727 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1728 error_setg_errno(errp
, errno
, "inet_ntop failed");
1732 address_item
= g_malloc0(sizeof(*address_item
));
1733 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1734 address_item
->value
->ip_address
= g_strdup(addr4
);
1735 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1737 if (ifa
->ifa_netmask
) {
1738 /* Count the number of set bits in netmask.
1739 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1740 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1741 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1743 } else if (ifa
->ifa_addr
&&
1744 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1745 /* interface with IPv6 address */
1746 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1747 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1748 error_setg_errno(errp
, errno
, "inet_ntop failed");
1752 address_item
= g_malloc0(sizeof(*address_item
));
1753 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1754 address_item
->value
->ip_address
= g_strdup(addr6
);
1755 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1757 if (ifa
->ifa_netmask
) {
1758 /* Count the number of set bits in netmask.
1759 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1760 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1761 address_item
->value
->prefix
=
1762 ctpop32(((uint32_t *) p
)[0]) +
1763 ctpop32(((uint32_t *) p
)[1]) +
1764 ctpop32(((uint32_t *) p
)[2]) +
1765 ctpop32(((uint32_t *) p
)[3]);
1769 if (!address_item
) {
1773 address_list
= &info
->value
->ip_addresses
;
1775 while (*address_list
&& (*address_list
)->next
) {
1776 address_list
= &(*address_list
)->next
;
1779 if (!*address_list
) {
1780 *address_list
= address_item
;
1782 (*address_list
)->next
= address_item
;
1785 info
->value
->has_ip_addresses
= true;
1795 qapi_free_GuestNetworkInterfaceList(head
);
1799 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
1801 static long sysconf_exact(int name
, const char *name_str
, Error
**errp
)
1806 ret
= sysconf(name
);
1809 error_setg(errp
, "sysconf(%s): value indefinite", name_str
);
1811 error_setg_errno(errp
, errno
, "sysconf(%s)", name_str
);
1817 /* Transfer online/offline status between @vcpu and the guest system.
1819 * On input either @errp or *@errp must be NULL.
1821 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1822 * - R: vcpu->logical_id
1824 * - W: vcpu->can_offline
1826 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1827 * - R: vcpu->logical_id
1830 * Written members remain unmodified on error.
1832 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1838 dirpath
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
1840 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
1842 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
1844 static const char fn
[] = "online";
1848 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
1850 if (errno
!= ENOENT
) {
1851 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
1852 } else if (sys2vcpu
) {
1853 vcpu
->online
= true;
1854 vcpu
->can_offline
= false;
1855 } else if (!vcpu
->online
) {
1856 error_setg(errp
, "logical processor #%" PRId64
" can't be "
1857 "offlined", vcpu
->logical_id
);
1858 } /* otherwise pretend successful re-onlining */
1860 unsigned char status
;
1862 res
= pread(fd
, &status
, 1, 0);
1864 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
1865 } else if (res
== 0) {
1866 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
1868 } else if (sys2vcpu
) {
1869 vcpu
->online
= (status
!= '0');
1870 vcpu
->can_offline
= true;
1871 } else if (vcpu
->online
!= (status
!= '0')) {
1872 status
= '0' + vcpu
->online
;
1873 if (pwrite(fd
, &status
, 1, 0) == -1) {
1874 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
1877 } /* otherwise pretend successful re-(on|off)-lining */
1890 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1893 GuestLogicalProcessorList
*head
, **link
;
1895 Error
*local_err
= NULL
;
1900 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
1902 while (local_err
== NULL
&& current
< sc_max
) {
1903 GuestLogicalProcessor
*vcpu
;
1904 GuestLogicalProcessorList
*entry
;
1906 vcpu
= g_malloc0(sizeof *vcpu
);
1907 vcpu
->logical_id
= current
++;
1908 vcpu
->has_can_offline
= true; /* lolspeak ftw */
1909 transfer_vcpu(vcpu
, true, &local_err
);
1911 entry
= g_malloc0(sizeof *entry
);
1912 entry
->value
= vcpu
;
1915 link
= &entry
->next
;
1918 if (local_err
== NULL
) {
1919 /* there's no guest with zero VCPUs */
1920 g_assert(head
!= NULL
);
1924 qapi_free_GuestLogicalProcessorList(head
);
1925 error_propagate(errp
, local_err
);
1929 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1932 Error
*local_err
= NULL
;
1935 while (vcpus
!= NULL
) {
1936 transfer_vcpu(vcpus
->value
, false, &local_err
);
1937 if (local_err
!= NULL
) {
1941 vcpus
= vcpus
->next
;
1944 if (local_err
!= NULL
) {
1945 if (processed
== 0) {
1946 error_propagate(errp
, local_err
);
1948 error_free(local_err
);
1955 void qmp_guest_set_user_password(const char *username
,
1956 const char *password
,
1960 Error
*local_err
= NULL
;
1961 char *passwd_path
= NULL
;
1964 int datafd
[2] = { -1, -1 };
1965 char *rawpasswddata
= NULL
;
1966 size_t rawpasswdlen
;
1967 char *chpasswddata
= NULL
;
1970 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1971 if (!rawpasswddata
) {
1974 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1975 rawpasswddata
[rawpasswdlen
] = '\0';
1977 if (strchr(rawpasswddata
, '\n')) {
1978 error_setg(errp
, "forbidden characters in raw password");
1982 if (strchr(username
, '\n') ||
1983 strchr(username
, ':')) {
1984 error_setg(errp
, "forbidden characters in username");
1988 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
1989 chpasswdlen
= strlen(chpasswddata
);
1991 passwd_path
= g_find_program_in_path("chpasswd");
1994 error_setg(errp
, "cannot find 'passwd' program in PATH");
1998 if (pipe(datafd
) < 0) {
1999 error_setg(errp
, "cannot create pipe FDs");
2009 reopen_fd_to_null(1);
2010 reopen_fd_to_null(2);
2013 execle(passwd_path
, "chpasswd", "-e", NULL
, environ
);
2015 execle(passwd_path
, "chpasswd", NULL
, environ
);
2017 _exit(EXIT_FAILURE
);
2018 } else if (pid
< 0) {
2019 error_setg_errno(errp
, errno
, "failed to create child process");
2025 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2026 error_setg_errno(errp
, errno
, "cannot write new account password");
2032 ga_wait_child(pid
, &status
, &local_err
);
2034 error_propagate(errp
, local_err
);
2038 if (!WIFEXITED(status
)) {
2039 error_setg(errp
, "child process has terminated abnormally");
2043 if (WEXITSTATUS(status
)) {
2044 error_setg(errp
, "child process has failed to set user password");
2049 g_free(chpasswddata
);
2050 g_free(rawpasswddata
);
2051 g_free(passwd_path
);
2052 if (datafd
[0] != -1) {
2055 if (datafd
[1] != -1) {
2060 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2061 int size
, Error
**errp
)
2067 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2069 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2073 res
= pread(fd
, buf
, size
, 0);
2075 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2076 } else if (res
== 0) {
2077 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2082 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2083 const char *buf
, int size
, Error
**errp
)
2088 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2090 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2094 if (pwrite(fd
, buf
, size
, 0) == -1) {
2095 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2101 /* Transfer online/offline status between @mem_blk and the guest system.
2103 * On input either @errp or *@errp must be NULL.
2105 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2106 * - R: mem_blk->phys_index
2107 * - W: mem_blk->online
2108 * - W: mem_blk->can_offline
2110 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2111 * - R: mem_blk->phys_index
2112 * - R: mem_blk->online
2113 *- R: mem_blk->can_offline
2114 * Written members remain unmodified on error.
2116 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2117 GuestMemoryBlockResponse
*result
,
2123 Error
*local_err
= NULL
;
2129 error_setg(errp
, "Internal error, 'result' should not be NULL");
2133 dp
= opendir("/sys/devices/system/memory/");
2134 /* if there is no 'memory' directory in sysfs,
2135 * we think this VM does not support online/offline memory block,
2136 * any other solution?
2138 if (!dp
&& errno
== ENOENT
) {
2140 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2146 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2147 mem_blk
->phys_index
);
2148 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2151 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2153 if (errno
== ENOENT
) {
2154 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2157 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2165 status
= g_malloc0(10);
2166 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2168 /* treat with sysfs file that not exist in old kernel */
2169 if (errno
== ENOENT
) {
2170 error_free(local_err
);
2172 mem_blk
->online
= true;
2173 mem_blk
->can_offline
= false;
2174 } else if (!mem_blk
->online
) {
2176 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2180 error_propagate(errp
, local_err
);
2183 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2190 char removable
= '0';
2192 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2194 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2196 /* if no 'removable' file, it doesn't support offline mem blk */
2197 if (errno
== ENOENT
) {
2198 error_free(local_err
);
2199 mem_blk
->can_offline
= false;
2201 error_propagate(errp
, local_err
);
2204 mem_blk
->can_offline
= (removable
!= '0');
2207 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2208 char *new_state
= mem_blk
->online
? g_strdup("online") :
2209 g_strdup("offline");
2211 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2215 error_free(local_err
);
2217 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2221 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2222 result
->has_error_code
= false;
2223 } /* otherwise pretend successful re-(on|off)-lining */
2234 result
->has_error_code
= true;
2235 result
->error_code
= errno
;
2239 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2241 GuestMemoryBlockList
*head
, **link
;
2242 Error
*local_err
= NULL
;
2249 dp
= opendir("/sys/devices/system/memory/");
2251 /* it's ok if this happens to be a system that doesn't expose
2252 * memory blocks via sysfs, but otherwise we should report
2255 if (errno
!= ENOENT
) {
2256 error_setg_errno(errp
, errno
, "Can't open directory"
2257 "\"/sys/devices/system/memory/\"\n");
2262 /* Note: the phys_index of memory block may be discontinuous,
2263 * this is because a memblk is the unit of the Sparse Memory design, which
2264 * allows discontinuous memory ranges (ex. NUMA), so here we should
2265 * traverse the memory block directory.
2267 while ((de
= readdir(dp
)) != NULL
) {
2268 GuestMemoryBlock
*mem_blk
;
2269 GuestMemoryBlockList
*entry
;
2271 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2272 !(de
->d_type
& DT_DIR
)) {
2276 mem_blk
= g_malloc0(sizeof *mem_blk
);
2277 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2278 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2279 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2280 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2282 entry
= g_malloc0(sizeof *entry
);
2283 entry
->value
= mem_blk
;
2286 link
= &entry
->next
;
2290 if (local_err
== NULL
) {
2291 /* there's no guest with zero memory blocks */
2293 error_setg(errp
, "guest reported zero memory blocks!");
2298 qapi_free_GuestMemoryBlockList(head
);
2299 error_propagate(errp
, local_err
);
2303 GuestMemoryBlockResponseList
*
2304 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2306 GuestMemoryBlockResponseList
*head
, **link
;
2307 Error
*local_err
= NULL
;
2312 while (mem_blks
!= NULL
) {
2313 GuestMemoryBlockResponse
*result
;
2314 GuestMemoryBlockResponseList
*entry
;
2315 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2317 result
= g_malloc0(sizeof(*result
));
2318 result
->phys_index
= current_mem_blk
->phys_index
;
2319 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2320 if (local_err
) { /* should never happen */
2323 entry
= g_malloc0(sizeof *entry
);
2324 entry
->value
= result
;
2327 link
= &entry
->next
;
2328 mem_blks
= mem_blks
->next
;
2333 qapi_free_GuestMemoryBlockResponseList(head
);
2334 error_propagate(errp
, local_err
);
2338 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2340 Error
*local_err
= NULL
;
2344 GuestMemoryBlockInfo
*info
;
2346 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2347 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2349 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2355 buf
= g_malloc0(20);
2356 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2360 error_propagate(errp
, local_err
);
2364 info
= g_new0(GuestMemoryBlockInfo
, 1);
2365 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2372 #else /* defined(__linux__) */
2374 void qmp_guest_suspend_disk(Error
**errp
)
2376 error_setg(errp
, QERR_UNSUPPORTED
);
2379 void qmp_guest_suspend_ram(Error
**errp
)
2381 error_setg(errp
, QERR_UNSUPPORTED
);
2384 void qmp_guest_suspend_hybrid(Error
**errp
)
2386 error_setg(errp
, QERR_UNSUPPORTED
);
2389 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2391 error_setg(errp
, QERR_UNSUPPORTED
);
2395 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2397 error_setg(errp
, QERR_UNSUPPORTED
);
2401 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2403 error_setg(errp
, QERR_UNSUPPORTED
);
2407 void qmp_guest_set_user_password(const char *username
,
2408 const char *password
,
2412 error_setg(errp
, QERR_UNSUPPORTED
);
2415 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2417 error_setg(errp
, QERR_UNSUPPORTED
);
2421 GuestMemoryBlockResponseList
*
2422 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2424 error_setg(errp
, QERR_UNSUPPORTED
);
2428 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2430 error_setg(errp
, QERR_UNSUPPORTED
);
2436 #if !defined(CONFIG_FSFREEZE)
2438 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
2440 error_setg(errp
, QERR_UNSUPPORTED
);
2444 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
2446 error_setg(errp
, QERR_UNSUPPORTED
);
2451 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
2453 error_setg(errp
, QERR_UNSUPPORTED
);
2458 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
2459 strList
*mountpoints
,
2462 error_setg(errp
, QERR_UNSUPPORTED
);
2467 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
2469 error_setg(errp
, QERR_UNSUPPORTED
);
2473 #endif /* CONFIG_FSFREEZE */
2475 #if !defined(CONFIG_FSTRIM)
2476 GuestFilesystemTrimResponse
*
2477 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
2479 error_setg(errp
, QERR_UNSUPPORTED
);
2484 /* add unsupported commands to the blacklist */
2485 GList
*ga_command_blacklist_init(GList
*blacklist
)
2487 #if !defined(__linux__)
2489 const char *list
[] = {
2490 "guest-suspend-disk", "guest-suspend-ram",
2491 "guest-suspend-hybrid", "guest-network-get-interfaces",
2492 "guest-get-vcpus", "guest-set-vcpus",
2493 "guest-get-memory-blocks", "guest-set-memory-blocks",
2494 "guest-get-memory-block-size", NULL
};
2495 char **p
= (char **)list
;
2498 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2503 #if !defined(CONFIG_FSFREEZE)
2505 const char *list
[] = {
2506 "guest-get-fsinfo", "guest-fsfreeze-status",
2507 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2508 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL
};
2509 char **p
= (char **)list
;
2512 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2517 #if !defined(CONFIG_FSTRIM)
2518 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
2524 /* register init/cleanup routines for stateful command groups */
2525 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2527 #if defined(CONFIG_FSFREEZE)
2528 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);