master
c 2,249 lines 66.8 KB
Raw
1 /*
2 * QEMU Guest Agent Linux-specific command implementations
3 *
4 * Copyright IBM Corp. 2011
5 *
6 * Authors:
7 * Michael Roth <mdroth@linux.vnet.ibm.com>
8 * Michal Privoznik <mprivozn@redhat.com>
9 *
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
12 */
13
14 #include "qemu/osdep.h"
15 #include "qemu/bswap.h"
16 #include "qapi/error.h"
17 #include "qga-qapi-commands.h"
18 #include "qapi/error.h"
19 #include "commands-common.h"
20 #include "cutils.h"
21 #include <mntent.h>
22 #include <sys/ioctl.h>
23 #include <mntent.h>
24 #include <linux/nvme_ioctl.h>
25 #include "block/nvme.h"
26
27 #ifdef CONFIG_LIBUDEV
28 #include <libudev.h>
29 #endif
30
31 #ifdef HAVE_GETIFADDRS
32 #include <net/if.h>
33 #endif
34
35 #include <sys/statvfs.h>
36
37 #if defined(CONFIG_FSFREEZE) || defined(CONFIG_FSTRIM)
38 static int dev_major_minor(const char *devpath,
39 unsigned int *devmajor, unsigned int *devminor)
40 {
41 struct stat st;
42
43 *devmajor = 0;
44 *devminor = 0;
45
46 if (stat(devpath, &st) < 0) {
47 slog("failed to stat device file '%s': %s", devpath, strerror(errno));
48 return -1;
49 }
50 if (S_ISDIR(st.st_mode)) {
51 /* It is bind mount */
52 return -2;
53 }
54 if (S_ISBLK(st.st_mode)) {
55 *devmajor = major(st.st_rdev);
56 *devminor = minor(st.st_rdev);
57 return 0;
58 }
59 return -1;
60 }
61
62 /*
63 * Check if we already have the devmajor:devminor in the mounts
64 * If thats the case return true.
65 */
66 static bool dev_exists(FsMountList *mounts, unsigned int devmajor, unsigned int devminor)
67 {
68 FsMount *mount;
69
70 QTAILQ_FOREACH(mount, mounts, next) {
71 if (mount->devmajor == devmajor && mount->devminor == devminor) {
72 return true;
73 }
74 }
75 return false;
76 }
77
78 static bool build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)
79 {
80 struct mntent *ment;
81 FsMount *mount;
82 char const *mtab = "/proc/self/mounts";
83 FILE *fp;
84 unsigned int devmajor, devminor;
85
86 fp = setmntent(mtab, "r");
87 if (!fp) {
88 error_setg(errp, "failed to open mtab file: '%s'", mtab);
89 return false;
90 }
91
92 while ((ment = getmntent(fp))) {
93 /*
94 * An entry which device name doesn't start with a '/' is
95 * either a dummy file system or a network file system.
96 * Add special handling for smbfs and cifs as is done by
97 * coreutils as well.
98 */
99 if ((ment->mnt_fsname[0] != '/') ||
100 (strcmp(ment->mnt_type, "smbfs") == 0) ||
101 (strcmp(ment->mnt_type, "cifs") == 0)) {
102 continue;
103 }
104 if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {
105 /* Skip bind mounts */
106 continue;
107 }
108 if (dev_exists(mounts, devmajor, devminor)) {
109 /* Skip already existing devices (bind mounts) */
110 continue;
111 }
112
113 mount = g_new0(FsMount, 1);
114 mount->dirname = g_strdup(ment->mnt_dir);
115 mount->devtype = g_strdup(ment->mnt_type);
116 mount->devmajor = devmajor;
117 mount->devminor = devminor;
118
119 QTAILQ_INSERT_TAIL(mounts, mount, next);
120 }
121
122 endmntent(fp);
123 return true;
124 }
125
126 static void decode_mntname(char *name, int len)
127 {
128 int i, j = 0;
129 for (i = 0; i <= len; i++) {
130 if (name[i] != '\\') {
131 name[j++] = name[i];
132 } else if (name[i + 1] == '\\') {
133 name[j++] = '\\';
134 i++;
135 } else if (name[i + 1] >= '0' && name[i + 1] <= '3' &&
136 name[i + 2] >= '0' && name[i + 2] <= '7' &&
137 name[i + 3] >= '0' && name[i + 3] <= '7') {
138 name[j++] = (name[i + 1] - '0') * 64 +
139 (name[i + 2] - '0') * 8 +
140 (name[i + 3] - '0');
141 i += 3;
142 } else {
143 name[j++] = name[i];
144 }
145 }
146 }
147
148 /*
149 * Walk the mount table and build a list of local file systems
150 */
151 bool build_fs_mount_list(FsMountList *mounts, Error **errp)
152 {
153 FsMount *mount;
154 char const *mountinfo = "/proc/self/mountinfo";
155 FILE *fp;
156 char *line = NULL, *dash;
157 size_t n;
158 char check;
159 unsigned int devmajor, devminor;
160 int ret, dir_s, dir_e, type_s, type_e, dev_s, dev_e;
161
162 fp = fopen(mountinfo, "r");
163 if (!fp) {
164 return build_fs_mount_list_from_mtab(mounts, errp);
165 }
166
167 while (getline(&line, &n, fp) != -1) {
168 ret = sscanf(line, "%*u %*u %u:%u %*s %n%*s%n%c",
169 &devmajor, &devminor, &dir_s, &dir_e, &check);
170 if (ret < 3) {
171 continue;
172 }
173 dash = strstr(line + dir_e, " - ");
174 if (!dash) {
175 continue;
176 }
177 ret = sscanf(dash, " - %n%*s%n %n%*s%n%c",
178 &type_s, &type_e, &dev_s, &dev_e, &check);
179 if (ret < 1) {
180 continue;
181 }
182 line[dir_e] = 0;
183 dash[type_e] = 0;
184 dash[dev_e] = 0;
185 decode_mntname(line + dir_s, dir_e - dir_s);
186 decode_mntname(dash + dev_s, dev_e - dev_s);
187 if (devmajor == 0) {
188 /* btrfs reports major number = 0 */
189 if (strcmp("btrfs", dash + type_s) != 0 ||
190 dev_major_minor(dash + dev_s, &devmajor, &devminor) < 0) {
191 continue;
192 }
193 }
194
195 if (dev_exists(mounts, devmajor, devminor)) {
196 /* Skip already existing devices (bind mounts) */
197 continue;
198 }
199
200 mount = g_new0(FsMount, 1);
201 mount->dirname = g_strdup(line + dir_s);
202 mount->devtype = g_strdup(dash + type_s);
203 mount->devmajor = devmajor;
204 mount->devminor = devminor;
205
206 QTAILQ_INSERT_TAIL(mounts, mount, next);
207 }
208 free(line);
209
210 fclose(fp);
211 return true;
212 }
213 #endif /* CONFIG_FSFREEZE || CONFIG_FSTRIM */
214
215 #ifdef CONFIG_FSFREEZE
216 /*
217 * Walk list of mounted file systems in the guest, and freeze the ones which
218 * are real local file systems.
219 */
220 int64_t qmp_guest_fsfreeze_do_freeze_list(bool has_mountpoints,
221 strList *mountpoints,
222 FsMountList mounts,
223 Error **errp)
224 {
225 struct FsMount *mount;
226 strList *list;
227 int fd, ret, i = 0;
228
229 QTAILQ_FOREACH_REVERSE(mount, &mounts, next) {
230 /* To issue fsfreeze in the reverse order of mounts, check if the
231 * mount is listed in the list here */
232 if (has_mountpoints) {
233 for (list = mountpoints; list; list = list->next) {
234 if (strcmp(list->value, mount->dirname) == 0) {
235 break;
236 }
237 }
238 if (!list) {
239 continue;
240 }
241 }
242
243 fd = qga_open_cloexec(mount->dirname, O_RDONLY, 0);
244 if (fd == -1) {
245 error_setg_errno(errp, errno, "failed to open %s", mount->dirname);
246 return -1;
247 }
248
249 /* we try to cull filesystems we know won't work in advance, but other
250 * filesystems may not implement fsfreeze for less obvious reasons.
251 * these will report EOPNOTSUPP. we simply ignore these when tallying
252 * the number of frozen filesystems.
253 * if a filesystem is mounted more than once (aka bind mount) a
254 * consecutive attempt to freeze an already frozen filesystem will
255 * return EBUSY.
256 *
257 * any other error means a failure to freeze a filesystem we
258 * expect to be freezable, so return an error in those cases
259 * and return system to thawed state.
260 */
261 ret = ioctl(fd, FIFREEZE);
262 if (ret == -1) {
263 if (errno != EOPNOTSUPP && errno != EBUSY) {
264 error_setg_errno(errp, errno, "failed to freeze %s",
265 mount->dirname);
266 close(fd);
267 return -1;
268 }
269 } else {
270 i++;
271 }
272 close(fd);
273 }
274 return i;
275 }
276
277 int qmp_guest_fsfreeze_do_thaw(Error **errp)
278 {
279 int ret;
280 FsMountList mounts;
281 FsMount *mount;
282 int fd, i = 0, logged;
283 Error *local_err = NULL;
284
285 QTAILQ_INIT(&mounts);
286 if (!build_fs_mount_list(&mounts, &local_err)) {
287 error_propagate(errp, local_err);
288 return -1;
289 }
290
291 QTAILQ_FOREACH(mount, &mounts, next) {
292 logged = false;
293 fd = qga_open_cloexec(mount->dirname, O_RDONLY, 0);
294 if (fd == -1) {
295 continue;
296 }
297 /* we have no way of knowing whether a filesystem was actually unfrozen
298 * as a result of a successful call to FITHAW, only that if an error
299 * was returned the filesystem was *not* unfrozen by that particular
300 * call.
301 *
302 * since multiple preceding FIFREEZEs require multiple calls to FITHAW
303 * to unfreeze, continuing issuing FITHAW until an error is returned,
304 * in which case either the filesystem is in an unfreezable state, or,
305 * more likely, it was thawed previously (and remains so afterward).
306 *
307 * also, since the most recent successful call is the one that did
308 * the actual unfreeze, we can use this to provide an accurate count
309 * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which
310 * may * be useful for determining whether a filesystem was unfrozen
311 * during the freeze/thaw phase by a process other than qemu-ga.
312 */
313 do {
314 ret = ioctl(fd, FITHAW);
315 if (ret == 0 && !logged) {
316 i++;
317 logged = true;
318 }
319 } while (ret == 0);
320 close(fd);
321 }
322
323 free_fs_mount_list(&mounts);
324
325 return i;
326 }
327 #endif /* CONFIG_FSFREEZE */
328
329 #if defined(CONFIG_FSFREEZE)
330
331 static char *get_pci_driver(char const *syspath, int pathlen, Error **errp)
332 {
333 char *path;
334 char *dpath;
335 char *driver = NULL;
336 char buf[PATH_MAX];
337 ssize_t len;
338
339 path = g_strndup(syspath, pathlen);
340 dpath = g_strdup_printf("%s/driver", path);
341 len = readlink(dpath, buf, sizeof(buf) - 1);
342 if (len != -1) {
343 buf[len] = 0;
344 driver = g_path_get_basename(buf);
345 }
346 g_free(dpath);
347 g_free(path);
348 return driver;
349 }
350
351 static int compare_uint(const void *_a, const void *_b)
352 {
353 unsigned int a = *(unsigned int *)_a;
354 unsigned int b = *(unsigned int *)_b;
355
356 return a < b ? -1 : a > b ? 1 : 0;
357 }
358
359 /* Walk the specified sysfs and build a sorted list of host or ata numbers */
360 static int build_hosts(char const *syspath, char const *host, bool ata,
361 unsigned int *hosts, int hosts_max, Error **errp)
362 {
363 char *path;
364 DIR *dir;
365 struct dirent *entry;
366 int i = 0;
367
368 path = g_strndup(syspath, host - syspath);
369 dir = opendir(path);
370 if (!dir) {
371 error_setg_errno(errp, errno, "opendir(\"%s\")", path);
372 g_free(path);
373 return -1;
374 }
375
376 while (i < hosts_max) {
377 entry = readdir(dir);
378 if (!entry) {
379 break;
380 }
381 if (ata && sscanf(entry->d_name, "ata%d", hosts + i) == 1) {
382 ++i;
383 } else if (!ata && sscanf(entry->d_name, "host%d", hosts + i) == 1) {
384 ++i;
385 }
386 }
387
388 qsort(hosts, i, sizeof(hosts[0]), compare_uint);
389
390 g_free(path);
391 closedir(dir);
392 return i;
393 }
394
395 /*
396 * Store disk device info for devices on the PCI bus.
397 * Returns true if information has been stored, or false for failure.
398 */
399 static bool build_guest_fsinfo_for_pci_dev(char const *syspath,
400 GuestDiskAddress *disk,
401 Error **errp)
402 {
403 unsigned int pci[4], host, hosts[8], tgt[3];
404 int i, offset, nhosts = 0, pcilen;
405 GuestPCIAddress *pciaddr = disk->pci_controller;
406 bool has_ata = false, has_host = false, has_tgt = false;
407 const char *p;
408 char *driver = NULL;
409 bool ret = false;
410
411 p = strstr(syspath, "/devices/pci");
412 if (!p || sscanf(p + 12, "%*x:%*x/%x:%x:%x.%x%n",
413 pci, pci + 1, pci + 2, pci + 3, &pcilen) < 4) {
414 g_debug("only pci device is supported: sysfs path '%s'", syspath);
415 return false;
416 }
417
418 p += 12 + pcilen;
419 while (true) {
420 driver = get_pci_driver(syspath, p - syspath, errp);
421 if (driver && (g_str_equal(driver, "ata_piix") ||
422 g_str_equal(driver, "sym53c8xx") ||
423 g_str_equal(driver, "virtio-pci") ||
424 g_str_equal(driver, "ahci") ||
425 g_str_equal(driver, "nvme") ||
426 g_str_equal(driver, "xhci_hcd") ||
427 g_str_equal(driver, "ehci-pci"))) {
428 break;
429 }
430
431 g_free(driver);
432 if (sscanf(p, "/%x:%x:%x.%x%n",
433 pci, pci + 1, pci + 2, pci + 3, &pcilen) == 4) {
434 p += pcilen;
435 continue;
436 }
437
438 g_debug("unsupported driver or sysfs path '%s'", syspath);
439 return false;
440 }
441
442 p = strstr(syspath, "/target");
443 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
444 tgt, tgt + 1, tgt + 2) == 3) {
445 has_tgt = true;
446 }
447
448 p = strstr(syspath, "/ata");
449 if (p) {
450 offset = 4;
451 has_ata = true;
452 } else {
453 p = strstr(syspath, "/host");
454 offset = 5;
455 }
456 if (p && sscanf(p + offset, "%u", &host) == 1) {
457 has_host = true;
458 nhosts = build_hosts(syspath, p, has_ata, hosts,
459 ARRAY_SIZE(hosts), errp);
460 if (nhosts < 0) {
461 goto cleanup;
462 }
463 }
464
465 pciaddr->domain = pci[0];
466 pciaddr->bus = pci[1];
467 pciaddr->slot = pci[2];
468 pciaddr->function = pci[3];
469
470 if (strcmp(driver, "ata_piix") == 0) {
471 /* a host per ide bus, target*:0:<unit>:0 */
472 if (!has_host || !has_tgt) {
473 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
474 goto cleanup;
475 }
476 for (i = 0; i < nhosts; i++) {
477 if (host == hosts[i]) {
478 disk->bus_type = GUEST_DISK_BUS_TYPE_IDE;
479 disk->bus = i;
480 disk->unit = tgt[1];
481 break;
482 }
483 }
484 if (i >= nhosts) {
485 g_debug("no host for '%s' (driver '%s')", syspath, driver);
486 goto cleanup;
487 }
488 } else if (strcmp(driver, "sym53c8xx") == 0) {
489 /* scsi(LSI Logic): target*:0:<unit>:0 */
490 if (!has_tgt) {
491 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
492 goto cleanup;
493 }
494 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
495 disk->unit = tgt[1];
496 } else if (strcmp(driver, "virtio-pci") == 0) {
497 if (has_tgt) {
498 /* virtio-scsi: target*:0:0:<unit> */
499 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
500 disk->unit = tgt[2];
501 } else {
502 /* virtio-blk: 1 disk per 1 device */
503 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
504 }
505 } else if (strcmp(driver, "ahci") == 0) {
506 /* ahci: 1 host per 1 unit */
507 if (!has_host || !has_tgt) {
508 g_debug("invalid sysfs path '%s' (driver '%s')", syspath, driver);
509 goto cleanup;
510 }
511 for (i = 0; i < nhosts; i++) {
512 if (host == hosts[i]) {
513 disk->unit = i;
514 disk->bus_type = GUEST_DISK_BUS_TYPE_SATA;
515 break;
516 }
517 }
518 if (i >= nhosts) {
519 g_debug("no host for '%s' (driver '%s')", syspath, driver);
520 goto cleanup;
521 }
522 } else if (strcmp(driver, "nvme") == 0) {
523 disk->bus_type = GUEST_DISK_BUS_TYPE_NVME;
524 } else if (strcmp(driver, "ehci-pci") == 0 || strcmp(driver, "xhci_hcd") == 0) {
525 disk->bus_type = GUEST_DISK_BUS_TYPE_USB;
526 } else {
527 g_debug("unknown driver '%s' (sysfs path '%s')", driver, syspath);
528 goto cleanup;
529 }
530
531 ret = true;
532
533 cleanup:
534 g_free(driver);
535 return ret;
536 }
537
538 /*
539 * Store disk device info for non-PCI virtio devices (for example s390x
540 * channel I/O devices). Returns true if information has been stored, or
541 * false for failure.
542 */
543 static bool build_guest_fsinfo_for_nonpci_virtio(char const *syspath,
544 GuestDiskAddress *disk,
545 Error **errp)
546 {
547 unsigned int tgt[3];
548 const char *p;
549
550 if (!strstr(syspath, "/virtio") || !strstr(syspath, "/block")) {
551 g_debug("Unsupported virtio device '%s'", syspath);
552 return false;
553 }
554
555 p = strstr(syspath, "/target");
556 if (p && sscanf(p + 7, "%*u:%*u:%*u/%*u:%u:%u:%u",
557 &tgt[0], &tgt[1], &tgt[2]) == 3) {
558 /* virtio-scsi: target*:0:<target>:<unit> */
559 disk->bus_type = GUEST_DISK_BUS_TYPE_SCSI;
560 disk->bus = tgt[0];
561 disk->target = tgt[1];
562 disk->unit = tgt[2];
563 } else {
564 /* virtio-blk: 1 disk per 1 device */
565 disk->bus_type = GUEST_DISK_BUS_TYPE_VIRTIO;
566 }
567
568 return true;
569 }
570
571 /*
572 * Store disk device info for CCW devices (s390x channel I/O devices).
573 * Returns true if information has been stored, or false for failure.
574 */
575 static bool build_guest_fsinfo_for_ccw_dev(char const *syspath,
576 GuestDiskAddress *disk,
577 Error **errp)
578 {
579 unsigned int cssid, ssid, subchno, devno;
580 const char *p;
581
582 p = strstr(syspath, "/devices/css");
583 if (!p || sscanf(p + 12, "%*x/%x.%x.%x/%*x.%*x.%x/",
584 &cssid, &ssid, &subchno, &devno) < 4) {
585 g_debug("could not parse ccw device sysfs path: %s", syspath);
586 return false;
587 }
588
589 disk->ccw_address = g_new0(GuestCCWAddress, 1);
590 disk->ccw_address->cssid = cssid;
591 disk->ccw_address->ssid = ssid;
592 disk->ccw_address->subchno = subchno;
593 disk->ccw_address->devno = devno;
594
595 if (strstr(p, "/virtio")) {
596 build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
597 }
598
599 return true;
600 }
601
602 /* Store disk device info specified by @sysfs into @fs */
603 static void build_guest_fsinfo_for_real_device(char const *syspath,
604 GuestFilesystemInfo *fs,
605 Error **errp)
606 {
607 GuestDiskAddress *disk;
608 GuestPCIAddress *pciaddr;
609 bool has_hwinf;
610 #ifdef CONFIG_LIBUDEV
611 struct udev *udev = NULL;
612 struct udev_device *udevice = NULL;
613 #endif
614
615 pciaddr = g_new0(GuestPCIAddress, 1);
616 pciaddr->domain = -1; /* -1 means field is invalid */
617 pciaddr->bus = -1;
618 pciaddr->slot = -1;
619 pciaddr->function = -1;
620
621 disk = g_new0(GuestDiskAddress, 1);
622 disk->pci_controller = pciaddr;
623 disk->bus_type = GUEST_DISK_BUS_TYPE_UNKNOWN;
624
625 #ifdef CONFIG_LIBUDEV
626 udev = udev_new();
627 udevice = udev_device_new_from_syspath(udev, syspath);
628 if (udev == NULL || udevice == NULL) {
629 g_debug("failed to query udev");
630 } else {
631 const char *devnode, *serial;
632 devnode = udev_device_get_devnode(udevice);
633 if (devnode != NULL) {
634 disk->dev = g_strdup(devnode);
635 }
636 serial = udev_device_get_property_value(udevice, "ID_SERIAL");
637 if (serial != NULL && *serial != 0) {
638 disk->serial = g_strdup(serial);
639 }
640 }
641
642 udev_unref(udev);
643 udev_device_unref(udevice);
644 #endif
645
646 if (strstr(syspath, "/devices/pci")) {
647 has_hwinf = build_guest_fsinfo_for_pci_dev(syspath, disk, errp);
648 } else if (strstr(syspath, "/devices/css")) {
649 has_hwinf = build_guest_fsinfo_for_ccw_dev(syspath, disk, errp);
650 } else if (strstr(syspath, "/virtio")) {
651 has_hwinf = build_guest_fsinfo_for_nonpci_virtio(syspath, disk, errp);
652 } else {
653 g_debug("Unsupported device type for '%s'", syspath);
654 has_hwinf = false;
655 }
656
657 if (has_hwinf || disk->dev || disk->serial) {
658 QAPI_LIST_PREPEND(fs->disk, disk);
659 } else {
660 qapi_free_GuestDiskAddress(disk);
661 }
662 }
663
664 static void build_guest_fsinfo_for_device(char const *devpath,
665 GuestFilesystemInfo *fs,
666 Error **errp);
667
668 /* Store a list of slave devices of virtual volume specified by @syspath into
669 * @fs */
670 static void build_guest_fsinfo_for_virtual_device(char const *syspath,
671 GuestFilesystemInfo *fs,
672 Error **errp)
673 {
674 Error *err = NULL;
675 DIR *dir;
676 char *dirpath;
677 struct dirent *entry;
678
679 dirpath = g_strdup_printf("%s/slaves", syspath);
680 dir = opendir(dirpath);
681 if (!dir) {
682 if (errno != ENOENT) {
683 error_setg_errno(errp, errno, "opendir(\"%s\")", dirpath);
684 }
685 g_free(dirpath);
686 return;
687 }
688
689 for (;;) {
690 errno = 0;
691 entry = readdir(dir);
692 if (entry == NULL) {
693 if (errno) {
694 error_setg_errno(errp, errno, "readdir(\"%s\")", dirpath);
695 }
696 break;
697 }
698
699 if (entry->d_type == DT_LNK) {
700 char *path;
701
702 g_debug(" slave device '%s'", entry->d_name);
703 path = g_strdup_printf("%s/slaves/%s", syspath, entry->d_name);
704 build_guest_fsinfo_for_device(path, fs, &err);
705 g_free(path);
706
707 if (err) {
708 error_propagate(errp, err);
709 break;
710 }
711 }
712 }
713
714 g_free(dirpath);
715 closedir(dir);
716 }
717
718 static bool is_disk_virtual(const char *devpath, Error **errp)
719 {
720 g_autofree char *syspath = realpath(devpath, NULL);
721
722 if (!syspath) {
723 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
724 return false;
725 }
726 return strstr(syspath, "/devices/virtual/block/") != NULL;
727 }
728
729 /* Dispatch to functions for virtual/real device */
730 static void build_guest_fsinfo_for_device(char const *devpath,
731 GuestFilesystemInfo *fs,
732 Error **errp)
733 {
734 ERRP_GUARD();
735 g_autofree char *syspath = NULL;
736 bool is_virtual = false;
737
738 syspath = realpath(devpath, NULL);
739 if (!syspath) {
740 if (errno != ENOENT) {
741 error_setg_errno(errp, errno, "realpath(\"%s\")", devpath);
742 return;
743 }
744
745 /* ENOENT: This devpath may not exist because of container config */
746 if (!fs->name) {
747 fs->name = g_path_get_basename(devpath);
748 }
749 return;
750 }
751
752 if (!fs->name) {
753 fs->name = g_path_get_basename(syspath);
754 }
755
756 g_debug(" parse sysfs path '%s'", syspath);
757 is_virtual = is_disk_virtual(syspath, errp);
758 if (*errp != NULL) {
759 return;
760 }
761 if (is_virtual) {
762 build_guest_fsinfo_for_virtual_device(syspath, fs, errp);
763 } else {
764 build_guest_fsinfo_for_real_device(syspath, fs, errp);
765 }
766 }
767
768 #ifdef CONFIG_LIBUDEV
769
770 /*
771 * Wrapper around build_guest_fsinfo_for_device() for getting just
772 * the disk address.
773 */
774 static GuestDiskAddress *get_disk_address(const char *syspath, Error **errp)
775 {
776 g_autoptr(GuestFilesystemInfo) fs = NULL;
777
778 fs = g_new0(GuestFilesystemInfo, 1);
779 build_guest_fsinfo_for_device(syspath, fs, errp);
780 if (fs->disk != NULL) {
781 return g_steal_pointer(&fs->disk->value);
782 }
783 return NULL;
784 }
785
786 static char *get_alias_for_syspath(const char *syspath)
787 {
788 struct udev *udev = NULL;
789 struct udev_device *udevice = NULL;
790 char *ret = NULL;
791
792 udev = udev_new();
793 if (udev == NULL) {
794 g_debug("failed to query udev");
795 goto out;
796 }
797 udevice = udev_device_new_from_syspath(udev, syspath);
798 if (udevice == NULL) {
799 g_debug("failed to query udev for path: %s", syspath);
800 goto out;
801 } else {
802 const char *alias = udev_device_get_property_value(
803 udevice, "DM_NAME");
804 /*
805 * NULL means there was an error and empty string means there is no
806 * alias. In case of no alias we return NULL instead of empty string.
807 */
808 if (alias == NULL) {
809 g_debug("failed to query udev for device alias for: %s",
810 syspath);
811 } else if (*alias != 0) {
812 ret = g_strdup(alias);
813 }
814 }
815
816 out:
817 udev_unref(udev);
818 udev_device_unref(udevice);
819 return ret;
820 }
821
822 static char *get_device_for_syspath(const char *syspath)
823 {
824 struct udev *udev = NULL;
825 struct udev_device *udevice = NULL;
826 char *ret = NULL;
827
828 udev = udev_new();
829 if (udev == NULL) {
830 g_debug("failed to query udev");
831 goto out;
832 }
833 udevice = udev_device_new_from_syspath(udev, syspath);
834 if (udevice == NULL) {
835 g_debug("failed to query udev for path: %s", syspath);
836 goto out;
837 } else {
838 ret = g_strdup(udev_device_get_devnode(udevice));
839 }
840
841 out:
842 udev_unref(udev);
843 udev_device_unref(udevice);
844 return ret;
845 }
846
847 static void get_disk_deps(const char *disk_dir, GuestDiskInfo *disk)
848 {
849 g_autofree char *deps_dir = NULL;
850 const gchar *dep;
851 GDir *dp_deps = NULL;
852
853 /* List dependent disks */
854 deps_dir = g_strdup_printf("%s/slaves", disk_dir);
855 g_debug(" listing entries in: %s", deps_dir);
856 dp_deps = g_dir_open(deps_dir, 0, NULL);
857 if (dp_deps == NULL) {
858 g_debug("failed to list entries in %s", deps_dir);
859 return;
860 }
861 disk->has_dependencies = true;
862 while ((dep = g_dir_read_name(dp_deps)) != NULL) {
863 g_autofree char *dep_dir = NULL;
864 char *dev_name;
865
866 /* Add dependent disks */
867 dep_dir = g_strdup_printf("%s/%s", deps_dir, dep);
868 dev_name = get_device_for_syspath(dep_dir);
869 if (dev_name != NULL) {
870 g_debug(" adding dependent device: %s", dev_name);
871 QAPI_LIST_PREPEND(disk->dependencies, dev_name);
872 }
873 }
874 g_dir_close(dp_deps);
875 }
876
877 /*
878 * Detect partitions subdirectory, name is "<disk_name><number>" or
879 * "<disk_name>p<number>"
880 *
881 * @disk_name -- last component of /sys path (e.g. sda)
882 * @disk_dir -- sys path of the disk (e.g. /sys/block/sda)
883 * @disk_dev -- device node of the disk (e.g. /dev/sda)
884 */
885 static GuestDiskInfoList *get_disk_partitions(
886 GuestDiskInfoList *list,
887 const char *disk_name, const char *disk_dir,
888 const char *disk_dev)
889 {
890 GuestDiskInfoList *ret = list;
891 struct dirent *de_disk;
892 DIR *dp_disk = NULL;
893 size_t len = strlen(disk_name);
894
895 dp_disk = opendir(disk_dir);
896 while ((de_disk = readdir(dp_disk)) != NULL) {
897 g_autofree char *partition_dir = NULL;
898 char *dev_name;
899 GuestDiskInfo *partition;
900
901 if (!(de_disk->d_type & DT_DIR)) {
902 continue;
903 }
904
905 if (!(strncmp(disk_name, de_disk->d_name, len) == 0 &&
906 ((*(de_disk->d_name + len) == 'p' &&
907 isdigit(*(de_disk->d_name + len + 1))) ||
908 isdigit(*(de_disk->d_name + len))))) {
909 continue;
910 }
911
912 partition_dir = g_strdup_printf("%s/%s",
913 disk_dir, de_disk->d_name);
914 dev_name = get_device_for_syspath(partition_dir);
915 if (dev_name == NULL) {
916 g_debug("Failed to get device name for syspath: %s",
917 disk_dir);
918 continue;
919 }
920 partition = g_new0(GuestDiskInfo, 1);
921 partition->name = dev_name;
922 partition->partition = true;
923 partition->has_dependencies = true;
924 /* Add parent disk as dependent for easier tracking of hierarchy */
925 QAPI_LIST_PREPEND(partition->dependencies, g_strdup(disk_dev));
926
927 QAPI_LIST_PREPEND(ret, partition);
928 }
929 closedir(dp_disk);
930
931 return ret;
932 }
933
934 static void get_nvme_smart(GuestDiskInfo *disk)
935 {
936 int fd;
937 GuestNVMeSmart *smart;
938 NvmeSmartLog log = {0};
939 struct nvme_admin_cmd cmd = {
940 .opcode = NVME_ADM_CMD_GET_LOG_PAGE,
941 .nsid = NVME_NSID_BROADCAST,
942 .addr = (uintptr_t)&log,
943 .data_len = sizeof(log),
944 .cdw10 = NVME_LOG_SMART_INFO | (1 << 15) /* RAE bit */
945 | (((sizeof(log) >> 2) - 1) << 16)
946 };
947
948 fd = qga_open_cloexec(disk->name, O_RDONLY, 0);
949 if (fd == -1) {
950 g_debug("Failed to open device: %s: %s", disk->name, g_strerror(errno));
951 return;
952 }
953
954 if (ioctl(fd, NVME_IOCTL_ADMIN_CMD, &cmd)) {
955 g_debug("Failed to get smart: %s: %s", disk->name, g_strerror(errno));
956 close(fd);
957 return;
958 }
959
960 disk->smart = g_new0(GuestDiskSmart, 1);
961 disk->smart->type = GUEST_DISK_BUS_TYPE_NVME;
962
963 smart = &disk->smart->u.nvme;
964 smart->critical_warning = log.critical_warning;
965 smart->temperature = lduw_le_p(&log.temperature); /* unaligned field */
966 smart->available_spare = log.available_spare;
967 smart->available_spare_threshold = log.available_spare_threshold;
968 smart->percentage_used = log.percentage_used;
969 smart->data_units_read_lo = le64_to_cpu(log.data_units_read[0]);
970 smart->data_units_read_hi = le64_to_cpu(log.data_units_read[1]);
971 smart->data_units_written_lo = le64_to_cpu(log.data_units_written[0]);
972 smart->data_units_written_hi = le64_to_cpu(log.data_units_written[1]);
973 smart->host_read_commands_lo = le64_to_cpu(log.host_read_commands[0]);
974 smart->host_read_commands_hi = le64_to_cpu(log.host_read_commands[1]);
975 smart->host_write_commands_lo = le64_to_cpu(log.host_write_commands[0]);
976 smart->host_write_commands_hi = le64_to_cpu(log.host_write_commands[1]);
977 smart->controller_busy_time_lo = le64_to_cpu(log.controller_busy_time[0]);
978 smart->controller_busy_time_hi = le64_to_cpu(log.controller_busy_time[1]);
979 smart->power_cycles_lo = le64_to_cpu(log.power_cycles[0]);
980 smart->power_cycles_hi = le64_to_cpu(log.power_cycles[1]);
981 smart->power_on_hours_lo = le64_to_cpu(log.power_on_hours[0]);
982 smart->power_on_hours_hi = le64_to_cpu(log.power_on_hours[1]);
983 smart->unsafe_shutdowns_lo = le64_to_cpu(log.unsafe_shutdowns[0]);
984 smart->unsafe_shutdowns_hi = le64_to_cpu(log.unsafe_shutdowns[1]);
985 smart->media_errors_lo = le64_to_cpu(log.media_errors[0]);
986 smart->media_errors_hi = le64_to_cpu(log.media_errors[1]);
987 smart->number_of_error_log_entries_lo =
988 le64_to_cpu(log.number_of_error_log_entries[0]);
989 smart->number_of_error_log_entries_hi =
990 le64_to_cpu(log.number_of_error_log_entries[1]);
991
992 close(fd);
993 }
994
995 static void get_disk_smart(GuestDiskInfo *disk)
996 {
997 if (disk->address
998 && (disk->address->bus_type == GUEST_DISK_BUS_TYPE_NVME)) {
999 get_nvme_smart(disk);
1000 }
1001 }
1002
1003 GuestDiskInfoList *qmp_guest_get_disks(Error **errp)
1004 {
1005 GuestDiskInfoList *ret = NULL;
1006 GuestDiskInfo *disk;
1007 DIR *dp = NULL;
1008 struct dirent *de = NULL;
1009
1010 g_debug("listing /sys/block directory");
1011 dp = opendir("/sys/block");
1012 if (dp == NULL) {
1013 error_setg_errno(errp, errno, "Can't open directory \"/sys/block\"");
1014 return NULL;
1015 }
1016 while ((de = readdir(dp)) != NULL) {
1017 g_autofree char *disk_dir = NULL, *line = NULL,
1018 *size_path = NULL;
1019 char *dev_name;
1020 Error *local_err = NULL;
1021 if (de->d_type != DT_LNK) {
1022 g_debug(" skipping entry: %s", de->d_name);
1023 continue;
1024 }
1025
1026 /* Check size and skip zero-sized disks */
1027 g_debug(" checking disk size");
1028 size_path = g_strdup_printf("/sys/block/%s/size", de->d_name);
1029 if (!g_file_get_contents(size_path, &line, NULL, NULL)) {
1030 g_debug(" failed to read disk size");
1031 continue;
1032 }
1033 if (g_strcmp0(line, "0\n") == 0) {
1034 g_debug(" skipping zero-sized disk");
1035 continue;
1036 }
1037
1038 g_debug(" adding %s", de->d_name);
1039 disk_dir = g_strdup_printf("/sys/block/%s", de->d_name);
1040 dev_name = get_device_for_syspath(disk_dir);
1041 if (dev_name == NULL) {
1042 g_debug("Failed to get device name for syspath: %s",
1043 disk_dir);
1044 continue;
1045 }
1046 disk = g_new0(GuestDiskInfo, 1);
1047 disk->name = dev_name;
1048 disk->partition = false;
1049 disk->alias = get_alias_for_syspath(disk_dir);
1050 QAPI_LIST_PREPEND(ret, disk);
1051
1052 /* Get address for non-virtual devices */
1053 bool is_virtual = is_disk_virtual(disk_dir, &local_err);
1054 if (local_err != NULL) {
1055 g_debug(" failed to check disk path, ignoring error: %s",
1056 error_get_pretty(local_err));
1057 error_free(local_err);
1058 local_err = NULL;
1059 /* Don't try to get the address */
1060 is_virtual = true;
1061 }
1062 if (!is_virtual) {
1063 disk->address = get_disk_address(disk_dir, &local_err);
1064 if (local_err != NULL) {
1065 g_debug(" failed to get device info, ignoring error: %s",
1066 error_get_pretty(local_err));
1067 error_free(local_err);
1068 local_err = NULL;
1069 }
1070 }
1071
1072 get_disk_deps(disk_dir, disk);
1073 get_disk_smart(disk);
1074 ret = get_disk_partitions(ret, de->d_name, disk_dir, dev_name);
1075 }
1076
1077 closedir(dp);
1078
1079 return ret;
1080 }
1081
1082 #endif
1083
1084 /* Return a list of the disk device(s)' info which @mount lies on */
1085 static GuestFilesystemInfo *build_guest_fsinfo(struct FsMount *mount,
1086 Error **errp)
1087 {
1088 GuestFilesystemInfo *fs = g_malloc0(sizeof(*fs));
1089 struct statvfs buf;
1090 unsigned long used, nonroot_total, fr_size;
1091 char *devpath = g_strdup_printf("/sys/dev/block/%u:%u",
1092 mount->devmajor, mount->devminor);
1093
1094 fs->mountpoint = g_strdup(mount->dirname);
1095 fs->type = g_strdup(mount->devtype);
1096 build_guest_fsinfo_for_device(devpath, fs, errp);
1097
1098 if (statvfs(fs->mountpoint, &buf) == 0) {
1099 fr_size = buf.f_frsize;
1100 used = buf.f_blocks - buf.f_bfree;
1101 nonroot_total = used + buf.f_bavail;
1102 fs->used_bytes = used * fr_size;
1103 fs->total_bytes = nonroot_total * fr_size;
1104 fs->total_bytes_privileged = buf.f_blocks * fr_size;
1105
1106 fs->has_total_bytes = true;
1107 fs->has_total_bytes_privileged = true;
1108 fs->has_used_bytes = true;
1109 }
1110
1111 g_free(devpath);
1112
1113 return fs;
1114 }
1115
1116 GuestFilesystemInfoList *qmp_guest_get_fsinfo(Error **errp)
1117 {
1118 FsMountList mounts;
1119 struct FsMount *mount;
1120 GuestFilesystemInfoList *ret = NULL;
1121 Error *local_err = NULL;
1122
1123 QTAILQ_INIT(&mounts);
1124 if (!build_fs_mount_list(&mounts, &local_err)) {
1125 error_propagate(errp, local_err);
1126 return NULL;
1127 }
1128
1129 QTAILQ_FOREACH(mount, &mounts, next) {
1130 g_debug("Building guest fsinfo for '%s'", mount->dirname);
1131
1132 QAPI_LIST_PREPEND(ret, build_guest_fsinfo(mount, &local_err));
1133 if (local_err) {
1134 error_propagate(errp, local_err);
1135 qapi_free_GuestFilesystemInfoList(ret);
1136 ret = NULL;
1137 break;
1138 }
1139 }
1140
1141 free_fs_mount_list(&mounts);
1142 return ret;
1143 }
1144 #endif /* CONFIG_FSFREEZE */
1145
1146 #if defined(CONFIG_FSTRIM)
1147 /*
1148 * Walk list of mounted file systems in the guest, and trim them.
1149 */
1150 GuestFilesystemTrimResponse *
1151 qmp_guest_fstrim(bool has_minimum, int64_t minimum, Error **errp)
1152 {
1153 GuestFilesystemTrimResponse *response;
1154 GuestFilesystemTrimResult *result;
1155 int ret = 0;
1156 FsMountList mounts;
1157 struct FsMount *mount;
1158 int fd;
1159 struct fstrim_range r;
1160
1161 slog("guest-fstrim called");
1162
1163 QTAILQ_INIT(&mounts);
1164 if (!build_fs_mount_list(&mounts, errp)) {
1165 return NULL;
1166 }
1167
1168 response = g_malloc0(sizeof(*response));
1169
1170 QTAILQ_FOREACH(mount, &mounts, next) {
1171 result = g_malloc0(sizeof(*result));
1172 result->path = g_strdup(mount->dirname);
1173
1174 QAPI_LIST_PREPEND(response->paths, result);
1175
1176 fd = qga_open_cloexec(mount->dirname, O_RDONLY, 0);
1177 if (fd == -1) {
1178 result->error = g_strdup_printf("failed to open: %s",
1179 strerror(errno));
1180 continue;
1181 }
1182
1183 /* We try to cull filesystems we know won't work in advance, but other
1184 * filesystems may not implement fstrim for less obvious reasons.
1185 * These will report EOPNOTSUPP; while in some other cases ENOTTY
1186 * will be reported (e.g. CD-ROMs).
1187 * Any other error means an unexpected error.
1188 */
1189 r.start = 0;
1190 r.len = -1;
1191 r.minlen = has_minimum ? minimum : 0;
1192 ret = ioctl(fd, FITRIM, &r);
1193 if (ret == -1) {
1194 if (errno == ENOTTY || errno == EOPNOTSUPP) {
1195 result->error = g_strdup("trim not supported");
1196 } else {
1197 result->error = g_strdup_printf("failed to trim: %s",
1198 strerror(errno));
1199 }
1200 close(fd);
1201 continue;
1202 }
1203
1204 result->has_minimum = true;
1205 result->minimum = r.minlen;
1206 result->has_trimmed = true;
1207 result->trimmed = r.len;
1208 close(fd);
1209 }
1210
1211 free_fs_mount_list(&mounts);
1212 return response;
1213 }
1214 #endif /* CONFIG_FSTRIM */
1215
1216 #define LINUX_SYS_STATE_FILE "/sys/power/state"
1217 #define SUSPEND_SUPPORTED 0
1218 #define SUSPEND_NOT_SUPPORTED 1
1219
1220 typedef enum {
1221 SUSPEND_MODE_DISK = 0,
1222 SUSPEND_MODE_RAM = 1,
1223 SUSPEND_MODE_HYBRID = 2,
1224 } SuspendMode;
1225
1226 /*
1227 * Executes a command in a child process using g_spawn_sync,
1228 * returning an int >= 0 representing the exit status of the
1229 * process.
1230 *
1231 * If the program wasn't found in path, returns -1.
1232 *
1233 * If a problem happened when creating the child process,
1234 * returns -1 and errp is set.
1235 */
1236 static int run_process_child(const char *command[], Error **errp)
1237 {
1238 int exit_status, spawn_flag;
1239 GError *g_err = NULL;
1240 bool success;
1241
1242 spawn_flag = G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL |
1243 G_SPAWN_STDERR_TO_DEV_NULL;
1244
1245 success = g_spawn_sync(NULL, (char **)command, NULL, spawn_flag,
1246 NULL, NULL, NULL, NULL,
1247 &exit_status, &g_err);
1248
1249 if (success) {
1250 return WEXITSTATUS(exit_status);
1251 }
1252
1253 if (g_err && (g_err->code != G_SPAWN_ERROR_NOENT)) {
1254 error_setg(errp, "failed to create child process, error '%s'",
1255 g_err->message);
1256 }
1257
1258 g_error_free(g_err);
1259 return -1;
1260 }
1261
1262 static bool systemd_supports_mode(SuspendMode mode, Error **errp)
1263 {
1264 const char *systemctl_args[3] = {"systemd-hibernate", "systemd-suspend",
1265 "systemd-hybrid-sleep"};
1266 const char *cmd[4] = {"systemctl", "status", systemctl_args[mode], NULL};
1267 int status;
1268
1269 status = run_process_child(cmd, errp);
1270
1271 /*
1272 * systemctl status uses LSB return codes so we can expect
1273 * status > 0 and be ok. To assert if the guest has support
1274 * for the selected suspend mode, status should be < 4. 4 is
1275 * the code for unknown service status, the return value when
1276 * the service does not exist. A common value is status = 3
1277 * (program is not running).
1278 */
1279 if (status > 0 && status < 4) {
1280 return true;
1281 }
1282
1283 return false;
1284 }
1285
1286 static void systemd_suspend(SuspendMode mode, Error **errp)
1287 {
1288 Error *local_err = NULL;
1289 const char *systemctl_args[3] = {"hibernate", "suspend", "hybrid-sleep"};
1290 const char *cmd[3] = {"systemctl", systemctl_args[mode], NULL};
1291 int status;
1292
1293 status = run_process_child(cmd, &local_err);
1294
1295 if (status == 0) {
1296 return;
1297 }
1298
1299 if ((status == -1) && !local_err) {
1300 error_setg(errp, "the helper program 'systemctl %s' was not found",
1301 systemctl_args[mode]);
1302 return;
1303 }
1304
1305 if (local_err) {
1306 error_propagate(errp, local_err);
1307 } else {
1308 error_setg(errp, "the helper program 'systemctl %s' returned an "
1309 "unexpected exit status code (%d)",
1310 systemctl_args[mode], status);
1311 }
1312 }
1313
1314 static bool pmutils_supports_mode(SuspendMode mode, Error **errp)
1315 {
1316 Error *local_err = NULL;
1317 const char *pmutils_args[3] = {"--hibernate", "--suspend",
1318 "--suspend-hybrid"};
1319 const char *cmd[3] = {"pm-is-supported", pmutils_args[mode], NULL};
1320 int status;
1321
1322 status = run_process_child(cmd, &local_err);
1323
1324 if (status == SUSPEND_SUPPORTED) {
1325 return true;
1326 }
1327
1328 if ((status == -1) && !local_err) {
1329 return false;
1330 }
1331
1332 if (local_err) {
1333 error_propagate(errp, local_err);
1334 } else {
1335 error_setg(errp,
1336 "the helper program '%s' returned an unexpected exit"
1337 " status code (%d)", "pm-is-supported", status);
1338 }
1339
1340 return false;
1341 }
1342
1343 static void pmutils_suspend(SuspendMode mode, Error **errp)
1344 {
1345 Error *local_err = NULL;
1346 const char *pmutils_binaries[3] = {"pm-hibernate", "pm-suspend",
1347 "pm-suspend-hybrid"};
1348 const char *cmd[2] = {pmutils_binaries[mode], NULL};
1349 int status;
1350
1351 status = run_process_child(cmd, &local_err);
1352
1353 if (status == 0) {
1354 return;
1355 }
1356
1357 if ((status == -1) && !local_err) {
1358 error_setg(errp, "the helper program '%s' was not found",
1359 pmutils_binaries[mode]);
1360 return;
1361 }
1362
1363 if (local_err) {
1364 error_propagate(errp, local_err);
1365 } else {
1366 error_setg(errp,
1367 "the helper program '%s' returned an unexpected exit"
1368 " status code (%d)", pmutils_binaries[mode], status);
1369 }
1370 }
1371
1372 static bool linux_sys_state_supports_mode(SuspendMode mode, Error **errp)
1373 {
1374 const char *sysfile_strs[3] = {"disk", "mem", NULL};
1375 const char *sysfile_str = sysfile_strs[mode];
1376 char buf[32]; /* hopefully big enough */
1377 int fd;
1378 ssize_t ret;
1379
1380 if (!sysfile_str) {
1381 error_setg(errp, "unknown guest suspend mode");
1382 return false;
1383 }
1384
1385 fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);
1386 if (fd < 0) {
1387 return false;
1388 }
1389
1390 ret = read(fd, buf, sizeof(buf) - 1);
1391 close(fd);
1392 if (ret <= 0) {
1393 return false;
1394 }
1395 buf[ret] = '\0';
1396
1397 if (strstr(buf, sysfile_str)) {
1398 return true;
1399 }
1400 return false;
1401 }
1402
1403 static void linux_sys_state_suspend(SuspendMode mode, Error **errp)
1404 {
1405 const char *sysfile_strs[3] = {"disk", "mem", NULL};
1406 const char *sysfile_str = sysfile_strs[mode];
1407 int fd;
1408
1409 if (!sysfile_str) {
1410 error_setg(errp, "unknown guest suspend mode");
1411 return;
1412 }
1413
1414 fd = open(LINUX_SYS_STATE_FILE, O_WRONLY);
1415 if (fd < 0 || write(fd, sysfile_str, strlen(sysfile_str)) < 0) {
1416 error_setg(errp, "suspend: cannot write to '%s': %m",
1417 LINUX_SYS_STATE_FILE);
1418 }
1419 if (fd >= 0) {
1420 close(fd);
1421 }
1422 }
1423
1424 static void guest_suspend(SuspendMode mode, Error **errp)
1425 {
1426 Error *local_err = NULL;
1427 bool mode_supported = false;
1428
1429 if (systemd_supports_mode(mode, &local_err)) {
1430 mode_supported = true;
1431 systemd_suspend(mode, &local_err);
1432
1433 if (!local_err) {
1434 return;
1435 }
1436 }
1437
1438 error_free(local_err);
1439 local_err = NULL;
1440
1441 if (pmutils_supports_mode(mode, &local_err)) {
1442 mode_supported = true;
1443 pmutils_suspend(mode, &local_err);
1444
1445 if (!local_err) {
1446 return;
1447 }
1448 }
1449
1450 error_free(local_err);
1451 local_err = NULL;
1452
1453 if (linux_sys_state_supports_mode(mode, &local_err)) {
1454 mode_supported = true;
1455 linux_sys_state_suspend(mode, &local_err);
1456 }
1457
1458 if (!mode_supported) {
1459 error_free(local_err);
1460 error_setg(errp,
1461 "the requested suspend mode is not supported by the guest");
1462 } else {
1463 error_propagate(errp, local_err);
1464 }
1465 }
1466
1467 void qmp_guest_suspend_disk(Error **errp)
1468 {
1469 guest_suspend(SUSPEND_MODE_DISK, errp);
1470 }
1471
1472 void qmp_guest_suspend_ram(Error **errp)
1473 {
1474 guest_suspend(SUSPEND_MODE_RAM, errp);
1475 }
1476
1477 void qmp_guest_suspend_hybrid(Error **errp)
1478 {
1479 guest_suspend(SUSPEND_MODE_HYBRID, errp);
1480 }
1481
1482 /* Transfer online/offline status between @vcpu and the guest system.
1483 *
1484 * On input either @errp or *@errp must be NULL.
1485 *
1486 * In system-to-@vcpu direction, the following @vcpu fields are accessed:
1487 * - R: vcpu->logical_id
1488 * - W: vcpu->online
1489 * - W: vcpu->can_offline
1490 *
1491 * In @vcpu-to-system direction, the following @vcpu fields are accessed:
1492 * - R: vcpu->logical_id
1493 * - R: vcpu->online
1494 *
1495 * Written members remain unmodified on error.
1496 */
1497 static void transfer_vcpu(GuestLogicalProcessor *vcpu, bool sys2vcpu,
1498 char *dirpath, Error **errp)
1499 {
1500 int fd;
1501 int res;
1502 int dirfd;
1503 static const char fn[] = "online";
1504
1505 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
1506 if (dirfd == -1) {
1507 error_setg_file_open(errp, errno, dirpath);
1508 return;
1509 }
1510
1511 fd = openat(dirfd, fn, sys2vcpu ? O_RDONLY : O_RDWR);
1512 if (fd == -1) {
1513 if (errno != ENOENT) {
1514 error_setg_errno(errp, errno, "could not open %s/%s",
1515 dirpath, fn);
1516 } else if (sys2vcpu) {
1517 vcpu->online = true;
1518 vcpu->can_offline = false;
1519 } else if (!vcpu->online) {
1520 error_setg(errp, "logical processor #%" PRId64 " can't be "
1521 "offlined", vcpu->logical_id);
1522 } /* otherwise pretend successful re-onlining */
1523 } else {
1524 unsigned char status;
1525
1526 res = pread(fd, &status, 1, 0);
1527 if (res == -1) {
1528 error_setg_errno(errp, errno, "pread(\"%s/%s\")", dirpath, fn);
1529 } else if (res == 0) {
1530 error_setg(errp, "pread(\"%s/%s\"): unexpected EOF", dirpath,
1531 fn);
1532 } else if (sys2vcpu) {
1533 vcpu->online = (status != '0');
1534 vcpu->can_offline = true;
1535 } else if (vcpu->online != (status != '0')) {
1536 status = '0' + vcpu->online;
1537 if (pwrite(fd, &status, 1, 0) == -1) {
1538 error_setg_errno(errp, errno, "pwrite(\"%s/%s\")", dirpath,
1539 fn);
1540 }
1541 } /* otherwise pretend successful re-(on|off)-lining */
1542
1543 res = close(fd);
1544 g_assert(res == 0);
1545 }
1546
1547 res = close(dirfd);
1548 g_assert(res == 0);
1549 }
1550
1551 GuestLogicalProcessorList *qmp_guest_get_vcpus(Error **errp)
1552 {
1553 GuestLogicalProcessorList *head, **tail;
1554 const char *cpu_dir = "/sys/devices/system/cpu";
1555 const gchar *line;
1556 g_autoptr(GDir) cpu_gdir = NULL;
1557 Error *local_err = NULL;
1558
1559 head = NULL;
1560 tail = &head;
1561 cpu_gdir = g_dir_open(cpu_dir, 0, NULL);
1562
1563 if (cpu_gdir == NULL) {
1564 error_setg_errno(errp, errno, "failed to list entries: %s", cpu_dir);
1565 return NULL;
1566 }
1567
1568 while (local_err == NULL && (line = g_dir_read_name(cpu_gdir)) != NULL) {
1569 GuestLogicalProcessor *vcpu;
1570 int64_t id;
1571 if (sscanf(line, "cpu%" PRId64, &id)) {
1572 g_autofree char *path = g_strdup_printf("/sys/devices/system/cpu/"
1573 "cpu%" PRId64 "/", id);
1574 vcpu = g_malloc0(sizeof *vcpu);
1575 vcpu->logical_id = id;
1576 vcpu->has_can_offline = true; /* lolspeak ftw */
1577 transfer_vcpu(vcpu, true, path, &local_err);
1578 QAPI_LIST_APPEND(tail, vcpu);
1579 }
1580 }
1581
1582 if (local_err == NULL) {
1583 /* there's no guest with zero VCPUs */
1584 g_assert(head != NULL);
1585 return head;
1586 }
1587
1588 qapi_free_GuestLogicalProcessorList(head);
1589 error_propagate(errp, local_err);
1590 return NULL;
1591 }
1592
1593 int64_t qmp_guest_set_vcpus(GuestLogicalProcessorList *vcpus, Error **errp)
1594 {
1595 int64_t processed;
1596 Error *local_err = NULL;
1597
1598 processed = 0;
1599 while (vcpus != NULL) {
1600 char *path = g_strdup_printf("/sys/devices/system/cpu/cpu%" PRId64 "/",
1601 vcpus->value->logical_id);
1602
1603 transfer_vcpu(vcpus->value, false, path, &local_err);
1604 g_free(path);
1605 if (local_err != NULL) {
1606 break;
1607 }
1608 ++processed;
1609 vcpus = vcpus->next;
1610 }
1611
1612 if (local_err != NULL) {
1613 if (processed == 0) {
1614 error_propagate(errp, local_err);
1615 } else {
1616 error_free(local_err);
1617 }
1618 }
1619
1620 return processed;
1621 }
1622
1623
1624 static void ga_read_sysfs_file(int dirfd, const char *pathname, char *buf,
1625 int size, Error **errp)
1626 {
1627 int fd;
1628 int res;
1629
1630 errno = 0;
1631 fd = openat(dirfd, pathname, O_RDONLY);
1632 if (fd == -1) {
1633 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
1634 return;
1635 }
1636
1637 res = pread(fd, buf, size, 0);
1638 if (res == -1) {
1639 error_setg_errno(errp, errno, "pread sysfs file \"%s\"", pathname);
1640 } else if (res == 0) {
1641 error_setg(errp, "pread sysfs file \"%s\": unexpected EOF", pathname);
1642 }
1643 close(fd);
1644 }
1645
1646 static void ga_write_sysfs_file(int dirfd, const char *pathname,
1647 const char *buf, int size, Error **errp)
1648 {
1649 int fd;
1650
1651 errno = 0;
1652 fd = openat(dirfd, pathname, O_WRONLY);
1653 if (fd == -1) {
1654 error_setg_errno(errp, errno, "open sysfs file \"%s\"", pathname);
1655 return;
1656 }
1657
1658 if (pwrite(fd, buf, size, 0) == -1) {
1659 error_setg_errno(errp, errno, "pwrite sysfs file \"%s\"", pathname);
1660 }
1661
1662 close(fd);
1663 }
1664
1665 /* Transfer online/offline status between @mem_blk and the guest system.
1666 *
1667 * On input either @errp or *@errp must be NULL.
1668 *
1669 * In system-to-@mem_blk direction, the following @mem_blk fields are accessed:
1670 * - R: mem_blk->phys_index
1671 * - W: mem_blk->online
1672 * - W: mem_blk->can_offline
1673 *
1674 * In @mem_blk-to-system direction, the following @mem_blk fields are accessed:
1675 * - R: mem_blk->phys_index
1676 * - R: mem_blk->online
1677 *- R: mem_blk->can_offline
1678 * Written members remain unmodified on error.
1679 */
1680 static void transfer_memory_block(GuestMemoryBlock *mem_blk, bool sys2memblk,
1681 GuestMemoryBlockResponse *result,
1682 Error **errp)
1683 {
1684 char *dirpath;
1685 int dirfd;
1686 char *status;
1687 Error *local_err = NULL;
1688
1689 if (!sys2memblk) {
1690 DIR *dp;
1691
1692 if (!result) {
1693 error_setg(errp, "Internal error, 'result' should not be NULL");
1694 return;
1695 }
1696 errno = 0;
1697 dp = opendir("/sys/devices/system/memory/");
1698 /* if there is no 'memory' directory in sysfs,
1699 * we think this VM does not support online/offline memory block,
1700 * any other solution?
1701 */
1702 if (!dp) {
1703 if (errno == ENOENT) {
1704 result->response =
1705 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
1706 }
1707 goto out1;
1708 }
1709 closedir(dp);
1710 }
1711
1712 dirpath = g_strdup_printf("/sys/devices/system/memory/memory%" PRId64 "/",
1713 mem_blk->phys_index);
1714 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
1715 if (dirfd == -1) {
1716 if (sys2memblk) {
1717 error_setg_file_open(errp, errno, dirpath);
1718 } else {
1719 if (errno == ENOENT) {
1720 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_NOT_FOUND;
1721 } else {
1722 result->response =
1723 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
1724 }
1725 }
1726 g_free(dirpath);
1727 goto out1;
1728 }
1729 g_free(dirpath);
1730
1731 status = g_malloc0(10);
1732 ga_read_sysfs_file(dirfd, "state", status, 10, &local_err);
1733 if (local_err) {
1734 /* treat with sysfs file that not exist in old kernel */
1735 if (errno == ENOENT) {
1736 error_free(local_err);
1737 if (sys2memblk) {
1738 mem_blk->online = true;
1739 mem_blk->can_offline = false;
1740 } else if (!mem_blk->online) {
1741 result->response =
1742 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_NOT_SUPPORTED;
1743 }
1744 } else {
1745 if (sys2memblk) {
1746 error_propagate(errp, local_err);
1747 } else {
1748 error_free(local_err);
1749 result->response =
1750 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
1751 }
1752 }
1753 goto out2;
1754 }
1755
1756 if (sys2memblk) {
1757 char removable = '0';
1758
1759 mem_blk->online = (strncmp(status, "online", 6) == 0);
1760
1761 ga_read_sysfs_file(dirfd, "removable", &removable, 1, &local_err);
1762 if (local_err) {
1763 /* if no 'removable' file, it doesn't support offline mem blk */
1764 if (errno == ENOENT) {
1765 error_free(local_err);
1766 mem_blk->can_offline = false;
1767 } else {
1768 error_propagate(errp, local_err);
1769 }
1770 } else {
1771 mem_blk->can_offline = (removable != '0');
1772 }
1773 } else {
1774 if (mem_blk->online != (strncmp(status, "online", 6) == 0)) {
1775 const char *new_state = mem_blk->online ? "online" : "offline";
1776
1777 ga_write_sysfs_file(dirfd, "state", new_state, strlen(new_state),
1778 &local_err);
1779 if (local_err) {
1780 error_free(local_err);
1781 result->response =
1782 GUEST_MEMORY_BLOCK_RESPONSE_TYPE_OPERATION_FAILED;
1783 goto out2;
1784 }
1785
1786 result->response = GUEST_MEMORY_BLOCK_RESPONSE_TYPE_SUCCESS;
1787 result->has_error_code = false;
1788 } /* otherwise pretend successful re-(on|off)-lining */
1789 }
1790 g_free(status);
1791 close(dirfd);
1792 return;
1793
1794 out2:
1795 g_free(status);
1796 close(dirfd);
1797 out1:
1798 if (!sys2memblk) {
1799 result->has_error_code = true;
1800 result->error_code = errno;
1801 }
1802 }
1803
1804 GuestMemoryBlockList *qmp_guest_get_memory_blocks(Error **errp)
1805 {
1806 GuestMemoryBlockList *head, **tail;
1807 Error *local_err = NULL;
1808 struct dirent *de;
1809 DIR *dp;
1810
1811 head = NULL;
1812 tail = &head;
1813
1814 dp = opendir("/sys/devices/system/memory/");
1815 if (!dp) {
1816 /* it's ok if this happens to be a system that doesn't expose
1817 * memory blocks via sysfs, but otherwise we should report
1818 * an error
1819 */
1820 if (errno != ENOENT) {
1821 error_setg_errno(errp, errno, "Can't open directory"
1822 "\"/sys/devices/system/memory/\"");
1823 }
1824 return NULL;
1825 }
1826
1827 /* Note: the phys_index of memory block may be discontinuous,
1828 * this is because a memblk is the unit of the Sparse Memory design, which
1829 * allows discontinuous memory ranges (ex. NUMA), so here we should
1830 * traverse the memory block directory.
1831 */
1832 while ((de = readdir(dp)) != NULL) {
1833 GuestMemoryBlock *mem_blk;
1834
1835 if ((strncmp(de->d_name, "memory", 6) != 0) ||
1836 !(de->d_type & DT_DIR)) {
1837 continue;
1838 }
1839
1840 mem_blk = g_malloc0(sizeof *mem_blk);
1841 /* The d_name is "memoryXXX", phys_index is block id, same as XXX */
1842 mem_blk->phys_index = strtoul(&de->d_name[6], NULL, 10);
1843 mem_blk->has_can_offline = true; /* lolspeak ftw */
1844 transfer_memory_block(mem_blk, true, NULL, &local_err);
1845 if (local_err) {
1846 break;
1847 }
1848
1849 QAPI_LIST_APPEND(tail, mem_blk);
1850 }
1851
1852 closedir(dp);
1853 if (local_err == NULL) {
1854 /* there's no guest with zero memory blocks */
1855 if (head == NULL) {
1856 error_setg(errp, "guest reported zero memory blocks!");
1857 }
1858 return head;
1859 }
1860
1861 qapi_free_GuestMemoryBlockList(head);
1862 error_propagate(errp, local_err);
1863 return NULL;
1864 }
1865
1866 GuestMemoryBlockResponseList *
1867 qmp_guest_set_memory_blocks(GuestMemoryBlockList *mem_blks, Error **errp)
1868 {
1869 GuestMemoryBlockResponseList *head, **tail;
1870 Error *local_err = NULL;
1871
1872 head = NULL;
1873 tail = &head;
1874
1875 while (mem_blks != NULL) {
1876 GuestMemoryBlockResponse *result;
1877 GuestMemoryBlock *current_mem_blk = mem_blks->value;
1878
1879 result = g_malloc0(sizeof(*result));
1880 result->phys_index = current_mem_blk->phys_index;
1881 transfer_memory_block(current_mem_blk, false, result, &local_err);
1882 if (local_err) { /* should never happen */
1883 goto err;
1884 }
1885
1886 QAPI_LIST_APPEND(tail, result);
1887 mem_blks = mem_blks->next;
1888 }
1889
1890 return head;
1891 err:
1892 qapi_free_GuestMemoryBlockResponseList(head);
1893 error_propagate(errp, local_err);
1894 return NULL;
1895 }
1896
1897 GuestMemoryBlockInfo *qmp_guest_get_memory_block_info(Error **errp)
1898 {
1899 Error *local_err = NULL;
1900 char *dirpath;
1901 int dirfd;
1902 char *buf;
1903 GuestMemoryBlockInfo *info;
1904
1905 dirpath = g_strdup_printf("/sys/devices/system/memory/");
1906 dirfd = open(dirpath, O_RDONLY | O_DIRECTORY);
1907 if (dirfd == -1) {
1908 error_setg_errno(errp, errno, "open(\"%s\")", dirpath);
1909 g_free(dirpath);
1910 return NULL;
1911 }
1912 g_free(dirpath);
1913
1914 buf = g_malloc0(20);
1915 ga_read_sysfs_file(dirfd, "block_size_bytes", buf, 20, &local_err);
1916 close(dirfd);
1917 if (local_err) {
1918 g_free(buf);
1919 error_propagate(errp, local_err);
1920 return NULL;
1921 }
1922
1923 info = g_new0(GuestMemoryBlockInfo, 1);
1924 info->size = strtol(buf, NULL, 16); /* the unit is bytes */
1925
1926 g_free(buf);
1927
1928 return info;
1929 }
1930
1931 #define MAX_NAME_LEN 128
1932 static GuestDiskStatsInfoList *guest_get_diskstats(Error **errp)
1933 {
1934 GuestDiskStatsInfoList *head = NULL, **tail = &head;
1935 const char *diskstats = "/proc/diskstats";
1936 FILE *fp;
1937 size_t n;
1938 char *line = NULL;
1939
1940 fp = fopen(diskstats, "r");
1941 if (fp == NULL) {
1942 error_setg_file_open(errp, errno, diskstats);
1943 return NULL;
1944 }
1945
1946 while (getline(&line, &n, fp) != -1) {
1947 g_autofree GuestDiskStatsInfo *diskstatinfo = NULL;
1948 g_autofree GuestDiskStats *diskstat = NULL;
1949 char dev_name[MAX_NAME_LEN];
1950 unsigned int ios_pgr, tot_ticks, rq_ticks, wr_ticks, dc_ticks, fl_ticks;
1951 unsigned long rd_ios, rd_merges_or_rd_sec, rd_ticks_or_wr_sec, wr_ios;
1952 unsigned long wr_merges, rd_sec_or_wr_ios, wr_sec;
1953 unsigned long dc_ios, dc_merges, dc_sec, fl_ios;
1954 unsigned int major, minor;
1955 int i;
1956
1957 i = sscanf(line, "%u %u %s %lu %lu %lu"
1958 "%lu %lu %lu %lu %u %u %u %u"
1959 "%lu %lu %lu %u %lu %u",
1960 &major, &minor, dev_name,
1961 &rd_ios, &rd_merges_or_rd_sec, &rd_sec_or_wr_ios,
1962 &rd_ticks_or_wr_sec, &wr_ios, &wr_merges, &wr_sec,
1963 &wr_ticks, &ios_pgr, &tot_ticks, &rq_ticks,
1964 &dc_ios, &dc_merges, &dc_sec, &dc_ticks,
1965 &fl_ios, &fl_ticks);
1966
1967 if (i < 7) {
1968 continue;
1969 }
1970
1971 diskstatinfo = g_new0(GuestDiskStatsInfo, 1);
1972 diskstatinfo->name = g_strdup(dev_name);
1973 diskstatinfo->major = major;
1974 diskstatinfo->minor = minor;
1975
1976 diskstat = g_new0(GuestDiskStats, 1);
1977 if (i == 7) {
1978 diskstat->has_read_ios = true;
1979 diskstat->read_ios = rd_ios;
1980 diskstat->has_read_sectors = true;
1981 diskstat->read_sectors = rd_merges_or_rd_sec;
1982 diskstat->has_write_ios = true;
1983 diskstat->write_ios = rd_sec_or_wr_ios;
1984 diskstat->has_write_sectors = true;
1985 diskstat->write_sectors = rd_ticks_or_wr_sec;
1986 }
1987 if (i >= 14) {
1988 diskstat->has_read_ios = true;
1989 diskstat->read_ios = rd_ios;
1990 diskstat->has_read_sectors = true;
1991 diskstat->read_sectors = rd_sec_or_wr_ios;
1992 diskstat->has_read_merges = true;
1993 diskstat->read_merges = rd_merges_or_rd_sec;
1994 diskstat->has_read_ticks = true;
1995 diskstat->read_ticks = rd_ticks_or_wr_sec;
1996 diskstat->has_write_ios = true;
1997 diskstat->write_ios = wr_ios;
1998 diskstat->has_write_sectors = true;
1999 diskstat->write_sectors = wr_sec;
2000 diskstat->has_write_merges = true;
2001 diskstat->write_merges = wr_merges;
2002 diskstat->has_write_ticks = true;
2003 diskstat->write_ticks = wr_ticks;
2004 diskstat->has_ios_pgr = true;
2005 diskstat->ios_pgr = ios_pgr;
2006 diskstat->has_total_ticks = true;
2007 diskstat->total_ticks = tot_ticks;
2008 diskstat->has_weight_ticks = true;
2009 diskstat->weight_ticks = rq_ticks;
2010 }
2011 if (i >= 18) {
2012 diskstat->has_discard_ios = true;
2013 diskstat->discard_ios = dc_ios;
2014 diskstat->has_discard_merges = true;
2015 diskstat->discard_merges = dc_merges;
2016 diskstat->has_discard_sectors = true;
2017 diskstat->discard_sectors = dc_sec;
2018 diskstat->has_discard_ticks = true;
2019 diskstat->discard_ticks = dc_ticks;
2020 }
2021 if (i >= 20) {
2022 diskstat->has_flush_ios = true;
2023 diskstat->flush_ios = fl_ios;
2024 diskstat->has_flush_ticks = true;
2025 diskstat->flush_ticks = fl_ticks;
2026 }
2027
2028 diskstatinfo->stats = g_steal_pointer(&diskstat);
2029 QAPI_LIST_APPEND(tail, diskstatinfo);
2030 diskstatinfo = NULL;
2031 }
2032 free(line);
2033 fclose(fp);
2034 return head;
2035 }
2036
2037 GuestDiskStatsInfoList *qmp_guest_get_diskstats(Error **errp)
2038 {
2039 return guest_get_diskstats(errp);
2040 }
2041
2042 GuestCpuStatsList *qmp_guest_get_cpustats(Error **errp)
2043 {
2044 GuestCpuStatsList *head = NULL, **tail = &head;
2045 const char *cpustats = "/proc/stat";
2046 int clk_tck = sysconf(_SC_CLK_TCK);
2047 FILE *fp;
2048 size_t n;
2049 char *line = NULL;
2050
2051 fp = fopen(cpustats, "r");
2052 if (fp == NULL) {
2053 error_setg_file_open(errp, errno, cpustats);
2054 return NULL;
2055 }
2056
2057 while (getline(&line, &n, fp) != -1) {
2058 GuestCpuStats *cpustat = NULL;
2059 GuestLinuxCpuStats *linuxcpustat;
2060 int i;
2061 unsigned long user, system, idle, iowait, irq, softirq, steal, guest;
2062 unsigned long nice, guest_nice;
2063 char name[64];
2064
2065 i = sscanf(line, "%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
2066 name, &user, &nice, &system, &idle, &iowait, &irq, &softirq,
2067 &steal, &guest, &guest_nice);
2068
2069 /* drop "cpu 1 2 3 ...", get "cpuX 1 2 3 ..." only */
2070 if ((i == EOF) || strncmp(name, "cpu", 3) || (name[3] == '\0')) {
2071 continue;
2072 }
2073
2074 if (i < 5) {
2075 slog("Parsing cpu stat from %s failed, see \"man proc\"", cpustats);
2076 break;
2077 }
2078
2079 cpustat = g_new0(GuestCpuStats, 1);
2080 cpustat->type = GUEST_CPU_STATS_TYPE_LINUX;
2081
2082 linuxcpustat = &cpustat->u.q_linux;
2083 linuxcpustat->cpu = atoi(&name[3]);
2084 linuxcpustat->user = user * 1000 / clk_tck;
2085 linuxcpustat->nice = nice * 1000 / clk_tck;
2086 linuxcpustat->system = system * 1000 / clk_tck;
2087 linuxcpustat->idle = idle * 1000 / clk_tck;
2088
2089 if (i > 5) {
2090 linuxcpustat->has_iowait = true;
2091 linuxcpustat->iowait = iowait * 1000 / clk_tck;
2092 }
2093
2094 if (i > 6) {
2095 linuxcpustat->has_irq = true;
2096 linuxcpustat->irq = irq * 1000 / clk_tck;
2097 linuxcpustat->has_softirq = true;
2098 linuxcpustat->softirq = softirq * 1000 / clk_tck;
2099 }
2100
2101 if (i > 8) {
2102 linuxcpustat->has_steal = true;
2103 linuxcpustat->steal = steal * 1000 / clk_tck;
2104 }
2105
2106 if (i > 9) {
2107 linuxcpustat->has_guest = true;
2108 linuxcpustat->guest = guest * 1000 / clk_tck;
2109 }
2110
2111 if (i > 10) {
2112 linuxcpustat->has_guest = true;
2113 linuxcpustat->guest = guest * 1000 / clk_tck;
2114 linuxcpustat->has_guestnice = true;
2115 linuxcpustat->guestnice = guest_nice * 1000 / clk_tck;
2116 }
2117
2118 QAPI_LIST_APPEND(tail, cpustat);
2119 }
2120
2121 free(line);
2122 fclose(fp);
2123 return head;
2124 }
2125
2126 static char *hex_to_ip_address(const void *hex_value, int is_ipv6)
2127 {
2128 if (is_ipv6) {
2129 char addr[INET6_ADDRSTRLEN];
2130 struct in6_addr in6;
2131 const char *hex_str = (const char *)hex_value;
2132 int i;
2133
2134 for (i = 0; i < 16; i++) {
2135 if (sscanf(&hex_str[i * 2], "%02hhx", &in6.s6_addr[i]) != 1) {
2136 return NULL;
2137 }
2138 }
2139 inet_ntop(AF_INET6, &in6, addr, INET6_ADDRSTRLEN);
2140
2141 return g_strdup(addr);
2142 } else {
2143 unsigned int hex_int = *(unsigned int *)hex_value;
2144 unsigned int byte1 = (hex_int >> 24) & 0xFF;
2145 unsigned int byte2 = (hex_int >> 16) & 0xFF;
2146 unsigned int byte3 = (hex_int >> 8) & 0xFF;
2147 unsigned int byte4 = hex_int & 0xFF;
2148
2149 return g_strdup_printf("%u.%u.%u.%u", byte4, byte3, byte2, byte1);
2150 }
2151 }
2152
2153 GuestNetworkRouteList *qmp_guest_network_get_route(Error **errp)
2154 {
2155 GuestNetworkRouteList *head = NULL, **tail = &head;
2156 const char *route_files[] = {"/proc/net/route", "/proc/net/ipv6_route"};
2157 FILE *fp;
2158 size_t n = 0;
2159 char *line = NULL;
2160 int firstLine;
2161 int is_ipv6;
2162 int i;
2163 char iface[IFNAMSIZ];
2164
2165 for (i = 0; i < 2; i++) {
2166 firstLine = 1;
2167 is_ipv6 = (i == 1);
2168 fp = fopen(route_files[i], "r");
2169 if (fp == NULL) {
2170 error_setg_errno(errp, errno, "open(\"%s\")", route_files[i]);
2171 continue;
2172 }
2173
2174 while (getline(&line, &n, fp) != -1) {
2175 if (firstLine && !is_ipv6) {
2176 firstLine = 0;
2177 continue;
2178 }
2179 g_autoptr(GuestNetworkRoute) route = g_new0(GuestNetworkRoute, 1);
2180
2181 if (is_ipv6) {
2182 char destination[33], source[33], next_hop[33];
2183 int des_prefixlen, src_prefixlen, metric, refcnt, use, flags;
2184 if (sscanf(line, "%32s %x %32s %x %32s %x %x %x %x %s",
2185 destination, &des_prefixlen, source,
2186 &src_prefixlen, next_hop, &metric, &refcnt,
2187 &use, &flags, iface) != 10) {
2188 continue;
2189 }
2190
2191 route->destination = hex_to_ip_address(destination, 1);
2192 if (route->destination == NULL) {
2193 continue;
2194 }
2195 route->iface = g_strdup(iface);
2196 route->source = hex_to_ip_address(source, 1);
2197 route->nexthop = hex_to_ip_address(next_hop, 1);
2198 route->desprefixlen = g_strdup_printf("%d", des_prefixlen);
2199 route->srcprefixlen = g_strdup_printf("%d", src_prefixlen);
2200 route->metric = metric;
2201 route->has_flags = true;
2202 route->flags = flags;
2203 route->has_refcnt = true;
2204 route->refcnt = refcnt;
2205 route->has_use = true;
2206 route->use = use;
2207 route->version = 6;
2208 } else {
2209 unsigned int destination, gateway, mask, flags;
2210 int refcnt, use, metric, mtu, window, irtt;
2211 if (sscanf(line, "%s %X %X %x %d %d %d %X %d %d %d",
2212 iface, &destination, &gateway, &flags, &refcnt,
2213 &use, &metric, &mask, &mtu, &window, &irtt) != 11) {
2214 continue;
2215 }
2216
2217 route->destination = hex_to_ip_address(&destination, 0);
2218 if (route->destination == NULL) {
2219 continue;
2220 }
2221 route->iface = g_strdup(iface);
2222 route->gateway = hex_to_ip_address(&gateway, 0);
2223 route->mask = hex_to_ip_address(&mask, 0);
2224 route->metric = metric;
2225 route->has_flags = true;
2226 route->flags = flags;
2227 route->has_refcnt = true;
2228 route->refcnt = refcnt;
2229 route->has_use = true;
2230 route->use = use;
2231 route->has_mtu = true;
2232 route->mtu = mtu;
2233 route->has_window = true;
2234 route->window = window;
2235 route->has_irtt = true;
2236 route->irtt = irtt;
2237 route->version = 4;
2238 }
2239
2240 QAPI_LIST_APPEND(tail, route);
2241 route = NULL;
2242 }
2243
2244 fclose(fp);
2245 }
2246
2247 free(line);
2248 return head;
2249 }