vircgroupv2.c 52.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"
33
#include "virbpf.h"
P
Pavel Hrdina 已提交
34 35 36
#include "vircgroup.h"
#include "vircgroupbackend.h"
#include "vircgroupv2.h"
37
#include "vircgroupv2devices.h"
38
#include "virerror.h"
39
#include "virfile.h"
P
Pavel Hrdina 已提交
40
#include "virlog.h"
41
#include "virstring.h"
42
#include "virsystemd.h"
P
Pavel Hrdina 已提交
43 44 45 46 47 48

VIR_LOG_INIT("util.cgroup");

#define VIR_FROM_THIS VIR_FROM_CGROUP

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

#ifdef __linux__

57 58 59 60 61 62 63 64 65 66 67 68 69 70
/* 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) {
71 72
        g_autofree char *contFile = NULL;
        g_autofree char *contStr = NULL;
73 74 75 76 77 78 79

        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. */
80
        contFile = g_strdup_printf("%s/cgroup.controllers", entry.mnt_dir);
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

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

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

        ret = true;
        break;
    }

 cleanup:
    VIR_FORCE_FCLOSE(mounts);
    return ret;
}


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

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

    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;
123 124 125 126 127 128 129

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

        if (!(tmp = strrchr(group->unified.placement, '/')))
            return false;
    }
130 131 132 133 134 135 136 137 138 139 140 141 142
    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;
}


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


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

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

    return 0;
}


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

    VIR_FREE(group->unified.mountPoint);

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


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

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

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

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

    return 0;
}


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

    return 0;
}


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


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

253
    if (parent) {
254 255 256
        contFile = g_strdup_printf("%s%s/cgroup.subtree_control",
                                   parent->unified.mountPoint,
                                   NULLSTR_EMPTY(parent->unified.placement));
257
    } else {
258 259 260
        contFile = g_strdup_printf("%s%s/cgroup.controllers",
                                   group->unified.mountPoint,
                                   NULLSTR_EMPTY(group->unified.placement));
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 293

    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,
294 295
                             int controllers,
                             virCgroupPtr parent)
296 297 298
{
    size_t i;

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

302 303 304
    /* 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;
305

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

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

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

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


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


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


337 338 339 340 341 342 343 344 345 346 347 348 349
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;
    }

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

    return 0;
}


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

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

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

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

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

391 392 393 394 395
    return 0;
}


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

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

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    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) {
426
            if (virCgroupSetValueStr(group, controller,
427 428 429 430
                                     "cgroup.type", "threaded") < 0) {
                return -1;
            }

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

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

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

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

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

    return 0;
}


477 478 479
static int
virCgroupV2Remove(virCgroupPtr group)
{
480
    g_autofree char *grppath = NULL;
481 482 483 484 485 486 487 488 489 490 491
    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;

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

495 496 497 498
    return virCgroupRemoveRecursively(grppath);
}


499 500 501 502 503 504 505 506 507 508 509 510 511 512
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);
}


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

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

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

    return ret;
}


529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
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);
}


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

    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;
    }

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

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

    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;
}


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

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

    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;
}


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

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

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
    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;
    }

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

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


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

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

646 647 648 649 650 651 652 653 654 655 656 657
    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"));
658 659
        return -1;
    }
660 661 662 663 664 665 666 667 668

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

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

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

    return 0;
}


681 682 683 684 685 686 687 688
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;
689
    g_autofree char *str1 = NULL;
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 717
    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 */
718
    for (i = 0; i < G_N_ELEMENTS(value_names); i++) {
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 744
        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;
}


745 746 747 748 749 750 751 752
static int
virCgroupV2GetBlkioIoDeviceServiced(virCgroupPtr group,
                                    const char *path,
                                    long long *bytes_read,
                                    long long *bytes_write,
                                    long long *requests_read,
                                    long long *requests_write)
{
753 754
    g_autofree char *str1 = NULL;
    g_autofree char *str2 = NULL;
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 786
    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;
    }

787
    for (i = 0; i < G_N_ELEMENTS(value_names); i++) {
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
        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;
}


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

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

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

822 823 824 825 826 827 828 829 830 831 832 833
    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);
834 835 836 837 838
}


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

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

852 853 854 855 856 857 858 859 860 861
    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)
862 863
        return -1;

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

    return 0;
}


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

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

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

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


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

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

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

921 922 923 924 925 926 927 928 929 930 931 932 933
    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;
934
        } else if (virStrToLong_ui(tmp, &tmp, 10, riops) < 0) {
935 936 937 938 939 940 941 942 943 944 945
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse '%s' as an integer"),
                           str);
            return -1;
        }
    }

    return 0;
}


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

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

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

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


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

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

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

