vircgroup.c 132.5 KB
Newer Older
1
/*
2
 * vircgroup.c: methods for managing control cgroups
3
 *
4
 * Copyright (C) 2010-2015 Red Hat, Inc.
5 6
 * Copyright IBM Corp. 2008
 *
O
Osier Yang 已提交
7 8 9 10 11 12 13 14 15 16 17
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25
 *
 * Authors:
 *  Dan Smith <danms@us.ibm.com>
 */
#include <config.h>

26 27
#if defined HAVE_MNTENT_H && defined HAVE_SYS_MOUNT_H \
    && defined HAVE_GETMNTENT_R
28
# include <mntent.h>
29 30
# include <sys/mount.h>
#endif
31 32
#include <fcntl.h>
#include <sys/stat.h>
33 34 35 36 37 38 39

#ifdef MAJOR_IN_MKDEV
# include <sys/mkdev.h>
#elif MAJOR_IN_SYSMACROS
# include <sys/sysmacros.h>
#endif

40
#include <sys/types.h>
41
#include <signal.h>
42
#include <dirent.h>
M
Michal Privoznik 已提交
43
#include <unistd.h>
44

45 46 47
#define __VIR_CGROUP_ALLOW_INCLUDE_PRIV_H__
#include "vircgrouppriv.h"

48
#include "virutil.h"
49
#include "viralloc.h"
50
#include "virerror.h"
51
#include "virlog.h"
E
Eric Blake 已提交
52
#include "virfile.h"
53
#include "virhash.h"
54
#include "virhashcode.h"
55
#include "virstring.h"
56
#include "virsystemd.h"
57
#include "virtypedparam.h"
58
#include "virhostcpu.h"
59
#include "virthread.h"
60

61 62
VIR_LOG_INIT("util.cgroup");

63 64
#define CGROUP_MAX_VAL 512

65 66
#define VIR_FROM_THIS VIR_FROM_CGROUP

67
#define CGROUP_NB_TOTAL_CPU_STAT_PARAM 3
68
#define CGROUP_NB_PER_CPU_STAT_PARAM   1
69

70
#if defined(__linux__) && defined(HAVE_GETMNTENT_R) && \
71
    defined(_DIRENT_HAVE_D_TYPE) && defined(_SC_CLK_TCK)
72 73 74
# define VIR_CGROUP_SUPPORTED
#endif

75
VIR_ENUM_IMPL(virCgroupController, VIR_CGROUP_CONTROLLER_LAST,
R
Ryota Ozaki 已提交
76
              "cpu", "cpuacct", "cpuset", "memory", "devices",
77 78
              "freezer", "blkio", "net_cls", "perf_event",
              "name=systemd");
79

80 81 82 83 84 85 86 87
typedef enum {
    VIR_CGROUP_NONE = 0, /* create subdir under each cgroup if possible. */
    VIR_CGROUP_MEM_HIERACHY = 1 << 0, /* call virCgroupSetMemoryUseHierarchy
                                       * before creating subcgroups and
                                       * attaching tasks
                                       */
} virCgroupFlags;

E
Eric Blake 已提交
88

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
/**
 * virCgroupGetDevicePermsString:
 *
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits
 *
 * Returns string corresponding to the appropriate bits set.
 */
const char *
virCgroupGetDevicePermsString(int perms)
{
    if (perms & VIR_CGROUP_DEVICE_READ) {
        if (perms & VIR_CGROUP_DEVICE_WRITE) {
            if (perms & VIR_CGROUP_DEVICE_MKNOD)
                return "rwm";
            else
                return "rw";
        } else {
            if (perms & VIR_CGROUP_DEVICE_MKNOD)
                return "rm";
            else
                return "r";
        }
    } else {
        if (perms & VIR_CGROUP_DEVICE_WRITE) {
            if (perms & VIR_CGROUP_DEVICE_MKNOD)
                return "wm";
            else
                return "w";
        } else {
            if (perms & VIR_CGROUP_DEVICE_MKNOD)
                return "m";
            else
                return "";
        }
    }
}


127
#ifdef VIR_CGROUP_SUPPORTED
E
Eric Blake 已提交
128 129
bool
virCgroupAvailable(void)
130
{
131
    bool ret = false;
132 133 134 135 136 137 138 139 140 141 142
    FILE *mounts = NULL;
    struct mntent entry;
    char buf[CGROUP_MAX_VAL];

    if (!virFileExists("/proc/cgroups"))
        return false;

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

    while (getmntent_r(mounts, &entry, buf, sizeof(buf)) != NULL) {
143 144 145 146
        /* We're looking for at least one 'cgroup' fs mount,
         * which is *not* a named mount. */
        if (STREQ(entry.mnt_type, "cgroup") &&
            !strstr(entry.mnt_opts, "name=")) {
147 148 149 150 151 152 153 154 155
            ret = true;
            break;
        }
    }

    VIR_FORCE_FCLOSE(mounts);
    return ret;
}

E
Eric Blake 已提交
156 157 158 159 160 161

static int
virCgroupPartitionNeedsEscaping(const char *path)
{
    FILE *fp = NULL;
    int ret = 0;
162
    VIR_AUTOFREE(char *) line = NULL;
E
Eric Blake 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    size_t buflen;

    /* If it starts with 'cgroup.' or a '_' of any
     * of the controller names from /proc/cgroups,
     * then we must prefix a '_'
     */
    if (STRPREFIX(path, "cgroup."))
        return 1;

    if (path[0] == '_' ||
        path[0] == '.')
        return 1;

    if (!(fp = fopen("/proc/cgroups", "r"))) {
        /* The API contract is that we return ENXIO
         * if cgroups are not available on a host */
        if (errno == ENOENT)
            errno = ENXIO;
        virReportSystemError(errno, "%s",
                             _("Cannot open /proc/cgroups"));
        return -1;
    }

    /*
     * Data looks like this:
     * #subsys_name hierarchy num_cgroups enabled
     * cpuset  2 4  1
     * cpu     3 48 1
     * cpuacct 3 48 1
     * memory  4 4  1
     * devices 5 4  1
     * freezer 6 4  1
     * net_cls 7 1  1
     */
    while (getline(&line, &buflen, fp) > 0) {
        char *tmp;
        size_t len;

        if (STRPREFIX(line, "#subsys_name"))
            continue;

        tmp = strchrnul(line, ' ');
        *tmp = '\0';
        len = tmp - line;

        if (STRPREFIX(path, line) &&
            path[len] == '.') {
            ret = 1;
            goto cleanup;
        }
    }

    if (ferror(fp)) {
        virReportSystemError(errno, "%s",
                             _("Error while reading /proc/cgroups"));
        goto cleanup;
    }

221
 cleanup:
E
Eric Blake 已提交
222 223 224 225 226 227 228 229 230
    VIR_FORCE_FCLOSE(fp);
    return ret;
}


static int
virCgroupPartitionEscape(char **path)
{
    int rc;
231
    char *newstr = NULL;
E
Eric Blake 已提交
232 233 234 235

    if ((rc = virCgroupPartitionNeedsEscaping(*path)) <= 0)
        return rc;

236
    if (virAsprintf(&newstr, "_%s", *path) < 0)
E
Eric Blake 已提交
237 238
        return -1;

239 240 241
    VIR_FREE(*path);
    *path = newstr;

E
Eric Blake 已提交
242 243
    return 0;
}
E
Eric Blake 已提交
244 245


246
static bool
247 248 249
virCgroupValidateMachineGroup(virCgroupPtr group,
                              const char *name,
                              const char *drivername,
250
                              const char *machinename)
251 252
{
    size_t i;
253 254 255 256
    VIR_AUTOFREE(char *) partname = NULL;
    VIR_AUTOFREE(char *) scopename_old = NULL;
    VIR_AUTOFREE(char *) scopename_new = NULL;
    VIR_AUTOFREE(char *) partmachinename = NULL;
257 258 259

    if (virAsprintf(&partname, "%s.libvirt-%s",
                    name, drivername) < 0)
260
        return false;
261 262

    if (virCgroupPartitionEscape(&partname) < 0)
263
        return false;
264

265 266 267
    if (virAsprintf(&partmachinename, "%s.libvirt-%s",
                    machinename, drivername) < 0 ||
        virCgroupPartitionEscape(&partmachinename) < 0)
268
        return false;
269

270
    if (!(scopename_old = virSystemdMakeScopeName(name, drivername, true)))
271
        return false;
272

273 274
    if (!(scopename_new = virSystemdMakeScopeName(machinename,
                                                  drivername, false)))
275
        return false;
276 277

    if (virCgroupPartitionEscape(&scopename_old) < 0)
278
        return false;
279

280
    if (virCgroupPartitionEscape(&scopename_new) < 0)
281
        return false;
282

283 284 285
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
        char *tmp;

286 287 288
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD)
            continue;

289 290 291 292 293
        if (!group->controllers[i].placement)
            continue;

        tmp = strrchr(group->controllers[i].placement, '/');
        if (!tmp)
294
            return false;
295

296 297 298
        if (i == VIR_CGROUP_CONTROLLER_CPU ||
            i == VIR_CGROUP_CONTROLLER_CPUACCT ||
            i == VIR_CGROUP_CONTROLLER_CPUSET) {
299 300 301 302
            if (STREQ(tmp, "/emulator"))
                *tmp = '\0';
            tmp = strrchr(group->controllers[i].placement, '/');
            if (!tmp)
303
                return false;
304 305
        }

306 307 308
        tmp++;

        if (STRNEQ(tmp, name) &&
309
            STRNEQ(tmp, machinename) &&
310
            STRNEQ(tmp, partname) &&
311
            STRNEQ(tmp, partmachinename) &&
312
            STRNEQ(tmp, scopename_old) &&
313
            STRNEQ(tmp, scopename_new)) {
E
Eric Blake 已提交
314
            VIR_DEBUG("Name '%s' for controller '%s' does not match "
315
                      "'%s', '%s', '%s', '%s' or '%s'",
E
Eric Blake 已提交
316
                      tmp, virCgroupControllerTypeToString(i),
317 318
                      name, machinename, partname,
                      scopename_old, scopename_new);
319
            return false;
320
        }
321 322
    }

323
    return true;
324
}
E
Eric Blake 已提交
325

L
Lai Jiangshan 已提交
326

E
Eric Blake 已提交
327 328 329
static int
virCgroupCopyMounts(virCgroupPtr group,
                    virCgroupPtr parent)
330
{
331
    size_t i;
332
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
333 334 335
        if (!parent->controllers[i].mountPoint)
            continue;

336 337 338
        if (VIR_STRDUP(group->controllers[i].mountPoint,
                       parent->controllers[i].mountPoint) < 0)
            return -1;
339

340 341 342
        if (VIR_STRDUP(group->controllers[i].linkPoint,
                       parent->controllers[i].linkPoint) < 0)
            return -1;
343 344 345 346
    }
    return 0;
}

E
Eric Blake 已提交
347

348
static int
349
virCgroupResolveMountLink(const char *mntDir,
350 351 352 353
                          const char *typeStr,
                          virCgroupControllerPtr controller)
{
    VIR_AUTOFREE(char *) linkSrc = NULL;
354
    VIR_AUTOFREE(char *) tmp = NULL;
355 356 357
    char *dirName;
    struct stat sb;

358 359 360 361
    if (VIR_STRDUP(tmp, mntDir) < 0)
        return -1;

    dirName = strrchr(tmp, '/');
362 363
    if (!dirName) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
364
                       _("Missing '/' separator in cgroup mount '%s'"), tmp);
365 366 367 368 369 370 371
        return -1;
    }

    if (!strchr(dirName + 1, ','))
        return 0;

    *dirName = '\0';
372
    if (virAsprintf(&linkSrc, "%s/%s", tmp, typeStr) < 0)
373 374 375 376 377 378
        return -1;
    *dirName = '/';

    if (lstat(linkSrc, &sb) < 0) {
        if (errno == ENOENT) {
            VIR_WARN("Controller %s co-mounted at %s is missing symlink at %s",
379
                     typeStr, tmp, linkSrc);
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
        } else {
            virReportSystemError(errno, _("Cannot stat %s"), linkSrc);
            return -1;
        }
    } else {
        if (!S_ISLNK(sb.st_mode)) {
            VIR_WARN("Expecting a symlink at %s for controller %s",
                     linkSrc, typeStr);
        } else {
            VIR_STEAL_PTR(controller->linkPoint, linkSrc);
        }
    }

    return 0;
}


397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
static bool
virCgroupMountOptsMatchController(const char *mntOpts,
                                  const char *typeStr)
{
    const char *tmp = mntOpts;
    int typeLen = strlen(typeStr);

    while (tmp) {
        const char *next = strchr(tmp, ',');
        int len;
        if (next) {
            len = next - tmp;
            next++;
        } else {
            len = strlen(tmp);
        }

        if (typeLen == len && STREQLEN(typeStr, tmp, len))
            return true;

        tmp = next;
    }

    return false;
}


424 425 426 427
/*
 * Process /proc/mounts figuring out what controllers are
 * mounted and where
 */
428 429 430 431
int
virCgroupDetectMountsFromFile(virCgroupPtr group,
                              const char *path,
                              bool checkLinks)
432
{
433
    size_t i;
434
    FILE *mounts = NULL;
435 436
    struct mntent entry;
    char buf[CGROUP_MAX_VAL];
437
    int ret = -1;
438

439
    mounts = fopen(path, "r");
440
    if (mounts == NULL) {
441
        virReportSystemError(errno, _("Unable to open %s"), path);
442
        return -1;
443 444 445
    }

    while (getmntent_r(mounts, &entry, buf, sizeof(buf)) != NULL) {
446 447
        if (STRNEQ(entry.mnt_type, "cgroup"))
            continue;
448

449
        for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
450
            const char *typestr = virCgroupControllerTypeToString(i);
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
            if (virCgroupMountOptsMatchController(entry.mnt_opts, typestr)) {
                /* Note that the lines in /proc/mounts have the same
                 * order than the mount operations, and that there may
                 * be duplicates due to bind mounts. This means
                 * that the same mount point may be processed more than
                 * once. We need to save the results of the last one,
                 * and we need to be careful to release the memory used
                 * by previous processing. */
                virCgroupControllerPtr controller = &group->controllers[i];

                VIR_FREE(controller->mountPoint);
                VIR_FREE(controller->linkPoint);
                if (VIR_STRDUP(controller->mountPoint, entry.mnt_dir) < 0)
                    goto cleanup;

                /* If it is a co-mount it has a filename like "cpu,cpuacct"
                 * and we must identify the symlink path */
                if (checkLinks &&
                    virCgroupResolveMountLink(entry.mnt_dir, typestr,
                                              controller) < 0) {
                    goto cleanup;
473
                }
474 475
            }
        }
476 477
    }

478 479
    ret = 0;
 cleanup:
480
    VIR_FORCE_FCLOSE(mounts);
481
    return ret;
482 483
}

484 485 486 487 488 489
static int
virCgroupDetectMounts(virCgroupPtr group)
{
    return virCgroupDetectMountsFromFile(group, "/proc/mounts", true);
}

490

E
Eric Blake 已提交
491 492 493 494
static int
virCgroupCopyPlacement(virCgroupPtr group,
                       const char *path,
                       virCgroupPtr parent)
495
{
496
    size_t i;
497
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
498 499 500
        if (!group->controllers[i].mountPoint)
            continue;

501 502 503
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD)
            continue;

504
        if (path[0] == '/') {
505 506
            if (VIR_STRDUP(group->controllers[i].placement, path) < 0)
                return -1;
507 508
        } else {
            /*
509 510 511
             * parent == "/" + path="" => "/"
             * parent == "/libvirt.service" + path == "" => "/libvirt.service"
             * parent == "/libvirt.service" + path == "foo" => "/libvirt.service/foo"
512 513 514 515 516 517 518
             */
            if (virAsprintf(&group->controllers[i].placement,
                            "%s%s%s",
                            parent->controllers[i].placement,
                            (STREQ(parent->controllers[i].placement, "/") ||
                             STREQ(path, "") ? "" : "/"),
                            path) < 0)
519
                return -1;
520 521 522 523 524 525 526
        }
    }

    return 0;
}


527
/*
528 529 530 531
 * virCgroupDetectPlacement:
 * @group: the group to process
 * @path: the relative path to append, not starting with '/'
 *
532 533
 * Process /proc/self/cgroup figuring out what cgroup
 * sub-path the current process is assigned to. ie not
534 535 536 537 538 539 540 541 542 543 544 545 546 547
 * necessarily in the root. The contents of this file
 * looks like
 *
 * 9:perf_event:/
 * 8:blkio:/
 * 7:net_cls:/
 * 6:freezer:/
 * 5:devices:/
 * 4:memory:/
 * 3:cpuacct,cpu:/
 * 2:cpuset:/
 * 1:name=systemd:/user/berrange/2
 *
 * It then appends @path to each detected path.
548
 */
E
Eric Blake 已提交
549 550 551 552
static int
virCgroupDetectPlacement(virCgroupPtr group,
                         pid_t pid,
                         const char *path)
