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