vircgroupv2.c 50.0 KB
Newer Older
P
Pavel Hrdina 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * vircgroupv2.c: methods for cgroups v2 backend
 *
 * Copyright (C) 2018 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <config.h>

22 23
#ifdef __linux__
# include <mntent.h>
24
# include <sys/mount.h>
25 26
#endif /* __linux__ */

P
Pavel Hrdina 已提交
27 28
#include "internal.h"

29
#define LIBVIRT_VIRCGROUPPRIV_H_ALLOW
P
Pavel Hrdina 已提交
30 31
#include "vircgrouppriv.h"

32
#include "viralloc.h"
P
Pavel Hrdina 已提交
33 34 35
#include "vircgroup.h"
#include "vircgroupbackend.h"
#include "vircgroupv2.h"
36
#include "vircgroupv2devices.h"
37
#include "virerror.h"
38
#include "virfile.h"
P
Pavel Hrdina 已提交
39
#include "virlog.h"
40
#include "virstring.h"
41
#include "virsystemd.h"
P
Pavel Hrdina 已提交
42 43 44 45 46 47

VIR_LOG_INIT("util.cgroup");

#define VIR_FROM_THIS VIR_FROM_CGROUP

VIR_ENUM_DECL(virCgroupV2Controller);
48 49
VIR_ENUM_IMPL(virCgroupV2Controller,
              VIR_CGROUP_CONTROLLER_LAST,
P
Pavel Hrdina 已提交
50
              "cpu", "cpuacct", "cpuset", "memory", "devices",
51 52
              "freezer", "io", "net_cls", "perf_event", "name=systemd",
);
P
Pavel Hrdina 已提交
53 54 55

#ifdef __linux__

56 57 58 59 60 61 62 63 64 65 66 67 68 69
/* We're looking for one 'cgroup2' fs mount which has some
 * controllers enabled. */
static bool
virCgroupV2Available(void)
{
    bool ret = false;
    FILE *mounts = NULL;
    struct mntent entry;
    char buf[CGROUP_MAX_VAL];

    if (!(mounts = fopen("/proc/mounts", "r")))
        return false;

    while (getmntent_r(mounts, &entry, buf, sizeof(buf)) != NULL) {
70 71
        g_autofree char *contFile = NULL;
        g_autofree char *contStr = NULL;
72 73 74 75 76 77 78

        if (STRNEQ(entry.mnt_type, "cgroup2"))
            continue;

        /* Systemd uses cgroup v2 for process tracking but no controller is
         * available. We should consider this configuration as cgroup v2 is
         * not available. */
79
        contFile = g_strdup_printf("%s/cgroup.controllers", entry.mnt_dir);
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

        if (virFileReadAll(contFile, 1024 * 1024, &contStr) < 0)
            goto cleanup;

        if (STREQ(contStr, ""))
            continue;

        ret = true;
        break;
    }

 cleanup:
    VIR_FORCE_FCLOSE(mounts);
    return ret;
}


97 98
static bool
virCgroupV2ValidateMachineGroup(virCgroupPtr group,
J
Ján Tomko 已提交
99
                                const char *name G_GNUC_UNUSED,
100 101 102
                                const char *drivername,
                                const char *machinename)
{
103 104
    g_autofree char *partmachinename = NULL;
    g_autofree char *scopename = NULL;
105 106
    char *tmp;

107
    partmachinename = g_strdup_printf("%s.libvirt-%s", machinename, drivername);
108 109 110 111 112 113 114 115 116 117 118 119 120 121

    if (virCgroupPartitionEscape(&partmachinename) < 0)
        return false;

    if (!(scopename = virSystemdMakeScopeName(machinename, drivername,
                                              false))) {
        return false;
    }

    if (virCgroupPartitionEscape(&scopename) < 0)
        return false;

    if (!(tmp = strrchr(group->unified.placement, '/')))
        return false;
122 123 124 125 126 127 128

    if (STREQ(tmp, "/emulator")) {
        *tmp = '\0';

        if (!(tmp = strrchr(group->unified.placement, '/')))
            return false;
    }
129 130 131 132 133 134 135 136 137 138 139 140 141
    tmp++;

    if (STRNEQ(tmp, partmachinename) &&
        STRNEQ(tmp, scopename)) {
        VIR_DEBUG("Name '%s' for unified does not match '%s' or '%s'",
                  tmp, partmachinename, scopename);
        return false;
    }

    return true;
}


142 143 144 145
static int
virCgroupV2CopyMounts(virCgroupPtr group,
                      virCgroupPtr parent)
{
146 147
    group->unified.mountPoint = g_strdup(parent->unified.mountPoint);
    return 0;
148 149 150
}


151 152 153 154 155
static int
virCgroupV2CopyPlacement(virCgroupPtr group,
                         const char *path,
                         virCgroupPtr parent)
{
156 157
    VIR_DEBUG("group=%p path=%s parent=%p", group, path, parent);

158
    if (path[0] == '/') {
159
        group->unified.placement = g_strdup(path);
160
    } else {
161
        bool delim = STREQ(parent->unified.placement, "/") || STREQ(path, "");
162 163 164 165 166
        /*
         * parent == "/" + path="" => "/"
         * parent == "/libvirt.service" + path == "" => "/libvirt.service"
         * parent == "/libvirt.service" + path == "foo" => "/libvirt.service/foo"
         */
167 168 169 170
        group->unified.placement = g_strdup_printf("%s%s%s",
                                                   parent->unified.placement,
                                                   delim ? "" : "/",
                                                   path);
171 172 173 174 175 176
    }

    return 0;
}


177 178 179
static int
virCgroupV2DetectMounts(virCgroupPtr group,
                        const char *mntType,
J
Ján Tomko 已提交
180
                        const char *mntOpts G_GNUC_UNUSED,
181 182 183 184 185 186 187
                        const char *mntDir)
{
    if (STRNEQ(mntType, "cgroup2"))
        return 0;

    VIR_FREE(group->unified.mountPoint);

188 189
    group->unified.mountPoint = g_strdup(mntDir);
    return 0;
190 191 192
}