553
{
554
    size_t i;
555 556
    FILE *mapping  = NULL;
    char line[1024];
557
    int ret = -1;
558
    VIR_AUTOFREE(char *) procfile = NULL;
559

560
    VIR_DEBUG("Detecting placement for pid %lld path %s",
M
Michal Privoznik 已提交
561
              (long long) pid, path);
562 563 564 565
    if (pid == -1) {
        if (VIR_STRDUP(procfile, "/proc/self/cgroup") < 0)
            goto cleanup;
    } else {
M
Michal Privoznik 已提交
566 567
        if (virAsprintf(&procfile, "/proc/%lld/cgroup",
                        (long long) pid) < 0)
568 569 570 571
            goto cleanup;
    }

    mapping = fopen(procfile, "r");
572
    if (mapping == NULL) {
573 574 575 576
        virReportSystemError(errno,
                             _("Unable to open '%s'"),
                             procfile);
        goto cleanup;
577 578
    }

579 580
    while (fgets(line, sizeof(line), mapping) != NULL) {
        char *controllers = strchr(line, ':');
581 582
        char *selfpath = controllers ? strchr(controllers + 1, ':') : NULL;
        char *nl = selfpath ? strchr(selfpath, '\n') : NULL;
583

584
        if (!controllers || !selfpath)
585 586 587 588 589
            continue;

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

590
        *selfpath = '\0';
591
        controllers++;
592
        selfpath++;
593

594
        for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
595
            const char *typestr = virCgroupControllerTypeToString(i);
596

597 598 599
            if (virCgroupMountOptsMatchController(controllers, typestr) &&
                group->controllers[i].mountPoint != NULL &&
                group->controllers[i].placement == NULL) {
600
                /*
601 602 603
                 * selfpath == "/" + path="" -> "/"
                 * selfpath == "/libvirt.service" + path == "" -> "/libvirt.service"
                 * selfpath == "/libvirt.service" + path == "foo" -> "/libvirt.service/foo"
604
                 */
605 606 607 608 609 610 611 612 613 614 615
                if (i == VIR_CGROUP_CONTROLLER_SYSTEMD) {
                    if (VIR_STRDUP(group->controllers[i].placement,
                                   selfpath) < 0)
                        goto cleanup;
                } else {
                    if (virAsprintf(&group->controllers[i].placement,
                                    "%s%s%s", selfpath,
                                    (STREQ(selfpath, "/") ||
                                     STREQ(path, "") ? "" : "/"),
                                    path) < 0)
                        goto cleanup;
616
                }
617 618 619 620
            }
        }
    }

621
    ret = 0;
622

623
 cleanup:
624
    VIR_FORCE_FCLOSE(mapping);
625
    return ret;
626 627
}

E
Eric Blake 已提交
628

629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
static int
virCgroupValidatePlacement(virCgroupPtr group,
                           pid_t pid)
{
    size_t i;

    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
        if (!group->controllers[i].mountPoint)
            continue;

        if (!group->controllers[i].placement) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not find placement for controller %s at %s"),
                           virCgroupControllerTypeToString(i),
                           group->controllers[i].placement);
            return -1;
        }

        VIR_DEBUG("Detected mount/mapping %zu:%s at %s in %s for pid %lld",
                  i,
                  virCgroupControllerTypeToString(i),
                  group->controllers[i].mountPoint,
                  group->controllers[i].placement,
                  (long long) pid);
    }

    return 0;
}


E
Eric Blake 已提交
659
static int
660 661
virCgroupDetectControllers(virCgroupPtr group,
                           int controllers)
662
{
663 664
    size_t i;
    size_t j;
665

666
    if (controllers >= 0) {
667
        VIR_DEBUG("Filtering controllers %d", controllers);
668
        /* First mark requested but non-existing controllers to be ignored */
669
        for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
670
            if (((1 << i) & controllers)) {
671
                /* Remove non-existent controllers  */
672
                if (!group->controllers[i].mountPoint) {
673
                    VIR_DEBUG("Requested controller '%s' not mounted, ignoring",
674
                              virCgroupControllerTypeToString(i));
675
                    controllers &= ~(1 << i);
676
                }
677 678 679 680 681 682 683 684 685
            }
        }
        for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
            VIR_DEBUG("Controller '%s' wanted=%s, mount='%s'",
                      virCgroupControllerTypeToString(i),
                      (1 << i) & controllers ? "yes" : "no",
                      NULLSTR(group->controllers[i].mountPoint));
            if (!((1 << i) & controllers) &&
                group->controllers[i].mountPoint) {
686 687
                /* Check whether a request to disable a controller
                 * clashes with co-mounting of controllers */
688
                for (j = 0; j < VIR_CGROUP_CONTROLLER_LAST; j++) {
689 690 691 692 693 694 695
                    if (j == i)
                        continue;
                    if (!((1 << j) & controllers))
                        continue;

                    if (STREQ_NULLABLE(group->controllers[i].mountPoint,
                                       group->controllers[j].mountPoint)) {
696 697 698 699 700
                        virReportSystemError(EINVAL,
                                             _("Controller '%s' is not wanted, but '%s' is co-mounted"),
                                             virCgroupControllerTypeToString(i),
                                             virCgroupControllerTypeToString(j));
                        return -1;
701 702 703 704 705 706 707 708
                    }
                }
                VIR_FREE(group->controllers[i].mountPoint);
            }
        }
    } else {
        VIR_DEBUG("Auto-detecting controllers");
        controllers = 0;
709
        for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
710 711 712 713 714 715 716
            VIR_DEBUG("Controller '%s' present=%s",
                      virCgroupControllerTypeToString(i),
                      group->controllers[i].mountPoint ? "yes" : "no");
            if (group->controllers[i].mountPoint == NULL)
                continue;
            controllers |= (1 << i);
        }
717
    }
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 744 745 746
    return controllers;
}


static int
virCgroupDetect(virCgroupPtr group,
                pid_t pid,
                int controllers,
                const char *path,
                virCgroupPtr parent)
{
    int rc;

    VIR_DEBUG("group=%p controllers=%d path=%s parent=%p",
              group, controllers, path, parent);

    if (parent) {
        if (virCgroupCopyMounts(group, parent) < 0)
            return -1;
    } else {
        if (virCgroupDetectMounts(group) < 0)
            return -1;
    }

    rc = virCgroupDetectControllers(group, controllers);
    if (rc < 0)
        return -1;

747
    /* Check that at least 1 controller is available */
748
    if (rc == 0) {
749 750 751
        virReportSystemError(ENXIO, "%s",
                             _("At least one cgroup controller is required"));
        return -1;
752
    }
753

754 755 756 757 758 759 760 761 762 763
    /* In some cases we can copy part of the placement info
     * based on the parent cgroup...
     */
    if ((parent || path[0] == '/') &&
        virCgroupCopyPlacement(group, path, parent) < 0)
        return -1;

    /* ... but use /proc/cgroups to fill in the rest */
    if (virCgroupDetectPlacement(group, pid, path) < 0)
        return -1;
764

765
    /* Check that for every mounted controller, we found our placement */
766 767
    if (virCgroupValidatePlacement(group, pid) < 0)
        return -1;
768

769
    return 0;
770 771
}

772

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
static char *
virCgroupGetBlockDevString(const char *path)
{
    char *ret = NULL;
    struct stat sb;

    if (stat(path, &sb) < 0) {
        virReportSystemError(errno,
                             _("Path '%s' is not accessible"),
                             path);
        return NULL;
    }

    if (!S_ISBLK(sb.st_mode)) {
        virReportSystemError(EINVAL,
                             _("Path '%s' must be a block device"),
                             path);
        return NULL;
    }

    /* Automatically append space after the string since all callers
     * use it anyway */
    if (virAsprintf(&ret, "%d:%d ", major(sb.st_rdev), minor(sb.st_rdev)) < 0)
        return NULL;

    return ret;
}


E
Eric Blake 已提交
802 803 804 805 806
static int
virCgroupSetValueStr(virCgroupPtr group,
                     int controller,
                     const char *key,
                     const char *value)
807
{
808
    VIR_AUTOFREE(char *) keypath = NULL;
809
    char *tmp = NULL;
810

811 812
    if (virCgroupPathOfController(group, controller, key, &keypath) < 0)
        return -1;
813

814
    VIR_DEBUG("Set value '%s' to '%s'", keypath, value);
815
    if (virFileWriteStr(keypath, value, 0) < 0) {
816 817 818 819 820
        if (errno == EINVAL &&
            (tmp = strrchr(keypath, '/'))) {
            virReportSystemError(errno,
                                 _("Invalid value '%s' for '%s'"),
                                 value, tmp + 1);
821
            return -1;
822
        }
823 824
        virReportSystemError(errno,
                             _("Unable to write to '%s'"), keypath);
825
        return -1;
826 827
    }

828
    return 0;
829 830
}

E
Eric Blake 已提交
831 832 833 834 835 836

static int
virCgroupGetValueStr(virCgroupPtr group,
                     int controller,
                     const char *key,
                     char **value)
837
{
838 839
    VIR_AUTOFREE(char *) keypath = NULL;
    int rc;
840

841
    *value = NULL;
842

843 844
    if (virCgroupPathOfController(group, controller, key, &keypath) < 0)
        return -1;
845

846
    VIR_DEBUG("Get value %s", keypath);
847

848 849 850
    if ((rc = virFileReadAll(keypath, 1024*1024, value)) < 0) {
        virReportSystemError(errno,
                             _("Unable to read from '%s'"), keypath);
851
        return -1;
852 853
    }

854 855 856
    /* Terminated with '\n' has sometimes harmful effects to the caller */
    if (rc > 0 && (*value)[rc - 1] == '\n')
        (*value)[rc - 1] = '\0';
857

858
    return 0;
859 860
}

E
Eric Blake 已提交
861

862 863 864 865 866 867 868
static int
virCgroupGetValueForBlkDev(virCgroupPtr group,
                           int controller,
                           const char *key,
                           const char *path,
                           char **value)
{
869 870
    VIR_AUTOFREE(char *) prefix = NULL;
    VIR_AUTOFREE(char *) str = NULL;
871 872
    char **lines = NULL;
    int ret = -1;
873 874

    if (virCgroupGetValueStr(group, controller, key, &str) < 0)
875
        goto error;
876 877

    if (!(prefix = virCgroupGetBlockDevString(path)))
878
        goto error;
879 880

    if (!(lines = virStringSplit(str, "\n", -1)))
881
        goto error;
882

883
    if (VIR_STRDUP(*value, virStringListGetFirstWithPrefix(lines, prefix)) < 0)
884
        goto error;
885

886 887 888 889
    ret = 0;
 error:
    virStringListFree(lines);
    return ret;
890 891 892
}


E
Eric Blake 已提交
893 894 895 896 897
static int
virCgroupSetValueU64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     unsigned long long int value)
898
{
899
    VIR_AUTOFREE(char *) strval = NULL;
900

901 902
    if (virAsprintf(&strval, "%llu", value) < 0)
        return -1;
903

904
    return virCgroupSetValueStr(group, controller, key, strval);
905 906 907
}


E
Eric Blake 已提交
908 909 910 911 912
static int
virCgroupSetValueI64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     long long int value)
913
{
914
    VIR_AUTOFREE(char *) strval = NULL;
915

916 917
    if (virAsprintf(&strval, "%lld", value) < 0)
        return -1;
918

919
    return virCgroupSetValueStr(group, controller, key, strval);
920 921
}

E
Eric Blake 已提交
922 923 924 925 926 927

static int
virCgroupGetValueI64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     long long int *value)
928
{
929
    VIR_AUTOFREE(char *) strval = NULL;
930

931
    if (virCgroupGetValueStr(group, controller, key, &strval) < 0)
932
        return -1;
933

934 935 936 937
    if (virStrToLong_ll(strval, NULL, 10, value) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       strval);
938
        return -1;
939
    }
940

941
    return 0;
942 943
}

E
Eric Blake 已提交
944 945 946 947 948 949

static int
virCgroupGetValueU64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     unsigned long long int *value)
950
{
951
    VIR_AUTOFREE(char *) strval = NULL;
952

953
    if (virCgroupGetValueStr(group, controller, key, &strval) < 0)
954
        return -1;
955

956 957 958 959
    if (virStrToLong_ull(strval, NULL, 10, value) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       strval);
960
        return -1;
961
    }
962

963
    return 0;
964 965 966
}


E
Eric Blake 已提交
967 968
static int
virCgroupCpuSetInherit(virCgroupPtr parent, virCgroupPtr group)
969
{
970
    size_t i;
971 972 973
    const char *inherit_values[] = {
        "cpuset.cpus",
        "cpuset.mems",
974
        "cpuset.memory_migrate",
975 976
    };

977
    VIR_DEBUG("Setting up inheritance %s -> %s", parent->path, group->path);
978
    for (i = 0; i < ARRAY_CARDINALITY(inherit_values); i++) {
979
        VIR_AUTOFREE(char *) value = NULL;
980

981 982 983 984
        if (virCgroupGetValueStr(parent,
                                 VIR_CGROUP_CONTROLLER_CPUSET,
                                 inherit_values[i],
                                 &value) < 0)
985
            return -1;
986 987 988

        VIR_DEBUG("Inherit %s = %s", inherit_values[i], value);

989 990 991
        if (virCgroupSetValueStr(group,
                                 VIR_CGROUP_CONTROLLER_CPUSET,
                                 inherit_values[i],
992
                                 value) < 0)
993
            return -1;
994 995
    }

996
    return 0;
997 998
}

E
Eric Blake 已提交
999 1000 1001

static int
virCgroupSetMemoryUseHierarchy(virCgroupPtr group)
1002 1003 1004 1005
{
    unsigned long long value;
    const char *filename = "memory.use_hierarchy";

1006 1007 1008
    if (virCgroupGetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             filename, &value) < 0)
1009
        return -1;
1010 1011 1012 1013 1014 1015

    /* Setting twice causes error, so if already enabled, skip setting */
    if (value == 1)
        return 0;

    VIR_DEBUG("Setting up %s/%s", group->path, filename);
1016 1017 1018
    if (virCgroupSetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             filename, 1) < 0)
1019
        return -1;
1020

1021
    return 0;
1022 1023
}

E
Eric Blake 已提交
1024 1025 1026 1027 1028 1029

static int
virCgroupMakeGroup(virCgroupPtr parent,
                   virCgroupPtr group,
                   bool create,
                   unsigned int flags)
1030
{
1031
    size_t i;
1032

1033
    VIR_DEBUG("Make group %s", group->path);
1034
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
1035
        VIR_AUTOFREE(char *) path = NULL;
1036

1037 1038 1039 1040 1041 1042
        /* We must never mkdir() in systemd's hierarchy */
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD) {
            VIR_DEBUG("Not creating systemd controller group");
            continue;
        }

1043
        /* Skip over controllers that aren't mounted */
1044 1045 1046
        if (!group->controllers[i].mountPoint) {
            VIR_DEBUG("Skipping unmounted controller %s",
                      virCgroupControllerTypeToString(i));
1047
            continue;
1048
        }
1049

1050
        if (virCgroupPathOfController(group, i, "", &path) < 0)
1051
            goto error;
1052

1053
        VIR_DEBUG("Make controller %s", path);
1054
        if (!virFileExists(path)) {
1055 1056
            if (!create ||
                mkdir(path, 0755) < 0) {
1057
                if (errno == EEXIST)
1058
                    continue;
1059 1060 1061 1062 1063
                /* With a kernel that doesn't support multi-level directory
                 * for blkio controller, libvirt will fail and disable all
                 * other controllers even though they are available. So
                 * treat blkio as unmounted if mkdir fails. */
                if (i == VIR_CGROUP_CONTROLLER_BLKIO) {
1064
                    VIR_DEBUG("Ignoring mkdir failure with blkio controller. Kernel probably too old");
1065 1066 1067
                    VIR_FREE(group->controllers[i].mountPoint);
                    continue;
                } else {
1068 1069 1070
                    virReportSystemError(errno,
                                         _("Failed to create controller %s for group"),
                                         virCgroupControllerTypeToString(i));
1071
                    goto error;
1072
                }
1073
            }
1074 1075 1076 1077
            if (i == VIR_CGROUP_CONTROLLER_CPUSET &&
                group->controllers[i].mountPoint != NULL &&
                virCgroupCpuSetInherit(parent, group) < 0) {
                goto error;
1078
            }
1079 1080 1081 1082
            /*
             * Note that virCgroupSetMemoryUseHierarchy should always be
             * called prior to creating subcgroups and attaching tasks.
             */
1083
            if ((flags & VIR_CGROUP_MEM_HIERACHY) &&
1084 1085 1086 1087
                i == VIR_CGROUP_CONTROLLER_MEMORY &&
                group->controllers[i].mountPoint != NULL &&
                virCgroupSetMemoryUseHierarchy(group) < 0) {
                goto error;
1088
            }
1089 1090 1091
        }
    }

1092
    VIR_DEBUG("Done making controllers for group");
1093
    return 0;
1094 1095 1096 1097

 error:
    virCgroupRemove(group);
    return -1;
1098 1099
}

1100

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
/**
 * virCgroupNew:
 * @path: path for the new group
 * @parent: parent group, or NULL
 * @controllers: bitmask of controllers to activate
 *
 * Create a new cgroup storing it in @group.
 *
 * If @path starts with a '/' it is treated as an
 * absolute path, and @parent is ignored. Otherwise
 * it is treated as being relative to @parent. If
 * @parent is NULL, then the placement of the current
 * process is used.
 *
1115
 * Returns 0 on success, -1 on error
1116
 */
