xref: /openbmc/qemu/qga/commands-posix.c (revision 05e385d2)
1 /*
2  * QEMU Guest Agent POSIX-specific command implementations
3  *
4  * Copyright IBM Corp. 2011
5  *
6  * Authors:
7  *  Michael Roth      <mdroth@linux.vnet.ibm.com>
8  *  Michal Privoznik  <mprivozn@redhat.com>
9  *
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.
12  */
13 
14 #include "qemu/osdep.h"
15 #include <sys/ioctl.h>
16 #include <sys/utsname.h>
17 #include <sys/wait.h>
18 #include <dirent.h>
19 #include "qga-qapi-commands.h"
20 #include "qapi/error.h"
21 #include "qapi/qmp/qerror.h"
22 #include "qemu/host-utils.h"
23 #include "qemu/sockets.h"
24 #include "qemu/base64.h"
25 #include "qemu/cutils.h"
26 #include "commands-common.h"
27 #include "block/nvme.h"
28 #include "cutils.h"
29 
30 #ifdef HAVE_UTMPX
31 #include <utmpx.h>
32 #endif
33 
34 #if defined(__linux__)
35 #include <mntent.h>
36 #include <sys/statvfs.h>
37 #include <linux/nvme_ioctl.h>
38 
39 #ifdef CONFIG_LIBUDEV
40 #include <libudev.h>
41 #endif
42 #endif
43 
44 #ifdef HAVE_GETIFADDRS
45 #include <arpa/inet.h>
46 #include <sys/socket.h>
47 #include <net/if.h>
48 #include <net/ethernet.h>
49 #include <sys/types.h>
50 #ifdef CONFIG_SOLARIS
51 #include <sys/sockio.h>
52 #endif
53 #endif
54 
55 static void ga_wait_child(pid_t pid, int *status, Error **errp)
56 {
57     pid_t rpid;
58 
59     *status = 0;
60 
61     do {
62         rpid = waitpid(pid, status, 0);
63     } while (rpid == -1 && errno == EINTR);
64 
65     if (rpid == -1) {
66         error_setg_errno(errp, errno, "failed to wait for child (pid: %d)",
67                          pid);
68         return;
69     }
70 
71     g_assert(rpid == pid);
72 }
73 
74 void qmp_guest_shutdown(bool has_mode, const char *mode, Error **errp)
75 {
76     const char *shutdown_flag;
77     Error *local_err = NULL;
78     pid_t pid;
79     int status;
80 
81 #ifdef CONFIG_SOLARIS
82     const char *powerdown_flag = "-i5";
83     const char *halt_flag = "-i0";
84     const char *reboot_flag = "-i6";
85 #elif defined(CONFIG_BSD)
86     const char *powerdown_flag = "-p";
87     const char *halt_flag = "-h";
88     const char *reboot_flag = "-r";
89 #else
90     const char *powerdown_flag = "-P";
91     const char *halt_flag = "-H";
92     const char *reboot_flag = "-r";
93 #endif
94 
95     slog("guest-shutdown called, mode: %s", mode);
96     if (!has_mode || strcmp(mode, "powerdown") == 0) {
97         shutdown_flag = powerdown_flag;
98     } else if (strcmp(mode, "halt") == 0) {
99         shutdown_flag = halt_flag;
100     } else if (strcmp(mode, "reboot") == 0) {
101         shutdown_flag = reboot_flag;
102     } else {
103         error_setg(errp,
104                    "mode is invalid (valid values are: halt|powerdown|reboot");
105         return;
106     }
107 
108     pid = fork();
109     if (pid == 0) {
110         /* child, start the shutdown */
111         setsid();
112         reopen_fd_to_null(0);
113         reopen_fd_to_null(1);
114         reopen_fd_to_null(2);
115 
116 #ifdef CONFIG_SOLARIS
117         execl("/sbin/shutdown", "shutdown", shutdown_flag, "-g0", "-y",
118               "hypervisor initiated shutdown", (char *)NULL);
119 #elif defined(CONFIG_BSD)
120         execl("/sbin/shutdown", "shutdown", shutdown_flag, "+0",
121                "hypervisor initiated shutdown", (char *)NULL);
122 #else
123         execl("/sbin/shutdown", "shutdown", "-h", shutdown_flag, "+0",
124                "hypervisor initiated shutdown", (char *)NULL);
125 #endif
126         _exit(EXIT_FAILURE);
127     } else if (pid < 0) {
128         error_setg_errno(errp, errno, "failed to create child process");
129         return;
130     }
131 
132     ga_wait_child(pid, &status, &local_err);
133     if (local_err) {
134         error_propagate(errp, local_err);
135         return;
136     }
137 
138     if (!WIFEXITED(status)) {
139         error_setg(errp, "child process has terminated abnormally");
140         return;
141     }
142 
143     if (WEXITSTATUS(status)) {
144         error_setg(errp, "child process has failed to shutdown");
145         return;
146     }
147 
148     /* succeeded */
149 }
150 
151 void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
152 {
153     int ret;
154     int status;
155     pid_t pid;
156     Error *local_err = NULL;
157     struct timeval tv;
158     static const char hwclock_path[] = "/sbin/hwclock";
159     static int hwclock_available = -1;
160 
161     if (hwclock_available < 0) {
162         hwclock_available = (access(hwclock_path, X_OK) == 0);
163     }
164 
165     if (!hwclock_available) {
166         error_setg(errp, QERR_UNSUPPORTED);
167         return;
168     }
169 
170     /* If user has passed a time, validate and set it. */
171     if (has_time) {
172         GDate date = { 0, };
173 
174         /* year-2038 will overflow in case time_t is 32bit */
175         if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
176             error_setg(errp, "Time %" PRId64 " is too large", time_ns);
177             return;
178         }
179 
180         tv.tv_sec = time_ns / 1000000000;
181         tv.tv_usec = (time_ns % 1000000000) / 1000;
182         g_date_set_time_t(&date, tv.tv_sec);
183         if (date.year < 1970 || date.year >= 2070) {
184             error_setg_errno(errp, errno, "Invalid time");
185             return;
186         }
187 
188         ret = settimeofday(&tv, NULL);
189         if (ret < 0) {
190             error_setg_errno(errp, errno, "Failed to set time to guest");
191             return;
192         }
193     }
194 
195     /* Now, if user has passed a time to set and the system time is set, we
196      * just need to synchronize the hardware clock. However, if no time was
197      * passed, user is requesting the opposite: set the system time from the
198      * hardware clock (RTC). */
199     pid = fork();
200     if (pid == 0) {
201         setsid();
202         reopen_fd_to_null(0);
203         reopen_fd_to_null(1);
204         reopen_fd_to_null(2);
205 
206         /* Use '/sbin/hwclock -w' to set RTC from the system time,
207          * or '/sbin/hwclock -s' to set the system time from RTC. */
208         execl(hwclock_path, "hwclock", has_time ? "-w" : "-s", NULL);
209         _exit(EXIT_FAILURE);
210     } else if (pid < 0) {
211         error_setg_errno(errp, errno, "failed to create child process");
212         return;
213     }
214 
215     ga_wait_child(pid, &status, &local_err);
216     if (local_err) {
217         error_propagate(errp, local_err);
218         return;
219     }
220 
221     if (!WIFEXITED(status)) {
222         error_setg(errp, "child process has terminated abnormally");
223         return;
224     }
225 
226     if (WEXITSTATUS(status)) {
227         error_setg(errp, "hwclock failed to set hardware clock to system time");
228         return;
229     }
230 }
231 
232 typedef enum {
233     RW_STATE_NEW,
234     RW_STATE_READING,
235     RW_STATE_WRITING,
236 } RwState;
237 
238 struct GuestFileHandle {
239     uint64_t id;
240     FILE *fh;
241     RwState state;
242     QTAILQ_ENTRY(GuestFileHandle) next;
243 };
244 
245 static struct {
246     QTAILQ_HEAD(, GuestFileHandle) filehandles;
247 } guest_file_state = {
248     .filehandles = QTAILQ_HEAD_INITIALIZER(guest_file_state.filehandles),
249 };
250 
251 static int64_t guest_file_handle_add(FILE *fh, Error **errp)
252 {
253     GuestFileHandle *gfh;
254     int64_t handle;
255 
256     handle = ga_get_fd_handle(ga_state, errp);
257     if (handle < 0) {
258         return -1;
259     }
260 
261     gfh = g_new0(GuestFileHandle, 1);
262     gfh->id = handle;
263     gfh->fh = fh;
264     QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);
265 
266     return handle;
267 }
268 
269 GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp)
270 {
271     GuestFileHandle *gfh;
272 
273     QTAILQ_FOREACH(gfh, &guest_file_state.filehandles, next)
274     {
275         if (gfh->id == id) {
276             return gfh;
277         }
278     }
279 
280     error_setg(errp, "handle '%" PRId64 "' has not been found", id);
281     return NULL;
282 }
283 
284 typedef const char * const ccpc;
285 
286 #ifndef O_BINARY
287 #define O_BINARY 0
288 #endif
289 
290 /* http://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html */
291 static const struct {
292     ccpc *forms;
293     int oflag_base;
294 } guest_file_open_modes[] = {
295     { (ccpc[]){ "r",          NULL }, O_RDONLY                                 },
296     { (ccpc[]){ "rb",         NULL }, O_RDONLY                      | O_BINARY },
297     { (ccpc[]){ "w",          NULL }, O_WRONLY | O_CREAT | O_TRUNC             },
298     { (ccpc[]){ "wb",         NULL }, O_WRONLY | O_CREAT | O_TRUNC  | O_BINARY },
299     { (ccpc[]){ "a",          NULL }, O_WRONLY | O_CREAT | O_APPEND            },
300     { (ccpc[]){ "ab",         NULL }, O_WRONLY | O_CREAT | O_APPEND | O_BINARY },
301     { (ccpc[]){ "r+",         NULL }, O_RDWR                                   },
302     { (ccpc[]){ "rb+", "r+b", NULL }, O_RDWR                        | O_BINARY },
303     { (ccpc[]){ "w+",         NULL }, O_RDWR   | O_CREAT | O_TRUNC             },
304     { (ccpc[]){ "wb+", "w+b", NULL }, O_RDWR   | O_CREAT | O_TRUNC  | O_BINARY },
305     { (ccpc[]){ "a+",         NULL }, O_RDWR   | O_CREAT | O_APPEND            },
306     { (ccpc[]){ "ab+", "a+b", NULL }, O_RDWR   | O_CREAT | O_APPEND | O_BINARY }
307 };
308 
309 static int
310 find_open_flag(const char *mode_str, Error **errp)
311 {
312     unsigned mode;
313 
314     for (mode = 0; mode < ARRAY_SIZE(guest_file_open_modes); ++mode) {
315         ccpc *form;
316 
317         form = guest_file_open_modes[mode].forms;
318         while (*form != NULL && strcmp(*form, mode_str) != 0) {
319             ++form;
320         }
321         if (*form != NULL) {
322             break;
323         }
324     }
325 
326     if (mode == ARRAY_SIZE(guest_file_open_modes)) {
327         error_setg(errp, "invalid file open mode '%s'", mode_str);
328         return -1;
329     }
330     return guest_file_open_modes[mode].oflag_base | O_NOCTTY | O_NONBLOCK;
331 }
332 
333 #define DEFAULT_NEW_FILE_MODE (S_IRUSR | S_IWUSR | \
334                                S_IRGRP | S_IWGRP | \
335                                S_IROTH | S_IWOTH)
336 
337 static FILE *
338 safe_open_or_create(const char *path, const char *mode, Error **errp)
339 {
340     int oflag;
341     int fd = -1;
342     FILE *f = NULL;
343 
344     oflag = find_open_flag(mode, errp);
345     if (oflag < 0) {
346         goto end;
347     }
348 
349     /* If the caller wants / allows creation of a new file, we implement it
350      * with a two step process: open() + (open() / fchmod()).
351      *
352      * First we insist on creating the file exclusively as a new file. If
353      * that succeeds, we're free to set any file-mode bits on it. (The
354      * motivation is that we want to set those file-mode bits independently
355      * of the current umask.)
356      *
357      * If the exclusive creation fails because the file already exists
358      * (EEXIST is not possible for any other reason), we just attempt to
359      * open the file, but in this case we won't be allowed to change the
360      * file-mode bits on the preexistent file.
361      *
362      * The pathname should never disappear between the two open()s in
363      * practice. If it happens, then someone very likely tried to race us.
364      * In this case just go ahead and report the ENOENT from the second
365      * open() to the caller.
366      *
367      * If the caller wants to open a preexistent file, then the first
368      * open() is decisive and its third argument is ignored, and the second
369      * open() and the fchmod() are never called.
370      */
371     fd = qga_open_cloexec(path, oflag | ((oflag & O_CREAT) ? O_EXCL : 0), 0);
372     if (fd == -1 && errno == EEXIST) {
373         oflag &= ~(unsigned)O_CREAT;
374         fd = qga_open_cloexec(path, oflag, 0);
375     }
376     if (fd == -1) {
377         error_setg_errno(errp, errno,
378                          "failed to open file '%s' (mode: '%s')",
379                          path, mode);
380         goto end;
381     }
382 
383     if ((oflag & O_CREAT) && fchmod(fd, DEFAULT_NEW_FILE_MODE) == -1) {
384         error_setg_errno(errp, errno, "failed to set permission "
385                          "0%03o on new file '%s' (mode: '%s')",
386                          (unsigned)DEFAULT_NEW_FILE_MODE, path, mode);
387         goto end;
388     }
389 
390     f = fdopen(fd, mode);
391     if (f == NULL) {
392         error_setg_errno(errp, errno, "failed to associate stdio stream with "
393                          "file descriptor %d, file '%s' (mode: '%s')",
394                          fd, path, mode);
395     }
396 
397 end:
398     if (f == NULL && fd != -1) {
399         close(fd);
400         if (oflag & O_CREAT) {
401             unlink(path);
402         }
403     }
404     return f;
405 }
406 
407 int64_t qmp_guest_file_open(const char *path, bool has_mode, const char *mode,
408                             Error **errp)
409 {
410     FILE *fh;
411     Error *local_err = NULL;
412     int64_t handle;
413 
414     if (!has_mode) {
415         mode = "r";
416     }
417     slog("guest-file-open called, filepath: %s, mode: %s", path, mode);
418     fh = safe_open_or_create(path, mode, &local_err);
419     if (local_err != NULL) {
420         error_propagate(errp, local_err);
421         return -1;
422     }
423 
424     /* set fd non-blocking to avoid common use cases (like reading from a
425      * named pipe) from hanging the agent
426      */
427     if (!g_unix_set_fd_nonblocking(fileno(fh), true, NULL)) {
428         fclose(fh);
429         error_setg_errno(errp, errno, "Failed to set FD nonblocking");
430         return -1;
431     }
432 
433     handle = guest_file_handle_add(fh, errp);
434     if (handle < 0) {
435         fclose(fh);
436         return -1;
437     }
438 
439     slog("guest-file-open, handle: %" PRId64, handle);
440     return handle;
441 }
442 
443 void qmp_guest_file_close(int64_t handle, Error **errp)
444 {
445     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
446     int ret;
447 
448     slog("guest-file-close called, handle: %" PRId64, handle);
449     if (!gfh) {
450         return;
451     }
452 
453     ret = fclose(gfh->fh);
454     if (ret == EOF) {
455         error_setg_errno(errp, errno, "failed to close handle");
456         return;
457     }
458 
459     QTAILQ_REMOVE(&guest_file_state.filehandles, gfh, next);
460     g_free(gfh);
461 }
462 
463 GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
464                                       int64_t count, Error **errp)
465 {
466     GuestFileRead *read_data = NULL;
467     guchar *buf;
468     FILE *fh = gfh->fh;
469     size_t read_count;
470 
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;
477         }
478         gfh->state = RW_STATE_NEW;
479     }
480 
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     } else {
486         buf[read_count] = 0;
487         read_data = g_new0(GuestFileRead, 1);
488         read_data->count = read_count;
489         read_data->eof = feof(fh);
490         if (read_count) {
491             read_data->buf_b64 = g_base64_encode(buf, read_count);
492         }
493         gfh->state = RW_STATE_READING;
494     }
495     g_free(buf);
496     clearerr(fh);
497 
498     return read_data;
499 }
500 
501 GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,
502                                      bool has_count, int64_t count,
503                                      Error **errp)
504 {
505     GuestFileWrite *write_data = NULL;
506     guchar *buf;
507     gsize buf_len;
508     int write_count;
509     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
510     FILE *fh;
511 
512     if (!gfh) {
513         return NULL;
514     }
515 
516     fh = gfh->fh;
517 
518     if (gfh->state == RW_STATE_READING) {
519         int ret = fseek(fh, 0, SEEK_CUR);
520         if (ret == -1) {
521             error_setg_errno(errp, errno, "failed to seek file");
522             return NULL;
523         }
524         gfh->state = RW_STATE_NEW;
525     }
526 
527     buf = qbase64_decode(buf_b64, -1, &buf_len, errp);
528     if (!buf) {
529         return NULL;
530     }
531 
532     if (!has_count) {
533         count = buf_len;
534     } else if (count < 0 || count > buf_len) {
535         error_setg(errp, "value '%" PRId64 "' is invalid for argument count",
536                    count);
537         g_free(buf);
538         return NULL;
539     }
540 
541     write_count = fwrite(buf, 1, count, fh);
542     if (ferror(fh)) {
543         error_setg_errno(errp, errno, "failed to write to file");
544         slog("guest-file-write failed, handle: %" PRId64, handle);
545     } else {
546         write_data = g_new0(GuestFileWrite, 1);
547         write_data->count = write_count;
548         write_data->eof = feof(fh);
549         gfh->state = RW_STATE_WRITING;
550     }
551     g_free(buf);
552     clearerr(fh);
553 
554     return write_data;
555 }
556 
557 struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,
558                                           GuestFileWhence *whence_code,
559                                           Error **errp)
560 {
561     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
562     GuestFileSeek *seek_data = NULL;
563     FILE *fh;
564     int ret;
565     int whence;
566     Error *err = NULL;
567 
568     if (!gfh) {
569         return NULL;
570     }
571 
572     /* We stupidly exposed 'whence':'int' in our qapi */
573     whence = ga_parse_whence(whence_code, &err);
574     if (err) {
575         error_propagate(errp, err);
576         return NULL;
577     }
578 
579     fh = gfh->fh;
580     ret = fseek(fh, offset, whence);
581     if (ret == -1) {
582         error_setg_errno(errp, errno, "failed to seek file");
583         if (errno == ESPIPE) {
584             /* file is non-seekable, stdio shouldn't be buffering anyways */
585             gfh->state = RW_STATE_NEW;
586         }
587     } else {
588         seek_data = g_new0(GuestFileSeek, 1);
589         seek_data->position = ftell(fh);
590         seek_data->eof = feof(fh);
591         gfh->state = RW_STATE_NEW;
592     }
593     clearerr(fh);
594 
595     return seek_data;
596 }
597 
598 void qmp_guest_file_flush(int64_t handle, Error **errp)
599 {
600     GuestFileHandle *gfh = guest_file_handle_find(handle, errp);
601     FILE *fh;
602     int ret;
603 
604     if (!gfh) {
605         return;
606     }
607 
608     fh = gfh->fh;
609     ret = fflush(fh);
610     if (ret == EOF) {
611         error_setg_errno(errp, errno, "failed to flush file");
612     } else {
613         gfh->state = RW_STATE_NEW;
614     }
615 }
616 
617 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
618 void free_fs_mount_list(FsMountList *mounts)
619 {
620      FsMount *mount, *temp;
621 
622      if (!mounts) {
623          return;
624      }
625 
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);
631      }
632 }
633 #endif
634 
635 #if defined(CONFIG_FSFREEZE)
636 typedef enum {
637     FSFREEZE_HOOK_THAW = 0,
638     FSFREEZE_HOOK_FREEZE,
639 } FsfreezeHookArg;
640 
641 static const char *fsfreeze_hook_arg_string[] = {
642     "thaw",
643     "freeze",
644 };
645 
646 static void execute_fsfreeze_hook(FsfreezeHookArg arg, Error **errp)
647 {
648     int status;
649     pid_t pid;
650     const char *hook;
651     const char *arg_str = fsfreeze_hook_arg_string[arg];
652     Error *local_err = NULL;
653 
654     hook = ga_fsfreeze_hook(ga_state);
655     if (!hook) {
656         return;
657     }
658     if (access(hook, X_OK) != 0) {
659         error_setg_errno(errp, errno, "can't access fsfreeze hook '%s'", hook);
660         return;
661     }
662 
663     slog("executing fsfreeze hook with arg '%s'", arg_str);
664     pid = fork();
665     if (pid == 0) {
666         setsid();
667         reopen_fd_to_null(0);
668         reopen_fd_to_null(1);
669         reopen_fd_to_null(2);
670 
671         execl(hook, hook, arg_str, NULL);
672         _exit(EXIT_FAILURE);
673     } else if (pid < 0) {
674         error_setg_errno(errp, errno, "failed to create child process");
675         return;
676     }
677 
678     ga_wait_child(pid, &status, &local_err);
679     if (local_err) {
680         error_propagate(errp, local_err);
681         return;
682     }
683 
684     if (!WIFEXITED(status)) {
685         error_setg(errp, "fsfreeze hook has terminated abnormally");
686         return;
687     }
688 
689     status = WEXITSTATUS(status);
690     if (status) {
691         error_setg(errp, "fsfreeze hook has failed with status %d", status);
692         return;
693     }
694 }
695 
696 /*
697  * Return status of freeze/thaw
698  */
699 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
700 {
701     if (ga_is_frozen(ga_state)) {
702         return GUEST_FSFREEZE_STATUS_FROZEN;
703     }
704 
705     return GUEST_FSFREEZE_STATUS_THAWED;
706 }
707 
708 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
709 {
710     return qmp_guest_fsfreeze_freeze_list(false, NULL, errp);
711 }
712 
713 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
714                                        strList *mountpoints,
715                                        Error **errp)
716 {
717     int ret;
718     FsMountList mounts;
719     Error *local_err = NULL;
720 
721     slog("guest-fsfreeze called");
722 
723     execute_fsfreeze_hook(FSFREEZE_HOOK_FREEZE, &local_err);
724     if (local_err) {
725         error_propagate(errp, local_err);
726         return -1;
727     }
728 
729     QTAILQ_INIT(&mounts);
730     if (!build_fs_mount_list(&mounts, &local_err)) {
731         error_propagate(errp, local_err);
732         return -1;
733     }
734 
735     /* cannot risk guest agent blocking itself on a write in this state */
736     ga_set_frozen(ga_state);
737 
738     ret = qmp_guest_fsfreeze_do_freeze_list(has_mountpoints, mountpoints,
739                                             mounts, errp);
740 
741     free_fs_mount_list(&mounts);
742     /* We may not issue any FIFREEZE here.
743      * Just unset ga_state here and ready for the next call.
744      */
745     if (ret == 0) {
746         ga_unset_frozen(ga_state);
747     } else if (ret < 0) {
748         qmp_guest_fsfreeze_thaw(NULL);
749     }
750     return ret;
751 }
752 
753 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
754 {
755     int ret;
756 
757     ret = qmp_guest_fsfreeze_do_thaw(errp);
758     if (ret >= 0) {
759         ga_unset_frozen(ga_state);
760         execute_fsfreeze_hook(FSFREEZE_HOOK_THAW, errp);
761     } else {
762         ret = 0;
763     }
764 
765     return ret;
766 }
767 
768 static void guest_fsfreeze_cleanup(void)
769 {
770     Error *err = NULL;
771 
772     if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {
773         qmp_guest_fsfreeze_thaw(&err);
774         if (err) {
775             slog("failed to clean up frozen filesystems: %s",
776                  error_get_pretty(err));
777             error_free(err);
778         }
779     }
780 }
781 #endif
782 
783 /* linux-specific implementations. avoid this if at all possible. */
784 #if defined(__linux__)
785 #if defined(CONFIG_FSFREEZE)
786 
787 static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
788 {
789     char *path;
790     char *dpath;
791     char *driver = NULL;
792     char buf[PATH_MAX];
793     ssize_t len;
794 
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_path_get_basename(buf);
801     }
802     g_free(dpath);
803     g_free(path);
804     return driver;
805 }
806 
807 static int compare_uint(const void *_a, const void *_b)
808 {
809     unsigned int a = *(unsigned int *)_a;
810     unsigned int b = *(unsigned int *)_b;
811 
812     return a < b ? -1 : a > b ? 1 : 0;
813 }
814 
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)
818 {
819     char *path;
820     DIR *dir;
821     struct dirent *entry;
822     int i = 0;
823 
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;
830     }
831 
832     while (i < hosts_max) {
833         entry = readdir(dir);
834         if (!entry) {
835             break;
836         }
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;
841         }
842     }
843 
844     qsort(hosts, i, sizeof(hosts[0]), compare_uint);
845 
846     g_free(path);
847     closedir(dir);
848     return i;
849 }
850 
851 /*
852  * Store disk device info for devices on the PCI bus.
853  * Returns true if information has been stored, or false for failure.
854  */
855 static bool build_guest_fsinfo_for_pci_dev(char const *syspath,
856                                            GuestDiskAddress *disk,
857                                            Error **errp)
858 {
859     unsigned int pci[4], host, hosts[8], tgt[3];
860     int i, nhosts = 0, pcilen;
861     GuestPCIAddress *pciaddr = disk->pci_controller;
862     bool has_ata = false, has_host = false, has_tgt = false;
863     char *p, *q, *driver = NULL;
864     bool ret = false;
865 
866     p = strstr(syspath, "/devices/pci");
867     if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
868                      pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
869         g_debug("only pci device is supported: sysfs path '%s'", syspath);
870         return false;
871     }
872 
873     p += 12 + pcilen;
874     while (true) {
875         driver = get_pci_driver(syspath, p - syspath, errp);
876         if (driver && (g_str_equal(driver, "ata_piix") ||
877                        g_str_equal(driver, "sym53c8xx") ||
878                        g_str_equal(driver, "virtio-pci") ||
879                        g_str_equal(driver, "ahci") ||
880                        g_str_equal(driver, "nvme"))) {
881             break;
882         }
883 
884         g_free(driver);
885         if (sscanf(p, "/%x:%x:%x.%x%n",
886                           pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) {
887             p += pcilen;
888             continue;
889         }
890 
891         g_debug("unsupported driver or sysfs path '%s'", syspath);
892         return false;
893     }
894 
895     p = strstr(syspath, "/target");
896     if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
897                     tgt, tgt + 1, tgt + 2) == 3) {
898         has_tgt = true;
899     }
900 
901     p = strstr(syspath, "/ata");
902     if (p) {
903         q = p + 4;
904         has_ata = true;
905     } else {
906         p = strstr(syspath, "/host");
907         q = p + 5;
908     }
909     if (p && sscanf(q, "%u", &host) == 1) {
910         has_host = true;
911         nhosts = build_hosts(syspath, p, has_ata, hosts,
912                              ARRAY_SIZE(hosts), errp);
913         if (nhosts < 0) {
914             goto cleanup;
915         }
916     }
917 
918     pciaddr->domain = pci[0];
919     pciaddr->bus = pci[1];
920     pciaddr->slot = pci[2];
921     pciaddr->function = pci[3];
922 
923     if (strcmp(driver, "ata_piix") == 0) {
924         /* a host per ide bus, target*:0:<unit>:0 */
925         if (!has_host || !has_tgt) {
926             g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
927             goto cleanup;
928         }
929         for (i = 0; i < nhosts; i++) {
930             if (host == hosts[i]) {
931                 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
932                 disk->bus = i;
933                 disk->unit = tgt[1];
934                 break;
935             }
936         }
937         if (i >= nhosts) {
938             g_debug("no host for '%s' (driver '%s')", syspath, driver);
939             goto cleanup;
940         }
941     } else if (strcmp(driver, "sym53c8xx") == 0) {
942         /* scsi(LSI Logic): target*:0:<unit>:0 */
943         if (!has_tgt) {
944             g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
945             goto cleanup;
946         }
947         disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
948         disk->unit = tgt[1];
949     } else if (strcmp(driver, "virtio-pci") == 0) {
950         if (has_tgt) {
951             /* virtio-scsi: target*:0:0:<unit> */
952             disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
953             disk->unit = tgt[2];
954         } else {
955             /* virtio-blk: 1 disk per 1 device */
956             disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
957         }
958     } else if (strcmp(driver, "ahci") == 0) {
959         /* ahci: 1 host per 1 unit */
960         if (!has_host || !has_tgt) {
961             g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
962             goto cleanup;
963         }
964         for (i = 0; i < nhosts; i++) {
965             if (host == hosts[i]) {
966                 disk->unit = i;
967                 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
968                 break;
969             }
970         }
971         if (i >= nhosts) {
972             g_debug("no host for '%s' (driver '%s')", syspath, driver);
973             goto cleanup;
974         }
975     } else if (strcmp(driver, "nvme") == 0) {
976         disk->bus_type = GUEST_DISK_BUS_TYPE_NVME;
977     } else {
978         g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
979         goto cleanup;
980     }
981 
982     ret = true;
983 
984 cleanup:
985     g_free(driver);
986     return ret;
987 }
988 
989 /*
990  * Store disk device info for non-PCI virtio devices (for example s390x
991  * channel I/O devices). Returns true if information has been stored, or
992  * false for failure.
993  */
994 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath,
995                                                  GuestDiskAddress *disk,
996                                                  Error **errp)
997 {
998     unsigned int tgt[3];
999     char *p;
1000 
1001     if (!strstr(syspath, "/virtio") || !strstr(syspath, "/block")) {
1002         g_debug("Unsupported virtio device '%s'", syspath);
1003         return false;
1004     }
1005 
1006     p = strstr(syspath, "/target");
1007     if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
1008                     &tgt[0], &tgt[1], &tgt[2]) == 3) {
1009         /* virtio-scsi: target*:0:<target>:<unit> */
1010         disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
1011         disk->bus = tgt[0];
1012         disk->target = tgt[1];
1013         disk->unit = tgt[2];
1014     } else {
1015         /* virtio-blk: 1 disk per 1 device */
1016         disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
1017     }
1018 
1019     return true;
1020 }
1021 
1022 /*
1023  * Store disk device info for CCW devices (s390x channel I/O devices).
1024  * Returns true if information has been stored, or false for failure.
1025  */
1026 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath,
1027                                            GuestDiskAddress *disk,
1028                                            Error **errp)
1029 {
1030     unsigned int cssid, ssid, subchno, devno;
1031     char *p;
1032 
1033     p = strstr(syspath, "/devices/css");
1034     if (!p || sscanf(p + 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
1035                      &cssid, &ssid, &subchno, &devno) < 4) {
1036         g_debug("could not parse ccw device sysfs path: %s", syspath);
1037         return false;
1038     }
1039 
1040     disk->has_ccw_address = true;
1041     disk->ccw_address = g_new0(GuestCCWAddress, 1);
1042     disk->ccw_address->cssid = cssid;
1043     disk->ccw_address->ssid = ssid;
1044     disk->ccw_address->subchno = subchno;
1045     disk->ccw_address->devno = devno;
1046 
1047     if (strstr(p, "/virtio")) {
1048         build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
1049     }
1050 
1051     return true;
1052 }
1053 
1054 /* Store disk device info specified by @sysfs into @fs */
1055 static void build_guest_fsinfo_for_real_device(char const *syspath,
1056                                                GuestFilesystemInfo *fs,
1057                                                Error **errp)
1058 {
1059     GuestDiskAddress *disk;
1060     GuestPCIAddress *pciaddr;
1061     bool has_hwinf;
1062 #ifdef CONFIG_LIBUDEV
1063     struct udev *udev = NULL;
1064     struct udev_device *udevice = NULL;
1065 #endif
1066 
1067     pciaddr = g_new0(GuestPCIAddress, 1);
1068     pciaddr->domain = -1;                       /* -1 means field is invalid */
1069     pciaddr->bus = -1;
1070     pciaddr->slot = -1;
1071     pciaddr->function = -1;
1072 
1073     disk = g_new0(GuestDiskAddress, 1);
1074     disk->pci_controller = pciaddr;
1075     disk->bus_type = GUEST_DISK_BUS_TYPE_UNKNOWN;
1076 
1077 #ifdef CONFIG_LIBUDEV
1078     udev = udev_new();
1079     udevice = udev_device_new_from_syspath(udev, syspath);
1080     if (udev == NULL || udevice == NULL) {
1081         g_debug("failed to query udev");
1082     } else {
1083         const char *devnode, *serial;
1084         devnode = udev_device_get_devnode(udevice);
1085         if (devnode != NULL) {
1086             disk->dev = g_strdup(devnode);
1087             disk->has_dev = true;
1088         }
1089         serial = udev_device_get_property_value(udevice, "ID_SERIAL");
1090         if (serial != NULL && *serial != 0) {
1091             disk->serial = g_strdup(serial);
1092             disk->has_serial = true;
1093         }
1094     }
1095 
1096     udev_unref(udev);
1097     udev_device_unref(udevice);
1098 #endif
1099 
1100     if (strstr(syspath, "/devices/pci")) {
1101         has_hwinf = build_guest_fsinfo_for_pci_dev(syspath, disk, errp);
1102     } else if (strstr(syspath, "/devices/css")) {
1103         has_hwinf = build_guest_fsinfo_for_ccw_dev(syspath, disk, errp);
1104     } else if (strstr(syspath, "/virtio")) {
1105         has_hwinf = build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
1106     } else {
1107         g_debug("Unsupported device type for '%s'", syspath);
1108         has_hwinf = false;
1109     }
1110 
1111     if (has_hwinf || disk->has_dev || disk->has_serial) {
1112         QAPI_LIST_PREPEND(fs->disk, disk);
1113     } else {
1114         qapi_free_GuestDiskAddress(disk);
1115     }
1116 }
1117 
1118 static void build_guest_fsinfo_for_device(char const *devpath,
1119                                           GuestFilesystemInfo *fs,
1120                                           Error **errp);
1121 
1122 /* Store a list of slave devices of virtual volume specified by @syspath into
1123  * @fs */
1124 static void build_guest_fsinfo_for_virtual_device(char const *syspath,
1125                                                   GuestFilesystemInfo *fs,
1126                                                   Error **errp)
1127 {
1128     Error *err = NULL;
1129     DIR *dir;
1130     char *dirpath;
1131     struct dirent *entry;
1132 
1133     dirpath = g_strdup_printf("%s/slaves", syspath);
1134     dir = opendir(dirpath);
1135     if (!dir) {
1136         if (errno != ENOENT) {
1137             error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
1138         }
1139         g_free(dirpath);
1140         return;
1141     }
1142 
1143     for (;;) {
1144         errno = 0;
1145         entry = readdir(dir);
1146         if (entry == NULL) {
1147             if (errno) {
1148                 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
1149             }
1150             break;
1151         }
1152 
1153         if (entry->d_type == DT_LNK) {
1154             char *path;
1155 
1156             g_debug(" slave device '%s'", entry->d_name);
1157             path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
1158             build_guest_fsinfo_for_device(path, fs, &err);
1159             g_free(path);
1160 
1161             if (err) {
1162                 error_propagate(errp, err);
1163                 break;
1164             }
1165         }
1166     }
1167 
1168     g_free(dirpath);
1169     closedir(dir);
1170 }
1171 
1172 static bool is_disk_virtual(const char *devpath, Error **errp)
1173 {
1174     g_autofree char *syspath = realpath(devpath, NULL);
1175 
1176     if (!syspath) {
1177         error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1178         return false;
1179     }
1180     return strstr(syspath, "/devices/virtual/block/") != NULL;
1181 }
1182 
1183 /* Dispatch to functions for virtual/real device */
1184 static void build_guest_fsinfo_for_device(char const *devpath,
1185                                           GuestFilesystemInfo *fs,
1186                                           Error **errp)
1187 {
1188     ERRP_GUARD();
1189     g_autofree char *syspath = NULL;
1190     bool is_virtual = false;
1191 
1192     syspath = realpath(devpath, NULL);
1193     if (!syspath) {
1194         if (errno != ENOENT) {
1195             error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
1196             return;
1197         }
1198 
1199         /* ENOENT: This devpath may not exist because of container config */
1200         if (!fs->name) {
1201             fs->name = g_path_get_basename(devpath);
1202         }
1203         return;
1204     }
1205 
1206     if (!fs->name) {
1207         fs->name = g_path_get_basename(syspath);
1208     }
1209 
1210     g_debug("  parse sysfs path '%s'", syspath);
1211     is_virtual = is_disk_virtual(syspath, errp);
1212     if (*errp != NULL) {
1213         return;
1214     }
1215     if (is_virtual) {
1216         build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
1217     } else {
1218         build_guest_fsinfo_for_real_device(syspath, fs, errp);
1219     }
1220 }
1221 
1222 #ifdef CONFIG_LIBUDEV
1223 
1224 /*
1225  * Wrapper around build_guest_fsinfo_for_device() for getting just
1226  * the disk address.
1227  */
1228 static GuestDiskAddress *get_disk_address(const char *syspath, Error **errp)
1229 {
1230     g_autoptr(GuestFilesystemInfo) fs = NULL;
1231 
1232     fs = g_new0(GuestFilesystemInfo, 1);
1233     build_guest_fsinfo_for_device(syspath, fs, errp);
1234     if (fs->disk != NULL) {
1235         return g_steal_pointer(&fs->disk->value);
1236     }
1237     return NULL;
1238 }
1239 
1240 static char *get_alias_for_syspath(const char *syspath)
1241 {
1242     struct udev *udev = NULL;
1243     struct udev_device *udevice = NULL;
1244     char *ret = NULL;
1245 
1246     udev = udev_new();
1247     if (udev == NULL) {
1248         g_debug("failed to query udev");
1249         goto out;
1250     }
1251     udevice = udev_device_new_from_syspath(udev, syspath);
1252     if (udevice == NULL) {
1253         g_debug("failed to query udev for path: %s", syspath);
1254         goto out;
1255     } else {
1256         const char *alias = udev_device_get_property_value(
1257             udevice, "DM_NAME");
1258         /*
1259          * NULL means there was an error and empty string means there is no
1260          * alias. In case of no alias we return NULL instead of empty string.
1261          */
1262         if (alias == NULL) {
1263             g_debug("failed to query udev for device alias for: %s",
1264                 syspath);
1265         } else if (*alias != 0) {
1266             ret = g_strdup(alias);
1267         }
1268     }
1269 
1270 out:
1271     udev_unref(udev);
1272     udev_device_unref(udevice);
1273     return ret;
1274 }
1275 
1276 static char *get_device_for_syspath(const char *syspath)
1277 {
1278     struct udev *udev = NULL;
1279     struct udev_device *udevice = NULL;
1280     char *ret = NULL;
1281 
1282     udev = udev_new();
1283     if (udev == NULL) {
1284         g_debug("failed to query udev");
1285         goto out;
1286     }
1287     udevice = udev_device_new_from_syspath(udev, syspath);
1288     if (udevice == NULL) {
1289         g_debug("failed to query udev for path: %s", syspath);
1290         goto out;
1291     } else {
1292         ret = g_strdup(udev_device_get_devnode(udevice));
1293     }
1294 
1295 out:
1296     udev_unref(udev);
1297     udev_device_unref(udevice);
1298     return ret;
1299 }
1300 
1301 static void get_disk_deps(const char *disk_dir, GuestDiskInfo *disk)
1302 {
1303     g_autofree char *deps_dir = NULL;
1304     const gchar *dep;
1305     GDir *dp_deps = NULL;
1306 
1307     /* List dependent disks */
1308     deps_dir = g_strdup_printf("%s/slaves", disk_dir);
1309     g_debug("  listing entries in: %s", deps_dir);
1310     dp_deps = g_dir_open(deps_dir, 0, NULL);
1311     if (dp_deps == NULL) {
1312         g_debug("failed to list entries in %s", deps_dir);
1313         return;
1314     }
1315     disk->has_dependencies = true;
1316     while ((dep = g_dir_read_name(dp_deps)) != NULL) {
1317         g_autofree char *dep_dir = NULL;
1318         char *dev_name;
1319 
1320         /* Add dependent disks */
1321         dep_dir = g_strdup_printf("%s/%s", deps_dir, dep);
1322         dev_name = get_device_for_syspath(dep_dir);
1323         if (dev_name != NULL) {
1324             g_debug("  adding dependent device: %s", dev_name);
1325             QAPI_LIST_PREPEND(disk->dependencies, dev_name);
1326         }
1327     }
1328     g_dir_close(dp_deps);
1329 }
1330 
1331 /*
1332  * Detect partitions subdirectory, name is "<disk_name><number>" or
1333  * "<disk_name>p<number>"
1334  *
1335  * @disk_name -- last component of /sys path (e.g. sda)
1336  * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
1337  * @disk_dev -- device node of the disk (e.g. /dev/sda)
1338  */
1339 static GuestDiskInfoList *get_disk_partitions(
1340     GuestDiskInfoList *list,
1341     const char *disk_name, const char *disk_dir,
1342     const char *disk_dev)
1343 {
1344     GuestDiskInfoList *ret = list;
1345     struct dirent *de_disk;
1346     DIR *dp_disk = NULL;
1347     size_t len = strlen(disk_name);
1348 
1349     dp_disk = opendir(disk_dir);
1350     while ((de_disk = readdir(dp_disk)) != NULL) {
1351         g_autofree char *partition_dir = NULL;
1352         char *dev_name;
1353         GuestDiskInfo *partition;
1354 
1355         if (!(de_disk->d_type & DT_DIR)) {
1356             continue;
1357         }
1358 
1359         if (!(strncmp(disk_name, de_disk->d_name, len) == 0 &&
1360             ((*(de_disk->d_name + len) == 'p' &&
1361             isdigit(*(de_disk->d_name + len + 1))) ||
1362                 isdigit(*(de_disk->d_name + len))))) {
1363             continue;
1364         }
1365 
1366         partition_dir = g_strdup_printf("%s/%s",
1367             disk_dir, de_disk->d_name);
1368         dev_name = get_device_for_syspath(partition_dir);
1369         if (dev_name == NULL) {
1370             g_debug("Failed to get device name for syspath: %s",
1371                 disk_dir);
1372             continue;
1373         }
1374         partition = g_new0(GuestDiskInfo, 1);
1375         partition->name = dev_name;
1376         partition->partition = true;
1377         partition->has_dependencies = true;
1378         /* Add parent disk as dependent for easier tracking of hierarchy */
1379         QAPI_LIST_PREPEND(partition->dependencies, g_strdup(disk_dev));
1380 
1381         QAPI_LIST_PREPEND(ret, partition);
1382     }
1383     closedir(dp_disk);
1384 
1385     return ret;
1386 }
1387 
1388 static void get_nvme_smart(GuestDiskInfo *disk)
1389 {
1390     int fd;
1391     GuestNVMeSmart *smart;
1392     NvmeSmartLog log = {0};
1393     struct nvme_admin_cmd cmd = {
1394         .opcode = NVME_ADM_CMD_GET_LOG_PAGE,
1395         .nsid = NVME_NSID_BROADCAST,
1396         .addr = (uintptr_t)&log,
1397         .data_len = sizeof(log),
1398         .cdw10 = NVME_LOG_SMART_INFO | (1 << 15) /* RAE bit */
1399                  | (((sizeof(log) >> 2) - 1) << 16)
1400     };
1401 
1402     fd = qga_open_cloexec(disk->name, O_RDONLY, 0);
1403     if (fd == -1) {
1404         g_debug("Failed to open device: %s: %s", disk->name, g_strerror(errno));
1405         return;
1406     }
1407 
1408     if (ioctl(fd, NVME_IOCTL_ADMIN_CMD, &cmd)) {
1409         g_debug("Failed to get smart: %s: %s", disk->name, g_strerror(errno));
1410         close(fd);
1411         return;
1412     }
1413 
1414     disk->has_smart = true;
1415     disk->smart = g_new0(GuestDiskSmart, 1);
1416     disk->smart->type = GUEST_DISK_BUS_TYPE_NVME;
1417 
1418     smart = &disk->smart->u.nvme;
1419     smart->critical_warning = log.critical_warning;
1420     smart->temperature = lduw_le_p(&log.temperature); /* unaligned field */
1421     smart->available_spare = log.available_spare;
1422     smart->available_spare_threshold = log.available_spare_threshold;
1423     smart->percentage_used = log.percentage_used;
1424     smart->data_units_read_lo = le64_to_cpu(log.data_units_read[0]);
1425     smart->data_units_read_hi = le64_to_cpu(log.data_units_read[1]);
1426     smart->data_units_written_lo = le64_to_cpu(log.data_units_written[0]);
1427     smart->data_units_written_hi = le64_to_cpu(log.data_units_written[1]);
1428     smart->host_read_commands_lo = le64_to_cpu(log.host_read_commands[0]);
1429     smart->host_read_commands_hi = le64_to_cpu(log.host_read_commands[1]);
1430     smart->host_write_commands_lo = le64_to_cpu(log.host_write_commands[0]);
1431     smart->host_write_commands_hi = le64_to_cpu(log.host_write_commands[1]);
1432     smart->controller_busy_time_lo = le64_to_cpu(log.controller_busy_time[0]);
1433     smart->controller_busy_time_hi = le64_to_cpu(log.controller_busy_time[1]);
1434     smart->power_cycles_lo = le64_to_cpu(log.power_cycles[0]);
1435     smart->power_cycles_hi = le64_to_cpu(log.power_cycles[1]);
1436     smart->power_on_hours_lo = le64_to_cpu(log.power_on_hours[0]);
1437     smart->power_on_hours_hi = le64_to_cpu(log.power_on_hours[1]);
1438     smart->unsafe_shutdowns_lo = le64_to_cpu(log.unsafe_shutdowns[0]);
1439     smart->unsafe_shutdowns_hi = le64_to_cpu(log.unsafe_shutdowns[1]);
1440     smart->media_errors_lo = le64_to_cpu(log.media_errors[0]);
1441     smart->media_errors_hi = le64_to_cpu(log.media_errors[1]);
1442     smart->number_of_error_log_entries_lo =
1443         le64_to_cpu(log.number_of_error_log_entries[0]);
1444     smart->number_of_error_log_entries_hi =
1445         le64_to_cpu(log.number_of_error_log_entries[1]);
1446 
1447     close(fd);
1448 }
1449 
1450 static void get_disk_smart(GuestDiskInfo *disk)
1451 {
1452     if (disk->has_address
1453         && (disk->address->bus_type == GUEST_DISK_BUS_TYPE_NVME)) {
1454         get_nvme_smart(disk);
1455     }
1456 }
1457 
1458 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1459 {
1460     GuestDiskInfoList *ret = NULL;
1461     GuestDiskInfo *disk;
1462     DIR *dp = NULL;
1463     struct dirent *de = NULL;
1464 
1465     g_debug("listing /sys/block directory");
1466     dp = opendir("/sys/block");
1467     if (dp == NULL) {
1468         error_setg_errno(errp, errno, "Can't open directory \"/sys/block\"");
1469         return NULL;
1470     }
1471     while ((de = readdir(dp)) != NULL) {
1472         g_autofree char *disk_dir = NULL, *line = NULL,
1473             *size_path = NULL;
1474         char *dev_name;
1475         Error *local_err = NULL;
1476         if (de->d_type != DT_LNK) {
1477             g_debug("  skipping entry: %s", de->d_name);
1478             continue;
1479         }
1480 
1481         /* Check size and skip zero-sized disks */
1482         g_debug("  checking disk size");
1483         size_path = g_strdup_printf("/sys/block/%s/size", de->d_name);
1484         if (!g_file_get_contents(size_path, &line, NULL, NULL)) {
1485             g_debug("  failed to read disk size");
1486             continue;
1487         }
1488         if (g_strcmp0(line, "0\n") == 0) {
1489             g_debug("  skipping zero-sized disk");
1490             continue;
1491         }
1492 
1493         g_debug("  adding %s", de->d_name);
1494         disk_dir = g_strdup_printf("/sys/block/%s", de->d_name);
1495         dev_name = get_device_for_syspath(disk_dir);
1496         if (dev_name == NULL) {
1497             g_debug("Failed to get device name for syspath: %s",
1498                 disk_dir);
1499             continue;
1500         }
1501         disk = g_new0(GuestDiskInfo, 1);
1502         disk->name = dev_name;
1503         disk->partition = false;
1504         disk->alias = get_alias_for_syspath(disk_dir);
1505         disk->has_alias = (disk->alias != NULL);
1506         QAPI_LIST_PREPEND(ret, disk);
1507 
1508         /* Get address for non-virtual devices */
1509         bool is_virtual = is_disk_virtual(disk_dir, &local_err);
1510         if (local_err != NULL) {
1511             g_debug("  failed to check disk path, ignoring error: %s",
1512                 error_get_pretty(local_err));
1513             error_free(local_err);
1514             local_err = NULL;
1515             /* Don't try to get the address */
1516             is_virtual = true;
1517         }
1518         if (!is_virtual) {
1519             disk->address = get_disk_address(disk_dir, &local_err);
1520             if (local_err != NULL) {
1521                 g_debug("  failed to get device info, ignoring error: %s",
1522                     error_get_pretty(local_err));
1523                 error_free(local_err);
1524                 local_err = NULL;
1525             } else if (disk->address != NULL) {
1526                 disk->has_address = true;
1527             }
1528         }
1529 
1530         get_disk_deps(disk_dir, disk);
1531         get_disk_smart(disk);
1532         ret = get_disk_partitions(ret, de->d_name, disk_dir, dev_name);
1533     }
1534 
1535     closedir(dp);
1536 
1537     return ret;
1538 }
1539 
1540 #else
1541 
1542 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1543 {
1544     error_setg(errp, QERR_UNSUPPORTED);
1545     return NULL;
1546 }
1547 
1548 #endif
1549 
1550 /* Return a list of the disk device(s)' info which @mount lies on */
1551 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1552                                                Error **errp)
1553 {
1554     GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1555     struct statvfs buf;
1556     unsigned long used, nonroot_total, fr_size;
1557     char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1558                                     mount->devmajor, mount->devminor);
1559 
1560     fs->mountpoint = g_strdup(mount->dirname);
1561     fs->type = g_strdup(mount->devtype);
1562     build_guest_fsinfo_for_device(devpath, fs, errp);
1563 
1564     if (statvfs(fs->mountpoint, &buf) == 0) {
1565         fr_size = buf.f_frsize;
1566         used = buf.f_blocks - buf.f_bfree;
1567         nonroot_total = used + buf.f_bavail;
1568         fs->used_bytes = used * fr_size;
1569         fs->total_bytes = nonroot_total * fr_size;
1570 
1571         fs->has_total_bytes = true;
1572         fs->has_used_bytes = true;
1573     }
1574 
1575     g_free(devpath);
1576 
1577     return fs;
1578 }
1579 
1580 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1581 {
1582     FsMountList mounts;
1583     struct FsMount *mount;
1584     GuestFilesystemInfoList *ret = NULL;
1585     Error *local_err = NULL;
1586 
1587     QTAILQ_INIT(&mounts);
1588     if (!build_fs_mount_list(&mounts, &local_err)) {
1589         error_propagate(errp, local_err);
1590         return NULL;
1591     }
1592 
1593     QTAILQ_FOREACH(mount, &mounts, next) {
1594         g_debug("Building guest fsinfo for '%s'", mount->dirname);
1595 
1596         QAPI_LIST_PREPEND(ret, build_guest_fsinfo(mount, &local_err));
1597         if (local_err) {
1598             error_propagate(errp, local_err);
1599             qapi_free_GuestFilesystemInfoList(ret);
1600             ret = NULL;
1601             break;
1602         }
1603     }
1604 
1605     free_fs_mount_list(&mounts);
1606     return ret;
1607 }
1608 #endif /* CONFIG_FSFREEZE */
1609 
1610 #if defined(CONFIG_FSTRIM)
1611 /*
1612  * Walk list of mounted file systems in the guest, and trim them.
1613  */
1614 GuestFilesystemTrimResponse *
1615 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1616 {
1617     GuestFilesystemTrimResponse *response;
1618     GuestFilesystemTrimResult *result;
1619     int ret = 0;
1620     FsMountList mounts;
1621     struct FsMount *mount;
1622     int fd;
1623     struct fstrim_range r;
1624 
1625     slog("guest-fstrim called");
1626 
1627     QTAILQ_INIT(&mounts);
1628     if (!build_fs_mount_list(&mounts, errp)) {
1629         return NULL;
1630     }
1631 
1632     response = g_malloc0(sizeof(*response));
1633 
1634     QTAILQ_FOREACH(mount, &mounts, next) {
1635         result = g_malloc0(sizeof(*result));
1636         result->path = g_strdup(mount->dirname);
1637 
1638         QAPI_LIST_PREPEND(response->paths, result);
1639 
1640         fd = qga_open_cloexec(mount->dirname, O_RDONLY, 0);
1641         if (fd == -1) {
1642             result->error = g_strdup_printf("failed to open: %s",
1643                                             strerror(errno));
1644             result->has_error = true;
1645             continue;
1646         }
1647 
1648         /* We try to cull filesystems we know won't work in advance, but other
1649          * filesystems may not implement fstrim for less obvious reasons.
1650          * These will report EOPNOTSUPP; while in some other cases ENOTTY
1651          * will be reported (e.g. CD-ROMs).
1652          * Any other error means an unexpected error.
1653          */
1654         r.start = 0;
1655         r.len = -1;
1656         r.minlen = has_minimum ? minimum : 0;
1657         ret = ioctl(fd, FITRIM, &r);
1658         if (ret == -1) {
1659             result->has_error = true;
1660             if (errno == ENOTTY || errno == EOPNOTSUPP) {
1661                 result->error = g_strdup("trim not supported");
1662             } else {
1663                 result->error = g_strdup_printf("failed to trim: %s",
1664                                                 strerror(errno));
1665             }
1666             close(fd);
1667             continue;
1668         }
1669 
1670         result->has_minimum = true;
1671         result->minimum = r.minlen;
1672         result->has_trimmed = true;
1673         result->trimmed = r.len;
1674         close(fd);
1675     }
1676 
1677     free_fs_mount_list(&mounts);
1678     return response;
1679 }
1680 #endif /* CONFIG_FSTRIM */
1681 
1682 
1683 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1684 #define SUSPEND_SUPPORTED 0
1685 #define SUSPEND_NOT_SUPPORTED 1
1686 
1687 typedef enum {
1688     SUSPEND_MODE_DISK = 0,
1689     SUSPEND_MODE_RAM = 1,
1690     SUSPEND_MODE_HYBRID = 2,
1691 } SuspendMode;
1692 
1693 /*
1694  * Executes a command in a child process using g_spawn_sync,
1695  * returning an int >= 0 representing the exit status of the
1696  * process.
1697  *
1698  * If the program wasn't found in path, returns -1.
1699  *
1700  * If a problem happened when creating the child process,
1701  * returns -1 and errp is set.
1702  */
1703 static int run_process_child(const char *command[], Error **errp)
1704 {
1705     int exit_status, spawn_flag;
1706     GError *g_err = NULL;
1707     bool success;
1708 
1709     spawn_flag = G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL |
1710                  G_SPAWN_STDERR_TO_DEV_NULL;
1711 
1712     success =  g_spawn_sync(NULL, (char **)command, NULL, spawn_flag,
1713                             NULL, NULL, NULL, NULL,
1714                             &exit_status, &g_err);
1715 
1716     if (success) {
1717         return WEXITSTATUS(exit_status);
1718     }
1719 
1720     if (g_err && (g_err->code != G_SPAWN_ERROR_NOENT)) {
1721         error_setg(errp, "failed to create child process, error '%s'",
1722                    g_err->message);
1723     }
1724 
1725     g_error_free(g_err);
1726     return -1;
1727 }
1728 
1729 static bool systemd_supports_mode(SuspendMode mode, Error **errp)
1730 {
1731     const char *systemctl_args[3] = {"systemd-hibernate", "systemd-suspend",
1732                                      "systemd-hybrid-sleep"};
1733     const char *cmd[4] = {"systemctl", "status", systemctl_args[mode], NULL};
1734     int status;
1735 
1736     status = run_process_child(cmd, errp);
1737 
1738     /*
1739      * systemctl status uses LSB return codes so we can expect
1740      * status > 0 and be ok. To assert if the guest has support
1741      * for the selected suspend mode, status should be < 4. 4 is
1742      * the code for unknown service status, the return value when
1743      * the service does not exist. A common value is status = 3
1744      * (program is not running).
1745      */
1746     if (status > 0 && status < 4) {
1747         return true;
1748     }
1749 
1750     return false;
1751 }
1752 
1753 static void systemd_suspend(SuspendMode mode, Error **errp)
1754 {
1755     Error *local_err = NULL;
1756     const char *systemctl_args[3] = {"hibernate", "suspend", "hybrid-sleep"};
1757     const char *cmd[3] = {"systemctl", systemctl_args[mode], NULL};
1758     int status;
1759 
1760     status = run_process_child(cmd, &local_err);
1761 
1762     if (status == 0) {
1763         return;
1764     }
1765 
1766     if ((status == -1) && !local_err) {
1767         error_setg(errp, "the helper program 'systemctl %s' was not found",
1768                    systemctl_args[mode]);
1769         return;
1770     }
1771 
1772     if (local_err) {
1773         error_propagate(errp, local_err);
1774     } else {
1775         error_setg(errp, "the helper program 'systemctl %s' returned an "
1776                    "unexpected exit status code (%d)",
1777                    systemctl_args[mode], status);
1778     }
1779 }
1780 
1781 static bool pmutils_supports_mode(SuspendMode mode, Error **errp)
1782 {
1783     Error *local_err = NULL;
1784     const char *pmutils_args[3] = {"--hibernate", "--suspend",
1785                                    "--suspend-hybrid"};
1786     const char *cmd[3] = {"pm-is-supported", pmutils_args[mode], NULL};
1787     int status;
1788 
1789     status = run_process_child(cmd, &local_err);
1790 
1791     if (status == SUSPEND_SUPPORTED) {
1792         return true;
1793     }
1794 
1795     if ((status == -1) && !local_err) {
1796         return false;
1797     }
1798 
1799     if (local_err) {
1800         error_propagate(errp, local_err);
1801     } else {
1802         error_setg(errp,
1803                    "the helper program '%s' returned an unexpected exit"
1804                    " status code (%d)", "pm-is-supported", status);
1805     }
1806 
1807     return false;
1808 }
1809 
1810 static void pmutils_suspend(SuspendMode mode, Error **errp)
1811 {
1812     Error *local_err = NULL;
1813     const char *pmutils_binaries[3] = {"pm-hibernate", "pm-suspend",
1814                                        "pm-suspend-hybrid"};
1815     const char *cmd[2] = {pmutils_binaries[mode], NULL};
1816     int status;
1817 
1818     status = run_process_child(cmd, &local_err);
1819 
1820     if (status == 0) {
1821         return;
1822     }
1823 
1824     if ((status == -1) && !local_err) {
1825         error_setg(errp, "the helper program '%s' was not found",
1826                    pmutils_binaries[mode]);
1827         return;
1828     }
1829 
1830     if (local_err) {
1831         error_propagate(errp, local_err);
1832     } else {
1833         error_setg(errp,
1834                    "the helper program '%s' returned an unexpected exit"
1835                    " status code (%d)", pmutils_binaries[mode], status);
1836     }
1837 }
1838 
1839 static bool linux_sys_state_supports_mode(SuspendMode mode, Error **errp)
1840 {
1841     const char *sysfile_strs[3] = {"disk", "mem", NULL};
1842     const char *sysfile_str = sysfile_strs[mode];
1843     char buf[32]; /* hopefully big enough */
1844     int fd;
1845     ssize_t ret;
1846 
1847     if (!sysfile_str) {
1848         error_setg(errp, "unknown guest suspend mode");
1849         return false;
1850     }
1851 
1852     fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
1853     if (fd < 0) {
1854         return false;
1855     }
1856 
1857     ret = read(fd, buf, sizeof(buf) - 1);
1858     close(fd);
1859     if (ret <= 0) {
1860         return false;
1861     }
1862     buf[ret] = '\0';
1863 
1864     if (strstr(buf, sysfile_str)) {
1865         return true;
1866     }
1867     return false;
1868 }
1869 
1870 static void linux_sys_state_suspend(SuspendMode mode, Error **errp)
1871 {
1872     Error *local_err = NULL;
1873     const char *sysfile_strs[3] = {"disk", "mem", NULL};
1874     const char *sysfile_str = sysfile_strs[mode];
1875     pid_t pid;
1876     int status;
1877 
1878     if (!sysfile_str) {
1879         error_setg(errp, "unknown guest suspend mode");
1880         return;
1881     }
1882 
1883     pid = fork();
1884     if (!pid) {
1885         /* child */
1886         int fd;
1887 
1888         setsid();
1889         reopen_fd_to_null(0);
1890         reopen_fd_to_null(1);
1891         reopen_fd_to_null(2);
1892 
1893         fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
1894         if (fd < 0) {
1895             _exit(EXIT_FAILURE);
1896         }
1897 
1898         if (write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
1899             _exit(EXIT_FAILURE);
1900         }
1901 
1902         _exit(EXIT_SUCCESS);
1903     } else if (pid < 0) {
1904         error_setg_errno(errp, errno, "failed to create child process");
1905         return;
1906     }
1907 
1908     ga_wait_child(pid, &status, &local_err);
1909     if (local_err) {
1910         error_propagate(errp, local_err);
1911         return;
1912     }
1913 
1914     if (WEXITSTATUS(status)) {
1915         error_setg(errp, "child process has failed to suspend");
1916     }
1917 
1918 }
1919 
1920 static void guest_suspend(SuspendMode mode, Error **errp)
1921 {
1922     Error *local_err = NULL;
1923     bool mode_supported = false;
1924 
1925     if (systemd_supports_mode(mode, &local_err)) {
1926         mode_supported = true;
1927         systemd_suspend(mode, &local_err);
1928     }
1929 
1930     if (!local_err) {
1931         return;
1932     }
1933 
1934     error_free(local_err);
1935     local_err = NULL;
1936 
1937     if (pmutils_supports_mode(mode, &local_err)) {
1938         mode_supported = true;
1939         pmutils_suspend(mode, &local_err);
1940     }
1941 
1942     if (!local_err) {
1943         return;
1944     }
1945 
1946     error_free(local_err);
1947     local_err = NULL;
1948 
1949     if (linux_sys_state_supports_mode(mode, &local_err)) {
1950         mode_supported = true;
1951         linux_sys_state_suspend(mode, &local_err);
1952     }
1953 
1954     if (!mode_supported) {
1955         error_free(local_err);
1956         error_setg(errp,
1957                    "the requested suspend mode is not supported by the guest");
1958     } else {
1959         error_propagate(errp, local_err);
1960     }
1961 }
1962 
1963 void qmp_guest_suspend_disk(Error **errp)
1964 {
1965     guest_suspend(SUSPEND_MODE_DISK, errp);
1966 }
1967 
1968 void qmp_guest_suspend_ram(Error **errp)
1969 {
1970     guest_suspend(SUSPEND_MODE_RAM, errp);
1971 }
1972 
1973 void qmp_guest_suspend_hybrid(Error **errp)
1974 {
1975     guest_suspend(SUSPEND_MODE_HYBRID, errp);
1976 }
1977 
1978 /* Transfer online/offline status between @vcpu and the guest system.
1979  *
1980  * On input either @errp or *@errp must be NULL.
1981  *
1982  * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1983  * - R: vcpu->logical_id
1984  * - W: vcpu->online
1985  * - W: vcpu->can_offline
1986  *
1987  * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1988  * - R: vcpu->logical_id
1989  * - R: vcpu->online
1990  *
1991  * Written members remain unmodified on error.
1992  */
1993 static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
1994                           char *dirpath, Error **errp)
1995 {
1996     int fd;
1997     int res;
1998     int dirfd;
1999     static const char fn[] = "online";
2000 
2001     dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2002     if (dirfd == -1) {
2003         error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2004         return;
2005     }
2006 
2007     fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
2008     if (fd == -1) {
2009         if (errno != ENOENT) {
2010             error_setg_errno(errp, errno, "open(\"%s/%s\")", dirpath, fn);
2011         } else if (sys2vcpu) {
2012             vcpu->online = true;
2013             vcpu->can_offline = false;
2014         } else if (!vcpu->online) {
2015             error_setg(errp, "logical processor #%" PRId64 " can't be "
2016                        "offlined", vcpu->logical_id);
2017         } /* otherwise pretend successful re-onlining */
2018     } else {
2019         unsigned char status;
2020 
2021         res = pread(fd, &status, 1, 0);
2022         if (res == -1) {
2023             error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
2024         } else if (res == 0) {
2025             error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
2026                        fn);
2027         } else if (sys2vcpu) {
2028             vcpu->online = (status != '0');
2029             vcpu->can_offline = true;
2030         } else if (vcpu->online != (status != '0')) {
2031             status = '0' + vcpu->online;
2032             if (pwrite(fd, &status, 1, 0) == -1) {
2033                 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
2034                                  fn);
2035             }
2036         } /* otherwise pretend successful re-(on|off)-lining */
2037 
2038         res = close(fd);
2039         g_assert(res == 0);
2040     }
2041 
2042     res = close(dirfd);
2043     g_assert(res == 0);
2044 }
2045 
2046 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2047 {
2048     GuestLogicalProcessorList *head, **tail;
2049     const char *cpu_dir = "/sys/devices/system/cpu";
2050     const gchar *line;
2051     g_autoptr(GDir) cpu_gdir = NULL;
2052     Error *local_err = NULL;
2053 
2054     head = NULL;
2055     tail = &head;
2056     cpu_gdir = g_dir_open(cpu_dir, 0, NULL);
2057 
2058     if (cpu_gdir == NULL) {
2059         error_setg_errno(errp, errno, "failed to list entries: %s", cpu_dir);
2060         return NULL;
2061     }
2062 
2063     while (local_err == NULL && (line = g_dir_read_name(cpu_gdir)) != NULL) {
2064         GuestLogicalProcessor *vcpu;
2065         int64_t id;
2066         if (sscanf(line, "cpu%" PRId64, &id)) {
2067             g_autofree char *path = g_strdup_printf("/sys/devices/system/cpu/"
2068                                                     "cpu%" PRId64 "/", id);
2069             vcpu = g_malloc0(sizeof *vcpu);
2070             vcpu->logical_id = id;
2071             vcpu->has_can_offline = true; /* lolspeak ftw */
2072             transfer_vcpu(vcpu, true, path, &local_err);
2073             QAPI_LIST_APPEND(tail, vcpu);
2074         }
2075     }
2076 
2077     if (local_err == NULL) {
2078         /* there's no guest with zero VCPUs */
2079         g_assert(head != NULL);
2080         return head;
2081     }
2082 
2083     qapi_free_GuestLogicalProcessorList(head);
2084     error_propagate(errp, local_err);
2085     return NULL;
2086 }
2087 
2088 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2089 {
2090     int64_t processed;
2091     Error *local_err = NULL;
2092 
2093     processed = 0;
2094     while (vcpus != NULL) {
2095         char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
2096                                      vcpus->value->logical_id);
2097 
2098         transfer_vcpu(vcpus->value, false, path, &local_err);
2099         g_free(path);
2100         if (local_err != NULL) {
2101             break;
2102         }
2103         ++processed;
2104         vcpus = vcpus->next;
2105     }
2106 
2107     if (local_err != NULL) {
2108         if (processed == 0) {
2109             error_propagate(errp, local_err);
2110         } else {
2111             error_free(local_err);
2112         }
2113     }
2114 
2115     return processed;
2116 }
2117 #endif /* __linux__ */
2118 
2119 #if defined(__linux__) || defined(__FreeBSD__)
2120 void qmp_guest_set_user_password(const char *username,
2121                                  const char *password,
2122                                  bool crypted,
2123                                  Error **errp)
2124 {
2125     Error *local_err = NULL;
2126     char *passwd_path = NULL;
2127     pid_t pid;
2128     int status;
2129     int datafd[2] = { -1, -1 };
2130     char *rawpasswddata = NULL;
2131     size_t rawpasswdlen;
2132     char *chpasswddata = NULL;
2133     size_t chpasswdlen;
2134 
2135     rawpasswddata = (char *)qbase64_decode(password, -1, &rawpasswdlen, errp);
2136     if (!rawpasswddata) {
2137         return;
2138     }
2139     rawpasswddata = g_renew(char, rawpasswddata, rawpasswdlen + 1);
2140     rawpasswddata[rawpasswdlen] = '\0';
2141 
2142     if (strchr(rawpasswddata, '\n')) {
2143         error_setg(errp, "forbidden characters in raw password");
2144         goto out;
2145     }
2146 
2147     if (strchr(username, '\n') ||
2148         strchr(username, ':')) {
2149         error_setg(errp, "forbidden characters in username");
2150         goto out;
2151     }
2152 
2153 #ifdef __FreeBSD__
2154     chpasswddata = g_strdup(rawpasswddata);
2155     passwd_path = g_find_program_in_path("pw");
2156 #else
2157     chpasswddata = g_strdup_printf("%s:%s\n", username, rawpasswddata);
2158     passwd_path = g_find_program_in_path("chpasswd");
2159 #endif
2160 
2161     chpasswdlen = strlen(chpasswddata);
2162 
2163     if (!passwd_path) {
2164         error_setg(errp, "cannot find 'passwd' program in PATH");
2165         goto out;
2166     }
2167 
2168     if (!g_unix_open_pipe(datafd, FD_CLOEXEC, NULL)) {
2169         error_setg(errp, "cannot create pipe FDs");
2170         goto out;
2171     }
2172 
2173     pid = fork();
2174     if (pid == 0) {
2175         close(datafd[1]);
2176         /* child */
2177         setsid();
2178         dup2(datafd[0], 0);
2179         reopen_fd_to_null(1);
2180         reopen_fd_to_null(2);
2181 
2182 #ifdef __FreeBSD__
2183         const char *h_arg;
2184         h_arg = (crypted) ? "-H" : "-h";
2185         execl(passwd_path, "pw", "usermod", "-n", username, h_arg, "0", NULL);
2186 #else
2187         if (crypted) {
2188             execl(passwd_path, "chpasswd", "-e", NULL);
2189         } else {
2190             execl(passwd_path, "chpasswd", NULL);
2191         }
2192 #endif
2193         _exit(EXIT_FAILURE);
2194     } else if (pid < 0) {
2195         error_setg_errno(errp, errno, "failed to create child process");
2196         goto out;
2197     }
2198     close(datafd[0]);
2199     datafd[0] = -1;
2200 
2201     if (qemu_write_full(datafd[1], chpasswddata, chpasswdlen) != chpasswdlen) {
2202         error_setg_errno(errp, errno, "cannot write new account password");
2203         goto out;
2204     }
2205     close(datafd[1]);
2206     datafd[1] = -1;
2207 
2208     ga_wait_child(pid, &status, &local_err);
2209     if (local_err) {
2210         error_propagate(errp, local_err);
2211         goto out;
2212     }
2213 
2214     if (!WIFEXITED(status)) {
2215         error_setg(errp, "child process has terminated abnormally");
2216         goto out;
2217     }
2218 
2219     if (WEXITSTATUS(status)) {
2220         error_setg(errp, "child process has failed to set user password");
2221         goto out;
2222     }
2223 
2224 out:
2225     g_free(chpasswddata);
2226     g_free(rawpasswddata);
2227     g_free(passwd_path);
2228     if (datafd[0] != -1) {
2229         close(datafd[0]);
2230     }
2231     if (datafd[1] != -1) {
2232         close(datafd[1]);
2233     }
2234 }
2235 #else /* __linux__ || __FreeBSD__ */
2236 void qmp_guest_set_user_password(const char *username,
2237                                  const char *password,
2238                                  bool crypted,
2239                                  Error **errp)
2240 {
2241     error_setg(errp, QERR_UNSUPPORTED);
2242 }
2243 #endif /* __linux__ || __FreeBSD__ */
2244 
2245 #ifdef __linux__
2246 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
2247                                int size, Error **errp)
2248 {
2249     int fd;
2250     int res;
2251 
2252     errno = 0;
2253     fd = openat(dirfd, pathname, O_RDONLY);
2254     if (fd == -1) {
2255         error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2256         return;
2257     }
2258 
2259     res = pread(fd, buf, size, 0);
2260     if (res == -1) {
2261         error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
2262     } else if (res == 0) {
2263         error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
2264     }
2265     close(fd);
2266 }
2267 
2268 static void ga_write_sysfs_file(int dirfd, const char *pathname,
2269                                 const char *buf, int size, Error **errp)
2270 {
2271     int fd;
2272 
2273     errno = 0;
2274     fd = openat(dirfd, pathname, O_WRONLY);
2275     if (fd == -1) {
2276         error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
2277         return;
2278     }
2279 
2280     if (pwrite(fd, buf, size, 0) == -1) {
2281         error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
2282     }
2283 
2284     close(fd);
2285 }
2286 
2287 /* Transfer online/offline status between @mem_blk and the guest system.
2288  *
2289  * On input either @errp or *@errp must be NULL.
2290  *
2291  * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
2292  * - R: mem_blk->phys_index
2293  * - W: mem_blk->online
2294  * - W: mem_blk->can_offline
2295  *
2296  * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
2297  * - R: mem_blk->phys_index
2298  * - R: mem_blk->online
2299  *-  R: mem_blk->can_offline
2300  * Written members remain unmodified on error.
2301  */
2302 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
2303                                   GuestMemoryBlockResponse *result,
2304                                   Error **errp)
2305 {
2306     char *dirpath;
2307     int dirfd;
2308     char *status;
2309     Error *local_err = NULL;
2310 
2311     if (!sys2memblk) {
2312         DIR *dp;
2313 
2314         if (!result) {
2315             error_setg(errp, "Internal error, 'result' should not be NULL");
2316             return;
2317         }
2318         errno = 0;
2319         dp = opendir("/sys/devices/system/memory/");
2320          /* if there is no 'memory' directory in sysfs,
2321          * we think this VM does not support online/offline memory block,
2322          * any other solution?
2323          */
2324         if (!dp) {
2325             if (errno == ENOENT) {
2326                 result->response =
2327                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2328             }
2329             goto out1;
2330         }
2331         closedir(dp);
2332     }
2333 
2334     dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
2335                               mem_blk->phys_index);
2336     dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2337     if (dirfd == -1) {
2338         if (sys2memblk) {
2339             error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2340         } else {
2341             if (errno == ENOENT) {
2342                 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
2343             } else {
2344                 result->response =
2345                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2346             }
2347         }
2348         g_free(dirpath);
2349         goto out1;
2350     }
2351     g_free(dirpath);
2352 
2353     status = g_malloc0(10);
2354     ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
2355     if (local_err) {
2356         /* treat with sysfs file that not exist in old kernel */
2357         if (errno == ENOENT) {
2358             error_free(local_err);
2359             if (sys2memblk) {
2360                 mem_blk->online = true;
2361                 mem_blk->can_offline = false;
2362             } else if (!mem_blk->online) {
2363                 result->response =
2364                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
2365             }
2366         } else {
2367             if (sys2memblk) {
2368                 error_propagate(errp, local_err);
2369             } else {
2370                 error_free(local_err);
2371                 result->response =
2372                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2373             }
2374         }
2375         goto out2;
2376     }
2377 
2378     if (sys2memblk) {
2379         char removable = '0';
2380 
2381         mem_blk->online = (strncmp(status, "online", 6) == 0);
2382 
2383         ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
2384         if (local_err) {
2385             /* if no 'removable' file, it doesn't support offline mem blk */
2386             if (errno == ENOENT) {
2387                 error_free(local_err);
2388                 mem_blk->can_offline = false;
2389             } else {
2390                 error_propagate(errp, local_err);
2391             }
2392         } else {
2393             mem_blk->can_offline = (removable != '0');
2394         }
2395     } else {
2396         if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
2397             const char *new_state = mem_blk->online ? "online" : "offline";
2398 
2399             ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
2400                                 &local_err);
2401             if (local_err) {
2402                 error_free(local_err);
2403                 result->response =
2404                     GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
2405                 goto out2;
2406             }
2407 
2408             result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
2409             result->has_error_code = false;
2410         } /* otherwise pretend successful re-(on|off)-lining */
2411     }
2412     g_free(status);
2413     close(dirfd);
2414     return;
2415 
2416 out2:
2417     g_free(status);
2418     close(dirfd);
2419 out1:
2420     if (!sys2memblk) {
2421         result->has_error_code = true;
2422         result->error_code = errno;
2423     }
2424 }
2425 
2426 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2427 {
2428     GuestMemoryBlockList *head, **tail;
2429     Error *local_err = NULL;
2430     struct dirent *de;
2431     DIR *dp;
2432 
2433     head = NULL;
2434     tail = &head;
2435 
2436     dp = opendir("/sys/devices/system/memory/");
2437     if (!dp) {
2438         /* it's ok if this happens to be a system that doesn't expose
2439          * memory blocks via sysfs, but otherwise we should report
2440          * an error
2441          */
2442         if (errno != ENOENT) {
2443             error_setg_errno(errp, errno, "Can't open directory"
2444                              "\"/sys/devices/system/memory/\"");
2445         }
2446         return NULL;
2447     }
2448 
2449     /* Note: the phys_index of memory block may be discontinuous,
2450      * this is because a memblk is the unit of the Sparse Memory design, which
2451      * allows discontinuous memory ranges (ex. NUMA), so here we should
2452      * traverse the memory block directory.
2453      */
2454     while ((de = readdir(dp)) != NULL) {
2455         GuestMemoryBlock *mem_blk;
2456 
2457         if ((strncmp(de->d_name, "memory", 6) != 0) ||
2458             !(de->d_type & DT_DIR)) {
2459             continue;
2460         }
2461 
2462         mem_blk = g_malloc0(sizeof *mem_blk);
2463         /* The d_name is "memoryXXX",  phys_index is block id, same as XXX */
2464         mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
2465         mem_blk->has_can_offline = true; /* lolspeak ftw */
2466         transfer_memory_block(mem_blk, true, NULL, &local_err);
2467         if (local_err) {
2468             break;
2469         }
2470 
2471         QAPI_LIST_APPEND(tail, mem_blk);
2472     }
2473 
2474     closedir(dp);
2475     if (local_err == NULL) {
2476         /* there's no guest with zero memory blocks */
2477         if (head == NULL) {
2478             error_setg(errp, "guest reported zero memory blocks!");
2479         }
2480         return head;
2481     }
2482 
2483     qapi_free_GuestMemoryBlockList(head);
2484     error_propagate(errp, local_err);
2485     return NULL;
2486 }
2487 
2488 GuestMemoryBlockResponseList *
2489 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2490 {
2491     GuestMemoryBlockResponseList *head, **tail;
2492     Error *local_err = NULL;
2493 
2494     head = NULL;
2495     tail = &head;
2496 
2497     while (mem_blks != NULL) {
2498         GuestMemoryBlockResponse *result;
2499         GuestMemoryBlock *current_mem_blk = mem_blks->value;
2500 
2501         result = g_malloc0(sizeof(*result));
2502         result->phys_index = current_mem_blk->phys_index;
2503         transfer_memory_block(current_mem_blk, false, result, &local_err);
2504         if (local_err) { /* should never happen */
2505             goto err;
2506         }
2507 
2508         QAPI_LIST_APPEND(tail, result);
2509         mem_blks = mem_blks->next;
2510     }
2511 
2512     return head;
2513 err:
2514     qapi_free_GuestMemoryBlockResponseList(head);
2515     error_propagate(errp, local_err);
2516     return NULL;
2517 }
2518 
2519 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2520 {
2521     Error *local_err = NULL;
2522     char *dirpath;
2523     int dirfd;
2524     char *buf;
2525     GuestMemoryBlockInfo *info;
2526 
2527     dirpath = g_strdup_printf("/sys/devices/system/memory/");
2528     dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
2529     if (dirfd == -1) {
2530         error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
2531         g_free(dirpath);
2532         return NULL;
2533     }
2534     g_free(dirpath);
2535 
2536     buf = g_malloc0(20);
2537     ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
2538     close(dirfd);
2539     if (local_err) {
2540         g_free(buf);
2541         error_propagate(errp, local_err);
2542         return NULL;
2543     }
2544 
2545     info = g_new0(GuestMemoryBlockInfo, 1);
2546     info->size = strtol(buf, NULL, 16); /* the unit is bytes */
2547 
2548     g_free(buf);
2549 
2550     return info;
2551 }
2552 
2553 #define MAX_NAME_LEN 128
2554 static GuestDiskStatsInfoList *guest_get_diskstats(Error **errp)
2555 {
2556 #ifdef CONFIG_LINUX
2557     GuestDiskStatsInfoList *head = NULL, **tail = &head;
2558     const char *diskstats = "/proc/diskstats";
2559     FILE *fp;
2560     size_t n;
2561     char *line = NULL;
2562 
2563     fp = fopen(diskstats, "r");
2564     if (fp  == NULL) {
2565         error_setg_errno(errp, errno, "open(\"%s\")", diskstats);
2566         return NULL;
2567     }
2568 
2569     while (getline(&line, &n, fp) != -1) {
2570         g_autofree GuestDiskStatsInfo *diskstatinfo = NULL;
2571         g_autofree GuestDiskStats *diskstat = NULL;
2572         char dev_name[MAX_NAME_LEN];
2573         unsigned int ios_pgr, tot_ticks, rq_ticks, wr_ticks, dc_ticks, fl_ticks;
2574         unsigned long rd_ios, rd_merges_or_rd_sec, rd_ticks_or_wr_sec, wr_ios;
2575         unsigned long wr_merges, rd_sec_or_wr_ios, wr_sec;
2576         unsigned long dc_ios, dc_merges, dc_sec, fl_ios;
2577         unsigned int major, minor;
2578         int i;
2579 
2580         i = sscanf(line, "%u %u %s %lu %lu %lu"
2581                    "%lu %lu %lu %lu %u %u %u %u"
2582                    "%lu %lu %lu %u %lu %u",
2583                    &major, &minor, dev_name,
2584                    &rd_ios, &rd_merges_or_rd_sec, &rd_sec_or_wr_ios,
2585                    &rd_ticks_or_wr_sec, &wr_ios, &wr_merges, &wr_sec,
2586                    &wr_ticks, &ios_pgr, &tot_ticks, &rq_ticks,
2587                    &dc_ios, &dc_merges, &dc_sec, &dc_ticks,
2588                    &fl_ios, &fl_ticks);
2589 
2590         if (i < 7) {
2591             continue;
2592         }
2593 
2594         diskstatinfo = g_new0(GuestDiskStatsInfo, 1);
2595         diskstatinfo->name = g_strdup(dev_name);
2596         diskstatinfo->major = major;
2597         diskstatinfo->minor = minor;
2598 
2599         diskstat = g_new0(GuestDiskStats, 1);
2600         if (i == 7) {
2601             diskstat->has_read_ios = true;
2602             diskstat->read_ios = rd_ios;
2603             diskstat->has_read_sectors = true;
2604             diskstat->read_sectors = rd_merges_or_rd_sec;
2605             diskstat->has_write_ios = true;
2606             diskstat->write_ios = rd_sec_or_wr_ios;
2607             diskstat->has_write_sectors = true;
2608             diskstat->write_sectors = rd_ticks_or_wr_sec;
2609         }
2610         if (i >= 14) {
2611             diskstat->has_read_ios = true;
2612             diskstat->read_ios = rd_ios;
2613             diskstat->has_read_sectors = true;
2614             diskstat->read_sectors = rd_sec_or_wr_ios;
2615             diskstat->has_read_merges = true;
2616             diskstat->read_merges = rd_merges_or_rd_sec;
2617             diskstat->has_read_ticks = true;
2618             diskstat->read_ticks = rd_ticks_or_wr_sec;
2619             diskstat->has_write_ios = true;
2620             diskstat->write_ios = wr_ios;
2621             diskstat->has_write_sectors = true;
2622             diskstat->write_sectors = wr_sec;
2623             diskstat->has_write_merges = true;
2624             diskstat->write_merges = wr_merges;
2625             diskstat->has_write_ticks = true;
2626             diskstat->write_ticks = wr_ticks;
2627             diskstat->has_ios_pgr = true;
2628             diskstat->ios_pgr = ios_pgr;
2629             diskstat->has_total_ticks = true;
2630             diskstat->total_ticks = tot_ticks;
2631             diskstat->has_weight_ticks = true;
2632             diskstat->weight_ticks = rq_ticks;
2633         }
2634         if (i >= 18) {
2635             diskstat->has_discard_ios = true;
2636             diskstat->discard_ios = dc_ios;
2637             diskstat->has_discard_merges = true;
2638             diskstat->discard_merges = dc_merges;
2639             diskstat->has_discard_sectors = true;
2640             diskstat->discard_sectors = dc_sec;
2641             diskstat->has_discard_ticks = true;
2642             diskstat->discard_ticks = dc_ticks;
2643         }
2644         if (i >= 20) {
2645             diskstat->has_flush_ios = true;
2646             diskstat->flush_ios = fl_ios;
2647             diskstat->has_flush_ticks = true;
2648             diskstat->flush_ticks = fl_ticks;
2649         }
2650 
2651         diskstatinfo->stats = g_steal_pointer(&diskstat);
2652         QAPI_LIST_APPEND(tail, diskstatinfo);
2653         diskstatinfo = NULL;
2654     }
2655     free(line);
2656     fclose(fp);
2657     return head;
2658 #else
2659     g_debug("disk stats reporting available only for Linux");
2660     return NULL;
2661 #endif
2662 }
2663 
2664 GuestDiskStatsInfoList *qmp_guest_get_diskstats(Error **errp)
2665 {
2666     return guest_get_diskstats(errp);
2667 }
2668 
2669 GuestCpuStatsList *qmp_guest_get_cpustats(Error **errp)
2670 {
2671     GuestCpuStatsList *head = NULL, **tail = &head;
2672     const char *cpustats = "/proc/stat";
2673     int clk_tck = sysconf(_SC_CLK_TCK);
2674     FILE *fp;
2675     size_t n;
2676     char *line = NULL;
2677 
2678     fp = fopen(cpustats, "r");
2679     if (fp  == NULL) {
2680         error_setg_errno(errp, errno, "open(\"%s\")", cpustats);
2681         return NULL;
2682     }
2683 
2684     while (getline(&line, &n, fp) != -1) {
2685         GuestCpuStats *cpustat = NULL;
2686         GuestLinuxCpuStats *linuxcpustat;
2687         int i;
2688         unsigned long user, system, idle, iowait, irq, softirq, steal, guest;
2689         unsigned long nice, guest_nice;
2690         char name[64];
2691 
2692         i = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2693                    name, &user, &nice, &system, &idle, &iowait, &irq, &softirq,
2694                    &steal, &guest, &guest_nice);
2695 
2696         /* drop "cpu 1 2 3 ...", get "cpuX 1 2 3 ..." only */
2697         if ((i == EOF) || strncmp(name, "cpu", 3) || (name[3] == '\0')) {
2698             continue;
2699         }
2700 
2701         if (i < 5) {
2702             slog("Parsing cpu stat from %s failed, see \"man proc\"", cpustats);
2703             break;
2704         }
2705 
2706         cpustat = g_new0(GuestCpuStats, 1);
2707         cpustat->type = GUEST_CPU_STATS_TYPE_LINUX;
2708 
2709         linuxcpustat = &cpustat->u.q_linux;
2710         linuxcpustat->cpu = atoi(&name[3]);
2711         linuxcpustat->user = user * 1000 / clk_tck;
2712         linuxcpustat->nice = nice * 1000 / clk_tck;
2713         linuxcpustat->system = system * 1000 / clk_tck;
2714         linuxcpustat->idle = idle * 1000 / clk_tck;
2715 
2716         if (i > 5) {
2717             linuxcpustat->has_iowait = true;
2718             linuxcpustat->iowait = iowait * 1000 / clk_tck;
2719         }
2720 
2721         if (i > 6) {
2722             linuxcpustat->has_irq = true;
2723             linuxcpustat->irq = irq * 1000 / clk_tck;
2724             linuxcpustat->has_softirq = true;
2725             linuxcpustat->softirq = softirq * 1000 / clk_tck;
2726         }
2727 
2728         if (i > 8) {
2729             linuxcpustat->has_steal = true;
2730             linuxcpustat->steal = steal * 1000 / clk_tck;
2731         }
2732 
2733         if (i > 9) {
2734             linuxcpustat->has_guest = true;
2735             linuxcpustat->guest = guest * 1000 / clk_tck;
2736         }
2737 
2738         if (i > 10) {
2739             linuxcpustat->has_guest = true;
2740             linuxcpustat->guest = guest * 1000 / clk_tck;
2741             linuxcpustat->has_guestnice = true;
2742             linuxcpustat->guestnice = guest_nice * 1000 / clk_tck;
2743         }
2744 
2745         QAPI_LIST_APPEND(tail, cpustat);
2746     }
2747 
2748     free(line);
2749     fclose(fp);
2750     return head;
2751 }
2752 
2753 #else /* defined(__linux__) */
2754 
2755 void qmp_guest_suspend_disk(Error **errp)
2756 {
2757     error_setg(errp, QERR_UNSUPPORTED);
2758 }
2759 
2760 void qmp_guest_suspend_ram(Error **errp)
2761 {
2762     error_setg(errp, QERR_UNSUPPORTED);
2763 }
2764 
2765 void qmp_guest_suspend_hybrid(Error **errp)
2766 {
2767     error_setg(errp, QERR_UNSUPPORTED);
2768 }
2769 
2770 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
2771 {
2772     error_setg(errp, QERR_UNSUPPORTED);
2773     return NULL;
2774 }
2775 
2776 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
2777 {
2778     error_setg(errp, QERR_UNSUPPORTED);
2779     return -1;
2780 }
2781 
2782 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
2783 {
2784     error_setg(errp, QERR_UNSUPPORTED);
2785     return NULL;
2786 }
2787 
2788 GuestMemoryBlockResponseList *
2789 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
2790 {
2791     error_setg(errp, QERR_UNSUPPORTED);
2792     return NULL;
2793 }
2794 
2795 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
2796 {
2797     error_setg(errp, QERR_UNSUPPORTED);
2798     return NULL;
2799 }
2800 
2801 #endif
2802 
2803 #ifdef HAVE_GETIFADDRS
2804 static GuestNetworkInterface *
2805 guest_find_interface(GuestNetworkInterfaceList *head,
2806                      const char *name)
2807 {
2808     for (; head; head = head->next) {
2809         if (strcmp(head->value->name, name) == 0) {
2810             return head->value;
2811         }
2812     }
2813 
2814     return NULL;
2815 }
2816 
2817 static int guest_get_network_stats(const char *name,
2818                        GuestNetworkInterfaceStat *stats)
2819 {
2820 #ifdef CONFIG_LINUX
2821     int name_len;
2822     char const *devinfo = "/proc/net/dev";
2823     FILE *fp;
2824     char *line = NULL, *colon;
2825     size_t n = 0;
2826     fp = fopen(devinfo, "r");
2827     if (!fp) {
2828         g_debug("failed to open network stats %s: %s", devinfo,
2829                 g_strerror(errno));
2830         return -1;
2831     }
2832     name_len = strlen(name);
2833     while (getline(&line, &n, fp) != -1) {
2834         long long dummy;
2835         long long rx_bytes;
2836         long long rx_packets;
2837         long long rx_errs;
2838         long long rx_dropped;
2839         long long tx_bytes;
2840         long long tx_packets;
2841         long long tx_errs;
2842         long long tx_dropped;
2843         char *trim_line;
2844         trim_line = g_strchug(line);
2845         if (trim_line[0] == '\0') {
2846             continue;
2847         }
2848         colon = strchr(trim_line, ':');
2849         if (!colon) {
2850             continue;
2851         }
2852         if (colon - name_len  == trim_line &&
2853            strncmp(trim_line, name, name_len) == 0) {
2854             if (sscanf(colon + 1,
2855                 "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
2856                   &rx_bytes, &rx_packets, &rx_errs, &rx_dropped,
2857                   &dummy, &dummy, &dummy, &dummy,
2858                   &tx_bytes, &tx_packets, &tx_errs, &tx_dropped,
2859                   &dummy, &dummy, &dummy, &dummy) != 16) {
2860                 continue;
2861             }
2862             stats->rx_bytes = rx_bytes;
2863             stats->rx_packets = rx_packets;
2864             stats->rx_errs = rx_errs;
2865             stats->rx_dropped = rx_dropped;
2866             stats->tx_bytes = tx_bytes;
2867             stats->tx_packets = tx_packets;
2868             stats->tx_errs = tx_errs;
2869             stats->tx_dropped = tx_dropped;
2870             fclose(fp);
2871             g_free(line);
2872             return 0;
2873         }
2874     }
2875     fclose(fp);
2876     g_free(line);
2877     g_debug("/proc/net/dev: Interface '%s' not found", name);
2878 #else /* !CONFIG_LINUX */
2879     g_debug("Network stats reporting available only for Linux");
2880 #endif /* !CONFIG_LINUX */
2881     return -1;
2882 }
2883 
2884 #ifndef __FreeBSD__
2885 /*
2886  * Fill "buf" with MAC address by ifaddrs. Pointer buf must point to a
2887  * buffer with ETHER_ADDR_LEN length at least.
2888  *
2889  * Returns false in case of an error, otherwise true. "obtained" argument
2890  * is true if a MAC address was obtained successful, otherwise false.
2891  */
2892 bool guest_get_hw_addr(struct ifaddrs *ifa, unsigned char *buf,
2893                        bool *obtained, Error **errp)
2894 {
2895     struct ifreq ifr;
2896     int sock;
2897 
2898     *obtained = false;
2899 
2900     /* we haven't obtained HW address yet */
2901     sock = socket(PF_INET, SOCK_STREAM, 0);
2902     if (sock == -1) {
2903         error_setg_errno(errp, errno, "failed to create socket");
2904         return false;
2905     }
2906 
2907     memset(&ifr, 0, sizeof(ifr));
2908     pstrcpy(ifr.ifr_name, IF_NAMESIZE, ifa->ifa_name);
2909     if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
2910         /*
2911          * We can't get the hw addr of this interface, but that's not a
2912          * fatal error.
2913          */
2914         if (errno == EADDRNOTAVAIL) {
2915             /* The interface doesn't have a hw addr (e.g. loopback). */
2916             g_debug("failed to get MAC address of %s: %s",
2917                     ifa->ifa_name, strerror(errno));
2918         } else{
2919             g_warning("failed to get MAC address of %s: %s",
2920                       ifa->ifa_name, strerror(errno));
2921         }
2922     } else {
2923 #ifdef CONFIG_SOLARIS
2924         memcpy(buf, &ifr.ifr_addr.sa_data, ETHER_ADDR_LEN);
2925 #else
2926         memcpy(buf, &ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
2927 #endif
2928         *obtained = true;
2929     }
2930     close(sock);
2931     return true;
2932 }
2933 #endif /* __FreeBSD__ */
2934 
2935 /*
2936  * Build information about guest interfaces
2937  */
2938 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
2939 {
2940     GuestNetworkInterfaceList *head = NULL, **tail = &head;
2941     struct ifaddrs *ifap, *ifa;
2942 
2943     if (getifaddrs(&ifap) < 0) {
2944         error_setg_errno(errp, errno, "getifaddrs failed");
2945         goto error;
2946     }
2947 
2948     for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
2949         GuestNetworkInterface *info;
2950         GuestIpAddressList **address_tail;
2951         GuestIpAddress *address_item = NULL;
2952         GuestNetworkInterfaceStat *interface_stat = NULL;
2953         char addr4[INET_ADDRSTRLEN];
2954         char addr6[INET6_ADDRSTRLEN];
2955         unsigned char mac_addr[ETHER_ADDR_LEN];
2956         bool obtained;
2957         void *p;
2958 
2959         g_debug("Processing %s interface", ifa->ifa_name);
2960 
2961         info = guest_find_interface(head, ifa->ifa_name);
2962 
2963         if (!info) {
2964             info = g_malloc0(sizeof(*info));
2965             info->name = g_strdup(ifa->ifa_name);
2966 
2967             QAPI_LIST_APPEND(tail, info);
2968         }
2969 
2970         if (!info->has_hardware_address) {
2971             if (!guest_get_hw_addr(ifa, mac_addr, &obtained, errp)) {
2972                 goto error;
2973             }
2974             if (obtained) {
2975                 info->hardware_address =
2976                     g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",
2977                                     (int) mac_addr[0], (int) mac_addr[1],
2978                                     (int) mac_addr[2], (int) mac_addr[3],
2979                                     (int) mac_addr[4], (int) mac_addr[5]);
2980                 info->has_hardware_address = true;
2981             }
2982         }
2983 
2984         if (ifa->ifa_addr &&
2985             ifa->ifa_addr->sa_family == AF_INET) {
2986             /* interface with IPv4 address */
2987             p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
2988             if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {
2989                 error_setg_errno(errp, errno, "inet_ntop failed");
2990                 goto error;
2991             }
2992 
2993             address_item = g_malloc0(sizeof(*address_item));
2994             address_item->ip_address = g_strdup(addr4);
2995             address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;
2996 
2997             if (ifa->ifa_netmask) {
2998                 /* Count the number of set bits in netmask.
2999                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
3000                 p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
3001                 address_item->prefix = ctpop32(((uint32_t *) p)[0]);
3002             }
3003         } else if (ifa->ifa_addr &&
3004                    ifa->ifa_addr->sa_family == AF_INET6) {
3005             /* interface with IPv6 address */
3006             p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
3007             if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {
3008                 error_setg_errno(errp, errno, "inet_ntop failed");
3009                 goto error;
3010             }
3011 
3012             address_item = g_malloc0(sizeof(*address_item));
3013             address_item->ip_address = g_strdup(addr6);
3014             address_item->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;
3015 
3016             if (ifa->ifa_netmask) {
3017                 /* Count the number of set bits in netmask.
3018                  * This is safe as '1' and '0' cannot be shuffled in netmask. */
3019                 p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;
3020                 address_item->prefix =
3021                     ctpop32(((uint32_t *) p)[0]) +
3022                     ctpop32(((uint32_t *) p)[1]) +
3023                     ctpop32(((uint32_t *) p)[2]) +
3024                     ctpop32(((uint32_t *) p)[3]);
3025             }
3026         }
3027 
3028         if (!address_item) {
3029             continue;
3030         }
3031 
3032         address_tail = &info->ip_addresses;
3033         while (*address_tail) {
3034             address_tail = &(*address_tail)->next;
3035         }
3036         QAPI_LIST_APPEND(address_tail, address_item);
3037 
3038         info->has_ip_addresses = true;
3039 
3040         if (!info->has_statistics) {
3041             interface_stat = g_malloc0(sizeof(*interface_stat));
3042             if (guest_get_network_stats(info->name, interface_stat) == -1) {
3043                 info->has_statistics = false;
3044                 g_free(interface_stat);
3045             } else {
3046                 info->statistics = interface_stat;
3047                 info->has_statistics = true;
3048             }
3049         }
3050     }
3051 
3052     freeifaddrs(ifap);
3053     return head;
3054 
3055 error:
3056     freeifaddrs(ifap);
3057     qapi_free_GuestNetworkInterfaceList(head);
3058     return NULL;
3059 }
3060 
3061 #else
3062 
3063 GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)
3064 {
3065     error_setg(errp, QERR_UNSUPPORTED);
3066     return NULL;
3067 }
3068 
3069 #endif /* HAVE_GETIFADDRS */
3070 
3071 #if !defined(CONFIG_FSFREEZE)
3072 
3073 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
3074 {
3075     error_setg(errp, QERR_UNSUPPORTED);
3076     return NULL;
3077 }
3078 
3079 GuestFsfreezeStatus qmp_guest_fsfreeze_status(Error **errp)
3080 {
3081     error_setg(errp, QERR_UNSUPPORTED);
3082 
3083     return 0;
3084 }
3085 
3086 int64_t qmp_guest_fsfreeze_freeze(Error **errp)
3087 {
3088     error_setg(errp, QERR_UNSUPPORTED);
3089 
3090     return 0;
3091 }
3092 
3093 int64_t qmp_guest_fsfreeze_freeze_list(bool has_mountpoints,
3094                                        strList *mountpoints,
3095                                        Error **errp)
3096 {
3097     error_setg(errp, QERR_UNSUPPORTED);
3098 
3099     return 0;
3100 }
3101 
3102 int64_t qmp_guest_fsfreeze_thaw(Error **errp)
3103 {
3104     error_setg(errp, QERR_UNSUPPORTED);
3105 
3106     return 0;
3107 }
3108 
3109 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
3110 {
3111     error_setg(errp, QERR_UNSUPPORTED);
3112     return NULL;
3113 }
3114 
3115 GuestDiskStatsInfoList *qmp_guest_get_diskstats(Error **errp)
3116 {
3117     error_setg(errp, QERR_UNSUPPORTED);
3118     return NULL;
3119 }
3120 
3121 GuestCpuStatsList *qmp_guest_get_cpustats(Error **errp)
3122 {
3123     error_setg(errp, QERR_UNSUPPORTED);
3124     return NULL;
3125 }
3126 
3127 #endif /* CONFIG_FSFREEZE */
3128 
3129 #if !defined(CONFIG_FSTRIM)
3130 GuestFilesystemTrimResponse *
3131 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
3132 {
3133     error_setg(errp, QERR_UNSUPPORTED);
3134     return NULL;
3135 }
3136 #endif
3137 
3138 /* add unsupported commands to the list of blocked RPCs */
3139 GList *ga_command_init_blockedrpcs(GList *blockedrpcs)
3140 {
3141 #if !defined(__linux__)
3142     {
3143         const char *list[] = {
3144             "guest-suspend-disk", "guest-suspend-ram",
3145             "guest-suspend-hybrid", "guest-get-vcpus", "guest-set-vcpus",
3146             "guest-get-memory-blocks", "guest-set-memory-blocks",
3147             "guest-get-memory-block-size", "guest-get-memory-block-info",
3148             NULL};
3149         char **p = (char **)list;
3150 
3151         while (*p) {
3152             blockedrpcs = g_list_append(blockedrpcs, g_strdup(*p++));
3153         }
3154     }
3155 #endif
3156 
3157 #if !defined(HAVE_GETIFADDRS)
3158     blockedrpcs = g_list_append(blockedrpcs,
3159                               g_strdup("guest-network-get-interfaces"));
3160 #endif
3161 
3162 #if !defined(CONFIG_FSFREEZE)
3163     {
3164         const char *list[] = {
3165             "guest-get-fsinfo", "guest-fsfreeze-status",
3166             "guest-fsfreeze-freeze", "guest-fsfreeze-freeze-list",
3167             "guest-fsfreeze-thaw", "guest-get-fsinfo",
3168             "guest-get-disks", NULL};
3169         char **p = (char **)list;
3170 
3171         while (*p) {
3172             blockedrpcs = g_list_append(blockedrpcs, g_strdup(*p++));
3173         }
3174     }
3175 #endif
3176 
3177 #if !defined(CONFIG_FSTRIM)
3178     blockedrpcs = g_list_append(blockedrpcs, g_strdup("guest-fstrim"));
3179 #endif
3180 
3181     blockedrpcs = g_list_append(blockedrpcs, g_strdup("guest-get-devices"));
3182 
3183     return blockedrpcs;
3184 }
3185 
3186 /* register init/cleanup routines for stateful command groups */
3187 void ga_command_state_init(GAState *s, GACommandState *cs)
3188 {
3189 #if defined(CONFIG_FSFREEZE)
3190     ga_command_state_add(cs, NULL, guest_fsfreeze_cleanup);
3191 #endif
3192 }
3193 
3194 #ifdef HAVE_UTMPX
3195 
3196 #define QGA_MICRO_SECOND_TO_SECOND 1000000
3197 
3198 static double ga_get_login_time(struct utmpx *user_info)
3199 {
3200     double seconds = (double)user_info->ut_tv.tv_sec;
3201     double useconds = (double)user_info->ut_tv.tv_usec;
3202     useconds /= QGA_MICRO_SECOND_TO_SECOND;
3203     return seconds + useconds;
3204 }
3205 
3206 GuestUserList *qmp_guest_get_users(Error **errp)
3207 {
3208     GHashTable *cache = NULL;
3209     GuestUserList *head = NULL, **tail = &head;
3210     struct utmpx *user_info = NULL;
3211     gpointer value = NULL;
3212     GuestUser *user = NULL;
3213     double login_time = 0;
3214 
3215     cache = g_hash_table_new(g_str_hash, g_str_equal);
3216     setutxent();
3217 
3218     for (;;) {
3219         user_info = getutxent();
3220         if (user_info == NULL) {
3221             break;
3222         } else if (user_info->ut_type != USER_PROCESS) {
3223             continue;
3224         } else if (g_hash_table_contains(cache, user_info->ut_user)) {
3225             value = g_hash_table_lookup(cache, user_info->ut_user);
3226             user = (GuestUser *)value;
3227             login_time = ga_get_login_time(user_info);
3228             /* We're ensuring the earliest login time to be sent */
3229             if (login_time < user->login_time) {
3230                 user->login_time = login_time;
3231             }
3232             continue;
3233         }
3234 
3235         user = g_new0(GuestUser, 1);
3236         user->user = g_strdup(user_info->ut_user);
3237         user->login_time = ga_get_login_time(user_info);
3238 
3239         g_hash_table_insert(cache, user->user, user);
3240 
3241         QAPI_LIST_APPEND(tail, user);
3242     }
3243     endutxent();
3244     g_hash_table_destroy(cache);
3245     return head;
3246 }
3247 
3248 #else
3249 
3250 GuestUserList *qmp_guest_get_users(Error **errp)
3251 {
3252     error_setg(errp, QERR_UNSUPPORTED);
3253     return NULL;
3254 }
3255 
3256 #endif
3257 
3258 /* Replace escaped special characters with theire real values. The replacement
3259  * is done in place -- returned value is in the original string.
3260  */
3261 static void ga_osrelease_replace_special(gchar *value)
3262 {
3263     gchar *p, *p2, quote;
3264 
3265     /* Trim the string at first space or semicolon if it is not enclosed in
3266      * single or double quotes. */
3267     if ((value[0] != '"') || (value[0] == '\'')) {
3268         p = strchr(value, ' ');
3269         if (p != NULL) {
3270             *p = 0;
3271         }
3272         p = strchr(value, ';');
3273         if (p != NULL) {
3274             *p = 0;
3275         }
3276         return;
3277     }
3278 
3279     quote = value[0];
3280     p2 = value;
3281     p = value + 1;
3282     while (*p != 0) {
3283         if (*p == '\\') {
3284             p++;
3285             switch (*p) {
3286             case '$':
3287             case '\'':
3288             case '"':
3289             case '\\':
3290             case '`':
3291                 break;
3292             default:
3293                 /* Keep literal backslash followed by whatever is there */
3294                 p--;
3295                 break;
3296             }
3297         } else if (*p == quote) {
3298             *p2 = 0;
3299             break;
3300         }
3301         *(p2++) = *(p++);
3302     }
3303 }
3304 
3305 static GKeyFile *ga_parse_osrelease(const char *fname)
3306 {
3307     gchar *content = NULL;
3308     gchar *content2 = NULL;
3309     GError *err = NULL;
3310     GKeyFile *keys = g_key_file_new();
3311     const char *group = "[os-release]\n";
3312 
3313     if (!g_file_get_contents(fname, &content, NULL, &err)) {
3314         slog("failed to read '%s', error: %s", fname, err->message);
3315         goto fail;
3316     }
3317 
3318     if (!g_utf8_validate(content, -1, NULL)) {
3319         slog("file is not utf-8 encoded: %s", fname);
3320         goto fail;
3321     }
3322     content2 = g_strdup_printf("%s%s", group, content);
3323 
3324     if (!g_key_file_load_from_data(keys, content2, -1, G_KEY_FILE_NONE,
3325                                    &err)) {
3326         slog("failed to parse file '%s', error: %s", fname, err->message);
3327         goto fail;
3328     }
3329 
3330     g_free(content);
3331     g_free(content2);
3332     return keys;
3333 
3334 fail:
3335     g_error_free(err);
3336     g_free(content);
3337     g_free(content2);
3338     g_key_file_free(keys);
3339     return NULL;
3340 }
3341 
3342 GuestOSInfo *qmp_guest_get_osinfo(Error **errp)
3343 {
3344     GuestOSInfo *info = NULL;
3345     struct utsname kinfo;
3346     GKeyFile *osrelease = NULL;
3347     const char *qga_os_release = g_getenv("QGA_OS_RELEASE");
3348 
3349     info = g_new0(GuestOSInfo, 1);
3350 
3351     if (uname(&kinfo) != 0) {
3352         error_setg_errno(errp, errno, "uname failed");
3353     } else {
3354         info->has_kernel_version = true;
3355         info->kernel_version = g_strdup(kinfo.version);
3356         info->has_kernel_release = true;
3357         info->kernel_release = g_strdup(kinfo.release);
3358         info->has_machine = true;
3359         info->machine = g_strdup(kinfo.machine);
3360     }
3361 
3362     if (qga_os_release != NULL) {
3363         osrelease = ga_parse_osrelease(qga_os_release);
3364     } else {
3365         osrelease = ga_parse_osrelease("/etc/os-release");
3366         if (osrelease == NULL) {
3367             osrelease = ga_parse_osrelease("/usr/lib/os-release");
3368         }
3369     }
3370 
3371     if (osrelease != NULL) {
3372         char *value;
3373 
3374 #define GET_FIELD(field, osfield) do { \
3375     value = g_key_file_get_value(osrelease, "os-release", osfield, NULL); \
3376     if (value != NULL) { \
3377         ga_osrelease_replace_special(value); \
3378         info->has_ ## field = true; \
3379         info->field = value; \
3380     } \
3381 } while (0)
3382         GET_FIELD(id, "ID");
3383         GET_FIELD(name, "NAME");
3384         GET_FIELD(pretty_name, "PRETTY_NAME");
3385         GET_FIELD(version, "VERSION");
3386         GET_FIELD(version_id, "VERSION_ID");
3387         GET_FIELD(variant, "VARIANT");
3388         GET_FIELD(variant_id, "VARIANT_ID");
3389 #undef GET_FIELD
3390 
3391         g_key_file_free(osrelease);
3392     }
3393 
3394     return info;
3395 }
3396 
3397 GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
3398 {
3399     error_setg(errp, QERR_UNSUPPORTED);
3400 
3401     return NULL;
3402 }
3403 
3404 #ifndef HOST_NAME_MAX
3405 # ifdef _POSIX_HOST_NAME_MAX
3406 #  define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
3407 # else
3408 #  define HOST_NAME_MAX 255
3409 # endif
3410 #endif
3411 
3412 char *qga_get_host_name(Error **errp)
3413 {
3414     long len = -1;
3415     g_autofree char *hostname = NULL;
3416 
3417 #ifdef _SC_HOST_NAME_MAX
3418     len = sysconf(_SC_HOST_NAME_MAX);
3419 #endif /* _SC_HOST_NAME_MAX */
3420 
3421     if (len < 0) {
3422         len = HOST_NAME_MAX;
3423     }
3424 
3425     /* Unfortunately, gethostname() below does not guarantee a
3426      * NULL terminated string. Therefore, allocate one byte more
3427      * to be sure. */
3428     hostname = g_new0(char, len + 1);
3429 
3430     if (gethostname(hostname, len) < 0) {
3431         error_setg_errno(errp, errno,
3432                          "cannot get hostname");
3433         return NULL;
3434     }
3435 
3436     return g_steal_pointer(&hostname);
3437 }
3438