193 194 195
static int
virCgroupV2DetectPlacement(virCgroupPtr group,
                           const char *path,
196
                           const char *controllers,
197 198 199 200 201
                           const char *selfpath)
{
    if (group->unified.placement)
        return 0;

202 203 204
    VIR_DEBUG("group=%p path=%s controllers=%s selfpath=%s",
              group, path, controllers, selfpath);

205 206 207 208
    /* controllers == "" indicates the cgroupv2 controller path */
    if (STRNEQ(controllers, ""))
        return 0;

209 210 211 212 213
    /*
     * selfpath == "/" + path="" -> "/"
     * selfpath == "/libvirt.service" + path == "" -> "/libvirt.service"
     * selfpath == "/libvirt.service" + path == "foo" -> "/libvirt.service/foo"
     */
214 215
    group->unified.placement = g_strdup_printf("%s%s%s", selfpath,
                                               (STREQ(selfpath, "/") || STREQ(path, "") ? "" : "/"), path);
216 217 218 219 220

    return 0;
}


221 222
static int
virCgroupV2ValidatePlacement(virCgroupPtr group,
J
Ján Tomko 已提交
223
                             pid_t pid G_GNUC_UNUSED)
224 225 226 227 228 229 230 231 232 233 234
{
    if (!group->unified.placement) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not find placement for v2 controller"));
        return -1;
    }

    return 0;
}


235 236 237
static char *
virCgroupV2StealPlacement(virCgroupPtr group)
{
M
Michal Privoznik 已提交
238
    return g_steal_pointer(&group->unified.placement);
239 240 241
}


242
static int
243 244
virCgroupV2ParseControllersFile(virCgroupPtr group,
                                virCgroupPtr parent)
245 246
{
    int rc;
247 248
    g_autofree char *contStr = NULL;
    g_autofree char *contFile = NULL;
249 250 251
    char **contList = NULL;
    char **tmp;

252
    if (parent) {
253 254 255
        contFile = g_strdup_printf("%s%s/cgroup.subtree_control",
                                   parent->unified.mountPoint,
                                   NULLSTR_EMPTY(parent->unified.placement));
256
    } else {
257 258 259
        contFile = g_strdup_printf("%s%s/cgroup.controllers",
                                   group->unified.mountPoint,
                                   NULLSTR_EMPTY(group->unified.placement));
260
    }
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

    rc = virFileReadAll(contFile, 1024 * 1024, &contStr);
    if (rc < 0) {
        virReportSystemError(errno, _("Unable to read from '%s'"), contFile);
        return -1;
    }

    virTrimSpaces(contStr, NULL);

    contList = virStringSplit(contStr, " ", 20);
    if (!contList)
        return -1;

    tmp = contList;

    while (*tmp) {
        int type = virCgroupV2ControllerTypeFromString(*tmp);

        if (type >= 0)
            group->unified.controllers |= 1 << type;

        tmp++;
    }

    virStringListFree(contList);

    return 0;
}


static int
virCgroupV2DetectControllers(virCgroupPtr group,
293 294
                             int controllers,
                             virCgroupPtr parent)
295 296 297
{
    size_t i;

298
    if (virCgroupV2ParseControllersFile(group, parent) < 0)
299
        return -1;
300

301 302 303
    /* In cgroup v2 there is no cpuacct controller, the cpu.stat file always
     * exists with usage stats. */
    group->unified.controllers |= 1 << VIR_CGROUP_CONTROLLER_CPUACCT;
304

305 306 307
    if (virCgroupV2DevicesAvailable(group))
        group->unified.controllers |= 1 << VIR_CGROUP_CONTROLLER_DEVICES;

308 309 310
    if (controllers >= 0)
        group->unified.controllers &= controllers;

311 312 313 314 315
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++)
        VIR_DEBUG("Controller '%s' present=%s",
                  virCgroupV2ControllerTypeToString(i),
                  (group->unified.controllers & 1 << i) ? "yes" : "no");

316
    return group->unified.controllers;
317 318 319
}


320 321 322 323 324 325 326 327
static bool
virCgroupV2HasController(virCgroupPtr group,
                         int controller)
{
    return group->unified.controllers & (1 << controller);
}


328 329 330 331
static int
virCgroupV2GetAnyController(virCgroupPtr group)
{
    /* The least significant bit is position 1. */
332
    return __builtin_ffs(group->unified.controllers) - 1;
333 334 335
}


336 337 338 339 340 341 342 343 344 345 346 347 348
static int
virCgroupV2PathOfController(virCgroupPtr group,
                            int controller,
                            const char *key,
                            char **path)
{
    if (!virCgroupV2HasController(group, controller)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("v2 controller '%s' is not available"),
                       virCgroupV2ControllerTypeToString(controller));
        return -1;
    }

349 350
    *path = g_strdup_printf("%s%s/%s", group->unified.mountPoint,
                            group->unified.placement, NULLSTR_EMPTY(key));
351 352 353 354 355

    return 0;
}


356 357 358 359 360 361 362
/**
 * virCgroupV2EnableController:
 *
 * Returns: -1 on fatal error
 *          -2 if we failed to write into cgroup.subtree_control
 *          0 on success
 */
363
static int
364 365
virCgroupV2EnableController(virCgroupPtr group,
                            virCgroupPtr parent,
366 367
                            int controller,
                            bool report)
368
{
369 370
    g_autofree char *val = NULL;
    g_autofree char *path = NULL;
371

372
    val = g_strdup_printf("+%s", virCgroupV2ControllerTypeToString(controller));
373

374 375
    if (virCgroupPathOfController(parent, controller,
                                  "cgroup.subtree_control", &path) < 0) {
376 377 378
        return -1;
    }

379 380 381 382 383 384 385 386 387
    if (virFileWriteStr(path, val, 0) < 0) {
        if (report) {
            virReportSystemError(errno,
                                 _("Failed to enable controller '%s' for '%s'"),
                                 val, path);
        }
        return -2;
    }

388 389
    group->unified.controllers |= 1 << controller;

390 391 392 393 394
    return 0;
}