E
Eric Blake 已提交
1117 1118 1119 1120 1121 1122
static int
virCgroupNew(pid_t pid,
             const char *path,
             virCgroupPtr parent,
             int controllers,
             virCgroupPtr *group)
1123
{
1124 1125
    VIR_DEBUG("pid=%lld path=%s parent=%p controllers=%d group=%p",
              (long long) pid, path, parent, controllers, group);
1126
    *group = NULL;
1127

1128 1129
    if (VIR_ALLOC((*group)) < 0)
        goto error;
1130

1131
    if (path[0] == '/' || !parent) {
1132 1133
        if (VIR_STRDUP((*group)->path, path) < 0)
            goto error;
1134 1135 1136 1137
    } else {
        if (virAsprintf(&(*group)->path, "%s%s%s",
                        parent->path,
                        STREQ(parent->path, "") ? "" : "/",
1138 1139
                        path) < 0)
            goto error;
1140 1141
    }

1142
    if (virCgroupDetect(*group, pid, controllers, path, parent) < 0)
1143
        goto error;
1144

1145 1146
    return 0;

1147
 error:
1148
    virCgroupFree(group);
1149
    *group = NULL;
1150

1151
    return -1;
1152
}
1153

1154

1155 1156
static int
virCgroupAddTaskInternal(virCgroupPtr group, pid_t pid, bool withSystemd)
1157
{
1158
    int ret = -1;
1159
    size_t i;
1160

1161
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
1162 1163 1164
        /* Skip over controllers not mounted */
        if (!group->controllers[i].mountPoint)
            continue;
1165

1166 1167 1168 1169
        /* We must never add tasks in systemd's hierarchy
         * unless we're intentionally trying to move a
         * task into a systemd machine scope */
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD && !withSystemd)
1170 1171
            continue;

1172
        if (virCgroupSetValueI64(group, i, "tasks", pid) < 0)
1173
            goto cleanup;
1174 1175
    }

1176
    ret = 0;
1177
 cleanup:
1178
    return ret;
1179 1180
}

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
/**
 * virCgroupAddTask:
 *
 * @group: The cgroup to add a task to
 * @pid: The pid of the task to add
 *
 * Will add the task to all controllers, except the
 * systemd unit controller.
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupAddTask(virCgroupPtr group, pid_t pid)
{
    return virCgroupAddTaskInternal(group, pid, false);
}

/**
 * virCgroupAddMachineTask:
 *
 * @group: The cgroup to add a task to
 * @pid: The pid of the task to add
 *
 * Will add the task to all controllers, including the
 * systemd unit controller.
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupAddMachineTask(virCgroupPtr group, pid_t pid)
{
    return virCgroupAddTaskInternal(group, pid, true);
}

E
Eric Blake 已提交
1215 1216 1217

static int
virCgroupSetPartitionSuffix(const char *path, char **res)
1218
{
1219
    char **tokens;
1220
    size_t i;
1221
    int ret = -1;
1222

1223
    if (!(tokens = virStringSplit(path, "/", 0)))
1224
        return ret;
1225

1226
    for (i = 0; tokens[i] != NULL; i++) {
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
        /* Whitelist the 3 top level fixed dirs
         * NB i == 0 is "", since we have leading '/'
         */
        if (i == 1 &&
            (STREQ(tokens[i], "machine") ||
             STREQ(tokens[i], "system") ||
             STREQ(tokens[i], "user"))) {
            continue;
        }
        /* If there is no suffix set already, then
         * add ".partition"
         */
        if (STRNEQ(tokens[i], "") &&
            !strchr(tokens[i], '.')) {
            if (VIR_REALLOC_N(tokens[i],
1242
                              strlen(tokens[i]) + strlen(".partition") + 1) < 0)
1243
                goto cleanup;
1244 1245
            strcat(tokens[i], ".partition");
        }
1246

1247
        if (virCgroupPartitionEscape(&(tokens[i])) < 0)
1248
            goto cleanup;
1249 1250
    }

1251
    if (!(*res = virStringListJoin((const char **)tokens, "/")))
1252
        goto cleanup;
1253

1254 1255 1256 1257 1258
    ret = 0;

 cleanup:
    virStringListFree(tokens);
    return ret;
1259 1260
}

E
Eric Blake 已提交
1261

1262 1263 1264 1265 1266 1267 1268
/**
 * virCgroupNewPartition:
 * @path: path for the partition
 * @create: true to create the cgroup tree
 * @controllers: mask of controllers to create
 *
 * Creates a new cgroup to represent the resource
1269
 * partition path identified by @path.
1270
 *
1271
 * Returns 0 on success, -1 on failure
1272
 */
E
Eric Blake 已提交
1273 1274 1275 1276 1277
int
virCgroupNewPartition(const char *path,
                      bool create,
                      int controllers,
                      virCgroupPtr *group)
1278
{
1279
    int ret = -1;
1280 1281
    VIR_AUTOFREE(char *) parentPath = NULL;
    VIR_AUTOFREE(char *) newPath = NULL;
1282
    virCgroupPtr parent = NULL;
1283 1284 1285
    VIR_DEBUG("path=%s create=%d controllers=%x",
              path, create, controllers);

1286 1287 1288 1289 1290 1291
    if (path[0] != '/') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Partition path '%s' must start with '/'"),
                       path);
        return -1;
    }
1292

1293
    if (virCgroupSetPartitionSuffix(path, &newPath) < 0)
1294
        goto cleanup;
1295

1296 1297
    if (virCgroupNew(-1, newPath, NULL, controllers, group) < 0)
        goto cleanup;
1298

1299
    if (STRNEQ(newPath, "/")) {
1300
        char *tmp;
1301
        if (VIR_STRDUP(parentPath, newPath) < 0)
1302
            goto cleanup;
1303 1304 1305 1306 1307

        tmp = strrchr(parentPath, '/');
        tmp++;
        *tmp = '\0';

1308
        if (virCgroupNew(-1, parentPath, NULL, controllers, &parent) < 0)
1309
            goto cleanup;
1310

1311
        if (virCgroupMakeGroup(parent, *group, create, VIR_CGROUP_NONE) < 0)
1312
            goto cleanup;
1313 1314
    }

1315 1316 1317
    ret = 0;
 cleanup:
    if (ret != 0)
1318 1319
        virCgroupFree(group);
    virCgroupFree(&parent);
1320
    return ret;
1321 1322
}

1323

G
Gao feng 已提交
1324
/**
1325
* virCgroupNewSelf:
G
Gao feng 已提交
1326 1327 1328
*
* @group: Pointer to returned virCgroupPtr
*
1329 1330 1331
* Obtain a cgroup representing the config of the
* current process
*
1332
* Returns 0 on success, or -1 on error
G
Gao feng 已提交
1333
*/
E
Eric Blake 已提交
1334 1335
int
virCgroupNewSelf(virCgroupPtr *group)
G
Gao feng 已提交
1336
{
1337
    return virCgroupNewDetect(-1, -1, group);
G
Gao feng 已提交
1338
}
1339

1340

1341 1342 1343 1344 1345 1346 1347 1348
/**
 * virCgroupNewDomainPartition:
 *
 * @partition: partition holding the domain
 * @driver: name of the driver
 * @name: name of the domain
 * @group: Pointer to returned virCgroupPtr
 *
1349
 * Returns 0 on success, or -1 on error
1350
 */
E
Eric Blake 已提交
1351 1352 1353 1354 1355 1356
int
virCgroupNewDomainPartition(virCgroupPtr partition,
                            const char *driver,
                            const char *name,
                            bool create,
                            virCgroupPtr *group)
1357
{
1358
    VIR_AUTOFREE(char *)grpname = NULL;
1359

1360
    if (virAsprintf(&grpname, "%s.libvirt-%s",
1361
                    name, driver) < 0)
1362
        return -1;
1363

1364
    if (virCgroupPartitionEscape(&grpname) < 0)
1365
        return -1;
1366

1367
    if (virCgroupNew(-1, grpname, partition, -1, group) < 0)
1368
        return -1;
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379

    /*
     * Create a cgroup with memory.use_hierarchy enabled to
     * surely account memory usage of lxc with ns subsystem
     * enabled. (To be exact, memory and ns subsystems are
     * enabled at the same time.)
     *
     * The reason why doing it here, not a upper group, say
     * a group for driver, is to avoid overhead to track
     * cumulative usage that we don't need.
     */
E
Eric Blake 已提交
1380 1381
    if (virCgroupMakeGroup(partition, *group, create,
                           VIR_CGROUP_MEM_HIERACHY) < 0) {
1382
        virCgroupFree(group);
1383
        return -1;
1384 1385
    }

1386
    return 0;
1387
}
1388

E
Eric Blake 已提交
1389

1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
/**
 * virCgroupNewThread:
 *
 * @domain: group for the domain
 * @name: enum to generate the name for the new thread
 * @id: id of the vcpu or iothread
 * @create: true to create if not already existing
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success, or -1 on error
 */
int
virCgroupNewThread(virCgroupPtr domain,
                   virCgroupThreadName nameval,
                   int id,
                   bool create,
                   virCgroupPtr *group)
{
1408
    VIR_AUTOFREE(char *) name = NULL;
1409 1410 1411 1412 1413
    int controllers;

    switch (nameval) {
    case VIR_CGROUP_THREAD_VCPU:
        if (virAsprintf(&name, "vcpu%d", id) < 0)
1414
            return -1;
1415 1416 1417
        break;
    case VIR_CGROUP_THREAD_EMULATOR:
        if (VIR_STRDUP(name, "emulator") < 0)
1418
            return -1;
1419 1420 1421
        break;
    case VIR_CGROUP_THREAD_IOTHREAD:
        if (virAsprintf(&name, "iothread%d", id) < 0)
1422
            return -1;
1423 1424 1425 1426
        break;
    case VIR_CGROUP_THREAD_LAST:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected name value %d"), nameval);
1427
        return -1;
1428 1429 1430 1431 1432 1433 1434
    }

    controllers = ((1 << VIR_CGROUP_CONTROLLER_CPU) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUACCT) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUSET));

    if (virCgroupNew(-1, name, domain, controllers, group) < 0)
1435
        return -1;
1436 1437

    if (virCgroupMakeGroup(domain, *group, create, VIR_CGROUP_NONE) < 0) {
1438
        virCgroupFree(group);
1439
        return -1;
1440 1441
    }

1442
    return 0;
1443 1444 1445
}


E
Eric Blake 已提交
1446 1447 1448 1449
int
virCgroupNewDetect(pid_t pid,
                   int controllers,
                   virCgroupPtr *group)
1450
{
1451
    return virCgroupNew(pid, "", NULL, controllers, group);
1452 1453
}

E
Eric Blake 已提交
1454

1455 1456 1457
/*
 * Returns 0 on success (but @group may be NULL), -1 on fatal error
 */
E
Eric Blake 已提交
1458 1459 1460 1461 1462
int
virCgroupNewDetectMachine(const char *name,
                          const char *drivername,
                          pid_t pid,
                          int controllers,
1463
                          char *machinename,
E
Eric Blake 已提交
1464
                          virCgroupPtr *group)
1465
{
1466
    if (virCgroupNewDetect(pid, controllers, group) < 0) {
1467 1468 1469 1470 1471
        if (virCgroupNewIgnoreError())
            return 0;
        return -1;
    }

1472
    if (!virCgroupValidateMachineGroup(*group, name, drivername, machinename)) {
1473 1474
        VIR_DEBUG("Failed to validate machine name for '%s' driver '%s'",
                  name, drivername);
1475
        virCgroupFree(group);
1476 1477 1478 1479 1480 1481
        return 0;
    }

    return 0;
}

E
Eric Blake 已提交
1482

1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
static int
virCgroupEnableMissingControllers(char *path,
                                  pid_t pidleader,
                                  int controllers,
                                  virCgroupPtr *group)
{
    virCgroupPtr parent = NULL;
    char *offset = path;
    int ret = -1;

    if (virCgroupNew(pidleader,
                     "",
                     NULL,
                     controllers,
                     &parent) < 0)
        return ret;

    for (;;) {
        virCgroupPtr tmp;
        char *t = strchr(offset + 1, '/');
        if (t)
            *t = '\0';

        if (virCgroupNew(pidleader,
                         path,
                         parent,
                         controllers,
                         &tmp) < 0)
            goto cleanup;

        if (virCgroupMakeGroup(parent, tmp, true, VIR_CGROUP_NONE) < 0) {
            virCgroupFree(&tmp);
            goto cleanup;
        }
        if (t) {
            *t = '/';
            offset = t;
            virCgroupFree(&parent);
            parent = tmp;
        } else {
            *group = tmp;
            break;
        }
    }

    ret = 0;
 cleanup:
    virCgroupFree(&parent);
    return ret;
}


1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
/*
 * Returns 0 on success, -1 on fatal error, -2 on systemd not available
 */
static int
virCgroupNewMachineSystemd(const char *name,
                           const char *drivername,
                           const unsigned char *uuid,
                           const char *rootdir,
                           pid_t pidleader,
                           bool isContainer,
1545 1546
                           size_t nnicindexes,
                           int *nicindexes,
1547 1548 1549
                           const char *partition,
                           int controllers,
                           virCgroupPtr *group)
1550
{
1551
    int rv;
1552
    virCgroupPtr init;
1553
    VIR_AUTOFREE(char *) path = NULL;
1554 1555 1556 1557 1558 1559 1560 1561

    VIR_DEBUG("Trying to setup machine '%s' via systemd", name);
    if ((rv = virSystemdCreateMachine(name,
                                      drivername,
                                      uuid,
                                      rootdir,
                                      pidleader,
                                      isContainer,
1562 1563
                                      nnicindexes,
                                      nicindexes,
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
                                      partition)) < 0)
        return rv;

    if (controllers != -1)
        controllers |= (1 << VIR_CGROUP_CONTROLLER_SYSTEMD);

    VIR_DEBUG("Detecting systemd placement");
    if (virCgroupNewDetect(pidleader,
                           controllers,
                           &init) < 0)
        return -1;
1575

1576 1577
    path = init->controllers[VIR_CGROUP_CONTROLLER_SYSTEMD].placement;
    init->controllers[VIR_CGROUP_CONTROLLER_SYSTEMD].placement = NULL;
1578
    virCgroupFree(&init);
1579 1580 1581

    if (!path || STREQ(path, "/") || path[0] != '/') {
        VIR_DEBUG("Systemd didn't setup its controller");
1582
        return -2;
1583 1584
    }

1585 1586 1587
    if (virCgroupEnableMissingControllers(path, pidleader,
                                          controllers, group) < 0) {
        return -1;
1588 1589
    }

1590 1591 1592
    if (virCgroupAddTask(*group, pidleader) < 0) {
        virErrorPtr saved = virSaveLastError();
        virCgroupRemove(*group);
1593
        virCgroupFree(group);
1594 1595 1596 1597 1598 1599
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
    }

1600
    return 0;
1601
}
1602

E
Eric Blake 已提交
1603

1604 1605 1606
/*
 * Returns 0 on success, -1 on fatal error
 */
1607
int virCgroupTerminateMachine(const char *name)
1608
{
1609
    return virSystemdTerminateMachine(name);
1610 1611 1612
}


1613 1614 1615
static int
virCgroupNewMachineManual(const char *name,
                          const char *drivername,
1616
                          pid_t pidleader,
1617 1618 1619 1620
                          const char *partition,
                          int controllers,
                          virCgroupPtr *group)
{
1621 1622
    virCgroupPtr parent = NULL;
    int ret = -1;
1623 1624

    VIR_DEBUG("Fallback to non-systemd setup");
1625 1626 1627 1628 1629
    if (virCgroupNewPartition(partition,
                              STREQ(partition, "/machine"),
                              controllers,
                              &parent) < 0) {
        if (virCgroupNewIgnoreError())
1630
            goto done;
1631

1632
        goto cleanup;
1633 1634 1635 1636 1637 1638 1639
    }

    if (virCgroupNewDomainPartition(parent,
                                    drivername,
                                    name,
                                    true,
                                    group) < 0)
1640
        goto cleanup;
1641

1642 1643 1644
    if (virCgroupAddTask(*group, pidleader) < 0) {
        virErrorPtr saved = virSaveLastError();
        virCgroupRemove(*group);
1645
        virCgroupFree(group);
1646 1647 1648 1649 1650 1651
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
    }

1652 1653 1654 1655
 done:
    ret = 0;

 cleanup:
1656
    virCgroupFree(&parent);
1657
    return ret;
1658 1659
}

E
Eric Blake 已提交
1660 1661 1662 1663 1664 1665 1666 1667

int
virCgroupNewMachine(const char *name,
                    const char *drivername,
                    const unsigned char *uuid,
                    const char *rootdir,
                    pid_t pidleader,
                    bool isContainer,
1668 1669
                    size_t nnicindexes,
                    int *nicindexes,
E
Eric Blake 已提交
1670 1671 1672
                    const char *partition,
                    int controllers,
                    virCgroupPtr *group)
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
{
    int rv;

    *group = NULL;

    if ((rv = virCgroupNewMachineSystemd(name,
                                         drivername,
                                         uuid,
                                         rootdir,
                                         pidleader,
                                         isContainer,
1684 1685
                                         nnicindexes,
                                         nicindexes,
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
                                         partition,
                                         controllers,
                                         group)) == 0)
        return 0;

    if (rv == -1)
        return -1;

    return virCgroupNewMachineManual(name,
                                     drivername,
1696
                                     pidleader,
1697 1698 1699 1700 1701
                                     partition,
                                     controllers,
                                     group);
}