990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    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;
1003
        } else if (virStrToLong_ui(tmp, &tmp, 10, wiops) < 0) {
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse '%s' as an integer"),
                           str);
            return -1;
        }
    }

    return 0;
}


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

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

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

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


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

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

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

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    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;
1072
        } else if (virStrToLong_ull(tmp, &tmp, 10, rbps) < 0) {
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse '%s' as an integer"),
                           str);
            return -1;
        }
    }

    return 0;
}


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

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

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

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


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

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

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

1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    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;
1141
        } else if (virStrToLong_ull(tmp, &tmp, 10, wbps) < 0) {
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to parse '%s' as an integer"),
                           str);
            return -1;
        }
    }

    return 0;
}


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 1179
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);
    }
}


1180 1181 1182 1183 1184 1185 1186 1187 1188
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)
{
1189
    g_autofree char *stat = NULL;
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    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 已提交
1207
    while (*line) {
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 1240
        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 已提交
1241 1242 1243 1244 1245

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

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

    return 0;
}


1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
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;
}


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


static int
virCgroupV2GetMemoryHardLimit(virCgroupPtr group,
                              unsigned long long *kb)
{
1285
    g_autofree char *value = NULL;
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 1313
    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;
}


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 1344
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)
{
1345
    g_autofree char *value = NULL;
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 1372
    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;
}


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 1403
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)
{
1404
    g_autofree char *value = NULL;
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 1432
    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;
}


1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
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;
}


1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
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);
}


1468 1469 1470 1471
static int
virCgroupV2SetCpuCfsPeriod(virCgroupPtr group,
                           unsigned long long cfs_period)
{
1472 1473
    g_autofree char *value = NULL;
    g_autofree char *str = NULL;
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    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;
    }
1496
    *tmp = '\0';
1497

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

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


static int
virCgroupV2GetCpuCfsPeriod(virCgroupPtr group,
                           unsigned long long *cfs_period)
{
1509
    g_autofree char *str = NULL;
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
    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;
    }

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

    return 0;
}


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 1562
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)
{
1563
    g_autofree char *str = NULL;
1564
    char *tmp;
1565 1566 1567 1568 1569 1570

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

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

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

    return 0;
}


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

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

    return virFileExists(path);
}


1601 1602 1603 1604
static int
virCgroupV2GetCpuacctUsage(virCgroupPtr group,
                           unsigned long long *usage)
{
1605
    g_autofree char *str = NULL;
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 1631
    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;
}


1632 1633 1634 1635 1636
static int
virCgroupV2GetCpuacctStat(virCgroupPtr group,
                          unsigned long long *user,
                          unsigned long long *sys)
{
1637
    g_autofree char *str = NULL;
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 1679
    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;
}


1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
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);
}


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


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


1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
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);
}


1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
static int
virCgroupV2AllowDevice(virCgroupPtr group,
                       char type,
                       int major,
                       int minor,
                       int perms)
{
    uint64_t key = virCgroupV2DevicesGetKey(major, minor);
    uint32_t val = virCgroupV2DevicesGetPerms(perms, type);
    int rc;

    if (virCgroupV2DevicesPrepareProg(group) < 0)
        return -1;

    rc = virBPFLookupElem(group->unified.devices.mapfd, &key, NULL);

    if (virBPFUpdateElem(group->unified.devices.mapfd, &key, &val) < 0) {
        virReportSystemError(errno, "%s",
                             _("failed to update device in BPF cgroup map"));
        return -1;
    }

    if (rc < 0)
        group->unified.devices.count++;

    return 0;
}


1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
static int
virCgroupV2DenyDevice(virCgroupPtr group,
                      char type,
                      int major,
                      int minor,
                      int perms)
{
    uint64_t key = virCgroupV2DevicesGetKey(major, minor);
    uint32_t newval = virCgroupV2DevicesGetPerms(perms, type);
    uint32_t val = 0;

    if (virCgroupV2DevicesPrepareProg(group) < 0)
        return -1;

    if (group->unified.devices.count <= 0 ||
        virBPFLookupElem(group->unified.devices.mapfd, &key, &val) < 0) {
        VIR_DEBUG("nothing to do, device is not allowed");
        return 0;
    }

    if (newval == val) {
        if (virBPFDeleteElem(group->unified.devices.mapfd, &key) < 0) {
            virReportSystemError(errno, "%s",
                                 _("failed to remove device from BPF cgroup map"));
            return -1;
        }
        group->unified.devices.count--;
    } else {
        val ^= val & newval;
        if (virBPFUpdateElem(group->unified.devices.mapfd, &key, &val) < 0) {
            virReportSystemError(errno, "%s",
                                 _("failed to update device in BPF cgroup map"));
            return -1;
        }
    }

    return 0;
}