static int
395
virCgroupV2MakeGroup(virCgroupPtr parent,
396 397 398 399
                     virCgroupPtr group,
                     bool create,
                     unsigned int flags)
{
400
    g_autofree char *path = NULL;
401 402
    int controller;

403 404 405 406 407
    if (flags & VIR_CGROUP_SYSTEMD) {
        VIR_DEBUG("Running with systemd so we should not create cgroups ourselves.");
        return 0;
    }

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    VIR_DEBUG("Make group %s", group->path);

    controller = virCgroupV2GetAnyController(group);
    if (virCgroupV2PathOfController(group, controller, "", &path) < 0)
        return -1;

    VIR_DEBUG("Make controller %s", path);

    if (!virFileExists(path) &&
        (!create || (mkdir(path, 0755) < 0 && errno != EEXIST))) {
        virReportSystemError(errno, _("Failed to create v2 cgroup '%s'"),
                             group->path);
        return -1;
    }

    if (create) {
        if (flags & VIR_CGROUP_THREAD) {
425
            if (virCgroupSetValueStr(group, controller,
426 427 428 429
                                     "cgroup.type", "threaded") < 0) {
                return -1;
            }

430
            if (virCgroupV2HasController(parent, VIR_CGROUP_CONTROLLER_CPU) &&
431
                virCgroupV2EnableController(group, parent,
432 433
                                            VIR_CGROUP_CONTROLLER_CPU,
                                            true) < 0) {
434 435
                return -1;
            }
436 437

            if (virCgroupV2HasController(parent, VIR_CGROUP_CONTROLLER_CPUSET) &&
438
                virCgroupV2EnableController(group, parent,
439 440
                                            VIR_CGROUP_CONTROLLER_CPUSET,
                                            true) < 0) {
441 442
                return -1;
            }
443 444 445
        } else {
            size_t i;
            for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
446 447
                int rc;

448 449 450 451
                if (!virCgroupV2HasController(parent, i))
                    continue;

                /* Controllers that are implicitly enabled if available. */
452 453
                if (i == VIR_CGROUP_CONTROLLER_CPUACCT ||
                    i == VIR_CGROUP_CONTROLLER_DEVICES) {
454
                    continue;
455
                }
456

457
                rc = virCgroupV2EnableController(group, parent, i, false);
458 459 460 461 462 463 464 465
                if (rc < 0) {
                    if (rc == -2) {
                        virResetLastError();
                        VIR_DEBUG("failed to enable '%s' controller, skipping",
                                  virCgroupV2ControllerTypeToString(i));
                        group->unified.controllers &= ~(1 << i);
                        continue;
                    }
466
                    return -1;
467
                }
468 469 470 471 472 473 474 475
            }
        }
    }

    return 0;
}


476 477 478
static int
virCgroupV2Remove(virCgroupPtr group)
{
479
    g_autofree char *grppath = NULL;
480 481 482 483 484 485 486 487 488 489 490
    int controller;

    /* Don't delete the root group, if we accidentally
       ended up in it for some reason */
    if (STREQ(group->unified.placement, "/"))
        return 0;

    controller = virCgroupV2GetAnyController(group);
    if (virCgroupV2PathOfController(group, controller, "", &grppath) < 0)
        return 0;

491 492 493
    if (virCgroupV2DevicesRemoveProg(group) < 0)
        return -1;

494 495 496 497
    return virCgroupRemoveRecursively(grppath);
}


498 499 500 501 502 503 504 505 506 507 508 509 510 511
static int
virCgroupV2AddTask(virCgroupPtr group,
                   pid_t pid,
                   unsigned int flags)
{
    int controller = virCgroupV2GetAnyController(group);

    if (flags & VIR_CGROUP_TASK_THREAD)
        return virCgroupSetValueI64(group, controller, "cgroup.threads", pid);
    else
        return virCgroupSetValueI64(group, controller, "cgroup.procs", pid);
}


512 513 514 515 516
static int
virCgroupV2HasEmptyTasks(virCgroupPtr cgroup,
                         int controller)
{
    int ret = -1;
517
    g_autofree char *content = NULL;
518 519 520 521 522 523 524 525 526 527

    ret = virCgroupGetValueStr(cgroup, controller, "cgroup.procs", &content);

    if (ret == 0 && content[0] == '\0')
        ret = 1;

    return ret;
}


528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
static int
virCgroupV2KillRecursive(virCgroupPtr group,
                         int signum,
                         virHashTablePtr pids)
{
    int controller = virCgroupV2GetAnyController(group);

    if (controller < 0)
        return -1;

    return virCgroupKillRecursiveInternal(group, signum, pids, controller,
                                          "cgroup.threads", false);
}


543 544 545 546 547
static int
virCgroupV2BindMount(virCgroupPtr group,
                     const char *oldroot,
                     const char *mountopts)
{
548 549
    g_autofree char *opts = NULL;
    g_autofree char *src = NULL;
550 551 552 553 554 555 556 557 558

    VIR_DEBUG("Mounting cgroups at '%s'", group->unified.mountPoint);

    if (virFileMakePath(group->unified.mountPoint) < 0) {
        virReportSystemError(errno, _("Unable to create directory %s"),
                             group->unified.mountPoint);
        return -1;
    }

559
    opts = g_strdup_printf("mode=755,size=65536%s", mountopts);
560

561
    src = g_strdup_printf("%s%s", oldroot, group->unified.mountPoint);
562 563 564 565 566 567 568 569 570 571 572

    if (mount(src, group->unified.mountPoint, "none", MS_BIND, NULL) < 0) {
        virReportSystemError(errno, _("Failed to bind cgroup '%s' on '%s'"),
                             src, group->unified.mountPoint);
        return -1;
    }

    return 0;
}


573 574 575 576
static int
virCgroupV2SetOwner(virCgroupPtr cgroup,
                    uid_t uid,
                    gid_t gid,
J
Ján Tomko 已提交
577
                    int controllers G_GNUC_UNUSED)
578
{
579
    g_autofree char *base = NULL;
580

581 582
    base = g_strdup_printf("%s%s", cgroup->unified.mountPoint,
                           cgroup->unified.placement);
583 584 585 586 587 588 589 590 591 592 593 594 595 596

    if (virFileChownFiles(base, uid, gid) < 0)
        return -1;

    if (chown(base, uid, gid) < 0) {
        virReportSystemError(errno, _("cannot chown '%s' to (%u, %u)"),
                             base, uid, gid);
        return -1;
    }

    return 0;
}


597 598 599 600
static int
virCgroupV2SetBlkioWeight(virCgroupPtr group,
                          unsigned int weight)
{
601 602
    g_autofree char *path = NULL;
    g_autofree char *value = NULL;
603
    const char *format = "%u";
604

605 606
    if (virCgroupV2PathOfController(group, VIR_CGROUP_CONTROLLER_BLKIO,
                                    "io.bfq.weight", &path) < 0) {
607
        return -1;
608
    }
609

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    if (!virFileExists(path)) {
        VIR_FREE(path);
        format = "default %u";

        if (virCgroupV2PathOfController(group, VIR_CGROUP_CONTROLLER_BLKIO,
                                        "io.weight", &path) < 0) {
            return -1;
        }
    }

    if (!virFileExists(path)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("blkio weight is valid only for bfq or cfq scheduler"));
        return -1;
    }