E
Eric Blake 已提交
1702 1703 1704

bool
virCgroupNewIgnoreError(void)
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
{
    if (virLastErrorIsSystemErrno(ENXIO) ||
        virLastErrorIsSystemErrno(EPERM) ||
        virLastErrorIsSystemErrno(EACCES)) {
        virResetLastError();
        VIR_DEBUG("No cgroups present/configured/accessible, ignoring error");
        return true;
    }
    return false;
}

E
Eric Blake 已提交
1716

E
Eric Blake 已提交
1717 1718 1719 1720 1721 1722
/**
 * virCgroupFree:
 *
 * @group: The group structure to free
 */
void
1723
virCgroupFree(virCgroupPtr *group)
E
Eric Blake 已提交
1724 1725 1726
{
    size_t i;

1727
    if (*group == NULL)
E
Eric Blake 已提交
1728 1729 1730
        return;

    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
1731 1732 1733
        VIR_FREE((*group)->controllers[i].mountPoint);
        VIR_FREE((*group)->controllers[i].linkPoint);
        VIR_FREE((*group)->controllers[i].placement);
E
Eric Blake 已提交
1734 1735
    }

1736 1737
    VIR_FREE((*group)->path);
    VIR_FREE(*group);
E
Eric Blake 已提交
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762
}


/**
 * virCgroupHasController: query whether a cgroup controller is present
 *
 * @cgroup: The group structure to be queried, or NULL
 * @controller: cgroup subsystem id
 *
 * Returns true if a cgroup controller is mounted and is associated
 * with this cgroup object.
 */
bool
virCgroupHasController(virCgroupPtr cgroup, int controller)
{
    if (!cgroup)
        return false;
    if (controller < 0 || controller >= VIR_CGROUP_CONTROLLER_LAST)
        return false;
    return cgroup->controllers[controller].mountPoint != NULL;
}


int
virCgroupPathOfController(virCgroupPtr group,
1763
                          unsigned int controller,
E
Eric Blake 已提交
1764 1765 1766
                          const char *key,
                          char **path)
{
1767 1768 1769
    if (controller >= VIR_CGROUP_CONTROLLER_LAST) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid controller id '%d'"), controller);
E
Eric Blake 已提交
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
        return -1;
    }

    if (group->controllers[controller].mountPoint == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Controller '%s' is not mounted"),
                       virCgroupControllerTypeToString(controller));
        return -1;
    }

    if (group->controllers[controller].placement == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Controller '%s' is not enabled for group"),
                       virCgroupControllerTypeToString(controller));
        return -1;
    }

    if (virAsprintf(path, "%s%s/%s",
                    group->controllers[controller].mountPoint,
                    group->controllers[controller].placement,
                    key ? key : "") < 0)
        return -1;

    return 0;
}


1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
/**
 * virCgroupGetBlkioIoServiced:
 *
 * @group: The cgroup to get throughput for
 * @bytes_read: Pointer to returned bytes read
 * @bytes_write: Pointer to returned bytes written
 * @requests_read: Pointer to returned read io ops
 * @requests_write: Pointer to returned write io ops
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioIoServiced(virCgroupPtr group,
                            long long *bytes_read,
                            long long *bytes_write,
                            long long *requests_read,
                            long long *requests_write)
{
    long long stats_val;
1816 1817 1818 1819
    VIR_AUTOFREE(char *) str1 = NULL;
    VIR_AUTOFREE(char *) str2 = NULL;
    char *p1 = NULL;
    char *p2 = NULL;
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
    size_t i;

    const char *value_names[] = {
        "Read ",
        "Write "
    };
    long long *bytes_ptrs[] = {
        bytes_read,
        bytes_write
    };
    long long *requests_ptrs[] = {
        requests_read,
        requests_write
    };

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

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "blkio.throttle.io_service_bytes", &str1) < 0)
1843
        return -1;
1844 1845 1846 1847

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "blkio.throttle.io_serviced", &str2) < 0)
1848
        return -1;
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861

    /* sum up all entries of the same kind, from all devices */
    for (i = 0; i < ARRAY_CARDINALITY(value_names); i++) {
        p1 = str1;
        p2 = str2;

        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 %sstat '%s'"),
                               value_names[i],
                               p1);
1862
                return -1;
1863 1864 1865 1866 1867 1868 1869 1870
            }

            if (stats_val < 0 ||
                (stats_val > 0 && *bytes_ptrs[i] > (LLONG_MAX - stats_val)))
            {
                virReportError(VIR_ERR_OVERFLOW,
                               _("Sum of byte %sstat overflows"),
                               value_names[i]);
1871
                return -1;
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
            }
            *bytes_ptrs[i] += stats_val;
        }

        while ((p2 = strstr(p2, value_names[i]))) {
            p2 += strlen(value_names[i]);
            if (virStrToLong_ll(p2, &p2, 10, &stats_val) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Cannot parse %srequest stat '%s'"),
                               value_names[i],
                               p2);
1883
                return -1;
1884 1885 1886 1887 1888 1889 1890 1891
            }

            if (stats_val < 0 ||
                (stats_val > 0 && *requests_ptrs[i] > (LLONG_MAX - stats_val)))
            {
                virReportError(VIR_ERR_OVERFLOW,
                               _("Sum of %srequest stat overflows"),
                               value_names[i]);
1892
                return -1;
1893 1894 1895 1896 1897
            }
            *requests_ptrs[i] += stats_val;
        }
    }

1898
    return 0;
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
}


/**
 * virCgroupGetBlkioIoDeviceServiced:
 *
 * @group: The cgroup to get throughput for
 * @path: The device to get throughput for
 * @bytes_read: Pointer to returned bytes read
 * @bytes_write: Pointer to returned bytes written
 * @requests_read: Pointer to returned read io ops
 * @requests_write: Pointer to returned write io ops
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioIoDeviceServiced(virCgroupPtr group,
                                  const char *path,
                                  long long *bytes_read,
                                  long long *bytes_write,
                                  long long *requests_read,
                                  long long *requests_write)
{
1922 1923 1924 1925 1926
    VIR_AUTOFREE(char *) str1 = NULL;
    VIR_AUTOFREE(char *) str2 = NULL;
    VIR_AUTOFREE(char *) str3 = NULL;
    char *p1 = NULL;
    char *p2 = NULL;
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
    size_t i;

    const char *value_names[] = {
        "Read ",
        "Write "
    };
    long long *bytes_ptrs[] = {
        bytes_read,
        bytes_write
    };
    long long *requests_ptrs[] = {
        requests_read,
        requests_write
    };

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "blkio.throttle.io_service_bytes", &str1) < 0)
1945
        return -1;
1946 1947 1948 1949

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "blkio.throttle.io_serviced", &str2) < 0)
1950
        return -1;
1951

1952
    if (!(str3 = virCgroupGetBlockDevString(path)))
1953
        return -1;
1954 1955 1956 1957 1958

    if (!(p1 = strstr(str1, str3))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot find byte stats for block device '%s'"),
                       str3);
1959
        return -1;
1960 1961 1962 1963 1964 1965
    }

    if (!(p2 = strstr(str2, str3))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot find request stats for block device '%s'"),
                       str3);
1966
        return -1;
1967 1968 1969 1970 1971 1972 1973
    }

    for (i = 0; i < ARRAY_CARDINALITY(value_names); i++) {
        if (!(p1 = strstr(p1, value_names[i]))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot find byte %sstats for block device '%s'"),
                           value_names[i], str3);
1974
            return -1;
1975 1976 1977 1978 1979 1980
        }

        if (virStrToLong_ll(p1 + strlen(value_names[i]), &p1, 10, bytes_ptrs[i]) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot parse %sstat '%s'"),
                           value_names[i], p1 + strlen(value_names[i]));
1981
            return -1;
1982 1983 1984 1985 1986 1987
        }

        if (!(p2 = strstr(p2, value_names[i]))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot find request %sstats for block device '%s'"),
                           value_names[i], str3);
1988
            return -1;
1989 1990 1991 1992 1993 1994
        }

        if (virStrToLong_ll(p2 + strlen(value_names[i]), &p2, 10, requests_ptrs[i]) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot parse %sstat '%s'"),
                           value_names[i], p2 + strlen(value_names[i]));
1995
            return -1;
1996 1997 1998
        }
    }

1999
    return 0;
2000 2001 2002
}


2003 2004 2005 2006 2007 2008
/**
 * virCgroupSetBlkioWeight:
 *
 * @group: The cgroup to change io weight for
 * @weight: The Weight for this cgroup
 *
2009
 * Returns: 0 on success, -1 on error
2010
 */
E
Eric Blake 已提交
2011 2012
int
virCgroupSetBlkioWeight(virCgroupPtr group, unsigned int weight)
2013 2014 2015 2016 2017 2018 2019
{
    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "blkio.weight",
                                weight);
}

E
Eric Blake 已提交
2020

2021 2022 2023 2024 2025 2026
/**
 * virCgroupGetBlkioWeight:
 *
 * @group: The cgroup to get weight for
 * @Weight: Pointer to returned weight
 *
2027
 * Returns: 0 on success, -1 on error
2028
 */
E
Eric Blake 已提交
2029 2030
int
virCgroupGetBlkioWeight(virCgroupPtr group, unsigned int *weight)
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
{
    unsigned long long tmp;
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_BLKIO,
                               "blkio.weight", &tmp);
    if (ret == 0)
        *weight = tmp;
    return ret;
}

2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
/**
 * virCgroupSetBlkioDeviceReadIops:
 * @group: The cgroup to change block io setting for
 * @path: The path of device
 * @riops: The new device read iops throttle, or 0 to clear
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupSetBlkioDeviceReadIops(virCgroupPtr group,
                                const char *path,
                                unsigned int riops)
{
2055 2056
    VIR_AUTOFREE(char *) str = NULL;
    VIR_AUTOFREE(char *) blkstr = NULL;
2057

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

2061
    if (virAsprintf(&str, "%s%u", blkstr, riops) < 0)
2062
        return -1;
2063

2064
    return virCgroupSetValueStr(group,
2065 2066 2067
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "blkio.throttle.read_iops_device",
                                str);
2068 2069
}

E
Eric Blake 已提交
2070

2071
/**
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
 * virCgroupSetBlkioDeviceWriteIops:
 * @group: The cgroup to change block io setting for
 * @path: The path of device
 * @wiops: The new device write iops throttle, or 0 to clear
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupSetBlkioDeviceWriteIops(virCgroupPtr group,
                                 const char *path,
                                 unsigned int wiops)
{
2084 2085
    VIR_AUTOFREE(char *) str = NULL;
    VIR_AUTOFREE(char *) blkstr = NULL;
2086

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

2090
    if (virAsprintf(&str, "%s%u", blkstr, wiops) < 0)
2091
        return -1;
2092

2093
    return virCgroupSetValueStr(group,
2094 2095 2096
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "blkio.throttle.write_iops_device",
                                str);
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
}


/**
 * virCgroupSetBlkioDeviceReadBps:
 * @group: The cgroup to change block io setting for
 * @path: The path of device
 * @rbps: The new device read bps throttle, or 0 to clear
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupSetBlkioDeviceReadBps(virCgroupPtr group,
                               const char *path,
                               unsigned long long rbps)
{
2113 2114
    VIR_AUTOFREE(char *) str = NULL;
    VIR_AUTOFREE(char *) blkstr = NULL;
2115

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

2119
    if (virAsprintf(&str, "%s%llu", blkstr, rbps) < 0)
2120
        return -1;
2121

2122
    return virCgroupSetValueStr(group,
2123 2124 2125
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "blkio.throttle.read_bps_device",
                                str);
2126 2127 2128 2129 2130 2131 2132
}

/**
 * virCgroupSetBlkioDeviceWriteBps:
 * @group: The cgroup to change block io setting for
 * @path: The path of device
 * @wbps: The new device write bps throttle, or 0 to clear
2133
 *
2134 2135 2136 2137 2138 2139 2140
 * Returns: 0 on success, -1 on error
 */
int
virCgroupSetBlkioDeviceWriteBps(virCgroupPtr group,
                                const char *path,
                                unsigned long long wbps)
{
2141 2142
    VIR_AUTOFREE(char *) str = NULL;
    VIR_AUTOFREE(char *) blkstr = NULL;
2143

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

2147
    if (virAsprintf(&str, "%s%llu", blkstr, wbps) < 0)
2148
        return -1;
2149

2150
    return virCgroupSetValueStr(group,
2151 2152 2153
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "blkio.throttle.write_bps_device",
                                str);
2154 2155 2156 2157 2158 2159 2160
}


/**
 * virCgroupSetBlkioDeviceWeight:
 * @group: The cgroup to change block io setting for
 * @path: The path of device
2161 2162
 * @weight: The new device weight (100-1000),
 * (10-1000) after kernel 2.6.39, or 0 to clear
2163
 *
2164
 * Returns: 0 on success, -1 on error
2165
 */
E
Eric Blake 已提交
2166 2167 2168 2169
int
virCgroupSetBlkioDeviceWeight(virCgroupPtr group,
                              const char *path,
                              unsigned int weight)
2170
{
2171 2172
    VIR_AUTOFREE(char *) str = NULL;
    VIR_AUTOFREE(char *) blkstr = NULL;
2173

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

2177
    if (virAsprintf(&str, "%s%d", blkstr, weight) < 0)
2178
        return -1;
2179

2180
    return virCgroupSetValueStr(group,
2181 2182 2183
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "blkio.weight_device",
                                str);
2184
}
2185

2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
/**
 * virCgroupGetBlkioDeviceReadIops:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @riops: Returned device read iops throttle, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceReadIops(virCgroupPtr group,
                                const char *path,
                                unsigned int *riops)
{
2199
    VIR_AUTOFREE(char *) str = NULL;
2200 2201 2202 2203 2204 2205

    if (virCgroupGetValueForBlkDev(group,
                                   VIR_CGROUP_CONTROLLER_BLKIO,
                                   "blkio.throttle.read_iops_device",
                                   path,
                                   &str) < 0)
2206
        return -1;
2207 2208 2209 2210 2211 2212 2213

    if (!str) {
        *riops = 0;
    } else if (virStrToLong_ui(str, NULL, 10, riops) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       str);
2214
        return -1;
2215 2216
    }

2217
    return 0;
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
}

/**
 * virCgroupGetBlkioDeviceWriteIops:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @wiops: Returned device write iops throttle, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceWriteIops(virCgroupPtr group,
                                 const char *path,
                                 unsigned int *wiops)
{
2233
    VIR_AUTOFREE(char *) str = NULL;
2234 2235 2236 2237 2238 2239

    if (virCgroupGetValueForBlkDev(group,
                                   VIR_CGROUP_CONTROLLER_BLKIO,
                                   "blkio.throttle.write_iops_device",
                                   path,
                                   &str) < 0)
2240
        return -1;
2241 2242 2243 2244 2245 2246 2247

    if (!str) {
        *wiops = 0;
    } else if (virStrToLong_ui(str, NULL, 10, wiops) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       str);
2248
        return -1;
2249 2250
    }

2251
    return 0;
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
}

/**
 * virCgroupGetBlkioDeviceReadBps:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @rbps: Returned device read bps throttle, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceReadBps(virCgroupPtr group,
                               const char *path,
                               unsigned long long *rbps)
{
2267
    VIR_AUTOFREE(char *) str = NULL;
2268 2269 2270 2271 2272 2273

    if (virCgroupGetValueForBlkDev(group,
                                   VIR_CGROUP_CONTROLLER_BLKIO,
                                   "blkio.throttle.read_bps_device",
                                   path,
                                   &str) < 0)
2274
        return -1;
2275 2276 2277 2278 2279 2280 2281

    if (!str) {
        *rbps = 0;
    } else if (virStrToLong_ull(str, NULL, 10, rbps) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       str);
2282
        return -1;
2283 2284
    }

2285
    return 0;
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
}

/**
 * virCgroupGetBlkioDeviceWriteBps:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @wbps: Returned device write bps throttle, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceWriteBps(virCgroupPtr group,
                                const char *path,
                                unsigned long long *wbps)
{
2301
    VIR_AUTOFREE(char *) str = NULL;
2302 2303 2304 2305 2306 2307

    if (virCgroupGetValueForBlkDev(group,
                                   VIR_CGROUP_CONTROLLER_BLKIO,
                                   "blkio.throttle.write_bps_device",
                                   path,
                                   &str) < 0)
2308
        return -1;
2309 2310 2311 2312 2313 2314 2315

    if (!str) {
        *wbps = 0;
    } else if (virStrToLong_ull(str, NULL, 10, wbps) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       str);
2316
        return -1;
2317 2318
    }

2319
    return 0;
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
}

/**
 * virCgroupGetBlkioDeviceWeight:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @weight: Returned device weight, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceWeight(virCgroupPtr group,
                              const char *path,
                              unsigned int *weight)
{
2335
    VIR_AUTOFREE(char *) str = NULL;
2336 2337 2338 2339 2340 2341

    if (virCgroupGetValueForBlkDev(group,
                                   VIR_CGROUP_CONTROLLER_BLKIO,
                                   "blkio.weight_device",
                                   path,
                                   &str) < 0)
2342
        return -1;
2343 2344 2345 2346 2347 2348 2349

    if (!str) {
        *weight = 0;
    } else if (virStrToLong_ui(str, NULL, 10, weight) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       str);
2350
        return -1;
2351 2352
    }

2353
    return 0;
2354 2355
}

2356

2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
/*
 * Retrieve the "memory.limit_in_bytes" value from the memory controller
 * root dir. This value cannot be modified by userspace and therefore
 * is the maximum limit value supported by cgroups on the local system.
 * Returns this value scaled to KB or falls back to the original
 * VIR_DOMAIN_MEMORY_PARAM_UNLIMITED. Either way, remember the return
 * value to avoid unnecessary cgroup filesystem access.
 */