P
Pavel Hrdina 已提交
1810 1811
virCgroupBackend virCgroupV2Backend = {
    .type = VIR_CGROUP_BACKEND_TYPE_V2,
1812 1813

    .available = virCgroupV2Available,
1814
    .validateMachineGroup = virCgroupV2ValidateMachineGroup,
1815
    .copyMounts = virCgroupV2CopyMounts,
1816
    .copyPlacement = virCgroupV2CopyPlacement,
1817
    .detectMounts = virCgroupV2DetectMounts,
1818
    .detectPlacement = virCgroupV2DetectPlacement,
1819
    .validatePlacement = virCgroupV2ValidatePlacement,
1820
    .stealPlacement = virCgroupV2StealPlacement,
1821
    .detectControllers = virCgroupV2DetectControllers,
1822
    .hasController = virCgroupV2HasController,
1823
    .getAnyController = virCgroupV2GetAnyController,
1824
    .pathOfController = virCgroupV2PathOfController,
1825
    .makeGroup = virCgroupV2MakeGroup,
1826
    .remove = virCgroupV2Remove,
1827
    .addTask = virCgroupV2AddTask,
1828
    .hasEmptyTasks = virCgroupV2HasEmptyTasks,
1829
    .killRecursive = virCgroupV2KillRecursive,
1830
    .bindMount = virCgroupV2BindMount,
1831
    .setOwner = virCgroupV2SetOwner,
1832 1833 1834

    .setBlkioWeight = virCgroupV2SetBlkioWeight,
    .getBlkioWeight = virCgroupV2GetBlkioWeight,
1835
    .getBlkioIoServiced = virCgroupV2GetBlkioIoServiced,
1836
    .getBlkioIoDeviceServiced = virCgroupV2GetBlkioIoDeviceServiced,
1837 1838
    .setBlkioDeviceWeight = virCgroupV2SetBlkioDeviceWeight,
    .getBlkioDeviceWeight = virCgroupV2GetBlkioDeviceWeight,
1839 1840
    .setBlkioDeviceReadIops = virCgroupV2SetBlkioDeviceReadIops,
    .getBlkioDeviceReadIops = virCgroupV2GetBlkioDeviceReadIops,
1841 1842
    .setBlkioDeviceWriteIops = virCgroupV2SetBlkioDeviceWriteIops,
    .getBlkioDeviceWriteIops = virCgroupV2GetBlkioDeviceWriteIops,
1843 1844
    .setBlkioDeviceReadBps = virCgroupV2SetBlkioDeviceReadBps,
    .getBlkioDeviceReadBps = virCgroupV2GetBlkioDeviceReadBps,
1845 1846
    .setBlkioDeviceWriteBps = virCgroupV2SetBlkioDeviceWriteBps,
    .getBlkioDeviceWriteBps = virCgroupV2GetBlkioDeviceWriteBps,
1847 1848

    .setMemory = virCgroupV2SetMemory,
1849
    .getMemoryStat = virCgroupV2GetMemoryStat,
1850
    .getMemoryUsage = virCgroupV2GetMemoryUsage,
1851 1852
    .setMemoryHardLimit = virCgroupV2SetMemoryHardLimit,
    .getMemoryHardLimit = virCgroupV2GetMemoryHardLimit,
1853 1854
    .setMemorySoftLimit = virCgroupV2SetMemorySoftLimit,
    .getMemorySoftLimit = virCgroupV2GetMemorySoftLimit,
1855 1856
    .setMemSwapHardLimit = virCgroupV2SetMemSwapHardLimit,
    .getMemSwapHardLimit = virCgroupV2GetMemSwapHardLimit,
1857
    .getMemSwapUsage = virCgroupV2GetMemSwapUsage,
1858

1859
    .allowDevice = virCgroupV2AllowDevice,
1860
    .denyDevice = virCgroupV2DenyDevice,
1861

1862 1863
    .setCpuShares = virCgroupV2SetCpuShares,
    .getCpuShares = virCgroupV2GetCpuShares,
1864 1865
    .setCpuCfsPeriod = virCgroupV2SetCpuCfsPeriod,
    .getCpuCfsPeriod = virCgroupV2GetCpuCfsPeriod,
1866 1867
    .setCpuCfsQuota = virCgroupV2SetCpuCfsQuota,
    .getCpuCfsQuota = virCgroupV2GetCpuCfsQuota,
1868
    .supportsCpuBW = virCgroupV2SupportsCpuBW,
1869 1870

    .getCpuacctUsage = virCgroupV2GetCpuacctUsage,
1871
    .getCpuacctStat = virCgroupV2GetCpuacctStat,
1872 1873 1874

    .setCpusetMems = virCgroupV2SetCpusetMems,
    .getCpusetMems = virCgroupV2GetCpusetMems,
1875 1876
    .setCpusetMemoryMigrate = virCgroupV2SetCpusetMemoryMigrate,
    .getCpusetMemoryMigrate = virCgroupV2GetCpusetMemoryMigrate,
1877 1878
    .setCpusetCpus = virCgroupV2SetCpusetCpus,
    .getCpusetCpus = virCgroupV2GetCpusetCpus,
P
Pavel Hrdina 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
};


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

#else /* !__linux__ */

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

#endif /* !__linux__ */