626
    value = g_strdup_printf(format, weight);
627 628

    return virCgroupSetValueRaw(path, value);
629 630 631 632 633 634 635
}


static int
virCgroupV2GetBlkioWeight(virCgroupPtr group,
                          unsigned int *weight)
{
636 637
    g_autofree char *path = NULL;
    g_autofree char *value = NULL;
638 639
    char *tmp;

640 641
    if (virCgroupV2PathOfController(group, VIR_CGROUP_CONTROLLER_BLKIO,
                                    "io.bfq.weight", &path) < 0) {
642 643 644
        return -1;
    }

645 646 647 648 649 650 651 652 653 654 655 656
    if (!virFileExists(path)) {
        VIR_FREE(path);

        if (virCgroupV2PathOfController(group, VIR_CGROUP_CONTROLLER_BLKIO,
                                        "io.weight", &path) < 0) {
            return -1;
        }
    }

    if (!virFileExists(path)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("blkio weight is valid only for bfq or cfq scheduler"));
657 658
        return -1;
    }
659 660 661 662 663 664 665 666 667

    if (virCgroupGetValueRaw(path, &value) < 0)
        return -1;

    if ((tmp = strstr(value, "default "))) {
        tmp += strlen("default ");
    } else {
        tmp = value;
    }
668

669
    if (virStrToLong_ui(tmp, &tmp, 10, weight) < 0) {
670 671 672 673 674 675 676 677 678 679
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       tmp);
        return -1;
    }

    return 0;
}


680 681 682 683 684 685 686 687
static int
virCgroupV2GetBlkioIoServiced(virCgroupPtr group,
                              long long *bytes_read,
                              long long *bytes_write,
                              long long *requests_read,
                              long long *requests_write)
{
    long long stats_val;
688
    g_autofree char *str1 = NULL;
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    char *p1;
    size_t i;

    const char *value_names[] = {
        "rbytes=",
        "wbytes=",
        "rios=",
        "wios=",
    };
    long long *value_ptrs[] = {
        bytes_read,
        bytes_write,
        requests_read,
        requests_write
    };

    *bytes_read = 0;
    *bytes_write = 0;
    *requests_read = 0;
    *requests_write = 0;

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "io.stat", &str1) < 0) {
        return -1;
    }

    /* sum up all entries of the same kind, from all devices */
717
    for (i = 0; i < G_N_ELEMENTS(value_names); i++) {
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
        p1 = str1;

        while ((p1 = strstr(p1, value_names[i]))) {
            p1 += strlen(value_names[i]);
            if (virStrToLong_ll(p1, &p1, 10, &stats_val) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Cannot parse byte '%s' stat '%s'"),
                               value_names[i], p1);
                return -1;
            }

            if (stats_val < 0 ||
                (stats_val > 0 && *value_ptrs[i] > (LLONG_MAX - stats_val))) {
                virReportError(VIR_ERR_OVERFLOW,
                               _("Sum of byte '%s' stat overflows"),
                               value_names[i]);
                return -1;
            }
            *value_ptrs[i] += stats_val;
        }
    }

    return 0;
}


744 745 746 747 748 749 750 751
static int
virCgroupV2GetBlkioIoDeviceServiced(virCgroupPtr group,
                                    const char *path,
                                    long long *bytes_read,
                                    long long *bytes_write,
                                    long long *requests_read,
                                    long long *requests_write)
{
752 753
    g_autofree char *str1 = NULL;
    g_autofree char *str2 = NULL;
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
    char *p1;
    size_t i;

    const char *value_names[] = {
        "rbytes=",
        "wbytes=",
        "rios=",
        "wios=",
    };
    long long *value_ptrs[] = {
        bytes_read,
        bytes_write,
        requests_read,
        requests_write
    };

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "io.stat", &str1) < 0) {
        return -1;
    }

    if (!(str2 = virCgroupGetBlockDevString(path)))
        return -1;

    if (!(p1 = strstr(str1, str2))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot find byte stats for block device '%s'"),
                       str2);
        return -1;
    }

786
    for (i = 0; i < G_N_ELEMENTS(value_names); i++) {
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
        if (!(p1 = strstr(p1, value_names[i]))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot find byte '%s' stats for block device '%s'"),
                           value_names[i], str2);
            return -1;
        }

        p1 += strlen(value_names[i]);
        if (virStrToLong_ll(p1, &p1, 10, value_ptrs[i]) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot parse '%s' stat '%s'"),
                           value_names[i], p1);
            return -1;
        }
    }

    return 0;
}


807 808
static int
virCgroupV2SetBlkioDeviceWeight(virCgroupPtr group,
809
                                const char *devPath,
810 811
                                unsigned int weight)
{
812 813 814
    g_autofree char *path = NULL;
    g_autofree char *str = NULL;
    g_autofree char *blkstr = NULL;
815

816
    if (!(blkstr = virCgroupGetBlockDevString(devPath)))
817 818
        return -1;

819
    str = g_strdup_printf("%s%d", blkstr, weight);
820

821 822 823 824 825 826 827 828 829 830 831 832
    if (virCgroupV2PathOfController(group, VIR_CGROUP_CONTROLLER_BLKIO,
                                    "io.weight", &path) < 0) {
        return -1;
    }

    if (!virFileExists(path)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("blkio device weight is valid only for cfq scheduler"));
        return -1;
    }

    return virCgroupSetValueRaw(path, str);
833 834 835 836 837
}


static int
virCgroupV2GetBlkioDeviceWeight(virCgroupPtr group,
838
                                const char *devPath,
839 840
                                unsigned int *weight)
{
841 842 843
    g_autofree char *path = NULL;
    g_autofree char *str = NULL;
    g_autofree char *value = NULL;
844
    char *tmp;
845

846 847
    if (virCgroupV2PathOfController(group, VIR_CGROUP_CONTROLLER_BLKIO,
                                    "io.weight", &path) < 0) {
848 849 850
        return -1;
    }

851 852 853 854 855 856 857 858 859 860
    if (!virFileExists(path)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("blkio device weight is valid only for cfq scheduler"));
        return -1;
    }

    if (virCgroupGetValueRaw(path, &value) < 0)
        return -1;

    if (virCgroupGetValueForBlkDev(value, devPath, &str) < 0)
861 862
        return -1;

863 864
    if (!str) {
        *weight = 0;
865
    } else if (virStrToLong_ui(str, &tmp, 10, weight) < 0) {
866 867 868 869 870 871 872 873 874 875
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       str);
        return -1;
    }

    return 0;
}