static unsigned long long int virCgroupMemoryUnlimitedKB;
static virOnceControl virCgroupMemoryOnce = VIR_ONCE_CONTROL_INITIALIZER;

static void
virCgroupMemoryOnceInit(void)
{
2371
    virCgroupPtr group;
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
    unsigned long long int mem_unlimited = 0ULL;

    if (virCgroupNew(-1, "/", NULL, -1, &group) < 0)
        goto cleanup;

    if (!virCgroupHasController(group, VIR_CGROUP_CONTROLLER_MEMORY))
        goto cleanup;

    ignore_value(virCgroupGetValueU64(group,
                                      VIR_CGROUP_CONTROLLER_MEMORY,
                                      "memory.limit_in_bytes",
                                      &mem_unlimited));
 cleanup:
2385
    virCgroupFree(&group);
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
    virCgroupMemoryUnlimitedKB = mem_unlimited >> 10;
}

static unsigned long long int
virCgroupGetMemoryUnlimitedKB(void)
{
    if (virOnce(&virCgroupMemoryOnce, virCgroupMemoryOnceInit) < 0)
        VIR_DEBUG("Init failed, will fall back to defaults.");

    if (virCgroupMemoryUnlimitedKB)
        return virCgroupMemoryUnlimitedKB;
    else
        return VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
}


2402 2403 2404 2405 2406 2407 2408 2409
/**
 * virCgroupSetMemory:
 *
 * @group: The cgroup to change memory for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2410 2411
int
virCgroupSetMemory(virCgroupPtr group, unsigned long long kb)
2412
{
2413 2414
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2415 2416 2417 2418 2419 2420 2421 2422
    if (kb > maxkb) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Memory '%llu' must be less than %llu"),
                       kb, maxkb);
        return -1;
    }

    if (kb == maxkb)
2423 2424 2425 2426 2427 2428 2429 2430 2431
        return virCgroupSetValueI64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.limit_in_bytes",
                                    -1);
    else
        return virCgroupSetValueU64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.limit_in_bytes",
                                    kb << 10);
2432 2433
}

E
Eric Blake 已提交
2434

2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
/**
 * virCgroupGetMemoryStat:
 *
 * @group: The cgroup to change memory for
 * @cache: page cache memory in KiB
 * @activeAnon: anonymous and swap cache memory in KiB
 * @inactiveAnon: anonymous and swap cache memory in KiB
 * @activeFile: file-backed memory in KiB
 * @inactiveFile: file-backed memory in KiB
 * @unevictable: memory that cannot be reclaimed KiB
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetMemoryStat(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)
{
    int ret = -1;
    char *stat = NULL;
    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;

    while (line) {
        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."));
            goto cleanup;
        }
        *valueStr = '\0';

        if (virStrToLong_ull(valueStr + 1, NULL, 10, &value) < 0)
            goto cleanup;

        if (STREQ(line, "cache"))
            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;
    }

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

    ret = 0;

 cleanup:
    VIR_FREE(stat);
    return ret;
}


R
Ryota Ozaki 已提交
2523 2524 2525 2526 2527 2528 2529 2530
/**
 * virCgroupGetMemoryUsage:
 *
 * @group: The cgroup to change memory for
 * @kb: Pointer to returned used memory in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2531 2532
int
virCgroupGetMemoryUsage(virCgroupPtr group, unsigned long *kb)
R
Ryota Ozaki 已提交
2533
{
C
Cole Robinson 已提交
2534
    long long unsigned int usage_in_bytes;
R
Ryota Ozaki 已提交
2535 2536 2537 2538 2539 2540 2541 2542 2543
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_MEMORY,
                               "memory.usage_in_bytes", &usage_in_bytes);
    if (ret == 0)
        *kb = (unsigned long) usage_in_bytes >> 10;
    return ret;
}

E
Eric Blake 已提交
2544

2545 2546 2547 2548 2549 2550 2551 2552
/**
 * virCgroupSetMemoryHardLimit:
 *
 * @group: The cgroup to change memory hard limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2553 2554
int
virCgroupSetMemoryHardLimit(virCgroupPtr group, unsigned long long kb)
2555 2556 2557 2558
{
    return virCgroupSetMemory(group, kb);
}

E
Eric Blake 已提交
2559

2560 2561 2562 2563 2564 2565 2566 2567
/**
 * virCgroupGetMemoryHardLimit:
 *
 * @group: The cgroup to get the memory hard limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2568 2569
int
virCgroupGetMemoryHardLimit(virCgroupPtr group, unsigned long long *kb)
2570 2571
{
    long long unsigned int limit_in_bytes;
2572 2573 2574 2575

    if (virCgroupGetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.limit_in_bytes", &limit_in_bytes) < 0)
2576
        return -1;
2577 2578

    *kb = limit_in_bytes >> 10;
2579
    if (*kb >= virCgroupGetMemoryUnlimitedKB())
2580 2581
        *kb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2582
    return 0;
2583 2584
}

E
Eric Blake 已提交
2585

2586 2587 2588 2589 2590 2591 2592 2593
/**
 * virCgroupSetMemorySoftLimit:
 *
 * @group: The cgroup to change memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2594 2595
int
virCgroupSetMemorySoftLimit(virCgroupPtr group, unsigned long long kb)
2596
{
2597 2598
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2599 2600 2601 2602 2603 2604 2605 2606
    if (kb > maxkb) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Memory '%llu' must be less than %llu"),
                       kb, maxkb);
        return -1;
    }

    if (kb == maxkb)
2607 2608 2609 2610 2611 2612 2613 2614 2615
        return virCgroupSetValueI64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.soft_limit_in_bytes",
                                    -1);
    else
        return virCgroupSetValueU64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.soft_limit_in_bytes",
                                    kb << 10);
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
}


/**
 * virCgroupGetMemorySoftLimit:
 *
 * @group: The cgroup to get the memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2627 2628
int
virCgroupGetMemorySoftLimit(virCgroupPtr group, unsigned long long *kb)
2629 2630
{
    long long unsigned int limit_in_bytes;
2631 2632 2633 2634

    if (virCgroupGetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.soft_limit_in_bytes", &limit_in_bytes) < 0)
2635
        return -1;
2636 2637

    *kb = limit_in_bytes >> 10;
2638
    if (*kb >= virCgroupGetMemoryUnlimitedKB())
2639 2640
        *kb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2641
    return 0;
2642 2643
}

E
Eric Blake 已提交
2644

2645
/**
2646
 * virCgroupSetMemSwapHardLimit:
2647
 *
2648 2649
 * @group: The cgroup to change mem+swap hard limit for
 * @kb: The mem+swap amount in kilobytes
2650 2651 2652
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2653 2654
int
virCgroupSetMemSwapHardLimit(virCgroupPtr group, unsigned long long kb)
2655
{
2656 2657
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2658 2659 2660 2661 2662 2663 2664 2665
    if (kb > maxkb) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Memory '%llu' must be less than %llu"),
                       kb, maxkb);
        return -1;
    }

    if (kb == maxkb)
2666 2667 2668 2669 2670 2671 2672 2673 2674
        return virCgroupSetValueI64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.memsw.limit_in_bytes",
                                    -1);
    else
        return virCgroupSetValueU64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.memsw.limit_in_bytes",
                                    kb << 10);
2675 2676
}

E
Eric Blake 已提交
2677

2678
/**
2679
 * virCgroupGetMemSwapHardLimit:
2680
 *
2681 2682
 * @group: The cgroup to get mem+swap hard limit for
 * @kb: The mem+swap amount in kilobytes
2683 2684 2685
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2686 2687
int
virCgroupGetMemSwapHardLimit(virCgroupPtr group, unsigned long long *kb)
2688 2689
{
    long long unsigned int limit_in_bytes;
2690 2691 2692 2693

    if (virCgroupGetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.memsw.limit_in_bytes", &limit_in_bytes) < 0)
2694
        return -1;
2695 2696

    *kb = limit_in_bytes >> 10;
2697
    if (*kb >= virCgroupGetMemoryUnlimitedKB())
2698 2699
        *kb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2700
    return 0;
2701 2702
}

E
Eric Blake 已提交
2703

G
Gao feng 已提交
2704 2705 2706 2707 2708 2709 2710 2711
/**
 * virCgroupGetMemSwapUsage:
 *
 * @group: The cgroup to get mem+swap usage for
 * @kb: The mem+swap amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2712 2713
int
virCgroupGetMemSwapUsage(virCgroupPtr group, unsigned long long *kb)
G
Gao feng 已提交
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
{
    long long unsigned int usage_in_bytes;
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_MEMORY,
                               "memory.memsw.usage_in_bytes", &usage_in_bytes);
    if (ret == 0)
        *kb = usage_in_bytes >> 10;
    return ret;
}

E
Eric Blake 已提交
2725

2726 2727 2728 2729 2730 2731 2732 2733
/**
 * virCgroupSetCpusetMems:
 *
 * @group: The cgroup to set cpuset.mems for
 * @mems: the numa nodes to set
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2734 2735
int
virCgroupSetCpusetMems(virCgroupPtr group, const char *mems)
2736 2737 2738 2739 2740 2741 2742
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.mems",
                                mems);
}

E
Eric Blake 已提交
2743

2744 2745 2746 2747 2748 2749 2750 2751
/**
 * virCgroupGetCpusetMems:
 *
 * @group: The cgroup to get cpuset.mems for
 * @mems: the numa nodes to get
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2752 2753
int
virCgroupGetCpusetMems(virCgroupPtr group, char **mems)
2754 2755 2756 2757 2758 2759 2760
{
    return virCgroupGetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.mems",
                                mems);
}

E
Eric Blake 已提交
2761

2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800
/**
 * virCgroupSetCpusetMemoryMigrate:
 *
 * @group: The cgroup to set cpuset.memory_migrate for
 * @migrate: Whether to migrate the memory on change or not
 *
 * Returns: 0 on success
 */
int
virCgroupSetCpusetMemoryMigrate(virCgroupPtr group, bool migrate)
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.memory_migrate",
                                migrate ? "1" : "0");
}


/**
 * virCgroupGetCpusetMemoryMigrate:
 *
 * @group: The cgroup to get cpuset.memory_migrate for
 * @migrate: Migration setting
 *
 * Returns: 0 on success
 */
int
virCgroupGetCpusetMemoryMigrate(virCgroupPtr group, bool *migrate)
{
    unsigned long long value = 0;
    int ret = virCgroupGetValueU64(group,
                                   VIR_CGROUP_CONTROLLER_CPUSET,
                                   "cpuset.memory_migrate",
                                   &value);
    *migrate = !!value;
    return ret;
}


2801 2802 2803 2804 2805 2806
/**
 * virCgroupSetCpusetCpus:
 *
 * @group: The cgroup to set cpuset.cpus for
 * @cpus: the cpus to set
 *
N
Nitesh Konkar 已提交
2807
 * Returns: 0 on success
2808
 */
E
Eric Blake 已提交
2809 2810
int
virCgroupSetCpusetCpus(virCgroupPtr group, const char *cpus)
2811 2812 2813 2814 2815 2816 2817
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.cpus",
                                cpus);
}

E
Eric Blake 已提交
2818

2819 2820 2821 2822 2823 2824
/**
 * virCgroupGetCpusetCpus:
 *
 * @group: The cgroup to get cpuset.cpus for
 * @cpus: the cpus to get
 *
N
Nitesh Konkar 已提交
2825
 * Returns: 0 on success
2826
 */
E
Eric Blake 已提交
2827 2828
int
virCgroupGetCpusetCpus(virCgroupPtr group, char **cpus)
2829 2830 2831 2832 2833 2834 2835
{
    return virCgroupGetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.cpus",
                                cpus);
}

E
Eric Blake 已提交
2836

2837 2838 2839
/**
 * virCgroupDenyAllDevices:
 *
2840
 * @group: The cgroup to deny all permissions, for all devices
2841 2842 2843
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2844 2845
int
virCgroupDenyAllDevices(virCgroupPtr group)
2846 2847
{
    return virCgroupSetValueStr(group,
2848 2849 2850
                                VIR_CGROUP_CONTROLLER_DEVICES,
                                "devices.deny",
                                "a");
2851 2852
}

2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
/**
 * virCgroupAllowAllDevices:
 *
 * Allows the permissiong for all devices by setting lines similar
 * to these ones (obviously the 'm' permission is an example):
 *
 * 'b *:* m'
 * 'c *:* m'
 *
 * @group: The cgroup to allow devices for
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
 *
 * Returns: 0 on success
 */
