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"
15 #include <sys/ioctl.h>
16 #include <sys/utsname.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"
32 #ifndef CONFIG_HAS_ENVIRON
34 #include <crt_externs.h>
35 #define environ (*_NSGetEnviron())
37 extern char **environ
;
41 #if defined(__linux__)
45 #include <arpa/inet.h>
46 #include <sys/socket.h>
50 #define CONFIG_FSFREEZE
57 static void ga_wait_child(pid_t pid
, int *status
, Error
**errp
)
64 rpid
= waitpid(pid
, status
, 0);
65 } while (rpid
== -1 && errno
== EINTR
);
68 error_setg_errno(errp
, errno
, "failed to wait for child (pid: %d)",
73 g_assert(rpid
== pid
);
76 void qmp_guest_shutdown(bool has_mode
, const char *mode
, Error
**errp
)
78 const char *shutdown_flag
;
79 Error
*local_err
= NULL
;
83 slog("guest-shutdown called, mode: %s", mode
);
84 if (!has_mode
|| strcmp(mode
, "powerdown") == 0) {
86 } else if (strcmp(mode
, "halt") == 0) {
88 } else if (strcmp(mode
, "reboot") == 0) {
92 "mode is invalid (valid values are: halt|powerdown|reboot");
98 /* child, start the shutdown */
100 reopen_fd_to_null(0);
101 reopen_fd_to_null(1);
102 reopen_fd_to_null(2);
104 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag
, "+0",
105 "hypervisor initiated shutdown", (char*)NULL
, environ
);
107 } else if (pid
< 0) {
108 error_setg_errno(errp
, errno
, "failed to create child process");
112 ga_wait_child(pid
, &status
, &local_err
);
114 error_propagate(errp
, local_err
);
118 if (!WIFEXITED(status
)) {
119 error_setg(errp
, "child process has terminated abnormally");
123 if (WEXITSTATUS(status
)) {
124 error_setg(errp
, "child process has failed to shutdown");
131 int64_t qmp_guest_get_time(Error
**errp
)
136 ret
= qemu_gettimeofday(&tq
);
138 error_setg_errno(errp
, errno
, "Failed to get time");
142 return tq
.tv_sec
* 1000000000LL + tq
.tv_usec
* 1000;
145 void qmp_guest_set_time(bool has_time
, int64_t time_ns
, Error
**errp
)
150 Error
*local_err
= NULL
;
153 /* If user has passed a time, validate and set it. */
157 /* year-2038 will overflow in case time_t is 32bit */
158 if (time_ns
/ 1000000000 != (time_t)(time_ns
/ 1000000000)) {
159 error_setg(errp
, "Time %" PRId64
" is too large", time_ns
);
163 tv
.tv_sec
= time_ns
/ 1000000000;
164 tv
.tv_usec
= (time_ns
% 1000000000) / 1000;
165 g_date_set_time_t(&date
, tv
.tv_sec
);
166 if (date
.year
< 1970 || date
.year
>= 2070) {
167 error_setg_errno(errp
, errno
, "Invalid time");
171 ret
= settimeofday(&tv
, NULL
);
173 error_setg_errno(errp
, errno
, "Failed to set time to guest");
178 /* Now, if user has passed a time to set and the system time is set, we
179 * just need to synchronize the hardware clock. However, if no time was
180 * passed, user is requesting the opposite: set the system time from the
181 * hardware clock (RTC). */
185 reopen_fd_to_null(0);
186 reopen_fd_to_null(1);
187 reopen_fd_to_null(2);
189 /* Use '/sbin/hwclock -w' to set RTC from the system time,
190 * or '/sbin/hwclock -s' to set the system time from RTC. */
191 execle("/sbin/hwclock", "hwclock", has_time
? "-w" : "-s",
194 } else if (pid
< 0) {
195 error_setg_errno(errp
, errno
, "failed to create child process");
199 ga_wait_child(pid
, &status
, &local_err
);
201 error_propagate(errp
, local_err
);
205 if (!WIFEXITED(status
)) {
206 error_setg(errp
, "child process has terminated abnormally");
210 if (WEXITSTATUS(status
)) {
211 error_setg(errp
, "hwclock failed to set hardware clock to system time");
222 typedef struct GuestFileHandle
{
226 QTAILQ_ENTRY(GuestFileHandle
) next
;
230 QTAILQ_HEAD(, GuestFileHandle
) filehandles
;
231 } guest_file_state
= {
232 .filehandles
= QTAILQ_HEAD_INITIALIZER(guest_file_state
.filehandles
),
235 static int64_t guest_file_handle_add(FILE *fh
, Error
**errp
)
237 GuestFileHandle
*gfh
;
240 handle
= ga_get_fd_handle(ga_state
, errp
);
245 gfh
= g_new0(GuestFileHandle
, 1);
248 QTAILQ_INSERT_TAIL(&guest_file_state
.filehandles
, gfh
, next
);
253 static GuestFileHandle
*guest_file_handle_find(int64_t id
, Error
**errp
)
255 GuestFileHandle
*gfh
;
257 QTAILQ_FOREACH(gfh
, &guest_file_state
.filehandles
, next
)
264 error_setg(errp
, "handle '%" PRId64
"' has not been found", id
);
268 typedef const char * const ccpc
;
274 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
275 static const struct {
278 } guest_file_open_modes
[] = {
279 { (ccpc
[]){ "r", NULL
}, O_RDONLY
},
280 { (ccpc
[]){ "rb", NULL
}, O_RDONLY
| O_BINARY
},
281 { (ccpc
[]){ "w", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
},
282 { (ccpc
[]){ "wb", NULL
}, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
},
283 { (ccpc
[]){ "a", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
},
284 { (ccpc
[]){ "ab", NULL
}, O_WRONLY
| O_CREAT
| O_APPEND
| O_BINARY
},
285 { (ccpc
[]){ "r+", NULL
}, O_RDWR
},
286 { (ccpc
[]){ "rb+", "r+b", NULL
}, O_RDWR
| O_BINARY
},
287 { (ccpc
[]){ "w+", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
},
288 { (ccpc
[]){ "wb+", "w+b", NULL
}, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
},
289 { (ccpc
[]){ "a+", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
},
290 { (ccpc
[]){ "ab+", "a+b", NULL
}, O_RDWR
| O_CREAT
| O_APPEND
| O_BINARY
}
294 find_open_flag(const char *mode_str
, Error
**errp
)
298 for (mode
= 0; mode
< ARRAY_SIZE(guest_file_open_modes
); ++mode
) {
301 form
= guest_file_open_modes
[mode
].forms
;
302 while (*form
!= NULL
&& strcmp(*form
, mode_str
) != 0) {
310 if (mode
== ARRAY_SIZE(guest_file_open_modes
)) {
311 error_setg(errp
, "invalid file open mode '%s'", mode_str
);
314 return guest_file_open_modes
[mode
].oflag_base
| O_NOCTTY
| O_NONBLOCK
;
317 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
318 S_IRGRP | S_IWGRP | \
322 safe_open_or_create(const char *path
, const char *mode
, Error
**errp
)
324 Error
*local_err
= NULL
;
327 oflag
= find_open_flag(mode
, &local_err
);
328 if (local_err
== NULL
) {
331 /* If the caller wants / allows creation of a new file, we implement it
332 * with a two step process: open() + (open() / fchmod()).
334 * First we insist on creating the file exclusively as a new file. If
335 * that succeeds, we're free to set any file-mode bits on it. (The
336 * motivation is that we want to set those file-mode bits independently
337 * of the current umask.)
339 * If the exclusive creation fails because the file already exists
340 * (EEXIST is not possible for any other reason), we just attempt to
341 * open the file, but in this case we won't be allowed to change the
342 * file-mode bits on the preexistent file.
344 * The pathname should never disappear between the two open()s in
345 * practice. If it happens, then someone very likely tried to race us.
346 * In this case just go ahead and report the ENOENT from the second
347 * open() to the caller.
349 * If the caller wants to open a preexistent file, then the first
350 * open() is decisive and its third argument is ignored, and the second
351 * open() and the fchmod() are never called.
353 fd
= open(path
, oflag
| ((oflag
& O_CREAT
) ? O_EXCL
: 0), 0);
354 if (fd
== -1 && errno
== EEXIST
) {
355 oflag
&= ~(unsigned)O_CREAT
;
356 fd
= open(path
, oflag
);
360 error_setg_errno(&local_err
, errno
, "failed to open file '%s' "
361 "(mode: '%s')", path
, mode
);
363 qemu_set_cloexec(fd
);
365 if ((oflag
& O_CREAT
) && fchmod(fd
, DEFAULT_NEW_FILE_MODE
) == -1) {
366 error_setg_errno(&local_err
, errno
, "failed to set permission "
367 "0%03o on new file '%s' (mode: '%s')",
368 (unsigned)DEFAULT_NEW_FILE_MODE
, path
, mode
);
372 f
= fdopen(fd
, mode
);
374 error_setg_errno(&local_err
, errno
, "failed to associate "
375 "stdio stream with file descriptor %d, "
376 "file '%s' (mode: '%s')", fd
, path
, mode
);
383 if (oflag
& O_CREAT
) {
389 error_propagate(errp
, local_err
);
393 int64_t qmp_guest_file_open(const char *path
, bool has_mode
, const char *mode
,
397 Error
*local_err
= NULL
;
403 slog("guest-file-open called, filepath: %s, mode: %s", path
, mode
);
404 fh
= safe_open_or_create(path
, mode
, &local_err
);
405 if (local_err
!= NULL
) {
406 error_propagate(errp
, local_err
);
410 /* set fd non-blocking to avoid common use cases (like reading from a
411 * named pipe) from hanging the agent
413 qemu_set_nonblock(fileno(fh
));
415 handle
= guest_file_handle_add(fh
, errp
);
421 slog("guest-file-open, handle: %" PRId64
, handle
);
425 void qmp_guest_file_close(int64_t handle
, Error
**errp
)
427 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
430 slog("guest-file-close called, handle: %" PRId64
, handle
);
435 ret
= fclose(gfh
->fh
);
437 error_setg_errno(errp
, errno
, "failed to close handle");
441 QTAILQ_REMOVE(&guest_file_state
.filehandles
, gfh
, next
);
445 struct GuestFileRead
*qmp_guest_file_read(int64_t handle
, bool has_count
,
446 int64_t count
, Error
**errp
)
448 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
449 GuestFileRead
*read_data
= NULL
;
459 count
= QGA_READ_COUNT_DEFAULT
;
460 } else if (count
< 0) {
461 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
468 /* explicitly flush when switching from writing to reading */
469 if (gfh
->state
== RW_STATE_WRITING
) {
470 int ret
= fflush(fh
);
472 error_setg_errno(errp
, errno
, "failed to flush file");
475 gfh
->state
= RW_STATE_NEW
;
478 buf
= g_malloc0(count
+1);
479 read_count
= fread(buf
, 1, count
, fh
);
481 error_setg_errno(errp
, errno
, "failed to read file");
482 slog("guest-file-read failed, handle: %" PRId64
, handle
);
485 read_data
= g_new0(GuestFileRead
, 1);
486 read_data
->count
= read_count
;
487 read_data
->eof
= feof(fh
);
489 read_data
->buf_b64
= g_base64_encode(buf
, read_count
);
491 gfh
->state
= RW_STATE_READING
;
499 GuestFileWrite
*qmp_guest_file_write(int64_t handle
, const char *buf_b64
,
500 bool has_count
, int64_t count
,
503 GuestFileWrite
*write_data
= NULL
;
507 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
516 if (gfh
->state
== RW_STATE_READING
) {
517 int ret
= fseek(fh
, 0, SEEK_CUR
);
519 error_setg_errno(errp
, errno
, "failed to seek file");
522 gfh
->state
= RW_STATE_NEW
;
525 buf
= qbase64_decode(buf_b64
, -1, &buf_len
, errp
);
532 } else if (count
< 0 || count
> buf_len
) {
533 error_setg(errp
, "value '%" PRId64
"' is invalid for argument count",
539 write_count
= fwrite(buf
, 1, count
, fh
);
541 error_setg_errno(errp
, errno
, "failed to write to file");
542 slog("guest-file-write failed, handle: %" PRId64
, handle
);
544 write_data
= g_new0(GuestFileWrite
, 1);
545 write_data
->count
= write_count
;
546 write_data
->eof
= feof(fh
);
547 gfh
->state
= RW_STATE_WRITING
;
555 struct GuestFileSeek
*qmp_guest_file_seek(int64_t handle
, int64_t offset
,
556 GuestFileWhence
*whence_code
,
559 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
560 GuestFileSeek
*seek_data
= NULL
;
570 /* We stupidly exposed 'whence':'int' in our qapi */
571 whence
= ga_parse_whence(whence_code
, &err
);
573 error_propagate(errp
, err
);
578 ret
= fseek(fh
, offset
, whence
);
580 error_setg_errno(errp
, errno
, "failed to seek file");
581 if (errno
== ESPIPE
) {
582 /* file is non-seekable, stdio shouldn't be buffering anyways */
583 gfh
->state
= RW_STATE_NEW
;
586 seek_data
= g_new0(GuestFileSeek
, 1);
587 seek_data
->position
= ftell(fh
);
588 seek_data
->eof
= feof(fh
);
589 gfh
->state
= RW_STATE_NEW
;
596 void qmp_guest_file_flush(int64_t handle
, Error
**errp
)
598 GuestFileHandle
*gfh
= guest_file_handle_find(handle
, errp
);
609 error_setg_errno(errp
, errno
, "failed to flush file");
611 gfh
->state
= RW_STATE_NEW
;
615 /* linux-specific implementations. avoid this if at all possible. */
616 #if defined(__linux__)
618 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
619 typedef struct FsMount
{
622 unsigned int devmajor
, devminor
;
623 QTAILQ_ENTRY(FsMount
) next
;
626 typedef QTAILQ_HEAD(FsMountList
, FsMount
) FsMountList
;
628 static void free_fs_mount_list(FsMountList
*mounts
)
630 FsMount
*mount
, *temp
;
636 QTAILQ_FOREACH_SAFE(mount
, mounts
, next
, temp
) {
637 QTAILQ_REMOVE(mounts
, mount
, next
);
638 g_free(mount
->dirname
);
639 g_free(mount
->devtype
);
644 static int dev_major_minor(const char *devpath
,
645 unsigned int *devmajor
, unsigned int *devminor
)
652 if (stat(devpath
, &st
) < 0) {
653 slog("failed to stat device file '%s': %s", devpath
, strerror(errno
));
656 if (S_ISDIR(st
.st_mode
)) {
657 /* It is bind mount */
660 if (S_ISBLK(st
.st_mode
)) {
661 *devmajor
= major(st
.st_rdev
);
662 *devminor
= minor(st
.st_rdev
);
669 * Walk the mount table and build a list of local file systems
671 static void build_fs_mount_list_from_mtab(FsMountList
*mounts
, Error
**errp
)
675 char const *mtab
= "/proc/self/mounts";
677 unsigned int devmajor
, devminor
;
679 fp
= setmntent(mtab
, "r");
681 error_setg(errp
, "failed to open mtab file: '%s'", mtab
);
685 while ((ment
= getmntent(fp
))) {
687 * An entry which device name doesn't start with a '/' is
688 * either a dummy file system or a network file system.
689 * Add special handling for smbfs and cifs as is done by
692 if ((ment
->mnt_fsname
[0] != '/') ||
693 (strcmp(ment
->mnt_type
, "smbfs") == 0) ||
694 (strcmp(ment
->mnt_type
, "cifs") == 0)) {
697 if (dev_major_minor(ment
->mnt_fsname
, &devmajor
, &devminor
) == -2) {
698 /* Skip bind mounts */
702 mount
= g_new0(FsMount
, 1);
703 mount
->dirname
= g_strdup(ment
->mnt_dir
);
704 mount
->devtype
= g_strdup(ment
->mnt_type
);
705 mount
->devmajor
= devmajor
;
706 mount
->devminor
= devminor
;
708 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
714 static void decode_mntname(char *name
, int len
)
717 for (i
= 0; i
<= len
; i
++) {
718 if (name
[i
] != '\\') {
720 } else if (name
[i
+ 1] == '\\') {
723 } else if (name
[i
+ 1] >= '0' && name
[i
+ 1] <= '3' &&
724 name
[i
+ 2] >= '0' && name
[i
+ 2] <= '7' &&
725 name
[i
+ 3] >= '0' && name
[i
+ 3] <= '7') {
726 name
[j
++] = (name
[i
+ 1] - '0') * 64 +
727 (name
[i
+ 2] - '0') * 8 +
736 static void build_fs_mount_list(FsMountList
*mounts
, Error
**errp
)
739 char const *mountinfo
= "/proc/self/mountinfo";
741 char *line
= NULL
, *dash
;
744 unsigned int devmajor
, devminor
;
745 int ret
, dir_s
, dir_e
, type_s
, type_e
, dev_s
, dev_e
;
747 fp
= fopen(mountinfo
, "r");
749 build_fs_mount_list_from_mtab(mounts
, errp
);
753 while (getline(&line
, &n
, fp
) != -1) {
754 ret
= sscanf(line
, "%*u %*u %u:%u %*s %n%*s%n%c",
755 &devmajor
, &devminor
, &dir_s
, &dir_e
, &check
);
759 dash
= strstr(line
+ dir_e
, " - ");
763 ret
= sscanf(dash
, " - %n%*s%n %n%*s%n%c",
764 &type_s
, &type_e
, &dev_s
, &dev_e
, &check
);
771 decode_mntname(line
+ dir_s
, dir_e
- dir_s
);
772 decode_mntname(dash
+ dev_s
, dev_e
- dev_s
);
774 /* btrfs reports major number = 0 */
775 if (strcmp("btrfs", dash
+ type_s
) != 0 ||
776 dev_major_minor(dash
+ dev_s
, &devmajor
, &devminor
) < 0) {
781 mount
= g_new0(FsMount
, 1);
782 mount
->dirname
= g_strdup(line
+ dir_s
);
783 mount
->devtype
= g_strdup(dash
+ type_s
);
784 mount
->devmajor
= devmajor
;
785 mount
->devminor
= devminor
;
787 QTAILQ_INSERT_TAIL(mounts
, mount
, next
);
795 #if defined(CONFIG_FSFREEZE)
797 static char *get_pci_driver(char const *syspath
, int pathlen
, Error
**errp
)
805 path
= g_strndup(syspath
, pathlen
);
806 dpath
= g_strdup_printf("%s/driver", path
);
807 len
= readlink(dpath
, buf
, sizeof(buf
) - 1);
810 driver
= g_strdup(basename(buf
));
817 static int compare_uint(const void *_a
, const void *_b
)
819 unsigned int a
= *(unsigned int *)_a
;
820 unsigned int b
= *(unsigned int *)_b
;
822 return a
< b
? -1 : a
> b
? 1 : 0;
825 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
826 static int build_hosts(char const *syspath
, char const *host
, bool ata
,
827 unsigned int *hosts
, int hosts_max
, Error
**errp
)
831 struct dirent
*entry
;
834 path
= g_strndup(syspath
, host
- syspath
);
837 error_setg_errno(errp
, errno
, "opendir(\"%s\")", path
);
842 while (i
< hosts_max
) {
843 entry
= readdir(dir
);
847 if (ata
&& sscanf(entry
->d_name
, "ata%d", hosts
+ i
) == 1) {
849 } else if (!ata
&& sscanf(entry
->d_name
, "host%d", hosts
+ i
) == 1) {
854 qsort(hosts
, i
, sizeof(hosts
[0]), compare_uint
);
861 /* Store disk device info specified by @sysfs into @fs */
862 static void build_guest_fsinfo_for_real_device(char const *syspath
,
863 GuestFilesystemInfo
*fs
,
866 unsigned int pci
[4], host
, hosts
[8], tgt
[3];
867 int i
, nhosts
= 0, pcilen
;
868 GuestDiskAddress
*disk
;
869 GuestPCIAddress
*pciaddr
;
870 GuestDiskAddressList
*list
= NULL
;
871 bool has_ata
= false, has_host
= false, has_tgt
= false;
872 char *p
, *q
, *driver
= NULL
;
874 p
= strstr(syspath
, "/devices/pci");
875 if (!p
|| sscanf(p
+ 12, "%*x:%*x/%x:%x:%x.%x%n",
876 pci
, pci
+ 1, pci
+ 2, pci
+ 3, &pcilen
) < 4) {
877 g_debug("only pci device is supported: sysfs path \"%s\"", syspath
);
881 driver
= get_pci_driver(syspath
, (p
+ 12 + pcilen
) - syspath
, errp
);
886 p
= strstr(syspath
, "/target");
887 if (p
&& sscanf(p
+ 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
888 tgt
, tgt
+ 1, tgt
+ 2) == 3) {
892 p
= strstr(syspath
, "/ata");
897 p
= strstr(syspath
, "/host");
900 if (p
&& sscanf(q
, "%u", &host
) == 1) {
902 nhosts
= build_hosts(syspath
, p
, has_ata
, hosts
,
903 sizeof(hosts
) / sizeof(hosts
[0]), errp
);
909 pciaddr
= g_malloc0(sizeof(*pciaddr
));
910 pciaddr
->domain
= pci
[0];
911 pciaddr
->bus
= pci
[1];
912 pciaddr
->slot
= pci
[2];
913 pciaddr
->function
= pci
[3];
915 disk
= g_malloc0(sizeof(*disk
));
916 disk
->pci_controller
= pciaddr
;
918 list
= g_malloc0(sizeof(*list
));
921 if (strcmp(driver
, "ata_piix") == 0) {
922 /* a host per ide bus, target*:0:<unit>:0 */
923 if (!has_host
|| !has_tgt
) {
924 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
927 for (i
= 0; i
< nhosts
; i
++) {
928 if (host
== hosts
[i
]) {
929 disk
->bus_type
= GUEST_DISK_BUS_TYPE_IDE
;
936 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
939 } else if (strcmp(driver
, "sym53c8xx") == 0) {
940 /* scsi(LSI Logic): target*:0:<unit>:0 */
942 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
945 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
947 } else if (strcmp(driver
, "virtio-pci") == 0) {
949 /* virtio-scsi: target*:0:0:<unit> */
950 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SCSI
;
953 /* virtio-blk: 1 disk per 1 device */
954 disk
->bus_type
= GUEST_DISK_BUS_TYPE_VIRTIO
;
956 } else if (strcmp(driver
, "ahci") == 0) {
957 /* ahci: 1 host per 1 unit */
958 if (!has_host
|| !has_tgt
) {
959 g_debug("invalid sysfs path '%s' (driver '%s')", syspath
, driver
);
962 for (i
= 0; i
< nhosts
; i
++) {
963 if (host
== hosts
[i
]) {
965 disk
->bus_type
= GUEST_DISK_BUS_TYPE_SATA
;
970 g_debug("no host for '%s' (driver '%s')", syspath
, driver
);
974 g_debug("unknown driver '%s' (sysfs path '%s')", driver
, syspath
);
978 list
->next
= fs
->disk
;
985 qapi_free_GuestDiskAddressList(list
);
990 static void build_guest_fsinfo_for_device(char const *devpath
,
991 GuestFilesystemInfo
*fs
,
994 /* Store a list of slave devices of virtual volume specified by @syspath into
996 static void build_guest_fsinfo_for_virtual_device(char const *syspath
,
997 GuestFilesystemInfo
*fs
,
1002 struct dirent
*entry
;
1004 dirpath
= g_strdup_printf("%s/slaves", syspath
);
1005 dir
= opendir(dirpath
);
1007 if (errno
!= ENOENT
) {
1008 error_setg_errno(errp
, errno
, "opendir(\"%s\")", dirpath
);
1016 entry
= readdir(dir
);
1017 if (entry
== NULL
) {
1019 error_setg_errno(errp
, errno
, "readdir(\"%s\")", dirpath
);
1024 if (entry
->d_type
== DT_LNK
) {
1027 g_debug(" slave device '%s'", entry
->d_name
);
1028 path
= g_strdup_printf("%s/slaves/%s", syspath
, entry
->d_name
);
1029 build_guest_fsinfo_for_device(path
, fs
, errp
);
1042 /* Dispatch to functions for virtual/real device */
1043 static void build_guest_fsinfo_for_device(char const *devpath
,
1044 GuestFilesystemInfo
*fs
,
1047 char *syspath
= realpath(devpath
, NULL
);
1050 error_setg_errno(errp
, errno
, "realpath(\"%s\")", devpath
);
1055 fs
->name
= g_strdup(basename(syspath
));
1058 g_debug(" parse sysfs path '%s'", syspath
);
1060 if (strstr(syspath
, "/devices/virtual/block/")) {
1061 build_guest_fsinfo_for_virtual_device(syspath
, fs
, errp
);
1063 build_guest_fsinfo_for_real_device(syspath
, fs
, errp
);
1069 /* Return a list of the disk device(s)' info which @mount lies on */
1070 static GuestFilesystemInfo
*build_guest_fsinfo(struct FsMount
*mount
,
1073 GuestFilesystemInfo
*fs
= g_malloc0(sizeof(*fs
));
1074 char *devpath
= g_strdup_printf("/sys/dev/block/%u:%u",
1075 mount
->devmajor
, mount
->devminor
);
1077 fs
->mountpoint
= g_strdup(mount
->dirname
);
1078 fs
->type
= g_strdup(mount
->devtype
);
1079 build_guest_fsinfo_for_device(devpath
, fs
, errp
);
1085 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
1088 struct FsMount
*mount
;
1089 GuestFilesystemInfoList
*new, *ret
= NULL
;
1090 Error
*local_err
= NULL
;
1092 QTAILQ_INIT(&mounts
);
1093 build_fs_mount_list(&mounts
, &local_err
);
1095 error_propagate(errp
, local_err
);
1099 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1100 g_debug("Building guest fsinfo for '%s'", mount
->dirname
);
1102 new = g_malloc0(sizeof(*ret
));
1103 new->value
= build_guest_fsinfo(mount
, &local_err
);
1107 error_propagate(errp
, local_err
);
1108 qapi_free_GuestFilesystemInfoList(ret
);
1114 free_fs_mount_list(&mounts
);
1120 FSFREEZE_HOOK_THAW
= 0,
1121 FSFREEZE_HOOK_FREEZE
,
1124 static const char *fsfreeze_hook_arg_string
[] = {
1129 static void execute_fsfreeze_hook(FsfreezeHookArg arg
, Error
**errp
)
1134 const char *arg_str
= fsfreeze_hook_arg_string
[arg
];
1135 Error
*local_err
= NULL
;
1137 hook
= ga_fsfreeze_hook(ga_state
);
1141 if (access(hook
, X_OK
) != 0) {
1142 error_setg_errno(errp
, errno
, "can't access fsfreeze hook '%s'", hook
);
1146 slog("executing fsfreeze hook with arg '%s'", arg_str
);
1150 reopen_fd_to_null(0);
1151 reopen_fd_to_null(1);
1152 reopen_fd_to_null(2);
1154 execle(hook
, hook
, arg_str
, NULL
, environ
);
1155 _exit(EXIT_FAILURE
);
1156 } else if (pid
< 0) {
1157 error_setg_errno(errp
, errno
, "failed to create child process");
1161 ga_wait_child(pid
, &status
, &local_err
);
1163 error_propagate(errp
, local_err
);
1167 if (!WIFEXITED(status
)) {
1168 error_setg(errp
, "fsfreeze hook has terminated abnormally");
1172 status
= WEXITSTATUS(status
);
1174 error_setg(errp
, "fsfreeze hook has failed with status %d", status
);
1180 * Return status of freeze/thaw
1182 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
1184 if (ga_is_frozen(ga_state
)) {
1185 return GUEST_FSFREEZE_STATUS_FROZEN
;
1188 return GUEST_FSFREEZE_STATUS_THAWED
;
1191 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
1193 return qmp_guest_fsfreeze_freeze_list(false, NULL
, errp
);
1197 * Walk list of mounted file systems in the guest, and freeze the ones which
1198 * are real local file systems.
1200 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
1201 strList
*mountpoints
,
1207 struct FsMount
*mount
;
1208 Error
*local_err
= NULL
;
1211 slog("guest-fsfreeze called");
1213 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE
, &local_err
);
1215 error_propagate(errp
, local_err
);
1219 QTAILQ_INIT(&mounts
);
1220 build_fs_mount_list(&mounts
, &local_err
);
1222 error_propagate(errp
, local_err
);
1226 /* cannot risk guest agent blocking itself on a write in this state */
1227 ga_set_frozen(ga_state
);
1229 QTAILQ_FOREACH_REVERSE(mount
, &mounts
, FsMountList
, next
) {
1230 /* To issue fsfreeze in the reverse order of mounts, check if the
1231 * mount is listed in the list here */
1232 if (has_mountpoints
) {
1233 for (list
= mountpoints
; list
; list
= list
->next
) {
1234 if (strcmp(list
->value
, mount
->dirname
) == 0) {
1243 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1245 error_setg_errno(errp
, errno
, "failed to open %s", mount
->dirname
);
1249 /* we try to cull filesystems we know won't work in advance, but other
1250 * filesystems may not implement fsfreeze for less obvious reasons.
1251 * these will report EOPNOTSUPP. we simply ignore these when tallying
1252 * the number of frozen filesystems.
1253 * if a filesystem is mounted more than once (aka bind mount) a
1254 * consecutive attempt to freeze an already frozen filesystem will
1257 * any other error means a failure to freeze a filesystem we
1258 * expect to be freezable, so return an error in those cases
1259 * and return system to thawed state.
1261 ret
= ioctl(fd
, FIFREEZE
);
1263 if (errno
!= EOPNOTSUPP
&& errno
!= EBUSY
) {
1264 error_setg_errno(errp
, errno
, "failed to freeze %s",
1275 free_fs_mount_list(&mounts
);
1279 free_fs_mount_list(&mounts
);
1280 qmp_guest_fsfreeze_thaw(NULL
);
1285 * Walk list of frozen file systems in the guest, and thaw them.
1287 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
1292 int fd
, i
= 0, logged
;
1293 Error
*local_err
= NULL
;
1295 QTAILQ_INIT(&mounts
);
1296 build_fs_mount_list(&mounts
, &local_err
);
1298 error_propagate(errp
, local_err
);
1302 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1304 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1308 /* we have no way of knowing whether a filesystem was actually unfrozen
1309 * as a result of a successful call to FITHAW, only that if an error
1310 * was returned the filesystem was *not* unfrozen by that particular
1313 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1314 * to unfreeze, continuing issuing FITHAW until an error is returned,
1315 * in which case either the filesystem is in an unfreezable state, or,
1316 * more likely, it was thawed previously (and remains so afterward).
1318 * also, since the most recent successful call is the one that did
1319 * the actual unfreeze, we can use this to provide an accurate count
1320 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1321 * may * be useful for determining whether a filesystem was unfrozen
1322 * during the freeze/thaw phase by a process other than qemu-ga.
1325 ret
= ioctl(fd
, FITHAW
);
1326 if (ret
== 0 && !logged
) {
1334 ga_unset_frozen(ga_state
);
1335 free_fs_mount_list(&mounts
);
1337 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW
, errp
);
1342 static void guest_fsfreeze_cleanup(void)
1346 if (ga_is_frozen(ga_state
) == GUEST_FSFREEZE_STATUS_FROZEN
) {
1347 qmp_guest_fsfreeze_thaw(&err
);
1349 slog("failed to clean up frozen filesystems: %s",
1350 error_get_pretty(err
));
1355 #endif /* CONFIG_FSFREEZE */
1357 #if defined(CONFIG_FSTRIM)
1359 * Walk list of mounted file systems in the guest, and trim them.
1361 GuestFilesystemTrimResponse
*
1362 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
1364 GuestFilesystemTrimResponse
*response
;
1365 GuestFilesystemTrimResultList
*list
;
1366 GuestFilesystemTrimResult
*result
;
1369 struct FsMount
*mount
;
1371 Error
*local_err
= NULL
;
1372 struct fstrim_range r
;
1374 slog("guest-fstrim called");
1376 QTAILQ_INIT(&mounts
);
1377 build_fs_mount_list(&mounts
, &local_err
);
1379 error_propagate(errp
, local_err
);
1383 response
= g_malloc0(sizeof(*response
));
1385 QTAILQ_FOREACH(mount
, &mounts
, next
) {
1386 result
= g_malloc0(sizeof(*result
));
1387 result
->path
= g_strdup(mount
->dirname
);
1389 list
= g_malloc0(sizeof(*list
));
1390 list
->value
= result
;
1391 list
->next
= response
->paths
;
1392 response
->paths
= list
;
1394 fd
= qemu_open(mount
->dirname
, O_RDONLY
);
1396 result
->error
= g_strdup_printf("failed to open: %s",
1398 result
->has_error
= true;
1402 /* We try to cull filesystems we know won't work in advance, but other
1403 * filesystems may not implement fstrim for less obvious reasons.
1404 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1405 * will be reported (e.g. CD-ROMs).
1406 * Any other error means an unexpected error.
1410 r
.minlen
= has_minimum
? minimum
: 0;
1411 ret
= ioctl(fd
, FITRIM
, &r
);
1413 result
->has_error
= true;
1414 if (errno
== ENOTTY
|| errno
== EOPNOTSUPP
) {
1415 result
->error
= g_strdup("trim not supported");
1417 result
->error
= g_strdup_printf("failed to trim: %s",
1424 result
->has_minimum
= true;
1425 result
->minimum
= r
.minlen
;
1426 result
->has_trimmed
= true;
1427 result
->trimmed
= r
.len
;
1431 free_fs_mount_list(&mounts
);
1434 #endif /* CONFIG_FSTRIM */
1437 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1438 #define SUSPEND_SUPPORTED 0
1439 #define SUSPEND_NOT_SUPPORTED 1
1441 static void bios_supports_mode(const char *pmutils_bin
, const char *pmutils_arg
,
1442 const char *sysfile_str
, Error
**errp
)
1444 Error
*local_err
= NULL
;
1449 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1453 char buf
[32]; /* hopefully big enough */
1458 reopen_fd_to_null(0);
1459 reopen_fd_to_null(1);
1460 reopen_fd_to_null(2);
1463 execle(pmutils_path
, pmutils_bin
, pmutils_arg
, NULL
, environ
);
1467 * If we get here either pm-utils is not installed or execle() has
1468 * failed. Let's try the manual method if the caller wants it.
1472 _exit(SUSPEND_NOT_SUPPORTED
);
1475 fd
= open(LINUX_SYS_STATE_FILE
, O_RDONLY
);
1477 _exit(SUSPEND_NOT_SUPPORTED
);
1480 ret
= read(fd
, buf
, sizeof(buf
)-1);
1482 _exit(SUSPEND_NOT_SUPPORTED
);
1486 if (strstr(buf
, sysfile_str
)) {
1487 _exit(SUSPEND_SUPPORTED
);
1490 _exit(SUSPEND_NOT_SUPPORTED
);
1491 } else if (pid
< 0) {
1492 error_setg_errno(errp
, errno
, "failed to create child process");
1496 ga_wait_child(pid
, &status
, &local_err
);
1498 error_propagate(errp
, local_err
);
1502 if (!WIFEXITED(status
)) {
1503 error_setg(errp
, "child process has terminated abnormally");
1507 switch (WEXITSTATUS(status
)) {
1508 case SUSPEND_SUPPORTED
:
1510 case SUSPEND_NOT_SUPPORTED
:
1512 "the requested suspend mode is not supported by the guest");
1516 "the helper program '%s' returned an unexpected exit status"
1517 " code (%d)", pmutils_path
, WEXITSTATUS(status
));
1522 g_free(pmutils_path
);
1525 static void guest_suspend(const char *pmutils_bin
, const char *sysfile_str
,
1528 Error
*local_err
= NULL
;
1533 pmutils_path
= g_find_program_in_path(pmutils_bin
);
1541 reopen_fd_to_null(0);
1542 reopen_fd_to_null(1);
1543 reopen_fd_to_null(2);
1546 execle(pmutils_path
, pmutils_bin
, NULL
, environ
);
1550 * If we get here either pm-utils is not installed or execle() has
1551 * failed. Let's try the manual method if the caller wants it.
1555 _exit(EXIT_FAILURE
);
1558 fd
= open(LINUX_SYS_STATE_FILE
, O_WRONLY
);
1560 _exit(EXIT_FAILURE
);
1563 if (write(fd
, sysfile_str
, strlen(sysfile_str
)) < 0) {
1564 _exit(EXIT_FAILURE
);
1567 _exit(EXIT_SUCCESS
);
1568 } else if (pid
< 0) {
1569 error_setg_errno(errp
, errno
, "failed to create child process");
1573 ga_wait_child(pid
, &status
, &local_err
);
1575 error_propagate(errp
, local_err
);
1579 if (!WIFEXITED(status
)) {
1580 error_setg(errp
, "child process has terminated abnormally");
1584 if (WEXITSTATUS(status
)) {
1585 error_setg(errp
, "child process has failed to suspend");
1590 g_free(pmutils_path
);
1593 void qmp_guest_suspend_disk(Error
**errp
)
1595 Error
*local_err
= NULL
;
1597 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err
);
1599 error_propagate(errp
, local_err
);
1603 guest_suspend("pm-hibernate", "disk", errp
);
1606 void qmp_guest_suspend_ram(Error
**errp
)
1608 Error
*local_err
= NULL
;
1610 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err
);
1612 error_propagate(errp
, local_err
);
1616 guest_suspend("pm-suspend", "mem", errp
);
1619 void qmp_guest_suspend_hybrid(Error
**errp
)
1621 Error
*local_err
= NULL
;
1623 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL
,
1626 error_propagate(errp
, local_err
);
1630 guest_suspend("pm-suspend-hybrid", NULL
, errp
);
1633 static GuestNetworkInterfaceList
*
1634 guest_find_interface(GuestNetworkInterfaceList
*head
,
1637 for (; head
; head
= head
->next
) {
1638 if (strcmp(head
->value
->name
, name
) == 0) {
1647 * Build information about guest interfaces
1649 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
1651 GuestNetworkInterfaceList
*head
= NULL
, *cur_item
= NULL
;
1652 struct ifaddrs
*ifap
, *ifa
;
1654 if (getifaddrs(&ifap
) < 0) {
1655 error_setg_errno(errp
, errno
, "getifaddrs failed");
1659 for (ifa
= ifap
; ifa
; ifa
= ifa
->ifa_next
) {
1660 GuestNetworkInterfaceList
*info
;
1661 GuestIpAddressList
**address_list
= NULL
, *address_item
= NULL
;
1662 char addr4
[INET_ADDRSTRLEN
];
1663 char addr6
[INET6_ADDRSTRLEN
];
1666 unsigned char *mac_addr
;
1669 g_debug("Processing %s interface", ifa
->ifa_name
);
1671 info
= guest_find_interface(head
, ifa
->ifa_name
);
1674 info
= g_malloc0(sizeof(*info
));
1675 info
->value
= g_malloc0(sizeof(*info
->value
));
1676 info
->value
->name
= g_strdup(ifa
->ifa_name
);
1679 head
= cur_item
= info
;
1681 cur_item
->next
= info
;
1686 if (!info
->value
->has_hardware_address
&&
1687 ifa
->ifa_flags
& SIOCGIFHWADDR
) {
1688 /* we haven't obtained HW address yet */
1689 sock
= socket(PF_INET
, SOCK_STREAM
, 0);
1691 error_setg_errno(errp
, errno
, "failed to create socket");
1695 memset(&ifr
, 0, sizeof(ifr
));
1696 pstrcpy(ifr
.ifr_name
, IF_NAMESIZE
, info
->value
->name
);
1697 if (ioctl(sock
, SIOCGIFHWADDR
, &ifr
) == -1) {
1698 error_setg_errno(errp
, errno
,
1699 "failed to get MAC address of %s",
1706 mac_addr
= (unsigned char *) &ifr
.ifr_hwaddr
.sa_data
;
1708 info
->value
->hardware_address
=
1709 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1710 (int) mac_addr
[0], (int) mac_addr
[1],
1711 (int) mac_addr
[2], (int) mac_addr
[3],
1712 (int) mac_addr
[4], (int) mac_addr
[5]);
1714 info
->value
->has_hardware_address
= true;
1717 if (ifa
->ifa_addr
&&
1718 ifa
->ifa_addr
->sa_family
== AF_INET
) {
1719 /* interface with IPv4 address */
1720 p
= &((struct sockaddr_in
*)ifa
->ifa_addr
)->sin_addr
;
1721 if (!inet_ntop(AF_INET
, p
, addr4
, sizeof(addr4
))) {
1722 error_setg_errno(errp
, errno
, "inet_ntop failed");
1726 address_item
= g_malloc0(sizeof(*address_item
));
1727 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1728 address_item
->value
->ip_address
= g_strdup(addr4
);
1729 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV4
;
1731 if (ifa
->ifa_netmask
) {
1732 /* Count the number of set bits in netmask.
1733 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1734 p
= &((struct sockaddr_in
*)ifa
->ifa_netmask
)->sin_addr
;
1735 address_item
->value
->prefix
= ctpop32(((uint32_t *) p
)[0]);
1737 } else if (ifa
->ifa_addr
&&
1738 ifa
->ifa_addr
->sa_family
== AF_INET6
) {
1739 /* interface with IPv6 address */
1740 p
= &((struct sockaddr_in6
*)ifa
->ifa_addr
)->sin6_addr
;
1741 if (!inet_ntop(AF_INET6
, p
, addr6
, sizeof(addr6
))) {
1742 error_setg_errno(errp
, errno
, "inet_ntop failed");
1746 address_item
= g_malloc0(sizeof(*address_item
));
1747 address_item
->value
= g_malloc0(sizeof(*address_item
->value
));
1748 address_item
->value
->ip_address
= g_strdup(addr6
);
1749 address_item
->value
->ip_address_type
= GUEST_IP_ADDRESS_TYPE_IPV6
;
1751 if (ifa
->ifa_netmask
) {
1752 /* Count the number of set bits in netmask.
1753 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1754 p
= &((struct sockaddr_in6
*)ifa
->ifa_netmask
)->sin6_addr
;
1755 address_item
->value
->prefix
=
1756 ctpop32(((uint32_t *) p
)[0]) +
1757 ctpop32(((uint32_t *) p
)[1]) +
1758 ctpop32(((uint32_t *) p
)[2]) +
1759 ctpop32(((uint32_t *) p
)[3]);
1763 if (!address_item
) {
1767 address_list
= &info
->value
->ip_addresses
;
1769 while (*address_list
&& (*address_list
)->next
) {
1770 address_list
= &(*address_list
)->next
;
1773 if (!*address_list
) {
1774 *address_list
= address_item
;
1776 (*address_list
)->next
= address_item
;
1779 info
->value
->has_ip_addresses
= true;
1789 qapi_free_GuestNetworkInterfaceList(head
);
1793 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
1795 static long sysconf_exact(int name
, const char *name_str
, Error
**errp
)
1800 ret
= sysconf(name
);
1803 error_setg(errp
, "sysconf(%s): value indefinite", name_str
);
1805 error_setg_errno(errp
, errno
, "sysconf(%s)", name_str
);
1811 /* Transfer online/offline status between @vcpu and the guest system.
1813 * On input either @errp or *@errp must be NULL.
1815 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1816 * - R: vcpu->logical_id
1818 * - W: vcpu->can_offline
1820 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1821 * - R: vcpu->logical_id
1824 * Written members remain unmodified on error.
1826 static void transfer_vcpu(GuestLogicalProcessor
*vcpu
, bool sys2vcpu
,
1832 dirpath
= g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64
"/",
1834 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
1836 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
1838 static const char fn
[] = "online";
1842 fd
= openat(dirfd
, fn
, sys2vcpu
? O_RDONLY
: O_RDWR
);
1844 if (errno
!= ENOENT
) {
1845 error_setg_errno(errp
, errno
, "open(\"%s/%s\")", dirpath
, fn
);
1846 } else if (sys2vcpu
) {
1847 vcpu
->online
= true;
1848 vcpu
->can_offline
= false;
1849 } else if (!vcpu
->online
) {
1850 error_setg(errp
, "logical processor #%" PRId64
" can't be "
1851 "offlined", vcpu
->logical_id
);
1852 } /* otherwise pretend successful re-onlining */
1854 unsigned char status
;
1856 res
= pread(fd
, &status
, 1, 0);
1858 error_setg_errno(errp
, errno
, "pread(\"%s/%s\")", dirpath
, fn
);
1859 } else if (res
== 0) {
1860 error_setg(errp
, "pread(\"%s/%s\"): unexpected EOF", dirpath
,
1862 } else if (sys2vcpu
) {
1863 vcpu
->online
= (status
!= '0');
1864 vcpu
->can_offline
= true;
1865 } else if (vcpu
->online
!= (status
!= '0')) {
1866 status
= '0' + vcpu
->online
;
1867 if (pwrite(fd
, &status
, 1, 0) == -1) {
1868 error_setg_errno(errp
, errno
, "pwrite(\"%s/%s\")", dirpath
,
1871 } /* otherwise pretend successful re-(on|off)-lining */
1884 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
1887 GuestLogicalProcessorList
*head
, **link
;
1889 Error
*local_err
= NULL
;
1894 sc_max
= SYSCONF_EXACT(_SC_NPROCESSORS_CONF
, &local_err
);
1896 while (local_err
== NULL
&& current
< sc_max
) {
1897 GuestLogicalProcessor
*vcpu
;
1898 GuestLogicalProcessorList
*entry
;
1900 vcpu
= g_malloc0(sizeof *vcpu
);
1901 vcpu
->logical_id
= current
++;
1902 vcpu
->has_can_offline
= true; /* lolspeak ftw */
1903 transfer_vcpu(vcpu
, true, &local_err
);
1905 entry
= g_malloc0(sizeof *entry
);
1906 entry
->value
= vcpu
;
1909 link
= &entry
->next
;
1912 if (local_err
== NULL
) {
1913 /* there's no guest with zero VCPUs */
1914 g_assert(head
!= NULL
);
1918 qapi_free_GuestLogicalProcessorList(head
);
1919 error_propagate(errp
, local_err
);
1923 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
1926 Error
*local_err
= NULL
;
1929 while (vcpus
!= NULL
) {
1930 transfer_vcpu(vcpus
->value
, false, &local_err
);
1931 if (local_err
!= NULL
) {
1935 vcpus
= vcpus
->next
;
1938 if (local_err
!= NULL
) {
1939 if (processed
== 0) {
1940 error_propagate(errp
, local_err
);
1942 error_free(local_err
);
1949 void qmp_guest_set_user_password(const char *username
,
1950 const char *password
,
1954 Error
*local_err
= NULL
;
1955 char *passwd_path
= NULL
;
1958 int datafd
[2] = { -1, -1 };
1959 char *rawpasswddata
= NULL
;
1960 size_t rawpasswdlen
;
1961 char *chpasswddata
= NULL
;
1964 rawpasswddata
= (char *)qbase64_decode(password
, -1, &rawpasswdlen
, errp
);
1965 if (!rawpasswddata
) {
1968 rawpasswddata
= g_renew(char, rawpasswddata
, rawpasswdlen
+ 1);
1969 rawpasswddata
[rawpasswdlen
] = '\0';
1971 if (strchr(rawpasswddata
, '\n')) {
1972 error_setg(errp
, "forbidden characters in raw password");
1976 if (strchr(username
, '\n') ||
1977 strchr(username
, ':')) {
1978 error_setg(errp
, "forbidden characters in username");
1982 chpasswddata
= g_strdup_printf("%s:%s\n", username
, rawpasswddata
);
1983 chpasswdlen
= strlen(chpasswddata
);
1985 passwd_path
= g_find_program_in_path("chpasswd");
1988 error_setg(errp
, "cannot find 'passwd' program in PATH");
1992 if (pipe(datafd
) < 0) {
1993 error_setg(errp
, "cannot create pipe FDs");
2003 reopen_fd_to_null(1);
2004 reopen_fd_to_null(2);
2007 execle(passwd_path
, "chpasswd", "-e", NULL
, environ
);
2009 execle(passwd_path
, "chpasswd", NULL
, environ
);
2011 _exit(EXIT_FAILURE
);
2012 } else if (pid
< 0) {
2013 error_setg_errno(errp
, errno
, "failed to create child process");
2019 if (qemu_write_full(datafd
[1], chpasswddata
, chpasswdlen
) != chpasswdlen
) {
2020 error_setg_errno(errp
, errno
, "cannot write new account password");
2026 ga_wait_child(pid
, &status
, &local_err
);
2028 error_propagate(errp
, local_err
);
2032 if (!WIFEXITED(status
)) {
2033 error_setg(errp
, "child process has terminated abnormally");
2037 if (WEXITSTATUS(status
)) {
2038 error_setg(errp
, "child process has failed to set user password");
2043 g_free(chpasswddata
);
2044 g_free(rawpasswddata
);
2045 g_free(passwd_path
);
2046 if (datafd
[0] != -1) {
2049 if (datafd
[1] != -1) {
2054 static void ga_read_sysfs_file(int dirfd
, const char *pathname
, char *buf
,
2055 int size
, Error
**errp
)
2061 fd
= openat(dirfd
, pathname
, O_RDONLY
);
2063 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2067 res
= pread(fd
, buf
, size
, 0);
2069 error_setg_errno(errp
, errno
, "pread sysfs file \"%s\"", pathname
);
2070 } else if (res
== 0) {
2071 error_setg(errp
, "pread sysfs file \"%s\": unexpected EOF", pathname
);
2076 static void ga_write_sysfs_file(int dirfd
, const char *pathname
,
2077 const char *buf
, int size
, Error
**errp
)
2082 fd
= openat(dirfd
, pathname
, O_WRONLY
);
2084 error_setg_errno(errp
, errno
, "open sysfs file \"%s\"", pathname
);
2088 if (pwrite(fd
, buf
, size
, 0) == -1) {
2089 error_setg_errno(errp
, errno
, "pwrite sysfs file \"%s\"", pathname
);
2095 /* Transfer online/offline status between @mem_blk and the guest system.
2097 * On input either @errp or *@errp must be NULL.
2099 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2100 * - R: mem_blk->phys_index
2101 * - W: mem_blk->online
2102 * - W: mem_blk->can_offline
2104 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2105 * - R: mem_blk->phys_index
2106 * - R: mem_blk->online
2107 *- R: mem_blk->can_offline
2108 * Written members remain unmodified on error.
2110 static void transfer_memory_block(GuestMemoryBlock
*mem_blk
, bool sys2memblk
,
2111 GuestMemoryBlockResponse
*result
,
2117 Error
*local_err
= NULL
;
2123 error_setg(errp
, "Internal error, 'result' should not be NULL");
2127 dp
= opendir("/sys/devices/system/memory/");
2128 /* if there is no 'memory' directory in sysfs,
2129 * we think this VM does not support online/offline memory block,
2130 * any other solution?
2133 if (errno
== ENOENT
) {
2135 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2142 dirpath
= g_strdup_printf("/sys/devices/system/memory/memory%" PRId64
"/",
2143 mem_blk
->phys_index
);
2144 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2147 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2149 if (errno
== ENOENT
) {
2150 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND
;
2153 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2161 status
= g_malloc0(10);
2162 ga_read_sysfs_file(dirfd
, "state", status
, 10, &local_err
);
2164 /* treat with sysfs file that not exist in old kernel */
2165 if (errno
== ENOENT
) {
2166 error_free(local_err
);
2168 mem_blk
->online
= true;
2169 mem_blk
->can_offline
= false;
2170 } else if (!mem_blk
->online
) {
2172 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED
;
2176 error_propagate(errp
, local_err
);
2179 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2186 char removable
= '0';
2188 mem_blk
->online
= (strncmp(status
, "online", 6) == 0);
2190 ga_read_sysfs_file(dirfd
, "removable", &removable
, 1, &local_err
);
2192 /* if no 'removable' file, it doesn't support offline mem blk */
2193 if (errno
== ENOENT
) {
2194 error_free(local_err
);
2195 mem_blk
->can_offline
= false;
2197 error_propagate(errp
, local_err
);
2200 mem_blk
->can_offline
= (removable
!= '0');
2203 if (mem_blk
->online
!= (strncmp(status
, "online", 6) == 0)) {
2204 const char *new_state
= mem_blk
->online
? "online" : "offline";
2206 ga_write_sysfs_file(dirfd
, "state", new_state
, strlen(new_state
),
2209 error_free(local_err
);
2211 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED
;
2215 result
->response
= GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS
;
2216 result
->has_error_code
= false;
2217 } /* otherwise pretend successful re-(on|off)-lining */
2228 result
->has_error_code
= true;
2229 result
->error_code
= errno
;
2233 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2235 GuestMemoryBlockList
*head
, **link
;
2236 Error
*local_err
= NULL
;
2243 dp
= opendir("/sys/devices/system/memory/");
2245 /* it's ok if this happens to be a system that doesn't expose
2246 * memory blocks via sysfs, but otherwise we should report
2249 if (errno
!= ENOENT
) {
2250 error_setg_errno(errp
, errno
, "Can't open directory"
2251 "\"/sys/devices/system/memory/\"");
2256 /* Note: the phys_index of memory block may be discontinuous,
2257 * this is because a memblk is the unit of the Sparse Memory design, which
2258 * allows discontinuous memory ranges (ex. NUMA), so here we should
2259 * traverse the memory block directory.
2261 while ((de
= readdir(dp
)) != NULL
) {
2262 GuestMemoryBlock
*mem_blk
;
2263 GuestMemoryBlockList
*entry
;
2265 if ((strncmp(de
->d_name
, "memory", 6) != 0) ||
2266 !(de
->d_type
& DT_DIR
)) {
2270 mem_blk
= g_malloc0(sizeof *mem_blk
);
2271 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2272 mem_blk
->phys_index
= strtoul(&de
->d_name
[6], NULL
, 10);
2273 mem_blk
->has_can_offline
= true; /* lolspeak ftw */
2274 transfer_memory_block(mem_blk
, true, NULL
, &local_err
);
2276 entry
= g_malloc0(sizeof *entry
);
2277 entry
->value
= mem_blk
;
2280 link
= &entry
->next
;
2284 if (local_err
== NULL
) {
2285 /* there's no guest with zero memory blocks */
2287 error_setg(errp
, "guest reported zero memory blocks!");
2292 qapi_free_GuestMemoryBlockList(head
);
2293 error_propagate(errp
, local_err
);
2297 GuestMemoryBlockResponseList
*
2298 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2300 GuestMemoryBlockResponseList
*head
, **link
;
2301 Error
*local_err
= NULL
;
2306 while (mem_blks
!= NULL
) {
2307 GuestMemoryBlockResponse
*result
;
2308 GuestMemoryBlockResponseList
*entry
;
2309 GuestMemoryBlock
*current_mem_blk
= mem_blks
->value
;
2311 result
= g_malloc0(sizeof(*result
));
2312 result
->phys_index
= current_mem_blk
->phys_index
;
2313 transfer_memory_block(current_mem_blk
, false, result
, &local_err
);
2314 if (local_err
) { /* should never happen */
2317 entry
= g_malloc0(sizeof *entry
);
2318 entry
->value
= result
;
2321 link
= &entry
->next
;
2322 mem_blks
= mem_blks
->next
;
2327 qapi_free_GuestMemoryBlockResponseList(head
);
2328 error_propagate(errp
, local_err
);
2332 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2334 Error
*local_err
= NULL
;
2338 GuestMemoryBlockInfo
*info
;
2340 dirpath
= g_strdup_printf("/sys/devices/system/memory/");
2341 dirfd
= open(dirpath
, O_RDONLY
| O_DIRECTORY
);
2343 error_setg_errno(errp
, errno
, "open(\"%s\")", dirpath
);
2349 buf
= g_malloc0(20);
2350 ga_read_sysfs_file(dirfd
, "block_size_bytes", buf
, 20, &local_err
);
2354 error_propagate(errp
, local_err
);
2358 info
= g_new0(GuestMemoryBlockInfo
, 1);
2359 info
->size
= strtol(buf
, NULL
, 16); /* the unit is bytes */
2366 #else /* defined(__linux__) */
2368 void qmp_guest_suspend_disk(Error
**errp
)
2370 error_setg(errp
, QERR_UNSUPPORTED
);
2373 void qmp_guest_suspend_ram(Error
**errp
)
2375 error_setg(errp
, QERR_UNSUPPORTED
);
2378 void qmp_guest_suspend_hybrid(Error
**errp
)
2380 error_setg(errp
, QERR_UNSUPPORTED
);
2383 GuestNetworkInterfaceList
*qmp_guest_network_get_interfaces(Error
**errp
)
2385 error_setg(errp
, QERR_UNSUPPORTED
);
2389 GuestLogicalProcessorList
*qmp_guest_get_vcpus(Error
**errp
)
2391 error_setg(errp
, QERR_UNSUPPORTED
);
2395 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList
*vcpus
, Error
**errp
)
2397 error_setg(errp
, QERR_UNSUPPORTED
);
2401 void qmp_guest_set_user_password(const char *username
,
2402 const char *password
,
2406 error_setg(errp
, QERR_UNSUPPORTED
);
2409 GuestMemoryBlockList
*qmp_guest_get_memory_blocks(Error
**errp
)
2411 error_setg(errp
, QERR_UNSUPPORTED
);
2415 GuestMemoryBlockResponseList
*
2416 qmp_guest_set_memory_blocks(GuestMemoryBlockList
*mem_blks
, Error
**errp
)
2418 error_setg(errp
, QERR_UNSUPPORTED
);
2422 GuestMemoryBlockInfo
*qmp_guest_get_memory_block_info(Error
**errp
)
2424 error_setg(errp
, QERR_UNSUPPORTED
);
2430 #if !defined(CONFIG_FSFREEZE)
2432 GuestFilesystemInfoList
*qmp_guest_get_fsinfo(Error
**errp
)
2434 error_setg(errp
, QERR_UNSUPPORTED
);
2438 GuestFsfreezeStatus
qmp_guest_fsfreeze_status(Error
**errp
)
2440 error_setg(errp
, QERR_UNSUPPORTED
);
2445 int64_t qmp_guest_fsfreeze_freeze(Error
**errp
)
2447 error_setg(errp
, QERR_UNSUPPORTED
);
2452 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints
,
2453 strList
*mountpoints
,
2456 error_setg(errp
, QERR_UNSUPPORTED
);
2461 int64_t qmp_guest_fsfreeze_thaw(Error
**errp
)
2463 error_setg(errp
, QERR_UNSUPPORTED
);
2467 #endif /* CONFIG_FSFREEZE */
2469 #if !defined(CONFIG_FSTRIM)
2470 GuestFilesystemTrimResponse
*
2471 qmp_guest_fstrim(bool has_minimum
, int64_t minimum
, Error
**errp
)
2473 error_setg(errp
, QERR_UNSUPPORTED
);
2478 /* add unsupported commands to the blacklist */
2479 GList
*ga_command_blacklist_init(GList
*blacklist
)
2481 #if !defined(__linux__)
2483 const char *list
[] = {
2484 "guest-suspend-disk", "guest-suspend-ram",
2485 "guest-suspend-hybrid", "guest-network-get-interfaces",
2486 "guest-get-vcpus", "guest-set-vcpus",
2487 "guest-get-memory-blocks", "guest-set-memory-blocks",
2488 "guest-get-memory-block-size", NULL
};
2489 char **p
= (char **)list
;
2492 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2497 #if !defined(CONFIG_FSFREEZE)
2499 const char *list
[] = {
2500 "guest-get-fsinfo", "guest-fsfreeze-status",
2501 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2502 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL
};
2503 char **p
= (char **)list
;
2506 blacklist
= g_list_append(blacklist
, g_strdup(*p
++));
2511 #if !defined(CONFIG_FSTRIM)
2512 blacklist
= g_list_append(blacklist
, g_strdup("guest-fstrim"));
2518 /* register init/cleanup routines for stateful command groups */
2519 void ga_command_state_init(GAState
*s
, GACommandState
*cs
)
2521 #if defined(CONFIG_FSFREEZE)
2522 ga_command_state_add(cs
, NULL
, guest_fsfreeze_cleanup
);
2528 #define QGA_MICRO_SECOND_TO_SECOND 1000000
2530 static double ga_get_login_time(struct utmpx
*user_info
)
2532 double seconds
= (double)user_info
->ut_tv
.tv_sec
;
2533 double useconds
= (double)user_info
->ut_tv
.tv_usec
;
2534 useconds
/= QGA_MICRO_SECOND_TO_SECOND
;
2535 return seconds
+ useconds
;
2538 GuestUserList
*qmp_guest_get_users(Error
**err
)
2540 GHashTable
*cache
= NULL
;
2541 GuestUserList
*head
= NULL
, *cur_item
= NULL
;
2542 struct utmpx
*user_info
= NULL
;
2543 gpointer value
= NULL
;
2544 GuestUser
*user
= NULL
;
2545 GuestUserList
*item
= NULL
;
2546 double login_time
= 0;
2548 cache
= g_hash_table_new(g_str_hash
, g_str_equal
);
2552 user_info
= getutxent();
2553 if (user_info
== NULL
) {
2555 } else if (user_info
->ut_type
!= USER_PROCESS
) {
2557 } else if (g_hash_table_contains(cache
, user_info
->ut_user
)) {
2558 value
= g_hash_table_lookup(cache
, user_info
->ut_user
);
2559 user
= (GuestUser
*)value
;
2560 login_time
= ga_get_login_time(user_info
);
2561 /* We're ensuring the earliest login time to be sent */
2562 if (login_time
< user
->login_time
) {
2563 user
->login_time
= login_time
;
2568 item
= g_new0(GuestUserList
, 1);
2569 item
->value
= g_new0(GuestUser
, 1);
2570 item
->value
->user
= g_strdup(user_info
->ut_user
);
2571 item
->value
->login_time
= ga_get_login_time(user_info
);
2573 g_hash_table_insert(cache
, item
->value
->user
, item
->value
);
2576 head
= cur_item
= item
;
2578 cur_item
->next
= item
;
2583 g_hash_table_destroy(cache
);
2589 GuestUserList
*qmp_guest_get_users(Error
**errp
)
2591 error_setg(errp
, QERR_UNSUPPORTED
);
2597 /* Replace escaped special characters with theire real values. The replacement
2598 * is done in place -- returned value is in the original string.
2600 static void ga_osrelease_replace_special(gchar
*value
)
2602 gchar
*p
, *p2
, quote
;
2604 /* Trim the string at first space or semicolon if it is not enclosed in
2605 * single or double quotes. */
2606 if ((value
[0] != '"') || (value
[0] == '\'')) {
2607 p
= strchr(value
, ' ');
2611 p
= strchr(value
, ';');
2632 /* Keep literal backslash followed by whatever is there */
2636 } else if (*p
== quote
) {
2644 static GKeyFile
*ga_parse_osrelease(const char *fname
)
2646 gchar
*content
= NULL
;
2647 gchar
*content2
= NULL
;
2649 GKeyFile
*keys
= g_key_file_new();
2650 const char *group
= "[os-release]\n";
2652 if (!g_file_get_contents(fname
, &content
, NULL
, &err
)) {
2653 slog("failed to read '%s', error: %s", fname
, err
->message
);
2657 if (!g_utf8_validate(content
, -1, NULL
)) {
2658 slog("file is not utf-8 encoded: %s", fname
);
2661 content2
= g_strdup_printf("%s%s", group
, content
);
2663 if (!g_key_file_load_from_data(keys
, content2
, -1, G_KEY_FILE_NONE
,
2665 slog("failed to parse file '%s', error: %s", fname
, err
->message
);
2677 g_key_file_free(keys
);
2681 GuestOSInfo
*qmp_guest_get_osinfo(Error
**errp
)
2683 GuestOSInfo
*info
= NULL
;
2684 struct utsname kinfo
;
2685 GKeyFile
*osrelease
= NULL
;
2686 const char *qga_os_release
= g_getenv("QGA_OS_RELEASE");
2688 info
= g_new0(GuestOSInfo
, 1);
2690 if (uname(&kinfo
) != 0) {
2691 error_setg_errno(errp
, errno
, "uname failed");
2693 info
->has_kernel_version
= true;
2694 info
->kernel_version
= g_strdup(kinfo
.version
);
2695 info
->has_kernel_release
= true;
2696 info
->kernel_release
= g_strdup(kinfo
.release
);
2697 info
->has_machine
= true;
2698 info
->machine
= g_strdup(kinfo
.machine
);
2701 if (qga_os_release
!= NULL
) {
2702 osrelease
= ga_parse_osrelease(qga_os_release
);
2704 osrelease
= ga_parse_osrelease("/etc/os-release");
2705 if (osrelease
== NULL
) {
2706 osrelease
= ga_parse_osrelease("/usr/lib/os-release");
2710 if (osrelease
!= NULL
) {
2713 #define GET_FIELD(field, osfield) do { \
2714 value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
2715 if (value != NULL) { \
2716 ga_osrelease_replace_special(value); \
2717 info->has_ ## field = true; \
2718 info->field = value; \
2721 GET_FIELD(id
, "ID");
2722 GET_FIELD(name
, "NAME");
2723 GET_FIELD(pretty_name
, "PRETTY_NAME");
2724 GET_FIELD(version
, "VERSION");
2725 GET_FIELD(version_id
, "VERSION_ID");
2726 GET_FIELD(variant
, "VARIANT");
2727 GET_FIELD(variant_id
, "VARIANT_ID");
2730 g_key_file_free(osrelease
);