876 877 878 879 880
static int
virCgroupV2SetBlkioDeviceReadIops(virCgroupPtr group,
                                  const char *path,
                                  unsigned int riops)
{
881 882
    g_autofree char *str = NULL;
    g_autofree char *blkstr = NULL;
883 884 885 886 887

    if (!(blkstr = virCgroupGetBlockDevString(path)))
        return -1;

    if (riops == 0) {
888
        str = g_strdup_printf("%sriops=max", blkstr);
889
    } else {
890
        str = g_strdup_printf("%sriops=%u", blkstr, riops);
891 892 893 894 895 896 897 898 899 900 901 902 903 904
    }

    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "io.max",
                                str);
}


static int
virCgroupV2GetBlkioDeviceReadIops(virCgroupPtr group,
                                  const char *path,
                                  unsigned int *riops)
{
905 906
    g_autofree char *str = NULL;
    g_autofree char *value = NULL;
907 908 909
    const char *name = "riops=";
    char *tmp;

910 911 912 913
    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "io.max",
                             &value) < 0) {
914 915 916
        return -1;
    }

917 918 919
    if (virCgroupGetValueForBlkDev(value, path, &str) < 0)
        return -1;

920 921 922 923 924 925 926 927 928 929 930 931 932
    if (!str) {
        *riops = 0;
    } else {
        if (!(tmp = strstr(str, name))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find '%s' limit for block device '%s'"),
                           name, path);
            return -1;
        }
        tmp += strlen(name);

        if (STREQLEN(tmp, "max", 3)) {
            *riops = 0;
933
        } else if (virStrToLong_ui(tmp, &tmp, 10, riops) < 0) {
934 935 936 937 938 939 940 941 942 943 944
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse '%s' as an integer"),
                           str);
            return -1;
        }
    }

    return 0;
}


945 946 947 948 949
static int
virCgroupV2SetBlkioDeviceWriteIops(virCgroupPtr group,
                                   const char *path,
                                   unsigned int wiops)
{
950 951
    g_autofree char *str = NULL;
    g_autofree char *blkstr = NULL;
952 953 954 955 956

    if (!(blkstr = virCgroupGetBlockDevString(path)))
        return -1;

    if (wiops == 0) {
957
        str = g_strdup_printf("%swiops=max", blkstr);
958
    } else {
959
        str = g_strdup_printf("%swiops=%u", blkstr, wiops);
960 961 962 963 964 965 966 967 968 969 970 971 972 973
    }

    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "io.max",
                                str);
}


static int
virCgroupV2GetBlkioDeviceWriteIops(virCgroupPtr group,
                                   const char *path,
                                   unsigned int *wiops)
{
974 975
    g_autofree char *str = NULL;
    g_autofree char *value = NULL;
976 977 978
    const char *name = "wiops=";
    char *tmp;

979 980 981 982
    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "io.max",
                             &value) < 0) {
983 984 985
        return -1;
    }

986 987 988
    if (virCgroupGetValueForBlkDev(value, path, &str) < 0)
        return -1;

989 990 991 992 993 994 995 996 997 998 999 1000 1001
    if (!str) {
        *wiops = 0;
    } else {
        if (!(tmp = strstr(str, name))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find '%s' limit for block device '%s'"),
                           name, path);
            return -1;
        }
        tmp += strlen(name);

        if (STREQLEN(tmp, "max", 3)) {
            *wiops = 0;
1002
        } else if (virStrToLong_ui(tmp, &tmp, 10, wiops) < 0) {
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse '%s' as an integer"),
                           str);
            return -1;
        }
    }

    return 0;
}


1014 1015 1016 1017 1018
static int
virCgroupV2SetBlkioDeviceReadBps(virCgroupPtr group,
                                 const char *path,
                                 unsigned long long rbps)
{
1019 1020
    g_autofree char *str = NULL;
    g_autofree char *blkstr = NULL;
1021 1022 1023 1024 1025

    if (!(blkstr = virCgroupGetBlockDevString(path)))
        return -1;

    if (rbps == 0) {
1026
        str = g_strdup_printf("%srbps=max", blkstr);
1027
    } else {
1028
        str = g_strdup_printf("%srbps=%llu", blkstr, rbps);
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    }

    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "io.max",
                                str);
}


static int
virCgroupV2GetBlkioDeviceReadBps(virCgroupPtr group,
                                 const char *path,
                                 unsigned long long *rbps)
{
1043 1044
    g_autofree char *str = NULL;
    g_autofree char *value = NULL;
1045 1046 1047
    const char *name = "rbps=";
    char *tmp;

1048 1049 1050 1051
    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "io.max",
                             &value) < 0) {
1052 1053 1054
        return -1;
    }

1055 1056 1057
    if (virCgroupGetValueForBlkDev(value, path, &str) < 0)
        return -1;

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    if (!str) {
        *rbps = 0;
    } else {
        if (!(tmp = strstr(str, name))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find '%s' limit for block device '%s'"),
                           name, path);
            return -1;
        }
        tmp += strlen(name);

        if (STREQLEN(tmp, "max", 3)) {
            *rbps = 0;
1071
        } else if (virStrToLong_ull(tmp, &tmp, 10, rbps) < 0) {
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse '%s' as an integer"),
                           str);
            return -1;
        }
    }

    return 0;
}


1083 1084 1085 1086 1087
static int
virCgroupV2SetBlkioDeviceWriteBps(virCgroupPtr group,
                                  const char *path,
                                  unsigned long long wbps)
{
1088 1089
    g_autofree char *str = NULL;
    g_autofree char *blkstr = NULL;
1090 1091 1092 1093 1094

    if (!(blkstr = virCgroupGetBlockDevString(path)))
        return -1;

    if (wbps == 0) {
1095
        str = g_strdup_printf("%swbps=max", blkstr);
1096
    } else {
1097
        str = g_strdup_printf("%swbps=%llu", blkstr, wbps);
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    }

    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "io.max",
                                str);
}


static int
virCgroupV2GetBlkioDeviceWriteBps(virCgroupPtr group,
                                  const char *path,
                                  unsigned long long *wbps)
{
1112 1113
    g_autofree char *str = NULL;
    g_autofree char *value = NULL;
1114 1115 1116
    const char *name = "wbps=";
    char *tmp;

1117 1118 1119 1120
    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "io.max",
                             &value) < 0) {
1121 1122 1123
        return -1;
    }