int
virCgroupAllowAllDevices(virCgroupPtr group, int perms)
{
    int ret = -1;

    if (virCgroupAllowDevice(group, 'b', -1, -1, perms) < 0)
        goto cleanup;

    if (virCgroupAllowDevice(group, 'c', -1, -1, perms) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    return ret;
}

E
Eric Blake 已提交
2884

2885 2886 2887 2888 2889
/**
 * virCgroupAllowDevice:
 *
 * @group: The cgroup to allow a device for
 * @type: The device type (i.e., 'c' or 'b')
2890 2891
 * @major: The major number of the device, a negative value means '*'
 * @minor: The minor number of the device, a negative value means '*'
2892
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
2893 2894 2895
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2896 2897 2898
int
virCgroupAllowDevice(virCgroupPtr group, char type, int major, int minor,
                     int perms)
2899
{
2900 2901 2902
    VIR_AUTOFREE(char *) devstr = NULL;
    VIR_AUTOFREE(char *) majorstr = NULL;
    VIR_AUTOFREE(char *) minorstr = NULL;
2903

2904
    if ((major < 0 && VIR_STRDUP(majorstr, "*") < 0) ||
2905
        (major >= 0 && virAsprintf(&majorstr, "%i", major) < 0))
2906
        return -1;
2907 2908

    if ((minor < 0 && VIR_STRDUP(minorstr, "*") < 0) ||
2909
        (minor >= 0 && virAsprintf(&minorstr, "%i", minor) < 0))
2910
        return -1;
2911 2912

    if (virAsprintf(&devstr, "%c %s:%s %s", type, majorstr, minorstr,
2913
                    virCgroupGetDevicePermsString(perms)) < 0)
2914
        return -1;
2915

2916 2917 2918 2919
    if (virCgroupSetValueStr(group,
                             VIR_CGROUP_CONTROLLER_DEVICES,
                             "devices.allow",
                             devstr) < 0)
2920
        return -1;
2921

2922
    return 0;
2923
}
2924

E
Eric Blake 已提交
2925

2926 2927 2928 2929 2930
/**
 * virCgroupAllowDevicePath:
 *
 * @group: The cgroup to allow the device for
 * @path: the device to allow
2931
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
2932
 * @ignoreEacces: Ignore lack of permission (mostly for NFS mounts)
2933 2934 2935 2936
 *
 * Queries the type of device and its major/minor number, and
 * adds that to the cgroup ACL
 *
2937 2938
 * Returns: 0 on success, 1 if path exists but is not a device or is not
 * accesible, or * -1 on error
2939
 */
E
Eric Blake 已提交
2940
int
2941 2942 2943 2944
virCgroupAllowDevicePath(virCgroupPtr group,
                         const char *path,
                         int perms,
                         bool ignoreEacces)
2945 2946 2947
{
    struct stat sb;

2948
    if (stat(path, &sb) < 0) {
2949 2950 2951
        if (errno == EACCES && ignoreEacces)
            return 1;

2952 2953 2954 2955 2956
        virReportSystemError(errno,
                             _("Path '%s' is not accessible"),
                             path);
        return -1;
    }
2957 2958

    if (!S_ISCHR(sb.st_mode) && !S_ISBLK(sb.st_mode))
2959
        return 1;
2960 2961 2962 2963

    return virCgroupAllowDevice(group,
                                S_ISCHR(sb.st_mode) ? 'c' : 'b',
                                major(sb.st_rdev),
2964 2965
                                minor(sb.st_rdev),
                                perms);
2966
}
D
Daniel P. Berrange 已提交
2967

2968 2969 2970 2971 2972 2973

/**
 * virCgroupDenyDevice:
 *
 * @group: The cgroup to deny a device for
 * @type: The device type (i.e., 'c' or 'b')
2974 2975
 * @major: The major number of the device, a negative value means '*'
 * @minor: The minor number of the device, a negative value means '*'
2976
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to deny
2977 2978 2979
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2980 2981 2982
int
virCgroupDenyDevice(virCgroupPtr group, char type, int major, int minor,
                    int perms)
2983
{
2984 2985 2986
    VIR_AUTOFREE(char *) devstr = NULL;
    VIR_AUTOFREE(char *) majorstr = NULL;
    VIR_AUTOFREE(char *) minorstr = NULL;
2987 2988 2989

    if ((major < 0 && VIR_STRDUP(majorstr, "*") < 0) ||
        (major >= 0 && virAsprintf(&majorstr, "%i", major) < 0))
2990
        return -1;
2991

2992 2993
    if ((minor < 0 && VIR_STRDUP(minorstr, "*") < 0) ||
        (minor >= 0 && virAsprintf(&minorstr, "%i", minor) < 0))
2994
        return -1;
2995 2996

    if (virAsprintf(&devstr, "%c %s:%s %s", type, majorstr, minorstr,
2997
                    virCgroupGetDevicePermsString(perms)) < 0)
2998
        return -1;
2999

3000 3001 3002 3003
    if (virCgroupSetValueStr(group,
                             VIR_CGROUP_CONTROLLER_DEVICES,
                             "devices.deny",
                             devstr) < 0)
3004
        return -1;
3005

3006
    return 0;
3007 3008
}

E
Eric Blake 已提交
3009

3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023
/**
 * virCgroupDenyDevicePath:
 *
 * @group: The cgroup to deny the device for
 * @path: the device to deny
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
 * @ignoreEacces: Ignore lack of permission (mostly for NFS mounts)
 *
 * Queries the type of device and its major/minor number, and
 * removes it from the cgroup ACL
 *
 * Returns: 0 on success, 1 if path exists but is not a device or is not
 * accessible, or -1 on error.
 */
E
Eric Blake 已提交
3024
int
3025 3026 3027 3028
virCgroupDenyDevicePath(virCgroupPtr group,
                        const char *path,
                        int perms,
                        bool ignoreEacces)
3029 3030 3031
{
    struct stat sb;

3032
    if (stat(path, &sb) < 0) {
3033 3034 3035
        if (errno == EACCES && ignoreEacces)
            return 1;

3036 3037 3038 3039 3040
        virReportSystemError(errno,
                             _("Path '%s' is not accessible"),
                             path);
        return -1;
    }
3041 3042

    if (!S_ISCHR(sb.st_mode) && !S_ISBLK(sb.st_mode))
3043
        return 1;
3044 3045 3046 3047

    return virCgroupDenyDevice(group,
                               S_ISCHR(sb.st_mode) ? 'c' : 'b',
                               major(sb.st_rdev),
3048 3049
                               minor(sb.st_rdev),
                               perms);
3050 3051
}

E
Eric Blake 已提交
3052

3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068
/* This function gets the sums of cpu time consumed by all vcpus.
 * For example, if there are 4 physical cpus, and 2 vcpus in a domain,
 * then for each vcpu, the cpuacct.usage_percpu looks like this:
 *   t0 t1 t2 t3
 * and we have 2 groups of such data:
 *   v\p   0   1   2   3
 *   0   t00 t01 t02 t03
 *   1   t10 t11 t12 t13
 * for each pcpu, the sum is cpu time consumed by all vcpus.
 *   s0 = t00 + t10
 *   s1 = t01 + t11
 *   s2 = t02 + t12
 *   s3 = t03 + t13
 */
static int
virCgroupGetPercpuVcpuSum(virCgroupPtr group,
3069
                          virBitmapPtr guestvcpus,
3070
                          unsigned long long *sum_cpu_time,
3071 3072
                          size_t nsum,
                          virBitmapPtr cpumap)
3073
{
3074
    int ret = -1;
3075
    ssize_t i = -1;
3076
    virCgroupPtr group_vcpu = NULL;
3077

3078
    while ((i = virBitmapNextSetBit(guestvcpus, i)) >= 0) {
3079
        VIR_AUTOFREE(char *) buf = NULL;
3080 3081
        char *pos;
        unsigned long long tmp;
3082
        ssize_t j;
3083

J
John Ferlan 已提交
3084 3085
        if (virCgroupNewThread(group, VIR_CGROUP_THREAD_VCPU, i,
                               false, &group_vcpu) < 0)
3086
            goto cleanup;
3087 3088

        if (virCgroupGetCpuacctPercpuUsage(group_vcpu, &buf) < 0)
3089
            goto cleanup;
3090 3091

        pos = buf;
3092 3093 3094
        for (j = virBitmapNextSetBit(cpumap, -1);
             j >= 0 && j < nsum;
             j = virBitmapNextSetBit(cpumap, j)) {
3095 3096 3097
            if (virStrToLong_ull(pos, &pos, 10, &tmp) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cpuacct parse error"));
3098
                goto cleanup;
3099 3100 3101
            }
            sum_cpu_time[j] += tmp;
        }
3102

3103
        virCgroupFree(&group_vcpu);
3104 3105
    }

3106 3107
    ret = 0;
 cleanup:
3108
    virCgroupFree(&group_vcpu);
3109
    return ret;
3110 3111 3112
}


3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
/**
 * virCgroupGetPercpuStats:
 * @cgroup: cgroup data structure
 * @params: typed parameter array where data is returned
 * @nparams: cardinality of @params
 * @start_cpu: offset of physical CPU to get data for
 * @ncpus: number of physical CPUs to get data for
 * @nvcpupids: number of vCPU threads for a domain (actual number of vcpus)
 *
 * This function is the worker that retrieves data in the appropriate format
 * for the terribly designed 'virDomainGetCPUStats' API. Sharing semantics with
 * the API, this function has two modes of operation depending on magic settings
 * of the input arguments. Please refer to docs of 'virDomainGetCPUStats' for
 * the usage patterns of the similarly named arguments.
 *
 * @nvcpupids determines the count of active vcpu threads for the vm. If the
 * threads could not be detected the percpu data is skipped.
 *
 * Please DON'T use this function anywhere else.
 */
3133 3134 3135 3136 3137
int
virCgroupGetPercpuStats(virCgroupPtr group,
                        virTypedParameterPtr params,
                        unsigned int nparams,
                        int start_cpu,
3138
                        unsigned int ncpus,
3139
                        virBitmapPtr guestvcpus)
3140
{
3141
    int ret = -1;
3142
    size_t i;
3143
    int need_cpus, total_cpus;
3144
    char *pos;
3145 3146
    VIR_AUTOFREE(char *) buf = NULL;
    VIR_AUTOFREE(unsigned long long *) sum_cpu_time = NULL;
3147 3148 3149
    virTypedParameterPtr ent;
    int param_idx;
    unsigned long long cpu_time;
3150
    virBitmapPtr cpumap = NULL;
3151 3152

    /* return the number of supported params */
3153
    if (nparams == 0 && ncpus != 0) {
3154
        if (!guestvcpus)
3155 3156 3157 3158
            return CGROUP_NB_PER_CPU_STAT_PARAM;
        else
            return CGROUP_NB_PER_CPU_STAT_PARAM + 1;
    }
3159 3160

    /* To parse account file, we need to know how many cpus are present.  */
3161
    if (!(cpumap = virHostCPUGetPresentBitmap()))
3162
        return -1;
3163

3164 3165
    total_cpus = virBitmapSize(cpumap);

3166
    /* return total number of cpus */
3167 3168 3169 3170
    if (ncpus == 0) {
        ret = total_cpus;
        goto cleanup;
    }
3171

3172
    if (start_cpu >= total_cpus) {
3173 3174
        virReportError(VIR_ERR_INVALID_ARG,
                       _("start_cpu %d larger than maximum of %d"),
3175
                       start_cpu, total_cpus - 1);
3176
        goto cleanup;
3177 3178 3179 3180
    }

    /* we get percpu cputime accounting info. */
    if (virCgroupGetCpuacctPercpuUsage(group, &buf))
3181
        goto cleanup;
3182 3183 3184 3185 3186 3187
    pos = buf;

    /* return percpu cputime in index 0 */
    param_idx = 0;

    /* number of cpus to compute */
J
Ján Tomko 已提交
3188
    need_cpus = MIN(total_cpus, start_cpu + ncpus);
3189

J
Ján Tomko 已提交
3190
    for (i = 0; i < need_cpus; i++) {
J
Ján Tomko 已提交
3191
        if (!virBitmapIsBitSet(cpumap, i)) {
3192 3193
            cpu_time = 0;
        } else if (virStrToLong_ull(pos, &pos, 10, &cpu_time) < 0) {
3194 3195
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cpuacct parse error"));
3196
            goto cleanup;
3197 3198 3199 3200 3201 3202
        }
        if (i < start_cpu)
            continue;
        ent = &params[(i - start_cpu) * nparams + param_idx];
        if (virTypedParameterAssign(ent, VIR_DOMAIN_CPU_STATS_CPUTIME,
                                    VIR_TYPED_PARAM_ULLONG, cpu_time) < 0)
3203
            goto cleanup;
3204 3205
    }

3206
    /* return percpu vcputime in index 1 */
3207
    param_idx = 1;
3208

3209
    if (guestvcpus && param_idx < nparams) {
3210
        if (VIR_ALLOC_N(sum_cpu_time, need_cpus) < 0)
3211
            goto cleanup;
3212 3213
        if (virCgroupGetPercpuVcpuSum(group, guestvcpus, sum_cpu_time,
                                      need_cpus, cpumap) < 0)
3214
            goto cleanup;
3215 3216

        for (i = start_cpu; i < need_cpus; i++) {
3217 3218
            int idx = (i - start_cpu) * nparams + param_idx;
            if (virTypedParameterAssign(&params[idx],
3219 3220 3221
                                        VIR_DOMAIN_CPU_STATS_VCPUTIME,
                                        VIR_TYPED_PARAM_ULLONG,
                                        sum_cpu_time[i]) < 0)
3222
                goto cleanup;
3223 3224 3225
        }

        param_idx++;
3226 3227
    }

3228 3229 3230 3231 3232
    ret = param_idx;

 cleanup:
    virBitmapFree(cpumap);
    return ret;
3233 3234
}

3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284

int
virCgroupGetDomainTotalCpuStats(virCgroupPtr group,
                                virTypedParameterPtr params,
                                int nparams)
{
    unsigned long long cpu_time;
    int ret;

    if (nparams == 0) /* return supported number of params */
        return CGROUP_NB_TOTAL_CPU_STAT_PARAM;
    /* entry 0 is cputime */
    ret = virCgroupGetCpuacctUsage(group, &cpu_time);
    if (ret < 0) {
        virReportSystemError(-ret, "%s", _("unable to get cpu account"));
        return -1;
    }

    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_CPU_STATS_CPUTIME,
                                VIR_TYPED_PARAM_ULLONG, cpu_time) < 0)
        return -1;

    if (nparams > 1) {
        unsigned long long user;
        unsigned long long sys;

        ret = virCgroupGetCpuacctStat(group, &user, &sys);
        if (ret < 0) {
            virReportSystemError(-ret, "%s", _("unable to get cpu account"));
            return -1;
        }

        if (virTypedParameterAssign(&params[1],
                                    VIR_DOMAIN_CPU_STATS_USERTIME,
                                    VIR_TYPED_PARAM_ULLONG, user) < 0)
            return -1;
        if (nparams > 2 &&
            virTypedParameterAssign(&params[2],
                                    VIR_DOMAIN_CPU_STATS_SYSTEMTIME,
                                    VIR_TYPED_PARAM_ULLONG, sys) < 0)
            return -1;

        if (nparams > CGROUP_NB_TOTAL_CPU_STAT_PARAM)
            nparams = CGROUP_NB_TOTAL_CPU_STAT_PARAM;
    }

    return nparams;
}


E
Eric Blake 已提交
3285 3286
int
virCgroupSetCpuShares(virCgroupPtr group, unsigned long long shares)
3287
{
3288 3289
    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
D
Daniel P. Berrange 已提交
3290
                                "cpu.shares", shares);
3291 3292
}

E
Eric Blake 已提交
3293 3294 3295

int
virCgroupGetCpuShares(virCgroupPtr group, unsigned long long *shares)
3296
{
3297 3298
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
D
Daniel P. Berrange 已提交
3299
                                "cpu.shares", shares);
3300
}
3301

E
Eric Blake 已提交
3302

3303 3304 3305 3306 3307 3308 3309 3310
/**
 * virCgroupSetCpuCfsPeriod:
 *
 * @group: The cgroup to change cpu.cfs_period_us for
 * @cfs_period: The bandwidth period in usecs
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
3311 3312
int
virCgroupSetCpuCfsPeriod(virCgroupPtr group, unsigned long long cfs_period)
3313
{
3314
    /* The cfs_period should be greater or equal than 1ms, and less or equal
3315 3316
     * than 1s.
     */
3317 3318 3319 3320 3321 3322
    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;
    }
3323 3324 3325 3326 3327 3328

    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.cfs_period_us", cfs_period);
}

E
Eric Blake 已提交
3329

3330 3331 3332 3333 3334 3335 3336 3337
/**
 * virCgroupGetCpuCfsPeriod:
 *
 * @group: The cgroup to get cpu.cfs_period_us for
 * @cfs_period: Pointer to the returned bandwidth period in usecs
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
3338 3339
int
virCgroupGetCpuCfsPeriod(virCgroupPtr group, unsigned long long *cfs_period)
3340 3341 3342 3343 3344 3345
{
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.cfs_period_us", cfs_period);
}

E
Eric Blake 已提交
3346

3347 3348 3349 3350 3351 3352 3353 3354 3355
/**
 * virCgroupSetCpuCfsQuota:
 *
 * @group: The cgroup to change cpu.cfs_quota_us for
 * @cfs_quota: the cpu bandwidth (in usecs) that this tg will be allowed to
 *             consume over period
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
3356 3357
int
virCgroupSetCpuCfsQuota(virCgroupPtr group, long long cfs_quota)
3358
{
3359 3360 3361 3362 3363 3364 3365 3366
    /* 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;
3367 3368 3369 3370 3371 3372 3373
    }

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

E
Eric Blake 已提交
3374 3375 3376

int
virCgroupGetCpuacctPercpuUsage(virCgroupPtr group, char **usage)
3377 3378 3379 3380 3381
{
    return virCgroupGetValueStr(group, VIR_CGROUP_CONTROLLER_CPUACCT,
                                "cpuacct.usage_percpu", usage);
}

E
Eric Blake 已提交
3382

3383
static int
E
Eric Blake 已提交
3384 3385 3386 3387 3388
virCgroupRemoveRecursively(char *grppath)
{
    DIR *grpdir;
    struct dirent *ent;
    int rc = 0;
E
Eric Blake 已提交
3389
    int direrr;
E
Eric Blake 已提交
3390

J
Ján Tomko 已提交
3391
    if (virDirOpenQuiet(&grpdir, grppath) < 0) {
E
Eric Blake 已提交
3392 3393 3394 3395 3396 3397 3398
        if (errno == ENOENT)
            return 0;
        rc = -errno;
        VIR_ERROR(_("Unable to open %s (%d)"), grppath, errno);
        return rc;
    }

E
Eric Blake 已提交
3399 3400 3401
    /* This is best-effort cleanup: we want to log failures with just
     * VIR_ERROR instead of normal virReportError */
    while ((direrr = virDirRead(grpdir, &ent, NULL)) > 0) {
3402
        VIR_AUTOFREE(char *) path = NULL;
E
Eric Blake 已提交
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413

        if (ent->d_type != DT_DIR) continue;

        if (virAsprintf(&path, "%s/%s", grppath, ent->d_name) == -1) {
            rc = -ENOMEM;
            break;
        }
        rc = virCgroupRemoveRecursively(path);
        if (rc != 0)
            break;
    }
E
Eric Blake 已提交
3414 3415 3416 3417 3418
    if (direrr < 0) {
        rc = -errno;
        VIR_ERROR(_("Failed to readdir for %s (%d)"), grppath, errno);
    }

J
Ján Tomko 已提交
3419
    VIR_DIR_CLOSE(grpdir);
E
Eric Blake 已提交
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450

    VIR_DEBUG("Removing cgroup %s", grppath);
    if (rmdir(grppath) != 0 && errno != ENOENT) {
        rc = -errno;
        VIR_ERROR(_("Unable to remove %s (%d)"), grppath, errno);
    }

    return rc;
}


/**
 * virCgroupRemove:
 *
 * @group: The group to be removed
 *
 * It first removes all child groups recursively
 * in depth first order and then removes @group
 * because the presence of the child groups
 * prevents removing @group.
 *
 * Returns: 0 on success
 */
int
virCgroupRemove(virCgroupPtr group)
{
    int rc = 0;
    size_t i;

    VIR_DEBUG("Removing cgroup %s", group->path);
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
3451 3452
        VIR_AUTOFREE(char *) grppath = NULL;

E
Eric Blake 已提交
3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480
        /* Skip over controllers not mounted */
        if (!group->controllers[i].mountPoint)
            continue;

        /* We must never rmdir() in systemd's hierarchy */
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD)
            continue;

        /* Don't delete the root group, if we accidentally
           ended up in it for some reason */
        if (STREQ(group->controllers[i].placement, "/"))
            continue;

        if (virCgroupPathOfController(group,
                                      i,
                                      NULL,
                                      &grppath) != 0)
            continue;

        VIR_DEBUG("Removing cgroup %s and all child cgroups", grppath);
        rc = virCgroupRemoveRecursively(grppath);
    }
    VIR_DEBUG("Done removing cgroup %s", group->path);

    return rc;
}


