qga: flush explicitly when needed
[qemu/ar7.git] / qga / commands-posix.c
blobcf1d7ec8c0c2c5890b478c359254bfe3bd72ba6c
1 /*
2 * QEMU Guest Agent POSIX-specific command implementations
4 * Copyright IBM Corp. 2011
6 * Authors:
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 <glib.h>
15 #include <sys/types.h>
16 #include <sys/ioctl.h>
17 #include <sys/wait.h>
18 #include <unistd.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <dirent.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <inttypes.h>
26 #include "qga/guest-agent-core.h"
27 #include "qga-qmp-commands.h"
28 #include "qapi/qmp/qerror.h"
29 #include "qemu/queue.h"
30 #include "qemu/host-utils.h"
31 #include "qemu/sockets.h"
33 #ifndef CONFIG_HAS_ENVIRON
34 #ifdef __APPLE__
35 #include <crt_externs.h>
36 #define environ (*_NSGetEnviron())
37 #else
38 extern char **environ;
39 #endif
40 #endif
42 #if defined(__linux__)
43 #include <mntent.h>
44 #include <linux/fs.h>
45 #include <ifaddrs.h>
46 #include <arpa/inet.h>
47 #include <sys/socket.h>
48 #include <net/if.h>
50 #ifdef FIFREEZE
51 #define CONFIG_FSFREEZE
52 #endif
53 #ifdef FITRIM
54 #define CONFIG_FSTRIM
55 #endif
56 #endif
58 static void ga_wait_child(pid_t pid, int *status, Error **errp)
60 pid_t rpid;
62 *status = 0;
64 do {
65 rpid = waitpid(pid, status, 0);
66 } while (rpid == -1 && errno == EINTR);
68 if (rpid == -1) {
69 error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
70 pid);
71 return;
74 g_assert(rpid == pid);
77 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
79 const char *shutdown_flag;
80 Error *local_err = NULL;
81 pid_t pid;
82 int status;
84 slog("guest-shutdown called, mode: %s", mode);
85 if (!has_mode || strcmp(mode, "powerdown") == 0) {
86 shutdown_flag = "-P";
87 } else if (strcmp(mode, "halt") == 0) {
88 shutdown_flag = "-H";
89 } else if (strcmp(mode, "reboot") == 0) {
90 shutdown_flag = "-r";
91 } else {
92 error_setg(errp,
93 "mode is invalid (valid values are: halt|powerdown|reboot");
94 return;
97 pid = fork();
98 if (pid == 0) {
99 /* child, start the shutdown */
100 setsid();
101 reopen_fd_to_null(0);
102 reopen_fd_to_null(1);
103 reopen_fd_to_null(2);
105 execle("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
106 "hypervisor initiated shutdown", (char*)NULL, environ);
107 _exit(EXIT_FAILURE);
108 } else if (pid < 0) {
109 error_setg_errno(errp, errno, "failed to create child process");
110 return;
113 ga_wait_child(pid, &status, &local_err);
114 if (local_err) {
115 error_propagate(errp, local_err);
116 return;
119 if (!WIFEXITED(status)) {
120 error_setg(errp, "child process has terminated abnormally");
121 return;
124 if (WEXITSTATUS(status)) {
125 error_setg(errp, "child process has failed to shutdown");
126 return;
129 /* succeeded */
132 int64_t qmp_guest_get_time(Error **errp)
134 int ret;
135 qemu_timeval tq;
136 int64_t time_ns;
138 ret = qemu_gettimeofday(&tq);
139 if (ret < 0) {
140 error_setg_errno(errp, errno, "Failed to get time");
141 return -1;
144 time_ns = tq.tv_sec * 1000000000LL + tq.tv_usec * 1000;
145 return time_ns;
148 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
150 int ret;
151 int status;
152 pid_t pid;
153 Error *local_err = NULL;
154 struct timeval tv;
156 /* If user has passed a time, validate and set it. */
157 if (has_time) {
158 GDate date = { 0, };
160 /* year-2038 will overflow in case time_t is 32bit */
161 if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
162 error_setg(errp, "Time %" PRId64 " is too large", time_ns);
163 return;
166 tv.tv_sec = time_ns / 1000000000;
167 tv.tv_usec = (time_ns % 1000000000) / 1000;
168 g_date_set_time_t(&date, tv.tv_sec);
169 if (date.year < 1970 || date.year >= 2070) {
170 error_setg_errno(errp, errno, "Invalid time");
171 return;
174 ret = settimeofday(&tv, NULL);
175 if (ret < 0) {
176 error_setg_errno(errp, errno, "Failed to set time to guest");
177 return;
181 /* Now, if user has passed a time to set and the system time is set, we
182 * just need to synchronize the hardware clock. However, if no time was
183 * passed, user is requesting the opposite: set the system time from the
184 * hardware clock (RTC). */
185 pid = fork();
186 if (pid == 0) {
187 setsid();
188 reopen_fd_to_null(0);
189 reopen_fd_to_null(1);
190 reopen_fd_to_null(2);
192 /* Use '/sbin/hwclock -w' to set RTC from the system time,
193 * or '/sbin/hwclock -s' to set the system time from RTC. */
194 execle("/sbin/hwclock", "hwclock", has_time ? "-w" : "-s",
195 NULL, environ);
196 _exit(EXIT_FAILURE);
197 } else if (pid < 0) {
198 error_setg_errno(errp, errno, "failed to create child process");
199 return;
202 ga_wait_child(pid, &status, &local_err);
203 if (local_err) {
204 error_propagate(errp, local_err);
205 return;
208 if (!WIFEXITED(status)) {
209 error_setg(errp, "child process has terminated abnormally");
210 return;
213 if (WEXITSTATUS(status)) {
214 error_setg(errp, "hwclock failed to set hardware clock to system time");
215 return;
219 typedef enum {
220 RW_STATE_NEW,
221 RW_STATE_READING,
222 RW_STATE_WRITING,
223 } RwState;
225 typedef struct GuestFileHandle {
226 uint64_t id;
227 FILE *fh;
228 RwState state;
229 QTAILQ_ENTRY(GuestFileHandle) next;
230 } GuestFileHandle;
232 static struct {
233 QTAILQ_HEAD(, GuestFileHandle) filehandles;
234 } guest_file_state = {
235 .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
238 static int64_t guest_file_handle_add(FILE *fh, Error **errp)
240 GuestFileHandle *gfh;
241 int64_t handle;
243 handle = ga_get_fd_handle(ga_state, errp);
244 if (handle < 0) {
245 return -1;
248 gfh = g_new0(GuestFileHandle, 1);
249 gfh->id = handle;
250 gfh->fh = fh;
251 QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
253 return handle;
256 static GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
258 GuestFileHandle *gfh;
260 QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
262 if (gfh->id == id) {
263 return gfh;
267 error_setg(errp, "handle '%" PRId64 "' has not been found", id);
268 return NULL;
271 typedef const char * const ccpc;
273 #ifndef O_BINARY
274 #define O_BINARY 0
275 #endif
277 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
278 static const struct {
279 ccpc *forms;
280 int oflag_base;
281 } guest_file_open_modes[] = {
282 { (ccpc[]){ "r", NULL }, O_RDONLY },
283 { (ccpc[]){ "rb", NULL }, O_RDONLY | O_BINARY },
284 { (ccpc[]){ "w", NULL }, O_WRONLY | O_CREAT | O_TRUNC },
285 { (ccpc[]){ "wb", NULL }, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY },
286 { (ccpc[]){ "a", NULL }, O_WRONLY | O_CREAT | O_APPEND },
287 { (ccpc[]){ "ab", NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
288 { (ccpc[]){ "r+", NULL }, O_RDWR },
289 { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR | O_BINARY },
290 { (ccpc[]){ "w+", NULL }, O_RDWR | O_CREAT | O_TRUNC },
291 { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR | O_CREAT | O_TRUNC | O_BINARY },
292 { (ccpc[]){ "a+", NULL }, O_RDWR | O_CREAT | O_APPEND },
293 { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR | O_CREAT | O_APPEND | O_BINARY }
296 static int
297 find_open_flag(const char *mode_str, Error **errp)
299 unsigned mode;
301 for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
302 ccpc *form;
304 form = guest_file_open_modes[mode].forms;
305 while (*form != NULL && strcmp(*form, mode_str) != 0) {
306 ++form;
308 if (*form != NULL) {
309 break;
313 if (mode == ARRAY_SIZE(guest_file_open_modes)) {
314 error_setg(errp, "invalid file open mode '%s'", mode_str);
315 return -1;
317 return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
320 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
321 S_IRGRP | S_IWGRP | \
322 S_IROTH | S_IWOTH)
324 static FILE *
325 safe_open_or_create(const char *path, const char *mode, Error **errp)
327 Error *local_err = NULL;
328 int oflag;
330 oflag = find_open_flag(mode, &local_err);
331 if (local_err == NULL) {
332 int fd;
334 /* If the caller wants / allows creation of a new file, we implement it
335 * with a two step process: open() + (open() / fchmod()).
337 * First we insist on creating the file exclusively as a new file. If
338 * that succeeds, we're free to set any file-mode bits on it. (The
339 * motivation is that we want to set those file-mode bits independently
340 * of the current umask.)
342 * If the exclusive creation fails because the file already exists
343 * (EEXIST is not possible for any other reason), we just attempt to
344 * open the file, but in this case we won't be allowed to change the
345 * file-mode bits on the preexistent file.
347 * The pathname should never disappear between the two open()s in
348 * practice. If it happens, then someone very likely tried to race us.
349 * In this case just go ahead and report the ENOENT from the second
350 * open() to the caller.
352 * If the caller wants to open a preexistent file, then the first
353 * open() is decisive and its third argument is ignored, and the second
354 * open() and the fchmod() are never called.
356 fd = open(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
357 if (fd == -1 && errno == EEXIST) {
358 oflag &= ~(unsigned)O_CREAT;
359 fd = open(path, oflag);
362 if (fd == -1) {
363 error_setg_errno(&local_err, errno, "failed to open file '%s' "
364 "(mode: '%s')", path, mode);
365 } else {
366 qemu_set_cloexec(fd);
368 if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
369 error_setg_errno(&local_err, errno, "failed to set permission "
370 "0%03o on new file '%s' (mode: '%s')",
371 (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
372 } else {
373 FILE *f;
375 f = fdopen(fd, mode);
376 if (f == NULL) {
377 error_setg_errno(&local_err, errno, "failed to associate "
378 "stdio stream with file descriptor %d, "
379 "file '%s' (mode: '%s')", fd, path, mode);
380 } else {
381 return f;
385 close(fd);
386 if (oflag & O_CREAT) {
387 unlink(path);
392 error_propagate(errp, local_err);
393 return NULL;
396 int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
397 Error **errp)
399 FILE *fh;
400 Error *local_err = NULL;
401 int64_t handle;
403 if (!has_mode) {
404 mode = "r";
406 slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
407 fh = safe_open_or_create(path, mode, &local_err);
408 if (local_err != NULL) {
409 error_propagate(errp, local_err);
410 return -1;
413 /* set fd non-blocking to avoid common use cases (like reading from a
414 * named pipe) from hanging the agent
416 qemu_set_nonblock(fileno(fh));
418 handle = guest_file_handle_add(fh, errp);
419 if (handle < 0) {
420 fclose(fh);
421 return -1;
424 slog("guest-file-open, handle: %" PRId64, handle);
425 return handle;
428 void qmp_guest_file_close(int64_t handle, Error **errp)
430 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
431 int ret;
433 slog("guest-file-close called, handle: %" PRId64, handle);
434 if (!gfh) {
435 return;
438 ret = fclose(gfh->fh);
439 if (ret == EOF) {
440 error_setg_errno(errp, errno, "failed to close handle");
441 return;
444 QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
445 g_free(gfh);
448 struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,
449 int64_t count, Error **errp)
451 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
452 GuestFileRead *read_data = NULL;
453 guchar *buf;
454 FILE *fh;
455 size_t read_count;
457 if (!gfh) {
458 return NULL;
461 if (!has_count) {
462 count = QGA_READ_COUNT_DEFAULT;
463 } else if (count < 0) {
464 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
465 count);
466 return NULL;
469 fh = gfh->fh;
471 /* explicitly flush when switching from writing to reading */
472 if (gfh->state == RW_STATE_WRITING) {
473 int ret = fflush(fh);
474 if (ret == EOF) {
475 error_setg_errno(errp, errno, "failed to flush file");
476 return NULL;
478 gfh->state = RW_STATE_NEW;
481 buf = g_malloc0(count+1);
482 read_count = fread(buf, 1, count, fh);
483 if (ferror(fh)) {
484 error_setg_errno(errp, errno, "failed to read file");
485 slog("guest-file-read failed, handle: %" PRId64, handle);
486 } else {
487 buf[read_count] = 0;
488 read_data = g_new0(GuestFileRead, 1);
489 read_data->count = read_count;
490 read_data->eof = feof(fh);
491 if (read_count) {
492 read_data->buf_b64 = g_base64_encode(buf, read_count);
494 gfh->state = RW_STATE_READING;
496 g_free(buf);
497 clearerr(fh);
499 return read_data;
502 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
503 bool has_count, int64_t count,
504 Error **errp)
506 GuestFileWrite *write_data = NULL;
507 guchar *buf;
508 gsize buf_len;
509 int write_count;
510 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
511 FILE *fh;
513 if (!gfh) {
514 return NULL;
517 fh = gfh->fh;
519 if (gfh->state == RW_STATE_READING) {
520 int ret = fseek(fh, 0, SEEK_CUR);
521 if (ret == -1) {
522 error_setg_errno(errp, errno, "failed to seek file");
523 return NULL;
525 gfh->state = RW_STATE_NEW;
528 buf = g_base64_decode(buf_b64, &buf_len);
530 if (!has_count) {
531 count = buf_len;
532 } else if (count < 0 || count > buf_len) {
533 error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
534 count);
535 g_free(buf);
536 return NULL;
539 write_count = fwrite(buf, 1, count, fh);
540 if (ferror(fh)) {
541 error_setg_errno(errp, errno, "failed to write to file");
542 slog("guest-file-write failed, handle: %" PRId64, handle);
543 } else {
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;
549 g_free(buf);
550 clearerr(fh);
552 return write_data;
555 struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
556 int64_t whence, Error **errp)
558 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
559 GuestFileSeek *seek_data = NULL;
560 FILE *fh;
561 int ret;
563 if (!gfh) {
564 return NULL;
567 fh = gfh->fh;
568 ret = fseek(fh, offset, whence);
569 if (ret == -1) {
570 error_setg_errno(errp, errno, "failed to seek file");
571 if (errno == ESPIPE) {
572 /* file is non-seekable, stdio shouldn't be buffering anyways */
573 gfh->state = RW_STATE_NEW;
575 } else {
576 seek_data = g_new0(GuestFileSeek, 1);
577 seek_data->position = ftell(fh);
578 seek_data->eof = feof(fh);
579 gfh->state = RW_STATE_NEW;
581 clearerr(fh);
583 return seek_data;
586 void qmp_guest_file_flush(int64_t handle, Error **errp)
588 GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
589 FILE *fh;
590 int ret;
592 if (!gfh) {
593 return;
596 fh = gfh->fh;
597 ret = fflush(fh);
598 if (ret == EOF) {
599 error_setg_errno(errp, errno, "failed to flush file");
600 } else {
601 gfh->state = RW_STATE_NEW;
605 /* linux-specific implementations. avoid this if at all possible. */
606 #if defined(__linux__)
608 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
609 typedef struct FsMount {
610 char *dirname;
611 char *devtype;
612 unsigned int devmajor, devminor;
613 QTAILQ_ENTRY(FsMount) next;
614 } FsMount;
616 typedef QTAILQ_HEAD(FsMountList, FsMount) FsMountList;
618 static void free_fs_mount_list(FsMountList *mounts)
620 FsMount *mount, *temp;
622 if (!mounts) {
623 return;
626 QTAILQ_FOREACH_SAFE(mount, mounts, next, temp) {
627 QTAILQ_REMOVE(mounts, mount, next);
628 g_free(mount->dirname);
629 g_free(mount->devtype);
630 g_free(mount);
634 static int dev_major_minor(const char *devpath,
635 unsigned int *devmajor, unsigned int *devminor)
637 struct stat st;
639 *devmajor = 0;
640 *devminor = 0;
642 if (stat(devpath, &st) < 0) {
643 slog("failed to stat device file '%s': %s", devpath, strerror(errno));
644 return -1;
646 if (S_ISDIR(st.st_mode)) {
647 /* It is bind mount */
648 return -2;
650 if (S_ISBLK(st.st_mode)) {
651 *devmajor = major(st.st_rdev);
652 *devminor = minor(st.st_rdev);
653 return 0;
655 return -1;
659 * Walk the mount table and build a list of local file systems
661 static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
663 struct mntent *ment;
664 FsMount *mount;
665 char const *mtab = "/proc/self/mounts";
666 FILE *fp;
667 unsigned int devmajor, devminor;
669 fp = setmntent(mtab, "r");
670 if (!fp) {
671 error_setg(errp, "failed to open mtab file: '%s'", mtab);
672 return;
675 while ((ment = getmntent(fp))) {
677 * An entry which device name doesn't start with a '/' is
678 * either a dummy file system or a network file system.
679 * Add special handling for smbfs and cifs as is done by
680 * coreutils as well.
682 if ((ment->mnt_fsname[0] != '/') ||
683 (strcmp(ment->mnt_type, "smbfs") == 0) ||
684 (strcmp(ment->mnt_type, "cifs") == 0)) {
685 continue;
687 if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
688 /* Skip bind mounts */
689 continue;
692 mount = g_new0(FsMount, 1);
693 mount->dirname = g_strdup(ment->mnt_dir);
694 mount->devtype = g_strdup(ment->mnt_type);
695 mount->devmajor = devmajor;
696 mount->devminor = devminor;
698 QTAILQ_INSERT_TAIL(mounts, mount, next);
701 endmntent(fp);
704 static void decode_mntname(char *name, int len)
706 int i, j = 0;
707 for (i = 0; i <= len; i++) {
708 if (name[i] != '\\') {
709 name[j++] = name[i];
710 } else if (name[i + 1] == '\\') {
711 name[j++] = '\\';
712 i++;
713 } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
714 name[i + 2] >= '0' && name[i + 2] <= '7' &&
715 name[i + 3] >= '0' && name[i + 3] <= '7') {
716 name[j++] = (name[i + 1] - '0') * 64 +
717 (name[i + 2] - '0') * 8 +
718 (name[i + 3] - '0');
719 i += 3;
720 } else {
721 name[j++] = name[i];
726 static void build_fs_mount_list(FsMountList *mounts, Error **errp)
728 FsMount *mount;
729 char const *mountinfo = "/proc/self/mountinfo";
730 FILE *fp;
731 char *line = NULL, *dash;
732 size_t n;
733 char check;
734 unsigned int devmajor, devminor;
735 int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
737 fp = fopen(mountinfo, "r");
738 if (!fp) {
739 build_fs_mount_list_from_mtab(mounts, errp);
740 return;
743 while (getline(&line, &n, fp) != -1) {
744 ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
745 &devmajor, &devminor, &dir_s, &dir_e, &check);
746 if (ret < 3) {
747 continue;
749 dash = strstr(line + dir_e, " - ");
750 if (!dash) {
751 continue;
753 ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
754 &type_s, &type_e, &dev_s, &dev_e, &check);
755 if (ret < 1) {
756 continue;
758 line[dir_e] = 0;
759 dash[type_e] = 0;
760 dash[dev_e] = 0;
761 decode_mntname(line + dir_s, dir_e - dir_s);
762 decode_mntname(dash + dev_s, dev_e - dev_s);
763 if (devmajor == 0) {
764 /* btrfs reports major number = 0 */
765 if (strcmp("btrfs", dash + type_s) != 0 ||
766 dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
767 continue;
771 mount = g_new0(FsMount, 1);
772 mount->dirname = g_strdup(line + dir_s);
773 mount->devtype = g_strdup(dash + type_s);
774 mount->devmajor = devmajor;
775 mount->devminor = devminor;
777 QTAILQ_INSERT_TAIL(mounts, mount, next);
779 free(line);
781 fclose(fp);
783 #endif
785 #if defined(CONFIG_FSFREEZE)
787 static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
789 char *path;
790 char *dpath;
791 char *driver = NULL;
792 char buf[PATH_MAX];
793 ssize_t len;
795 path = g_strndup(syspath, pathlen);
796 dpath = g_strdup_printf("%s/driver", path);
797 len = readlink(dpath, buf, sizeof(buf) - 1);
798 if (len != -1) {
799 buf[len] = 0;
800 driver = g_strdup(basename(buf));
802 g_free(dpath);
803 g_free(path);
804 return driver;
807 static int compare_uint(const void *_a, const void *_b)
809 unsigned int a = *(unsigned int *)_a;
810 unsigned int b = *(unsigned int *)_b;
812 return a < b ? -1 : a > b ? 1 : 0;
815 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
816 static int build_hosts(char const *syspath, char const *host, bool ata,
817 unsigned int *hosts, int hosts_max, Error **errp)
819 char *path;
820 DIR *dir;
821 struct dirent *entry;
822 int i = 0;
824 path = g_strndup(syspath, host - syspath);
825 dir = opendir(path);
826 if (!dir) {
827 error_setg_errno(errp, errno, "opendir(\"%s\")", path);
828 g_free(path);
829 return -1;
832 while (i < hosts_max) {
833 entry = readdir(dir);
834 if (!entry) {
835 break;
837 if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
838 ++i;
839 } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
840 ++i;
844 qsort(hosts, i, sizeof(hosts[0]), compare_uint);
846 g_free(path);
847 closedir(dir);
848 return i;
851 /* Store disk device info specified by @sysfs into @fs */
852 static void build_guest_fsinfo_for_real_device(char const *syspath,
853 GuestFilesystemInfo *fs,
854 Error **errp)
856 unsigned int pci[4], host, hosts[8], tgt[3];
857 int i, nhosts = 0, pcilen;
858 GuestDiskAddress *disk;
859 GuestPCIAddress *pciaddr;
860 GuestDiskAddressList *list = NULL;
861 bool has_ata = false, has_host = false, has_tgt = false;
862 char *p, *q, *driver = NULL;
864 p = strstr(syspath, "/devices/pci");
865 if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
866 pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
867 g_debug("only pci device is supported: sysfs path \"%s\"", syspath);
868 return;
871 driver = get_pci_driver(syspath, (p + 12 + pcilen) - syspath, errp);
872 if (!driver) {
873 goto cleanup;
876 p = strstr(syspath, "/target");
877 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
878 tgt, tgt + 1, tgt + 2) == 3) {
879 has_tgt = true;
882 p = strstr(syspath, "/ata");
883 if (p) {
884 q = p + 4;
885 has_ata = true;
886 } else {
887 p = strstr(syspath, "/host");
888 q = p + 5;
890 if (p && sscanf(q, "%u", &host) == 1) {
891 has_host = true;
892 nhosts = build_hosts(syspath, p, has_ata, hosts,
893 sizeof(hosts) / sizeof(hosts[0]), errp);
894 if (nhosts < 0) {
895 goto cleanup;
899 pciaddr = g_malloc0(sizeof(*pciaddr));
900 pciaddr->domain = pci[0];
901 pciaddr->bus = pci[1];
902 pciaddr->slot = pci[2];
903 pciaddr->function = pci[3];
905 disk = g_malloc0(sizeof(*disk));
906 disk->pci_controller = pciaddr;
908 list = g_malloc0(sizeof(*list));
909 list->value = disk;
911 if (strcmp(driver, "ata_piix") == 0) {
912 /* a host per ide bus, target*:0:<unit>:0 */
913 if (!has_host || !has_tgt) {
914 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
915 goto cleanup;
917 for (i = 0; i < nhosts; i++) {
918 if (host == hosts[i]) {
919 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
920 disk->bus = i;
921 disk->unit = tgt[1];
922 break;
925 if (i >= nhosts) {
926 g_debug("no host for '%s' (driver '%s')", syspath, driver);
927 goto cleanup;
929 } else if (strcmp(driver, "sym53c8xx") == 0) {
930 /* scsi(LSI Logic): target*:0:<unit>:0 */
931 if (!has_tgt) {
932 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
933 goto cleanup;
935 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
936 disk->unit = tgt[1];
937 } else if (strcmp(driver, "virtio-pci") == 0) {
938 if (has_tgt) {
939 /* virtio-scsi: target*:0:0:<unit> */
940 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
941 disk->unit = tgt[2];
942 } else {
943 /* virtio-blk: 1 disk per 1 device */
944 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
946 } else if (strcmp(driver, "ahci") == 0) {
947 /* ahci: 1 host per 1 unit */
948 if (!has_host || !has_tgt) {
949 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
950 goto cleanup;
952 for (i = 0; i < nhosts; i++) {
953 if (host == hosts[i]) {
954 disk->unit = i;
955 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
956 break;
959 if (i >= nhosts) {
960 g_debug("no host for '%s' (driver '%s')", syspath, driver);
961 goto cleanup;
963 } else {
964 g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
965 goto cleanup;
968 list->next = fs->disk;
969 fs->disk = list;
970 g_free(driver);
971 return;
973 cleanup:
974 if (list) {
975 qapi_free_GuestDiskAddressList(list);
977 g_free(driver);
980 static void build_guest_fsinfo_for_device(char const *devpath,
981 GuestFilesystemInfo *fs,
982 Error **errp);
984 /* Store a list of slave devices of virtual volume specified by @syspath into
985 * @fs */
986 static void build_guest_fsinfo_for_virtual_device(char const *syspath,
987 GuestFilesystemInfo *fs,
988 Error **errp)
990 DIR *dir;
991 char *dirpath;
992 struct dirent *entry;
994 dirpath = g_strdup_printf("%s/slaves", syspath);
995 dir = opendir(dirpath);
996 if (!dir) {
997 error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
998 g_free(dirpath);
999 return;
1002 for (;;) {
1003 errno = 0;
1004 entry = readdir(dir);
1005 if (entry == NULL) {
1006 if (errno) {
1007 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
1009 break;
1012 if (entry->d_type == DT_LNK) {
1013 char *path;
1015 g_debug(" slave device '%s'", entry->d_name);
1016 path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
1017 build_guest_fsinfo_for_device(path, fs, errp);
1018 g_free(path);
1020 if (*errp) {
1021 break;
1026 g_free(dirpath);
1027 closedir(dir);
1030 /* Dispatch to functions for virtual/real device */
1031 static void build_guest_fsinfo_for_device(char const *devpath,
1032 GuestFilesystemInfo *fs,
1033 Error **errp)
1035 char *syspath = realpath(devpath, NULL);
1037 if (!syspath) {
1038 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1039 return;
1042 if (!fs->name) {
1043 fs->name = g_strdup(basename(syspath));
1046 g_debug(" parse sysfs path '%s'", syspath);
1048 if (strstr(syspath, "/devices/virtual/block/")) {
1049 build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1050 } else {
1051 build_guest_fsinfo_for_real_device(syspath, fs, errp);
1054 free(syspath);
1057 /* Return a list of the disk device(s)' info which @mount lies on */
1058 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1059 Error **errp)
1061 GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1062 char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1063 mount->devmajor, mount->devminor);
1065 fs->mountpoint = g_strdup(mount->dirname);
1066 fs->type = g_strdup(mount->devtype);
1067 build_guest_fsinfo_for_device(devpath, fs, errp);
1069 g_free(devpath);
1070 return fs;
1073 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1075 FsMountList mounts;
1076 struct FsMount *mount;
1077 GuestFilesystemInfoList *new, *ret = NULL;
1078 Error *local_err = NULL;
1080 QTAILQ_INIT(&mounts);
1081 build_fs_mount_list(&mounts, &local_err);
1082 if (local_err) {
1083 error_propagate(errp, local_err);
1084 return NULL;
1087 QTAILQ_FOREACH(mount, &mounts, next) {
1088 g_debug("Building guest fsinfo for '%s'", mount->dirname);
1090 new = g_malloc0(sizeof(*ret));
1091 new->value = build_guest_fsinfo(mount, &local_err);
1092 new->next = ret;
1093 ret = new;
1094 if (local_err) {
1095 error_propagate(errp, local_err);
1096 qapi_free_GuestFilesystemInfoList(ret);
1097 ret = NULL;
1098 break;
1102 free_fs_mount_list(&mounts);
1103 return ret;
1107 typedef enum {
1108 FSFREEZE_HOOK_THAW = 0,
1109 FSFREEZE_HOOK_FREEZE,
1110 } FsfreezeHookArg;
1112 static const char *fsfreeze_hook_arg_string[] = {
1113 "thaw",
1114 "freeze",
1117 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
1119 int status;
1120 pid_t pid;
1121 const char *hook;
1122 const char *arg_str = fsfreeze_hook_arg_string[arg];
1123 Error *local_err = NULL;
1125 hook = ga_fsfreeze_hook(ga_state);
1126 if (!hook) {
1127 return;
1129 if (access(hook, X_OK) != 0) {
1130 error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
1131 return;
1134 slog("executing fsfreeze hook with arg '%s'", arg_str);
1135 pid = fork();
1136 if (pid == 0) {
1137 setsid();
1138 reopen_fd_to_null(0);
1139 reopen_fd_to_null(1);
1140 reopen_fd_to_null(2);
1142 execle(hook, hook, arg_str, NULL, environ);
1143 _exit(EXIT_FAILURE);
1144 } else if (pid < 0) {
1145 error_setg_errno(errp, errno, "failed to create child process");
1146 return;
1149 ga_wait_child(pid, &status, &local_err);
1150 if (local_err) {
1151 error_propagate(errp, local_err);
1152 return;
1155 if (!WIFEXITED(status)) {
1156 error_setg(errp, "fsfreeze hook has terminated abnormally");
1157 return;
1160 status = WEXITSTATUS(status);
1161 if (status) {
1162 error_setg(errp, "fsfreeze hook has failed with status %d", status);
1163 return;
1168 * Return status of freeze/thaw
1170 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
1172 if (ga_is_frozen(ga_state)) {
1173 return GUEST_FSFREEZE_STATUS_FROZEN;
1176 return GUEST_FSFREEZE_STATUS_THAWED;
1179 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
1181 return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
1185 * Walk list of mounted file systems in the guest, and freeze the ones which
1186 * are real local file systems.
1188 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
1189 strList *mountpoints,
1190 Error **errp)
1192 int ret = 0, i = 0;
1193 strList *list;
1194 FsMountList mounts;
1195 struct FsMount *mount;
1196 Error *local_err = NULL;
1197 int fd;
1199 slog("guest-fsfreeze called");
1201 execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
1202 if (local_err) {
1203 error_propagate(errp, local_err);
1204 return -1;
1207 QTAILQ_INIT(&mounts);
1208 build_fs_mount_list(&mounts, &local_err);
1209 if (local_err) {
1210 error_propagate(errp, local_err);
1211 return -1;
1214 /* cannot risk guest agent blocking itself on a write in this state */
1215 ga_set_frozen(ga_state);
1217 QTAILQ_FOREACH_REVERSE(mount, &mounts, FsMountList, next) {
1218 /* To issue fsfreeze in the reverse order of mounts, check if the
1219 * mount is listed in the list here */
1220 if (has_mountpoints) {
1221 for (list = mountpoints; list; list = list->next) {
1222 if (strcmp(list->value, mount->dirname) == 0) {
1223 break;
1226 if (!list) {
1227 continue;
1231 fd = qemu_open(mount->dirname, O_RDONLY);
1232 if (fd == -1) {
1233 error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
1234 goto error;
1237 /* we try to cull filesytems we know won't work in advance, but other
1238 * filesytems may not implement fsfreeze for less obvious reasons.
1239 * these will report EOPNOTSUPP. we simply ignore these when tallying
1240 * the number of frozen filesystems.
1242 * any other error means a failure to freeze a filesystem we
1243 * expect to be freezable, so return an error in those cases
1244 * and return system to thawed state.
1246 ret = ioctl(fd, FIFREEZE);
1247 if (ret == -1) {
1248 if (errno != EOPNOTSUPP) {
1249 error_setg_errno(errp, errno, "failed to freeze %s",
1250 mount->dirname);
1251 close(fd);
1252 goto error;
1254 } else {
1255 i++;
1257 close(fd);
1260 free_fs_mount_list(&mounts);
1261 return i;
1263 error:
1264 free_fs_mount_list(&mounts);
1265 qmp_guest_fsfreeze_thaw(NULL);
1266 return 0;
1270 * Walk list of frozen file systems in the guest, and thaw them.
1272 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
1274 int ret;
1275 FsMountList mounts;
1276 FsMount *mount;
1277 int fd, i = 0, logged;
1278 Error *local_err = NULL;
1280 QTAILQ_INIT(&mounts);
1281 build_fs_mount_list(&mounts, &local_err);
1282 if (local_err) {
1283 error_propagate(errp, local_err);
1284 return 0;
1287 QTAILQ_FOREACH(mount, &mounts, next) {
1288 logged = false;
1289 fd = qemu_open(mount->dirname, O_RDONLY);
1290 if (fd == -1) {
1291 continue;
1293 /* we have no way of knowing whether a filesystem was actually unfrozen
1294 * as a result of a successful call to FITHAW, only that if an error
1295 * was returned the filesystem was *not* unfrozen by that particular
1296 * call.
1298 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
1299 * to unfreeze, continuing issuing FITHAW until an error is returned,
1300 * in which case either the filesystem is in an unfreezable state, or,
1301 * more likely, it was thawed previously (and remains so afterward).
1303 * also, since the most recent successful call is the one that did
1304 * the actual unfreeze, we can use this to provide an accurate count
1305 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
1306 * may * be useful for determining whether a filesystem was unfrozen
1307 * during the freeze/thaw phase by a process other than qemu-ga.
1309 do {
1310 ret = ioctl(fd, FITHAW);
1311 if (ret == 0 && !logged) {
1312 i++;
1313 logged = true;
1315 } while (ret == 0);
1316 close(fd);
1319 ga_unset_frozen(ga_state);
1320 free_fs_mount_list(&mounts);
1322 execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
1324 return i;
1327 static void guest_fsfreeze_cleanup(void)
1329 Error *err = NULL;
1331 if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
1332 qmp_guest_fsfreeze_thaw(&err);
1333 if (err) {
1334 slog("failed to clean up frozen filesystems: %s",
1335 error_get_pretty(err));
1336 error_free(err);
1340 #endif /* CONFIG_FSFREEZE */
1342 #if defined(CONFIG_FSTRIM)
1344 * Walk list of mounted file systems in the guest, and trim them.
1346 GuestFilesystemTrimResponse *
1347 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1349 GuestFilesystemTrimResponse *response;
1350 GuestFilesystemTrimResultList *list;
1351 GuestFilesystemTrimResult *result;
1352 int ret = 0;
1353 FsMountList mounts;
1354 struct FsMount *mount;
1355 int fd;
1356 Error *local_err = NULL;
1357 struct fstrim_range r;
1359 slog("guest-fstrim called");
1361 QTAILQ_INIT(&mounts);
1362 build_fs_mount_list(&mounts, &local_err);
1363 if (local_err) {
1364 error_propagate(errp, local_err);
1365 return NULL;
1368 response = g_malloc0(sizeof(*response));
1370 QTAILQ_FOREACH(mount, &mounts, next) {
1371 result = g_malloc0(sizeof(*result));
1372 result->path = g_strdup(mount->dirname);
1374 list = g_malloc0(sizeof(*list));
1375 list->value = result;
1376 list->next = response->paths;
1377 response->paths = list;
1379 fd = qemu_open(mount->dirname, O_RDONLY);
1380 if (fd == -1) {
1381 result->error = g_strdup_printf("failed to open: %s",
1382 strerror(errno));
1383 result->has_error = true;
1384 continue;
1387 /* We try to cull filesytems we know won't work in advance, but other
1388 * filesytems may not implement fstrim for less obvious reasons. These
1389 * will report EOPNOTSUPP; while in some other cases ENOTTY will be
1390 * reported (e.g. CD-ROMs).
1391 * Any other error means an unexpected error.
1393 r.start = 0;
1394 r.len = -1;
1395 r.minlen = has_minimum ? minimum : 0;
1396 ret = ioctl(fd, FITRIM, &r);
1397 if (ret == -1) {
1398 result->has_error = true;
1399 if (errno == ENOTTY || errno == EOPNOTSUPP) {
1400 result->error = g_strdup("trim not supported");
1401 } else {
1402 result->error = g_strdup_printf("failed to trim: %s",
1403 strerror(errno));
1405 close(fd);
1406 continue;
1409 result->has_minimum = true;
1410 result->minimum = r.minlen;
1411 result->has_trimmed = true;
1412 result->trimmed = r.len;
1413 close(fd);
1416 free_fs_mount_list(&mounts);
1417 return response;
1419 #endif /* CONFIG_FSTRIM */
1422 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1423 #define SUSPEND_SUPPORTED 0
1424 #define SUSPEND_NOT_SUPPORTED 1
1426 static void bios_supports_mode(const char *pmutils_bin, const char *pmutils_arg,
1427 const char *sysfile_str, Error **errp)
1429 Error *local_err = NULL;
1430 char *pmutils_path;
1431 pid_t pid;
1432 int status;
1434 pmutils_path = g_find_program_in_path(pmutils_bin);
1436 pid = fork();
1437 if (!pid) {
1438 char buf[32]; /* hopefully big enough */
1439 ssize_t ret;
1440 int fd;
1442 setsid();
1443 reopen_fd_to_null(0);
1444 reopen_fd_to_null(1);
1445 reopen_fd_to_null(2);
1447 if (pmutils_path) {
1448 execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);
1452 * If we get here either pm-utils is not installed or execle() has
1453 * failed. Let's try the manual method if the caller wants it.
1456 if (!sysfile_str) {
1457 _exit(SUSPEND_NOT_SUPPORTED);
1460 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
1461 if (fd < 0) {
1462 _exit(SUSPEND_NOT_SUPPORTED);
1465 ret = read(fd, buf, sizeof(buf)-1);
1466 if (ret <= 0) {
1467 _exit(SUSPEND_NOT_SUPPORTED);
1469 buf[ret] = '\0';
1471 if (strstr(buf, sysfile_str)) {
1472 _exit(SUSPEND_SUPPORTED);
1475 _exit(SUSPEND_NOT_SUPPORTED);
1476 } else if (pid < 0) {
1477 error_setg_errno(errp, errno, "failed to create child process");
1478 goto out;
1481 ga_wait_child(pid, &status, &local_err);
1482 if (local_err) {
1483 error_propagate(errp, local_err);
1484 goto out;
1487 if (!WIFEXITED(status)) {
1488 error_setg(errp, "child process has terminated abnormally");
1489 goto out;
1492 switch (WEXITSTATUS(status)) {
1493 case SUSPEND_SUPPORTED:
1494 goto out;
1495 case SUSPEND_NOT_SUPPORTED:
1496 error_setg(errp,
1497 "the requested suspend mode is not supported by the guest");
1498 goto out;
1499 default:
1500 error_setg(errp,
1501 "the helper program '%s' returned an unexpected exit status"
1502 " code (%d)", pmutils_path, WEXITSTATUS(status));
1503 goto out;
1506 out:
1507 g_free(pmutils_path);
1510 static void guest_suspend(const char *pmutils_bin, const char *sysfile_str,
1511 Error **errp)
1513 Error *local_err = NULL;
1514 char *pmutils_path;
1515 pid_t pid;
1516 int status;
1518 pmutils_path = g_find_program_in_path(pmutils_bin);
1520 pid = fork();
1521 if (pid == 0) {
1522 /* child */
1523 int fd;
1525 setsid();
1526 reopen_fd_to_null(0);
1527 reopen_fd_to_null(1);
1528 reopen_fd_to_null(2);
1530 if (pmutils_path) {
1531 execle(pmutils_path, pmutils_bin, NULL, environ);
1535 * If we get here either pm-utils is not installed or execle() has
1536 * failed. Let's try the manual method if the caller wants it.
1539 if (!sysfile_str) {
1540 _exit(EXIT_FAILURE);
1543 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
1544 if (fd < 0) {
1545 _exit(EXIT_FAILURE);
1548 if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
1549 _exit(EXIT_FAILURE);
1552 _exit(EXIT_SUCCESS);
1553 } else if (pid < 0) {
1554 error_setg_errno(errp, errno, "failed to create child process");
1555 goto out;
1558 ga_wait_child(pid, &status, &local_err);
1559 if (local_err) {
1560 error_propagate(errp, local_err);
1561 goto out;
1564 if (!WIFEXITED(status)) {
1565 error_setg(errp, "child process has terminated abnormally");
1566 goto out;
1569 if (WEXITSTATUS(status)) {
1570 error_setg(errp, "child process has failed to suspend");
1571 goto out;
1574 out:
1575 g_free(pmutils_path);
1578 void qmp_guest_suspend_disk(Error **errp)
1580 Error *local_err = NULL;
1582 bios_supports_mode("pm-is-supported", "--hibernate", "disk", &local_err);
1583 if (local_err) {
1584 error_propagate(errp, local_err);
1585 return;
1588 guest_suspend("pm-hibernate", "disk", errp);
1591 void qmp_guest_suspend_ram(Error **errp)
1593 Error *local_err = NULL;
1595 bios_supports_mode("pm-is-supported", "--suspend", "mem", &local_err);
1596 if (local_err) {
1597 error_propagate(errp, local_err);
1598 return;
1601 guest_suspend("pm-suspend", "mem", errp);
1604 void qmp_guest_suspend_hybrid(Error **errp)
1606 Error *local_err = NULL;
1608 bios_supports_mode("pm-is-supported", "--suspend-hybrid", NULL,
1609 &local_err);
1610 if (local_err) {
1611 error_propagate(errp, local_err);
1612 return;
1615 guest_suspend("pm-suspend-hybrid", NULL, errp);
1618 static GuestNetworkInterfaceList *
1619 guest_find_interface(GuestNetworkInterfaceList *head,
1620 const char *name)
1622 for (; head; head = head->next) {
1623 if (strcmp(head->value->name, name) == 0) {
1624 break;
1628 return head;
1632 * Build information about guest interfaces
1634 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
1636 GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;
1637 struct ifaddrs *ifap, *ifa;
1639 if (getifaddrs(&ifap) < 0) {
1640 error_setg_errno(errp, errno, "getifaddrs failed");
1641 goto error;
1644 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1645 GuestNetworkInterfaceList *info;
1646 GuestIpAddressList **address_list = NULL, *address_item = NULL;
1647 char addr4[INET_ADDRSTRLEN];
1648 char addr6[INET6_ADDRSTRLEN];
1649 int sock;
1650 struct ifreq ifr;
1651 unsigned char *mac_addr;
1652 void *p;
1654 g_debug("Processing %s interface", ifa->ifa_name);
1656 info = guest_find_interface(head, ifa->ifa_name);
1658 if (!info) {
1659 info = g_malloc0(sizeof(*info));
1660 info->value = g_malloc0(sizeof(*info->value));
1661 info->value->name = g_strdup(ifa->ifa_name);
1663 if (!cur_item) {
1664 head = cur_item = info;
1665 } else {
1666 cur_item->next = info;
1667 cur_item = info;
1671 if (!info->value->has_hardware_address &&
1672 ifa->ifa_flags & SIOCGIFHWADDR) {
1673 /* we haven't obtained HW address yet */
1674 sock = socket(PF_INET, SOCK_STREAM, 0);
1675 if (sock == -1) {
1676 error_setg_errno(errp, errno, "failed to create socket");
1677 goto error;
1680 memset(&ifr, 0, sizeof(ifr));
1681 pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);
1682 if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
1683 error_setg_errno(errp, errno,
1684 "failed to get MAC address of %s",
1685 ifa->ifa_name);
1686 close(sock);
1687 goto error;
1690 close(sock);
1691 mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
1693 info->value->hardware_address =
1694 g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
1695 (int) mac_addr[0], (int) mac_addr[1],
1696 (int) mac_addr[2], (int) mac_addr[3],
1697 (int) mac_addr[4], (int) mac_addr[5]);
1699 info->value->has_hardware_address = true;
1702 if (ifa->ifa_addr &&
1703 ifa->ifa_addr->sa_family == AF_INET) {
1704 /* interface with IPv4 address */
1705 p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1706 if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
1707 error_setg_errno(errp, errno, "inet_ntop failed");
1708 goto error;
1711 address_item = g_malloc0(sizeof(*address_item));
1712 address_item->value = g_malloc0(sizeof(*address_item->value));
1713 address_item->value->ip_address = g_strdup(addr4);
1714 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
1716 if (ifa->ifa_netmask) {
1717 /* Count the number of set bits in netmask.
1718 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1719 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
1720 address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);
1722 } else if (ifa->ifa_addr &&
1723 ifa->ifa_addr->sa_family == AF_INET6) {
1724 /* interface with IPv6 address */
1725 p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
1726 if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
1727 error_setg_errno(errp, errno, "inet_ntop failed");
1728 goto error;
1731 address_item = g_malloc0(sizeof(*address_item));
1732 address_item->value = g_malloc0(sizeof(*address_item->value));
1733 address_item->value->ip_address = g_strdup(addr6);
1734 address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
1736 if (ifa->ifa_netmask) {
1737 /* Count the number of set bits in netmask.
1738 * This is safe as '1' and '0' cannot be shuffled in netmask. */
1739 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
1740 address_item->value->prefix =
1741 ctpop32(((uint32_t *) p)[0]) +
1742 ctpop32(((uint32_t *) p)[1]) +
1743 ctpop32(((uint32_t *) p)[2]) +
1744 ctpop32(((uint32_t *) p)[3]);
1748 if (!address_item) {
1749 continue;
1752 address_list = &info->value->ip_addresses;
1754 while (*address_list && (*address_list)->next) {
1755 address_list = &(*address_list)->next;
1758 if (!*address_list) {
1759 *address_list = address_item;
1760 } else {
1761 (*address_list)->next = address_item;
1764 info->value->has_ip_addresses = true;
1769 freeifaddrs(ifap);
1770 return head;
1772 error:
1773 freeifaddrs(ifap);
1774 qapi_free_GuestNetworkInterfaceList(head);
1775 return NULL;
1778 #define SYSCONF_EXACT(name, errp) sysconf_exact((name), #name, (errp))
1780 static long sysconf_exact(int name, const char *name_str, Error **errp)
1782 long ret;
1784 errno = 0;
1785 ret = sysconf(name);
1786 if (ret == -1) {
1787 if (errno == 0) {
1788 error_setg(errp, "sysconf(%s): value indefinite", name_str);
1789 } else {
1790 error_setg_errno(errp, errno, "sysconf(%s)", name_str);
1793 return ret;
1796 /* Transfer online/offline status between @vcpu and the guest system.
1798 * On input either @errp or *@errp must be NULL.
1800 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1801 * - R: vcpu->logical_id
1802 * - W: vcpu->online
1803 * - W: vcpu->can_offline
1805 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1806 * - R: vcpu->logical_id
1807 * - R: vcpu->online
1809 * Written members remain unmodified on error.
1811 static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
1812 Error **errp)
1814 char *dirpath;
1815 int dirfd;
1817 dirpath = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
1818 vcpu->logical_id);
1819 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
1820 if (dirfd == -1) {
1821 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
1822 } else {
1823 static const char fn[] = "online";
1824 int fd;
1825 int res;
1827 fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
1828 if (fd == -1) {
1829 if (errno != ENOENT) {
1830 error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
1831 } else if (sys2vcpu) {
1832 vcpu->online = true;
1833 vcpu->can_offline = false;
1834 } else if (!vcpu->online) {
1835 error_setg(errp, "logical processor #%" PRId64 " can't be "
1836 "offlined", vcpu->logical_id);
1837 } /* otherwise pretend successful re-onlining */
1838 } else {
1839 unsigned char status;
1841 res = pread(fd, &status, 1, 0);
1842 if (res == -1) {
1843 error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
1844 } else if (res == 0) {
1845 error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
1846 fn);
1847 } else if (sys2vcpu) {
1848 vcpu->online = (status != '0');
1849 vcpu->can_offline = true;
1850 } else if (vcpu->online != (status != '0')) {
1851 status = '0' + vcpu->online;
1852 if (pwrite(fd, &status, 1, 0) == -1) {
1853 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
1854 fn);
1856 } /* otherwise pretend successful re-(on|off)-lining */
1858 res = close(fd);
1859 g_assert(res == 0);
1862 res = close(dirfd);
1863 g_assert(res == 0);
1866 g_free(dirpath);
1869 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1871 int64_t current;
1872 GuestLogicalProcessorList *head, **link;
1873 long sc_max;
1874 Error *local_err = NULL;
1876 current = 0;
1877 head = NULL;
1878 link = &head;
1879 sc_max = SYSCONF_EXACT(_SC_NPROCESSORS_CONF, &local_err);
1881 while (local_err == NULL && current < sc_max) {
1882 GuestLogicalProcessor *vcpu;
1883 GuestLogicalProcessorList *entry;
1885 vcpu = g_malloc0(sizeof *vcpu);
1886 vcpu->logical_id = current++;
1887 vcpu->has_can_offline = true; /* lolspeak ftw */
1888 transfer_vcpu(vcpu, true, &local_err);
1890 entry = g_malloc0(sizeof *entry);
1891 entry->value = vcpu;
1893 *link = entry;
1894 link = &entry->next;
1897 if (local_err == NULL) {
1898 /* there's no guest with zero VCPUs */
1899 g_assert(head != NULL);
1900 return head;
1903 qapi_free_GuestLogicalProcessorList(head);
1904 error_propagate(errp, local_err);
1905 return NULL;
1908 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1910 int64_t processed;
1911 Error *local_err = NULL;
1913 processed = 0;
1914 while (vcpus != NULL) {
1915 transfer_vcpu(vcpus->value, false, &local_err);
1916 if (local_err != NULL) {
1917 break;
1919 ++processed;
1920 vcpus = vcpus->next;
1923 if (local_err != NULL) {
1924 if (processed == 0) {
1925 error_propagate(errp, local_err);
1926 } else {
1927 error_free(local_err);
1931 return processed;
1934 void qmp_guest_set_user_password(const char *username,
1935 const char *password,
1936 bool crypted,
1937 Error **errp)
1939 Error *local_err = NULL;
1940 char *passwd_path = NULL;
1941 pid_t pid;
1942 int status;
1943 int datafd[2] = { -1, -1 };
1944 char *rawpasswddata = NULL;
1945 size_t rawpasswdlen;
1946 char *chpasswddata = NULL;
1947 size_t chpasswdlen;
1949 rawpasswddata = (char *)g_base64_decode(password, &rawpasswdlen);
1950 rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
1951 rawpasswddata[rawpasswdlen] = '\0';
1953 if (strchr(rawpasswddata, '\n')) {
1954 error_setg(errp, "forbidden characters in raw password");
1955 goto out;
1958 if (strchr(username, '\n') ||
1959 strchr(username, ':')) {
1960 error_setg(errp, "forbidden characters in username");
1961 goto out;
1964 chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
1965 chpasswdlen = strlen(chpasswddata);
1967 passwd_path = g_find_program_in_path("chpasswd");
1969 if (!passwd_path) {
1970 error_setg(errp, "cannot find 'passwd' program in PATH");
1971 goto out;
1974 if (pipe(datafd) < 0) {
1975 error_setg(errp, "cannot create pipe FDs");
1976 goto out;
1979 pid = fork();
1980 if (pid == 0) {
1981 close(datafd[1]);
1982 /* child */
1983 setsid();
1984 dup2(datafd[0], 0);
1985 reopen_fd_to_null(1);
1986 reopen_fd_to_null(2);
1988 if (crypted) {
1989 execle(passwd_path, "chpasswd", "-e", NULL, environ);
1990 } else {
1991 execle(passwd_path, "chpasswd", NULL, environ);
1993 _exit(EXIT_FAILURE);
1994 } else if (pid < 0) {
1995 error_setg_errno(errp, errno, "failed to create child process");
1996 goto out;
1998 close(datafd[0]);
1999 datafd[0] = -1;
2001 if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
2002 error_setg_errno(errp, errno, "cannot write new account password");
2003 goto out;
2005 close(datafd[1]);
2006 datafd[1] = -1;
2008 ga_wait_child(pid, &status, &local_err);
2009 if (local_err) {
2010 error_propagate(errp, local_err);
2011 goto out;
2014 if (!WIFEXITED(status)) {
2015 error_setg(errp, "child process has terminated abnormally");
2016 goto out;
2019 if (WEXITSTATUS(status)) {
2020 error_setg(errp, "child process has failed to set user password");
2021 goto out;
2024 out:
2025 g_free(chpasswddata);
2026 g_free(rawpasswddata);
2027 g_free(passwd_path);
2028 if (datafd[0] != -1) {
2029 close(datafd[0]);
2031 if (datafd[1] != -1) {
2032 close(datafd[1]);
2036 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2037 int size, Error **errp)
2039 int fd;
2040 int res;
2042 errno = 0;
2043 fd = openat(dirfd, pathname, O_RDONLY);
2044 if (fd == -1) {
2045 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2046 return;
2049 res = pread(fd, buf, size, 0);
2050 if (res == -1) {
2051 error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2052 } else if (res == 0) {
2053 error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2055 close(fd);
2058 static void ga_write_sysfs_file(int dirfd, const char *pathname,
2059 const char *buf, int size, Error **errp)
2061 int fd;
2063 errno = 0;
2064 fd = openat(dirfd, pathname, O_WRONLY);
2065 if (fd == -1) {
2066 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2067 return;
2070 if (pwrite(fd, buf, size, 0) == -1) {
2071 error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2074 close(fd);
2077 /* Transfer online/offline status between @mem_blk and the guest system.
2079 * On input either @errp or *@errp must be NULL.
2081 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2082 * - R: mem_blk->phys_index
2083 * - W: mem_blk->online
2084 * - W: mem_blk->can_offline
2086 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2087 * - R: mem_blk->phys_index
2088 * - R: mem_blk->online
2089 *- R: mem_blk->can_offline
2090 * Written members remain unmodified on error.
2092 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2093 GuestMemoryBlockResponse *result,
2094 Error **errp)
2096 char *dirpath;
2097 int dirfd;
2098 char *status;
2099 Error *local_err = NULL;
2101 if (!sys2memblk) {
2102 DIR *dp;
2104 if (!result) {
2105 error_setg(errp, "Internal error, 'result' should not be NULL");
2106 return;
2108 errno = 0;
2109 dp = opendir("/sys/devices/system/memory/");
2110 /* if there is no 'memory' directory in sysfs,
2111 * we think this VM does not support online/offline memory block,
2112 * any other solution?
2114 if (!dp && errno == ENOENT) {
2115 result->response =
2116 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2117 goto out1;
2119 closedir(dp);
2122 dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2123 mem_blk->phys_index);
2124 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2125 if (dirfd == -1) {
2126 if (sys2memblk) {
2127 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2128 } else {
2129 if (errno == ENOENT) {
2130 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2131 } else {
2132 result->response =
2133 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2136 g_free(dirpath);
2137 goto out1;
2139 g_free(dirpath);
2141 status = g_malloc0(10);
2142 ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2143 if (local_err) {
2144 /* treat with sysfs file that not exist in old kernel */
2145 if (errno == ENOENT) {
2146 error_free(local_err);
2147 if (sys2memblk) {
2148 mem_blk->online = true;
2149 mem_blk->can_offline = false;
2150 } else if (!mem_blk->online) {
2151 result->response =
2152 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2154 } else {
2155 if (sys2memblk) {
2156 error_propagate(errp, local_err);
2157 } else {
2158 result->response =
2159 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2162 goto out2;
2165 if (sys2memblk) {
2166 char removable = '0';
2168 mem_blk->online = (strncmp(status, "online", 6) == 0);
2170 ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2171 if (local_err) {
2172 /* if no 'removable' file, it doesn't support offline mem blk */
2173 if (errno == ENOENT) {
2174 error_free(local_err);
2175 mem_blk->can_offline = false;
2176 } else {
2177 error_propagate(errp, local_err);
2179 } else {
2180 mem_blk->can_offline = (removable != '0');
2182 } else {
2183 if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2184 char *new_state = mem_blk->online ? g_strdup("online") :
2185 g_strdup("offline");
2187 ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2188 &local_err);
2189 g_free(new_state);
2190 if (local_err) {
2191 error_free(local_err);
2192 result->response =
2193 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2194 goto out2;
2197 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2198 result->has_error_code = false;
2199 } /* otherwise pretend successful re-(on|off)-lining */
2201 g_free(status);
2202 close(dirfd);
2203 return;
2205 out2:
2206 g_free(status);
2207 close(dirfd);
2208 out1:
2209 if (!sys2memblk) {
2210 result->has_error_code = true;
2211 result->error_code = errno;
2215 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2217 GuestMemoryBlockList *head, **link;
2218 Error *local_err = NULL;
2219 struct dirent *de;
2220 DIR *dp;
2222 head = NULL;
2223 link = &head;
2225 dp = opendir("/sys/devices/system/memory/");
2226 if (!dp) {
2227 /* it's ok if this happens to be a system that doesn't expose
2228 * memory blocks via sysfs, but otherwise we should report
2229 * an error
2231 if (errno != ENOENT) {
2232 error_setg_errno(errp, errno, "Can't open directory"
2233 "\"/sys/devices/system/memory/\"\n");
2235 return NULL;
2238 /* Note: the phys_index of memory block may be discontinuous,
2239 * this is because a memblk is the unit of the Sparse Memory design, which
2240 * allows discontinuous memory ranges (ex. NUMA), so here we should
2241 * traverse the memory block directory.
2243 while ((de = readdir(dp)) != NULL) {
2244 GuestMemoryBlock *mem_blk;
2245 GuestMemoryBlockList *entry;
2247 if ((strncmp(de->d_name, "memory", 6) != 0) ||
2248 !(de->d_type & DT_DIR)) {
2249 continue;
2252 mem_blk = g_malloc0(sizeof *mem_blk);
2253 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
2254 mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2255 mem_blk->has_can_offline = true; /* lolspeak ftw */
2256 transfer_memory_block(mem_blk, true, NULL, &local_err);
2258 entry = g_malloc0(sizeof *entry);
2259 entry->value = mem_blk;
2261 *link = entry;
2262 link = &entry->next;
2265 closedir(dp);
2266 if (local_err == NULL) {
2267 /* there's no guest with zero memory blocks */
2268 if (head == NULL) {
2269 error_setg(errp, "guest reported zero memory blocks!");
2271 return head;
2274 qapi_free_GuestMemoryBlockList(head);
2275 error_propagate(errp, local_err);
2276 return NULL;
2279 GuestMemoryBlockResponseList *
2280 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2282 GuestMemoryBlockResponseList *head, **link;
2283 Error *local_err = NULL;
2285 head = NULL;
2286 link = &head;
2288 while (mem_blks != NULL) {
2289 GuestMemoryBlockResponse *result;
2290 GuestMemoryBlockResponseList *entry;
2291 GuestMemoryBlock *current_mem_blk = mem_blks->value;
2293 result = g_malloc0(sizeof(*result));
2294 result->phys_index = current_mem_blk->phys_index;
2295 transfer_memory_block(current_mem_blk, false, result, &local_err);
2296 if (local_err) { /* should never happen */
2297 goto err;
2299 entry = g_malloc0(sizeof *entry);
2300 entry->value = result;
2302 *link = entry;
2303 link = &entry->next;
2304 mem_blks = mem_blks->next;
2307 return head;
2308 err:
2309 qapi_free_GuestMemoryBlockResponseList(head);
2310 error_propagate(errp, local_err);
2311 return NULL;
2314 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2316 Error *local_err = NULL;
2317 char *dirpath;
2318 int dirfd;
2319 char *buf;
2320 GuestMemoryBlockInfo *info;
2322 dirpath = g_strdup_printf("/sys/devices/system/memory/");
2323 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2324 if (dirfd == -1) {
2325 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2326 g_free(dirpath);
2327 return NULL;
2329 g_free(dirpath);
2331 buf = g_malloc0(20);
2332 ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
2333 close(dirfd);
2334 if (local_err) {
2335 g_free(buf);
2336 error_propagate(errp, local_err);
2337 return NULL;
2340 info = g_new0(GuestMemoryBlockInfo, 1);
2341 info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2343 g_free(buf);
2345 return info;
2348 #else /* defined(__linux__) */
2350 void qmp_guest_suspend_disk(Error **errp)
2352 error_setg(errp, QERR_UNSUPPORTED);
2355 void qmp_guest_suspend_ram(Error **errp)
2357 error_setg(errp, QERR_UNSUPPORTED);
2360 void qmp_guest_suspend_hybrid(Error **errp)
2362 error_setg(errp, QERR_UNSUPPORTED);
2365 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2367 error_setg(errp, QERR_UNSUPPORTED);
2368 return NULL;
2371 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2373 error_setg(errp, QERR_UNSUPPORTED);
2374 return NULL;
2377 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2379 error_setg(errp, QERR_UNSUPPORTED);
2380 return -1;
2383 void qmp_guest_set_user_password(const char *username,
2384 const char *password,
2385 bool crypted,
2386 Error **errp)
2388 error_setg(errp, QERR_UNSUPPORTED);
2391 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2393 error_setg(errp, QERR_UNSUPPORTED);
2394 return NULL;
2397 GuestMemoryBlockResponseList *
2398 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2400 error_setg(errp, QERR_UNSUPPORTED);
2401 return NULL;
2404 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2406 error_setg(errp, QERR_UNSUPPORTED);
2407 return NULL;
2410 #endif
2412 #if !defined(CONFIG_FSFREEZE)
2414 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
2416 error_setg(errp, QERR_UNSUPPORTED);
2417 return NULL;
2420 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
2422 error_setg(errp, QERR_UNSUPPORTED);
2424 return 0;
2427 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
2429 error_setg(errp, QERR_UNSUPPORTED);
2431 return 0;
2434 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
2435 strList *mountpoints,
2436 Error **errp)
2438 error_setg(errp, QERR_UNSUPPORTED);
2440 return 0;
2443 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
2445 error_setg(errp, QERR_UNSUPPORTED);
2447 return 0;
2449 #endif /* CONFIG_FSFREEZE */
2451 #if !defined(CONFIG_FSTRIM)
2452 GuestFilesystemTrimResponse *
2453 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
2455 error_setg(errp, QERR_UNSUPPORTED);
2456 return NULL;
2458 #endif
2460 /* add unsupported commands to the blacklist */
2461 GList *ga_command_blacklist_init(GList *blacklist)
2463 #if !defined(__linux__)
2465 const char *list[] = {
2466 "guest-suspend-disk", "guest-suspend-ram",
2467 "guest-suspend-hybrid", "guest-network-get-interfaces",
2468 "guest-get-vcpus", "guest-set-vcpus",
2469 "guest-get-memory-blocks", "guest-set-memory-blocks",
2470 "guest-get-memory-block-size", NULL};
2471 char **p = (char **)list;
2473 while (*p) {
2474 blacklist = g_list_append(blacklist, g_strdup(*p++));
2477 #endif
2479 #if !defined(CONFIG_FSFREEZE)
2481 const char *list[] = {
2482 "guest-get-fsinfo", "guest-fsfreeze-status",
2483 "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
2484 "guest-fsfreeze-thaw", "guest-get-fsinfo", NULL};
2485 char **p = (char **)list;
2487 while (*p) {
2488 blacklist = g_list_append(blacklist, g_strdup(*p++));
2491 #endif
2493 #if !defined(CONFIG_FSTRIM)
2494 blacklist = g_list_append(blacklist, g_strdup("guest-fstrim"));
2495 #endif
2497 return blacklist;
2500 /* register init/cleanup routines for stateful command groups */
2501 void ga_command_state_init(GAState *s, GACommandState *cs)
2503 #if defined(CONFIG_FSFREEZE)
2504 ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
2505 #endif