1124 1125 1126
    if (virCgroupGetValueForBlkDev(value, path, &str) < 0)
        return -1;

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    if (!str) {
        *wbps = 0;
    } else {
        if (!(tmp = strstr(str, name))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find '%s' limit for block device '%s'"),
                           name, path);
            return -1;
        }
        tmp += strlen(name);

        if (STREQLEN(tmp, "max", 3)) {
            *wbps = 0;
1140
        } else if (virStrToLong_ull(tmp, &tmp, 10, wbps) < 0) {
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse '%s' as an integer"),
                           str);
            return -1;
        }
    }

    return 0;
}


1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
static int
virCgroupV2SetMemory(virCgroupPtr group,
                     unsigned long long kb)
{
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

    if (kb > maxkb) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Memory '%llu' must be less than %llu"),
                       kb, maxkb);
        return -1;
    }

    if (kb == maxkb) {
        return virCgroupSetValueStr(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.max",
                                    "max");
    } else {
        return virCgroupSetValueU64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.max",
                                    kb << 10);
    }
}


1179 1180 1181 1182 1183 1184 1185 1186 1187
static int
virCgroupV2GetMemoryStat(virCgroupPtr group,
                         unsigned long long *cache,
                         unsigned long long *activeAnon,
                         unsigned long long *inactiveAnon,
                         unsigned long long *activeFile,
                         unsigned long long *inactiveFile,
                         unsigned long long *unevictable)
{
1188
    g_autofree char *stat = NULL;
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
    char *line = NULL;
    unsigned long long cacheVal = 0;
    unsigned long long activeAnonVal = 0;
    unsigned long long inactiveAnonVal = 0;
    unsigned long long activeFileVal = 0;
    unsigned long long inactiveFileVal = 0;
    unsigned long long unevictableVal = 0;

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.stat",
                             &stat) < 0) {
        return -1;
    }

    line = stat;

P
Peter Chubb 已提交
1206
    while (*line) {
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        char *newLine = strchr(line, '\n');
        char *valueStr = strchr(line, ' ');
        unsigned long long value;

        if (newLine)
            *newLine = '\0';

        if (!valueStr) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Cannot parse 'memory.stat' cgroup file."));
            return -1;
        }
        *valueStr = '\0';

        if (virStrToLong_ull(valueStr + 1, NULL, 10, &value) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse '%s' as an integer"),
                           valueStr + 1);
            return -1;
        }

        if (STREQ(line, "file"))
            cacheVal = value >> 10;
        else if (STREQ(line, "active_anon"))
            activeAnonVal = value >> 10;
        else if (STREQ(line, "inactive_anon"))
            inactiveAnonVal = value >> 10;
        else if (STREQ(line, "active_file"))
            activeFileVal = value >> 10;
        else if (STREQ(line, "inactive_file"))
            inactiveFileVal = value >> 10;
        else if (STREQ(line, "unevictable"))
            unevictableVal = value >> 10;
P
Peter Chubb 已提交
1240 1241 1242 1243 1244

        if (newLine)
            line = newLine + 1;
        else
            break;
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
    }

    *cache = cacheVal;
    *activeAnon = activeAnonVal;
    *inactiveAnon = inactiveAnonVal;
    *activeFile = activeFileVal;
    *inactiveFile = inactiveFileVal;
    *unevictable = unevictableVal;

    return 0;
}


1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
static int
virCgroupV2GetMemoryUsage(virCgroupPtr group,
                          unsigned long *kb)
{
    unsigned long long usage_in_bytes;
    int ret = virCgroupGetValueU64(group,
                                   VIR_CGROUP_CONTROLLER_MEMORY,
                                   "memory.current", &usage_in_bytes);
    if (ret == 0)
        *kb = (unsigned long) usage_in_bytes >> 10;
    return ret;
}


1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
static int
virCgroupV2SetMemoryHardLimit(virCgroupPtr group,
                              unsigned long long kb)
{
    return virCgroupV2SetMemory(group, kb);
}


static int
virCgroupV2GetMemoryHardLimit(virCgroupPtr group,
                              unsigned long long *kb)
{
1284
    g_autofree char *value = NULL;
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    unsigned long long max;

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.max", &value) < 0) {
        return -1;
    }

    if (STREQ(value, "max")) {
        *kb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
        return 0;
    }

    if (virStrToLong_ull(value, NULL, 10, &max) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse value '%s' as number."),
                       value);
        return -1;
    }

    *kb = max >> 10;
    if (*kb >= VIR_DOMAIN_MEMORY_PARAM_UNLIMITED)
        *kb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

    return 0;
}


1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
static int
virCgroupV2SetMemorySoftLimit(virCgroupPtr group,
                              unsigned long long kb)
{
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

    if (kb > maxkb) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Memory '%llu' must be less than %llu"),
                       kb, maxkb);
        return -1;
    }

    if (kb == maxkb) {
        return virCgroupSetValueStr(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.high",
                                    "max");
    } else {
        return virCgroupSetValueU64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.high",
                                    kb << 10);
    }
}


static int
virCgroupV2GetMemorySoftLimit(virCgroupPtr group,
                              unsigned long long *kb)
{
1344
    g_autofree char *value = NULL;
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
    unsigned long long high;

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.high", &value) < 0)
        return -1;

    if (STREQ(value, "max")) {
        *kb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
        return 0;
    }

    if (virStrToLong_ull(value, NULL, 10, &high) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse value '%s' as number."),
                       value);
        return -1;
    }

    *kb = high >> 10;
    if (*kb >= VIR_DOMAIN_MEMORY_PARAM_UNLIMITED)
        *kb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

    return 0;
}


1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
static int
virCgroupV2SetMemSwapHardLimit(virCgroupPtr group,
                               unsigned long long kb)
{
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

    if (kb > maxkb) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Memory '%llu' must be less than %llu"),
                       kb, maxkb);
        return -1;
    }

    if (kb == maxkb) {
        return virCgroupSetValueStr(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.swap.max",
                                    "max");
    } else {
        return virCgroupSetValueU64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.swap.max",
                                    kb << 10);
    }
}


static int
virCgroupV2GetMemSwapHardLimit(virCgroupPtr group,
                               unsigned long long *kb)
{
1403
    g_autofree char *value = NULL;
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
    unsigned long long max;

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.swap.max", &value) < 0) {
        return -1;
    }

    if (STREQ(value, "max")) {
        *kb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
        return 0;
    }

    if (virStrToLong_ull(value, NULL, 10, &max) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse value '%s' as number."),
                       value);
        return -1;
    }

    *kb = max >> 10;
    if (*kb >= VIR_DOMAIN_MEMORY_PARAM_UNLIMITED)
        *kb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

    return 0;
}