3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505
static int
virCgroupPathOfAnyController(virCgroupPtr group,
                             const char *name,
                             char **keypath)
{
    size_t i;

    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
        /* Reject any controller with a placement
         * of '/' to avoid doing bad stuff to the root
         * cgroup
         */
        if (group->controllers[i].mountPoint &&
            group->controllers[i].placement &&
            STRNEQ(group->controllers[i].placement, "/")) {
            return virCgroupPathOfController(group, i, name, keypath);
        }
    }

    virReportSystemError(ENOSYS, "%s",
                         _("No controllers are mounted"));
    return -1;
}


3506 3507 3508
/*
 * Returns 1 if some PIDs are killed, 0 if none are killed, or -1 on error
 */
E
Eric Blake 已提交
3509 3510
static int
virCgroupKillInternal(virCgroupPtr group, int signum, virHashTablePtr pids)
3511
{
3512
    int ret = -1;
3513
    bool killedAny = false;
3514
    VIR_AUTOFREE(char *) keypath = NULL;
3515
    bool done = false;
E
Eric Blake 已提交
3516 3517 3518
    FILE *fp = NULL;
    VIR_DEBUG("group=%p path=%s signum=%d pids=%p",
              group, group->path, signum, pids);
3519

3520
    if (virCgroupPathOfAnyController(group, "tasks", &keypath) < 0)
3521
        return -1;
3522 3523 3524 3525 3526 3527 3528

    /* PIDs may be forking as we kill them, so loop
     * until there are no new PIDs found
     */
    while (!done) {
        done = true;
        if (!(fp = fopen(keypath, "r"))) {
3529 3530 3531 3532 3533 3534
            if (errno == ENOENT) {
                VIR_DEBUG("No file %s, assuming done", keypath);
                killedAny = false;
                goto done;
            }

3535 3536 3537
            virReportSystemError(errno,
                                 _("Failed to read %s"),
                                 keypath);
3538 3539 3540
            goto cleanup;
        } else {
            while (!feof(fp)) {
M
Michal Privoznik 已提交
3541 3542
                long pid_value;
                if (fscanf(fp, "%ld", &pid_value) != 1) {
3543 3544
                    if (feof(fp))
                        break;
3545 3546 3547
                    virReportSystemError(errno,
                                         _("Failed to read %s"),
                                         keypath);
E
Eric Blake 已提交
3548
                    goto cleanup;
3549
                }
3550
                if (virHashLookup(pids, (void*)pid_value))
3551 3552
                    continue;

M
Michal Privoznik 已提交
3553
                VIR_DEBUG("pid=%ld", pid_value);
3554 3555
                /* Cgroups is a Linux concept, so this cast is safe.  */
                if (kill((pid_t)pid_value, signum) < 0) {
3556
                    if (errno != ESRCH) {
3557
                        virReportSystemError(errno,
M
Michal Privoznik 已提交
3558
                                             _("Failed to kill process %ld"),
3559
                                             pid_value);
3560 3561 3562 3563
                        goto cleanup;
                    }
                    /* Leave RC == 0 since we didn't kill one */
                } else {
3564
                    killedAny = true;
3565 3566 3567
                    done = false;
                }

3568
                ignore_value(virHashAddEntry(pids, (void*)pid_value, (void*)1));
3569 3570 3571 3572 3573
            }
            VIR_FORCE_FCLOSE(fp);
        }
    }

3574
 done:
3575
    ret = killedAny ? 1 : 0;
3576

3577
 cleanup:
E
Eric Blake 已提交
3578
    VIR_FORCE_FCLOSE(fp);
3579

3580
    return ret;
3581 3582 3583
}


E
Eric Blake 已提交
3584 3585
static uint32_t
virCgroupPidCode(const void *name, uint32_t seed)
3586
{
M
Michal Privoznik 已提交
3587
    long pid_value = (long)(intptr_t)name;
3588
    return virHashCodeGen(&pid_value, sizeof(pid_value), seed);
3589
}
E
Eric Blake 已提交
3590 3591 3592 3593


static bool
virCgroupPidEqual(const void *namea, const void *nameb)
3594 3595 3596
{
    return namea == nameb;
}
E
Eric Blake 已提交
3597 3598 3599 3600


static void *
virCgroupPidCopy(const void *name)
3601 3602 3603 3604
{
    return (void*)name;
}

E
Eric Blake 已提交
3605 3606 3607 3608 3609 3610

static int
virCgroupKillRecursiveInternal(virCgroupPtr group,
                               int signum,
                               virHashTablePtr pids,
                               bool dormdir)
3611
{
3612
    int ret = -1;
3613
    int rc;
3614
    bool killedAny = false;
3615
    VIR_AUTOFREE(char *) keypath = NULL;
3616
    DIR *dp = NULL;
3617
    virCgroupPtr subgroup = NULL;
3618
    struct dirent *ent;
E
Eric Blake 已提交
3619
    int direrr;
E
Eric Blake 已提交
3620 3621
    VIR_DEBUG("group=%p path=%s signum=%d pids=%p",
              group, group->path, signum, pids);
3622

3623
    if (virCgroupPathOfAnyController(group, "", &keypath) < 0)
3624
        return -1;
3625

3626
    if ((rc = virCgroupKillInternal(group, signum, pids)) < 0)
3627
        goto cleanup;
3628 3629
    if (rc == 1)
        killedAny = true;
3630

3631
    VIR_DEBUG("Iterate over children of %s (killedAny=%d)", keypath, killedAny);
J
Ján Tomko 已提交
3632
    if ((rc = virDirOpenIfExists(&dp, keypath)) < 0)
3633
        goto cleanup;
J
Ján Tomko 已提交
3634 3635 3636 3637 3638

    if (rc == 0) {
        VIR_DEBUG("Path %s does not exist, assuming done", keypath);
        killedAny = false;
        goto done;
3639 3640
    }

E
Eric Blake 已提交
3641
    while ((direrr = virDirRead(dp, &ent, keypath)) > 0) {
3642 3643 3644 3645 3646
        if (ent->d_type != DT_DIR)
            continue;

        VIR_DEBUG("Process subdir %s", ent->d_name);

3647
        if (virCgroupNew(-1, ent->d_name, group, -1, &subgroup) < 0)
3648 3649
            goto cleanup;

E
Eric Blake 已提交
3650 3651
        if ((rc = virCgroupKillRecursiveInternal(subgroup, signum, pids,
                                                 true)) < 0)
3652 3653
            goto cleanup;
        if (rc == 1)
3654
            killedAny = true;
3655 3656 3657

        if (dormdir)
            virCgroupRemove(subgroup);
3658

3659
        virCgroupFree(&subgroup);
3660
    }
E
Eric Blake 已提交
3661 3662
    if (direrr < 0)
        goto cleanup;
3663

3664
 done:
3665
    ret = killedAny ? 1 : 0;
3666

3667
 cleanup:
3668
    virCgroupFree(&subgroup);
J
Ján Tomko 已提交
3669
    VIR_DIR_CLOSE(dp);
3670
    return ret;
3671 3672
}

E
Eric Blake 已提交
3673 3674 3675

int
virCgroupKillRecursive(virCgroupPtr group, int signum)
3676
{
3677
    int ret;
3678
    VIR_DEBUG("group=%p path=%s signum=%d", group, group->path, signum);
3679 3680 3681 3682 3683 3684
    virHashTablePtr pids = virHashCreateFull(100,
                                             NULL,
                                             virCgroupPidCode,
                                             virCgroupPidEqual,
                                             virCgroupPidCopy,
                                             NULL);
3685

3686 3687 3688 3689 3690
    ret = virCgroupKillRecursiveInternal(group, signum, pids, false);

    virHashFree(pids);

    return ret;
3691 3692 3693
}


E
Eric Blake 已提交
3694 3695
int
virCgroupKillPainfully(virCgroupPtr group)
3696
{
3697
    size_t i;
3698
    int ret;
3699
    VIR_DEBUG("cgroup=%p path=%s", group, group->path);
3700
    for (i = 0; i < 15; i++) {
3701 3702 3703 3704 3705 3706
        int signum;
        if (i == 0)
            signum = SIGTERM;
        else if (i == 8)
            signum = SIGKILL;
        else
J
Ján Tomko 已提交
3707
            signum = 0; /* Just check for existence */
3708

3709 3710 3711 3712
        ret = virCgroupKillRecursive(group, signum);
        VIR_DEBUG("Iteration %zu rc=%d", i, ret);
        /* If ret == -1 we hit error, if 0 we ran out of PIDs */
        if (ret <= 0)
3713 3714 3715 3716
            break;

        usleep(200 * 1000);
    }
3717 3718
    VIR_DEBUG("Complete %d", ret);
    return ret;
3719
}
3720

E
Eric Blake 已提交
3721 3722 3723

static char *
virCgroupIdentifyRoot(virCgroupPtr group)
3724 3725 3726 3727
{
    char *ret = NULL;
    size_t i;

3728
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
3729 3730 3731 3732 3733 3734 3735 3736 3737 3738
        char *tmp;
        if (!group->controllers[i].mountPoint)
            continue;
        if (!(tmp = strrchr(group->controllers[i].mountPoint, '/'))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not find directory separator in %s"),
                           group->controllers[i].mountPoint);
            return NULL;
        }

3739 3740 3741
        if (VIR_STRNDUP(ret, group->controllers[i].mountPoint,
                        tmp - group->controllers[i].mountPoint) < 0)
            return NULL;
3742 3743 3744 3745 3746 3747 3748 3749 3750
        return ret;
    }

    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("Could not find any mounted controllers"));
    return NULL;
}


3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
/**
 * virCgroupGetCpuCfsQuota:
 *
 * @group: The cgroup to get cpu.cfs_quota_us for
 * @cfs_quota: Pointer to the returned cpu bandwidth (in usecs) that this tg
 *             will be allowed to consume over period
 *
 * Returns: 0 on success
 */
int
virCgroupGetCpuCfsQuota(virCgroupPtr group, long long *cfs_quota)
{
    return virCgroupGetValueI64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.cfs_quota_us", cfs_quota);
}


int
virCgroupGetCpuacctUsage(virCgroupPtr group, unsigned long long *usage)
{
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPUACCT,
                                "cpuacct.usage", usage);
}


int
virCgroupGetCpuacctStat(virCgroupPtr group, unsigned long long *user,
                        unsigned long long *sys)
{
3782
    VIR_AUTOFREE(char *) str = NULL;
3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
    char *p;
    static double scale = -1.0;

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

    if (!(p = STRSKIP(str, "user ")) ||
        virStrToLong_ull(p, &p, 10, user) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse user stat '%s'"),
                       p);
3795
        return -1;
3796 3797 3798 3799 3800 3801
    }
    if (!(p = STRSKIP(p, "\nsystem ")) ||
        virStrToLong_ull(p, NULL, 10, sys) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse sys stat '%s'"),
                       p);
3802
        return -1;
3803 3804 3805 3806 3807 3808 3809 3810 3811
    }
    /* times reported are in system ticks (generally 100 Hz), but that
     * rate can theoretically vary between machines.  Scale things
     * into approximate nanoseconds.  */
    if (scale < 0) {
        long ticks_per_sec = sysconf(_SC_CLK_TCK);
        if (ticks_per_sec == -1) {
            virReportSystemError(errno, "%s",
                                 _("Cannot determine system clock HZ"));
3812
            return -1;
3813 3814 3815 3816 3817 3818
        }
        scale = 1000000000.0 / ticks_per_sec;
    }
    *user *= scale;
    *sys *= scale;

3819
    return 0;
3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840
}


int
virCgroupSetFreezerState(virCgroupPtr group, const char *state)
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_FREEZER,
                                "freezer.state", state);
}


int
virCgroupGetFreezerState(virCgroupPtr group, char **state)
{
    return virCgroupGetValueStr(group,
                                VIR_CGROUP_CONTROLLER_FREEZER,
                                "freezer.state", state);
}


E
Eric Blake 已提交
3841
int
3842 3843
virCgroupBindMount(virCgroupPtr group, const char *oldroot,
                   const char *mountopts)
3844 3845
{
    size_t i;
3846 3847
    VIR_AUTOFREE(char *) opts = NULL;
    VIR_AUTOFREE(char *) root = NULL;
3848 3849 3850 3851 3852 3853 3854 3855 3856 3857

    if (!(root = virCgroupIdentifyRoot(group)))
        return -1;

    VIR_DEBUG("Mounting cgroups at '%s'", root);

    if (virFileMakePath(root) < 0) {
        virReportSystemError(errno,
                             _("Unable to create directory %s"),
                             root);
3858
        return -1;
3859 3860 3861
    }

    if (virAsprintf(&opts,
3862
                    "mode=755,size=65536%s", mountopts) < 0)
3863
        return -1;
3864 3865 3866 3867 3868

    if (mount("tmpfs", root, "tmpfs", MS_NOSUID|MS_NODEV|MS_NOEXEC, opts) < 0) {
        virReportSystemError(errno,
                             _("Failed to mount %s on %s type %s"),
                             "tmpfs", root, "tmpfs");
3869
        return -1;
3870 3871
    }

3872
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
3873 3874 3875 3876
        if (!group->controllers[i].mountPoint)
            continue;

        if (!virFileExists(group->controllers[i].mountPoint)) {
3877
            VIR_AUTOFREE(char *) src = NULL;
3878
            if (virAsprintf(&src, "%s%s",
3879
                            oldroot,
3880
                            group->controllers[i].mountPoint) < 0)
3881
                return -1;
3882

E
Eric Blake 已提交
3883 3884
            VIR_DEBUG("Create mount point '%s'",
                      group->controllers[i].mountPoint);
3885 3886 3887 3888
            if (virFileMakePath(group->controllers[i].mountPoint) < 0) {
                virReportSystemError(errno,
                                     _("Unable to create directory %s"),
                                     group->controllers[i].mountPoint);
3889
                return -1;
3890 3891
            }

3892
            if (mount(src, group->controllers[i].mountPoint, "none", MS_BIND,
E
Eric Blake 已提交
3893
                      NULL) < 0) {
3894 3895 3896
                virReportSystemError(errno,
                                     _("Failed to bind cgroup '%s' on '%s'"),
                                     src, group->controllers[i].mountPoint);
3897
                return -1;
3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910
            }
        }

        if (group->controllers[i].linkPoint) {
            VIR_DEBUG("Link mount point '%s' to '%s'",
                      group->controllers[i].mountPoint,
                      group->controllers[i].linkPoint);
            if (symlink(group->controllers[i].mountPoint,
                        group->controllers[i].linkPoint) < 0) {
                virReportSystemError(errno,
                                     _("Unable to symlink directory %s to %s"),
                                     group->controllers[i].mountPoint,
                                     group->controllers[i].linkPoint);
3911
                return -1;
3912 3913 3914 3915
            }
        }
    }

3916
    return 0;
3917
}
3918 3919


3920 3921 3922 3923 3924 3925 3926 3927
int virCgroupSetOwner(virCgroupPtr cgroup,
                      uid_t uid,
                      gid_t gid,
                      int controllers)
{
    int ret = -1;
    size_t i;
    DIR *dh = NULL;
E
Eric Blake 已提交
3928
    int direrr;
3929 3930

    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
3931
        VIR_AUTOFREE(char *) base = NULL;
3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943
        struct dirent *de;

        if (!((1 << i) & controllers))
            continue;

        if (!cgroup->controllers[i].mountPoint)
            continue;

        if (virAsprintf(&base, "%s%s", cgroup->controllers[i].mountPoint,
                        cgroup->controllers[i].placement) < 0)
            goto cleanup;

J
Ján Tomko 已提交
3944
        if (virDirOpen(&dh, base) < 0)
3945 3946
            goto cleanup;

E
Eric Blake 已提交
3947
        while ((direrr = virDirRead(dh, &de, base)) > 0) {
3948 3949
            VIR_AUTOFREE(char *) entry = NULL;

3950 3951 3952 3953 3954 3955 3956 3957 3958 3959
            if (virAsprintf(&entry, "%s/%s", base, de->d_name) < 0)
                goto cleanup;

            if (chown(entry, uid, gid) < 0) {
                virReportSystemError(errno,
                                     _("cannot chown '%s' to (%u, %u)"),
                                     entry, uid, gid);
                goto cleanup;
            }
        }
E
Eric Blake 已提交
3960 3961
        if (direrr < 0)
            goto cleanup;
3962 3963 3964 3965 3966 3967 3968 3969

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

J
Ján Tomko 已提交
3970
        VIR_DIR_CLOSE(dh);
3971 3972 3973 3974 3975
    }

    ret = 0;

 cleanup:
J
Ján Tomko 已提交
3976
    VIR_DIR_CLOSE(dh);
3977 3978 3979 3980
    return ret;
}


3981 3982 3983 3984 3985 3986 3987 3988 3989 3990
/**
 * virCgroupSupportsCpuBW():
 * Check whether the host supports CFS bandwidth.
 *
 * Return true when CFS bandwidth is supported,
 * false when CFS bandwidth is not supported.
 */
bool
virCgroupSupportsCpuBW(virCgroupPtr cgroup)
{
3991
    VIR_AUTOFREE(char *) path = NULL;
3992 3993 3994 3995 3996 3997 3998

    if (!cgroup)
        return false;

    if (virCgroupPathOfController(cgroup, VIR_CGROUP_CONTROLLER_CPU,
                                  "cpu.cfs_period_us", &path) < 0) {
        virResetLastError();
3999
        return false;
4000 4001
    }

4002
    return virFileExists(path);
4003 4004
}

4005 4006 4007 4008
int
virCgroupHasEmptyTasks(virCgroupPtr cgroup, int controller)
{
    int ret = -1;
4009
    VIR_AUTOFREE(char *) content = NULL;
4010

4011 4012 4013
    if (!cgroup)
        return -1;

4014 4015 4016 4017 4018 4019 4020
    ret = virCgroupGetValueStr(cgroup, controller, "tasks", &content);

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

    return ret;
}
4021

4022 4023 4024
bool
virCgroupControllerAvailable(int controller)
{
4025 4026
    virCgroupPtr cgroup;
    bool ret = false;
4027 4028

    if (virCgroupNewSelf(&cgroup) < 0)
4029
        return ret;
4030

4031
    ret = virCgroupHasController(cgroup, controller);
4032
    virCgroupFree(&cgroup);
4033
    return ret;
4034 4035
}

4036 4037
#else /* !VIR_CGROUP_SUPPORTED */

4038 4039 4040 4041 4042 4043 4044
bool
virCgroupAvailable(void)
{
    return false;
}


4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055
int
virCgroupDetectMountsFromFile(virCgroupPtr group ATTRIBUTE_UNUSED,
                              const char *path ATTRIBUTE_UNUSED,
                              bool checkLinks ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089
int
virCgroupNewPartition(const char *path ATTRIBUTE_UNUSED,
                      bool create ATTRIBUTE_UNUSED,
                      int controllers ATTRIBUTE_UNUSED,
                      virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupNewSelf(virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupNewDomainPartition(virCgroupPtr partition ATTRIBUTE_UNUSED,
                            const char *driver ATTRIBUTE_UNUSED,
                            const char *name ATTRIBUTE_UNUSED,
                            bool create ATTRIBUTE_UNUSED,
                            virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102
int
virCgroupNewThread(virCgroupPtr domain ATTRIBUTE_UNUSED,
                   virCgroupThreadName nameval ATTRIBUTE_UNUSED,
                   int id ATTRIBUTE_UNUSED,
                   bool create ATTRIBUTE_UNUSED,
                   virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113
int
virCgroupNewDetect(pid_t pid ATTRIBUTE_UNUSED,
                   int controllers ATTRIBUTE_UNUSED,
                   virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4114 4115 4116 4117 4118
int
virCgroupNewDetectMachine(const char *name ATTRIBUTE_UNUSED,
                          const char *drivername ATTRIBUTE_UNUSED,
                          pid_t pid ATTRIBUTE_UNUSED,
                          int controllers ATTRIBUTE_UNUSED,
4119
                          char *machinename ATTRIBUTE_UNUSED,
4120 4121 4122 4123 4124 4125 4126
                          virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

J
Ján Tomko 已提交
4127

4128
int virCgroupTerminateMachine(const char *name ATTRIBUTE_UNUSED)
J
Ján Tomko 已提交
4129 4130 4131 4132 4133 4134 4135
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4136 4137 4138 4139 4140 4141 4142
int
virCgroupNewMachine(const char *name ATTRIBUTE_UNUSED,
                    const char *drivername ATTRIBUTE_UNUSED,
                    const unsigned char *uuid ATTRIBUTE_UNUSED,
                    const char *rootdir ATTRIBUTE_UNUSED,
                    pid_t pidleader ATTRIBUTE_UNUSED,
                    bool isContainer ATTRIBUTE_UNUSED,
4143 4144
                    size_t nnicindexes ATTRIBUTE_UNUSED,
                    int *nicindexes ATTRIBUTE_UNUSED,
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161
                    const char *partition ATTRIBUTE_UNUSED,
                    int controllers ATTRIBUTE_UNUSED,
                    virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


bool
virCgroupNewIgnoreError(void)
{
    VIR_DEBUG("No cgroups present/configured/accessible, ignoring error");
    return true;
}

4162 4163

void
4164
virCgroupFree(virCgroupPtr *group ATTRIBUTE_UNUSED)
4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
}


bool
virCgroupHasController(virCgroupPtr cgroup ATTRIBUTE_UNUSED,
                       int controller ATTRIBUTE_UNUSED)
{
    return false;
}


4179 4180
int
virCgroupPathOfController(virCgroupPtr group ATTRIBUTE_UNUSED,
4181
                          unsigned int controller ATTRIBUTE_UNUSED,
4182 4183 4184 4185 4186 4187 4188 4189 4190
                          const char *key ATTRIBUTE_UNUSED,
                          char **path ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4191 4192 4193 4194 4195 4196 4197 4198 4199 4200
int
virCgroupAddTask(virCgroupPtr group ATTRIBUTE_UNUSED,
                 pid_t pid ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4201 4202 4203 4204 4205 4206 4207 4208 4209 4210
int
virCgroupAddMachineTask(virCgroupPtr group ATTRIBUTE_UNUSED,
                        pid_t pid ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237
int
virCgroupGetBlkioIoServiced(virCgroupPtr group ATTRIBUTE_UNUSED,
                            long long *bytes_read ATTRIBUTE_UNUSED,
                            long long *bytes_write ATTRIBUTE_UNUSED,
                            long long *requests_read ATTRIBUTE_UNUSED,
                            long long *requests_write ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetBlkioIoDeviceServiced(virCgroupPtr group ATTRIBUTE_UNUSED,
                                  const char *path ATTRIBUTE_UNUSED,
                                  long long *bytes_read ATTRIBUTE_UNUSED,
                                  long long *bytes_write ATTRIBUTE_UNUSED,
                                  long long *requests_read ATTRIBUTE_UNUSED,
                                  long long *requests_write ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
int
virCgroupSetBlkioWeight(virCgroupPtr group ATTRIBUTE_UNUSED,
                        unsigned int weight ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetBlkioWeight(virCgroupPtr group ATTRIBUTE_UNUSED,
                        unsigned int *weight ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4258 4259 4260 4261 4262 4263 4264 4265 4266 4267
int
virCgroupSetBlkioDeviceWeight(virCgroupPtr group ATTRIBUTE_UNUSED,
                              const char *path ATTRIBUTE_UNUSED,
                              unsigned int weight ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307
int
virCgroupSetBlkioDeviceReadIops(virCgroupPtr group ATTRIBUTE_UNUSED,
                                const char *path ATTRIBUTE_UNUSED,
                                unsigned int riops ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupSetBlkioDeviceWriteIops(virCgroupPtr group ATTRIBUTE_UNUSED,
                                 const char *path ATTRIBUTE_UNUSED,
                                 unsigned int wiops ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupSetBlkioDeviceReadBps(virCgroupPtr group ATTRIBUTE_UNUSED,
                               const char *path ATTRIBUTE_UNUSED,
                               unsigned long long rbps ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupSetBlkioDeviceWriteBps(virCgroupPtr group ATTRIBUTE_UNUSED,
                                const char *path ATTRIBUTE_UNUSED,
                                unsigned long long wbps ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

4308 4309 4310
int
virCgroupGetBlkioDeviceWeight(virCgroupPtr group ATTRIBUTE_UNUSED,
                              const char *path ATTRIBUTE_UNUSED,
4311
                              unsigned int *weight ATTRIBUTE_UNUSED)
4312 4313 4314 4315 4316 4317 4318 4319 4320
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupGetBlkioDeviceReadIops(virCgroupPtr group ATTRIBUTE_UNUSED,
                                const char *path ATTRIBUTE_UNUSED,
4321
                                unsigned int *riops ATTRIBUTE_UNUSED)
4322 4323 4324 4325 4326 4327 4328 4329 4330
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupGetBlkioDeviceWriteIops(virCgroupPtr group ATTRIBUTE_UNUSED,
                                 const char *path ATTRIBUTE_UNUSED,
4331
                                 unsigned int *wiops ATTRIBUTE_UNUSED)
4332 4333 4334 4335 4336 4337 4338 4339 4340
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupGetBlkioDeviceReadBps(virCgroupPtr group ATTRIBUTE_UNUSED,
                               const char *path ATTRIBUTE_UNUSED,
4341
                               unsigned long long *rbps ATTRIBUTE_UNUSED)
4342 4343 4344 4345 4346 4347 4348 4349 4350
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupGetBlkioDeviceWriteBps(virCgroupPtr group ATTRIBUTE_UNUSED,
                                const char *path ATTRIBUTE_UNUSED,
4351
                                unsigned long long *wbps ATTRIBUTE_UNUSED)
4352 4353 4354 4355 4356
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}
4357

4358 4359 4360 4361 4362 4363 4364 4365 4366 4367
int
virCgroupSetMemory(virCgroupPtr group ATTRIBUTE_UNUSED,
                   unsigned long long kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


P
Pavel Hrdina 已提交
4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382
int
virCgroupGetMemoryStat(virCgroupPtr group ATTRIBUTE_UNUSED,
                       unsigned long long *cache ATTRIBUTE_UNUSED,
                       unsigned long long *activeAnon ATTRIBUTE_UNUSED,
                       unsigned long long *inactiveAnon ATTRIBUTE_UNUSED,
                       unsigned long long *activeFile ATTRIBUTE_UNUSED,
                       unsigned long long *inactiveFile ATTRIBUTE_UNUSED,
                       unsigned long long *unevictable ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481
int
virCgroupGetMemoryUsage(virCgroupPtr group ATTRIBUTE_UNUSED,
                        unsigned long *kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupSetMemoryHardLimit(virCgroupPtr group ATTRIBUTE_UNUSED,
                            unsigned long long kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetMemoryHardLimit(virCgroupPtr group ATTRIBUTE_UNUSED,
                            unsigned long long *kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupSetMemorySoftLimit(virCgroupPtr group ATTRIBUTE_UNUSED,
                            unsigned long long kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetMemorySoftLimit(virCgroupPtr group ATTRIBUTE_UNUSED,
                            unsigned long long *kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupSetMemSwapHardLimit(virCgroupPtr group ATTRIBUTE_UNUSED,
                             unsigned long long kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetMemSwapHardLimit(virCgroupPtr group ATTRIBUTE_UNUSED,
                             unsigned long long *kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetMemSwapUsage(virCgroupPtr group ATTRIBUTE_UNUSED,
                         unsigned long long *kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupSetCpusetMems(virCgroupPtr group ATTRIBUTE_UNUSED,
                       const char *mems ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetCpusetMems(virCgroupPtr group ATTRIBUTE_UNUSED,
                       char **mems ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501

int
virCgroupSetCpusetMemoryMigrate(virCgroupPtr group ATTRIBUTE_UNUSED,
                                bool migrate ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetCpusetMemoryMigrate(virCgroupPtr group ATTRIBUTE_UNUSED,
                                bool *migrate ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521

int
virCgroupSetCpusetCpus(virCgroupPtr group ATTRIBUTE_UNUSED,
                       const char *cpus ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetCpusetCpus(virCgroupPtr group ATTRIBUTE_UNUSED,
                       char **cpus ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

4522 4523 4524 4525 4526 4527 4528 4529
int
virCgroupAllowAllDevices(virCgroupPtr group ATTRIBUTE_UNUSED,
                         int perms ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}
4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552

int
virCgroupDenyAllDevices(virCgroupPtr group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupAllowDevice(virCgroupPtr group ATTRIBUTE_UNUSED,
                     char type ATTRIBUTE_UNUSED,
                     int major ATTRIBUTE_UNUSED,
                     int minor ATTRIBUTE_UNUSED,
                     int perms ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4553 4554 4555
int
virCgroupAllowDevicePath(virCgroupPtr group ATTRIBUTE_UNUSED,
                         const char *path ATTRIBUTE_UNUSED,
4556 4557
                         int perms ATTRIBUTE_UNUSED,
                         bool ignoreEaccess ATTRIBUTE_UNUSED)
4558 4559 4560 4561 4562 4563 4564
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577
int
virCgroupDenyDevice(virCgroupPtr group ATTRIBUTE_UNUSED,
                    char type ATTRIBUTE_UNUSED,
                    int major ATTRIBUTE_UNUSED,
                    int minor ATTRIBUTE_UNUSED,
                    int perms ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4578 4579 4580
int
virCgroupDenyDevicePath(virCgroupPtr group ATTRIBUTE_UNUSED,
                        const char *path ATTRIBUTE_UNUSED,
4581 4582
                        int perms ATTRIBUTE_UNUSED,
                        bool ignoreEacces ATTRIBUTE_UNUSED)
4583 4584 4585 4586 4587 4588 4589
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648
int
virCgroupSetCpuShares(virCgroupPtr group ATTRIBUTE_UNUSED,
                      unsigned long long shares ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetCpuShares(virCgroupPtr group ATTRIBUTE_UNUSED,
                      unsigned long long *shares ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupSetCpuCfsPeriod(virCgroupPtr group ATTRIBUTE_UNUSED,
                         unsigned long long cfs_period ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetCpuCfsPeriod(virCgroupPtr group ATTRIBUTE_UNUSED,
                         unsigned long long *cfs_period ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupSetCpuCfsQuota(virCgroupPtr group ATTRIBUTE_UNUSED,
                        long long cfs_quota ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupRemove(virCgroupPtr group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667
int
virCgroupKillRecursive(virCgroupPtr group ATTRIBUTE_UNUSED,
                       int signum ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupKillPainfully(virCgroupPtr group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708
int
virCgroupGetCpuCfsQuota(virCgroupPtr group ATTRIBUTE_UNUSED,
                        long long *cfs_quota ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetCpuacctUsage(virCgroupPtr group ATTRIBUTE_UNUSED,
                         unsigned long long *usage ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetCpuacctPercpuUsage(virCgroupPtr group ATTRIBUTE_UNUSED,
                               char **usage ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetCpuacctStat(virCgroupPtr group ATTRIBUTE_UNUSED,
                        unsigned long long *user ATTRIBUTE_UNUSED,
                        unsigned long long *sys ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719
int
virCgroupGetDomainTotalCpuStats(virCgroupPtr group ATTRIBUTE_UNUSED,
                                virTypedParameterPtr params ATTRIBUTE_UNUSED,
                                int nparams ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739
int
virCgroupSetFreezerState(virCgroupPtr group ATTRIBUTE_UNUSED,
                         const char *state ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupGetFreezerState(virCgroupPtr group ATTRIBUTE_UNUSED,
                         char **state ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


E
Eric Blake 已提交
4740
int
4741 4742 4743
virCgroupBindMount(virCgroupPtr group ATTRIBUTE_UNUSED,
                   const char *oldroot ATTRIBUTE_UNUSED,
                   const char *mountopts ATTRIBUTE_UNUSED)
4744
{
4745 4746 4747
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
4748
}
4749

4750 4751 4752 4753 4754 4755 4756 4757

bool
virCgroupSupportsCpuBW(virCgroupPtr cgroup ATTRIBUTE_UNUSED)
{
    VIR_DEBUG("Control groups not supported on this platform");
    return false;
}

E
Eric Blake 已提交
4758 4759 4760 4761 4762 4763

int
virCgroupGetPercpuStats(virCgroupPtr group ATTRIBUTE_UNUSED,
                        virTypedParameterPtr params ATTRIBUTE_UNUSED,
                        unsigned int nparams ATTRIBUTE_UNUSED,
                        int start_cpu ATTRIBUTE_UNUSED,
J
Ján Tomko 已提交
4764
                        unsigned int ncpus ATTRIBUTE_UNUSED,
4765
                        virBitmapPtr guestvcpus ATTRIBUTE_UNUSED)
E
Eric Blake 已提交
4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


int
virCgroupSetOwner(virCgroupPtr cgroup ATTRIBUTE_UNUSED,
                  uid_t uid ATTRIBUTE_UNUSED,
                  gid_t gid ATTRIBUTE_UNUSED,
                  int controllers ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

4784 4785 4786 4787 4788 4789 4790 4791 4792
int
virCgroupHasEmptyTasks(virCgroupPtr cgroup ATTRIBUTE_UNUSED,
                       int controller ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

4793 4794 4795 4796 4797
bool
virCgroupControllerAvailable(int controller ATTRIBUTE_UNUSED)
{
    return false;
}
4798
#endif /* !VIR_CGROUP_SUPPORTED */
4799 4800 4801 4802 4803 4804 4805


int
virCgroupDelThread(virCgroupPtr cgroup,
                   virCgroupThreadName nameval,
                   int idx)
{
4806
    virCgroupPtr new_cgroup = NULL;
4807 4808 4809 4810 4811 4812 4813

    if (cgroup) {
        if (virCgroupNewThread(cgroup, nameval, idx, false, &new_cgroup) < 0)
            return -1;

        /* Remove the offlined cgroup */
        virCgroupRemove(new_cgroup);
4814
        virCgroupFree(&new_cgroup);
4815 4816 4817 4818
    }

    return 0;
}