1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
static int
virCgroupV2GetMemSwapUsage(virCgroupPtr group,
                           unsigned long long *kb)
{
    unsigned long long usage_in_bytes;
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_MEMORY,
                               "memory.swap.current", &usage_in_bytes);
    if (ret == 0)
        *kb = (unsigned long) usage_in_bytes >> 10;
    return ret;
}


1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
static int
virCgroupV2SetCpuShares(virCgroupPtr group,
                        unsigned long long shares)
{
    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.weight", shares);
}


static int
virCgroupV2GetCpuShares(virCgroupPtr group,
                        unsigned long long *shares)
{
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.weight", shares);
}


1467 1468 1469 1470
static int
virCgroupV2SetCpuCfsPeriod(virCgroupPtr group,
                           unsigned long long cfs_period)
{
1471 1472
    g_autofree char *value = NULL;
    g_autofree char *str = NULL;
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
    char *tmp;

    /* The cfs_period should be greater or equal than 1ms, and less or equal
     * than 1s.
     */
    if (cfs_period < 1000 || cfs_period > 1000000) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("cfs_period '%llu' must be in range (1000, 1000000)"),
                       cfs_period);
        return -1;
    }

    if (virCgroupGetValueStr(group, VIR_CGROUP_CONTROLLER_CPU,
                             "cpu.max", &str) < 0) {
        return -1;
    }

    if (!(tmp = strchr(str, ' '))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Invalid 'cpu.max' data."));
        return -1;
    }
1495
    *tmp = '\0';
1496

1497
    value = g_strdup_printf("%s %llu", str, cfs_period);
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507

    return virCgroupSetValueStr(group, VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.max", value);
}


static int
virCgroupV2GetCpuCfsPeriod(virCgroupPtr group,
                           unsigned long long *cfs_period)
{
1508
    g_autofree char *str = NULL;
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
    char *tmp;

    if (virCgroupGetValueStr(group, VIR_CGROUP_CONTROLLER_CPU,
                             "cpu.max", &str) < 0) {
        return -1;
    }

    if (!(tmp = strchr(str, ' '))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Invalid 'cpu.max' data."));
        return -1;
    }

1522
    if (virStrToLong_ull(tmp, &tmp, 10, cfs_period) < 0) {
1523 1524 1525 1526 1527 1528 1529 1530 1531
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse value '%s' from cpu.max."), str);
        return -1;
    }

    return 0;
}


1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
static int
virCgroupV2SetCpuCfsQuota(virCgroupPtr group,
                          long long cfs_quota)
{
    /* The cfs_quota should be greater or equal than 1ms */
    if (cfs_quota >= 0 &&
        (cfs_quota < 1000 ||
         cfs_quota > ULLONG_MAX / 1000)) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("cfs_quota '%lld' must be in range (1000, %llu)"),
                       cfs_quota, ULLONG_MAX / 1000);
        return -1;
    }

    if (cfs_quota == ULLONG_MAX / 1000) {
        return virCgroupSetValueStr(group,
                                    VIR_CGROUP_CONTROLLER_CPU,
                                    "cpu.max", "max");
    }

    return virCgroupSetValueI64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.max", cfs_quota);
}


static int
virCgroupV2GetCpuCfsQuota(virCgroupPtr group,
                          long long *cfs_quota)
{
1562
    g_autofree char *str = NULL;
1563
    char *tmp;
1564 1565 1566 1567 1568 1569

    if (virCgroupGetValueStr(group, VIR_CGROUP_CONTROLLER_CPU,
                             "cpu.max", &str) < 0) {
        return -1;
    }

1570
    if (STREQLEN(str, "max", 3)) {
1571
        *cfs_quota = ULLONG_MAX / 1000;
1572 1573
        return 0;
    }
1574

1575
    if (virStrToLong_ll(str, &tmp, 10, cfs_quota) < 0) {
1576 1577 1578 1579 1580 1581 1582 1583 1584
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse value '%s' from cpu.max."), str);
        return -1;
    }

    return 0;
}


1585 1586 1587
static bool
virCgroupV2SupportsCpuBW(virCgroupPtr cgroup)
{
1588
    g_autofree char *path = NULL;
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599

    if (virCgroupV2PathOfController(cgroup, VIR_CGROUP_CONTROLLER_CPU,
                                    "cpu.max", &path) < 0) {
        virResetLastError();
        return false;
    }

    return virFileExists(path);
}


1600 1601 1602 1603
static int
virCgroupV2GetCpuacctUsage(virCgroupPtr group,
                           unsigned long long *usage)
{
1604
    g_autofree char *str = NULL;
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
    char *tmp;

    if (virCgroupGetValueStr(group, VIR_CGROUP_CONTROLLER_CPUACCT,
                             "cpu.stat", &str) < 0) {
        return -1;
    }

    if (!(tmp = strstr(str, "usage_usec "))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot parse cpu usage stat '%s'"), str);
        return -1;
    }
    tmp += strlen("usage_usec ");

    if (virStrToLong_ull(tmp, &tmp, 10, usage) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse value '%s' as number."), tmp);
        return -1;
    }

    *usage *= 1000;

    return 0;
}


1631 1632 1633 1634 1635
static int
virCgroupV2GetCpuacctStat(virCgroupPtr group,
                          unsigned long long *user,
                          unsigned long long *sys)
{
1636
    g_autofree char *str = NULL;
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
    char *tmp;
    unsigned long long userVal = 0;
    unsigned long long sysVal = 0;

    if (virCgroupGetValueStr(group, VIR_CGROUP_CONTROLLER_CPUACCT,
                             "cpu.stat", &str) < 0) {
        return -1;
    }

    if (!(tmp = strstr(str, "user_usec "))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot parse cpu user stat '%s'"), str);
        return -1;
    }
    tmp += strlen("user_usec ");

    if (virStrToLong_ull(tmp, &tmp, 10, &userVal) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse value '%s' as number."), tmp);
        return -1;
    }

    if (!(tmp = strstr(str, "system_usec "))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot parse cpu sys stat '%s'"), str);
        return -1;
    }
    tmp += strlen("system_usec ");

    if (virStrToLong_ull(tmp, &tmp, 10, &sysVal) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse value '%s' as number."), tmp);
        return -1;
    }

    *user = userVal * 1000;
    *sys = sysVal * 1000;

    return 0;
}


1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
static int
virCgroupV2SetCpusetMems(virCgroupPtr group,
                         const char *mems)
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.mems",
                                mems);
}


static int
virCgroupV2GetCpusetMems(virCgroupPtr group,
                         char **mems)
{
    return virCgroupGetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.mems",
                                mems);
}


1701
static int
J
Ján Tomko 已提交
1702 1703
virCgroupV2SetCpusetMemoryMigrate(virCgroupPtr group G_GNUC_UNUSED,
                                  bool migrate G_GNUC_UNUSED)
1704 1705 1706 1707 1708 1709
{
    return 0;
}


static int
J
Ján Tomko 已提交
1710
virCgroupV2GetCpusetMemoryMigrate(virCgroupPtr group G_GNUC_UNUSED,
1711 1712 1713 1714 1715 1716 1717
                                  bool *migrate)
{
    *migrate = true;
    return 0;
}


1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
static int
virCgroupV2SetCpusetCpus(virCgroupPtr group,
                         const char *cpus)
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.cpus",
                                cpus);
}


static int
virCgroupV2GetCpusetCpus(virCgroupPtr group,
                         char **cpus)
{
    return virCgroupGetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.cpus",
                                cpus);
}


P
Pavel Hrdina 已提交
1740 1741
virCgroupBackend virCgroupV2Backend = {
    .type = VIR_CGROUP_BACKEND_TYPE_V2,
1742 1743

    .available = virCgroupV2Available,
1744
    .validateMachineGroup = virCgroupV2ValidateMachineGroup,
1745
    .copyMounts = virCgroupV2CopyMounts,
1746
    .copyPlacement = virCgroupV2CopyPlacement,
1747
    .detectMounts = virCgroupV2DetectMounts,
1748
    .detectPlacement = virCgroupV2DetectPlacement,
1749
    .validatePlacement = virCgroupV2ValidatePlacement,
1750
    .stealPlacement = virCgroupV2StealPlacement,
1751
    .detectControllers = virCgroupV2DetectControllers,
1752
    .hasController = virCgroupV2HasController,
1753
    .getAnyController = virCgroupV2GetAnyController,
1754
    .pathOfController = virCgroupV2PathOfController,
1755
    .makeGroup = virCgroupV2MakeGroup,
1756
    .remove = virCgroupV2Remove,
1757
    .addTask = virCgroupV2AddTask,
1758
    .hasEmptyTasks = virCgroupV2HasEmptyTasks,
1759
    .killRecursive = virCgroupV2KillRecursive,
1760
    .bindMount = virCgroupV2BindMount,
1761
    .setOwner = virCgroupV2SetOwner,
1762 1763 1764

    .setBlkioWeight = virCgroupV2SetBlkioWeight,
    .getBlkioWeight = virCgroupV2GetBlkioWeight,
1765
    .getBlkioIoServiced = virCgroupV2GetBlkioIoServiced,
1766
    .getBlkioIoDeviceServiced = virCgroupV2GetBlkioIoDeviceServiced,
1767 1768
    .setBlkioDeviceWeight = virCgroupV2SetBlkioDeviceWeight,
    .getBlkioDeviceWeight = virCgroupV2GetBlkioDeviceWeight,
1769 1770
    .setBlkioDeviceReadIops = virCgroupV2SetBlkioDeviceReadIops,
    .getBlkioDeviceReadIops = virCgroupV2GetBlkioDeviceReadIops,
1771 1772
    .setBlkioDeviceWriteIops = virCgroupV2SetBlkioDeviceWriteIops,
    .getBlkioDeviceWriteIops = virCgroupV2GetBlkioDeviceWriteIops,
1773 1774
    .setBlkioDeviceReadBps = virCgroupV2SetBlkioDeviceReadBps,
    .getBlkioDeviceReadBps = virCgroupV2GetBlkioDeviceReadBps,
1775 1776
    .setBlkioDeviceWriteBps = virCgroupV2SetBlkioDeviceWriteBps,
    .getBlkioDeviceWriteBps = virCgroupV2GetBlkioDeviceWriteBps,
1777 1778

    .setMemory = virCgroupV2SetMemory,
1779
    .getMemoryStat = virCgroupV2GetMemoryStat,
1780
    .getMemoryUsage = virCgroupV2GetMemoryUsage,
1781 1782
    .setMemoryHardLimit = virCgroupV2SetMemoryHardLimit,
    .getMemoryHardLimit = virCgroupV2GetMemoryHardLimit,
1783 1784
    .setMemorySoftLimit = virCgroupV2SetMemorySoftLimit,
    .getMemorySoftLimit = virCgroupV2GetMemorySoftLimit,
1785 1786
    .setMemSwapHardLimit = virCgroupV2SetMemSwapHardLimit,
    .getMemSwapHardLimit = virCgroupV2GetMemSwapHardLimit,
1787
    .getMemSwapUsage = virCgroupV2GetMemSwapUsage,
1788 1789 1790

    .setCpuShares = virCgroupV2SetCpuShares,
    .getCpuShares = virCgroupV2GetCpuShares,
1791 1792
    .setCpuCfsPeriod = virCgroupV2SetCpuCfsPeriod,
    .getCpuCfsPeriod = virCgroupV2GetCpuCfsPeriod,
1793 1794
    .setCpuCfsQuota = virCgroupV2SetCpuCfsQuota,
    .getCpuCfsQuota = virCgroupV2GetCpuCfsQuota,
1795
    .supportsCpuBW = virCgroupV2SupportsCpuBW,
1796 1797

    .getCpuacctUsage = virCgroupV2GetCpuacctUsage,
1798
    .getCpuacctStat = virCgroupV2GetCpuacctStat,
1799 1800 1801

    .setCpusetMems = virCgroupV2SetCpusetMems,
    .getCpusetMems = virCgroupV2GetCpusetMems,
1802 1803
    .setCpusetMemoryMigrate = virCgroupV2SetCpusetMemoryMigrate,
    .getCpusetMemoryMigrate = virCgroupV2GetCpusetMemoryMigrate,
1804 1805
    .setCpusetCpus = virCgroupV2SetCpusetCpus,
    .getCpusetCpus = virCgroupV2GetCpusetCpus,
P
Pavel Hrdina 已提交
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
};


void
virCgroupV2Register(void)
{
    virCgroupBackendRegister(&virCgroupV2Backend);
}

#else /* !__linux__ */

void
virCgroupV2Register(void)
{
    VIR_INFO("Control groups not supported on this platform");
}

#endif /* !__linux__ */