vircgroup.c 123.5 KB
Newer Older
1
/*
2
 * vircgroup.c: methods for managing control cgroups
3
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2010-2014 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 26
 *
 * Authors:
 *  Dan Smith <danms@us.ibm.com>
 */
#include <config.h>

#include <stdio.h>
27
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
28
# include <mntent.h>
D
Daniel P. Berrange 已提交
29
#endif
30 31 32
#if defined HAVE_SYS_MOUNT_H
# include <sys/mount.h>
#endif
33 34 35 36 37 38
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
39
#include <signal.h>
40
#include <dirent.h>
41

42 43 44
#define __VIR_CGROUP_ALLOW_INCLUDE_PRIV_H__
#include "vircgrouppriv.h"

45
#include "virutil.h"
46
#include "viralloc.h"
47
#include "virerror.h"
48
#include "virlog.h"
E
Eric Blake 已提交
49
#include "virfile.h"
50
#include "virhash.h"
51
#include "virhashcode.h"
52
#include "virstring.h"
53
#include "virsystemd.h"
54
#include "virtypedparam.h"
55

56 57
#include "nodeinfo.h"

58 59
VIR_LOG_INIT("util.cgroup");

60 61
#define CGROUP_MAX_VAL 512

62 63
#define VIR_FROM_THIS VIR_FROM_CGROUP

64
#define CGROUP_NB_TOTAL_CPU_STAT_PARAM 3
65
#define CGROUP_NB_PER_CPU_STAT_PARAM   1
66

67
#if defined(__linux__) && defined(HAVE_GETMNTENT_R) && \
68
    defined(_DIRENT_HAVE_D_TYPE) && defined(_SC_CLK_TCK)
69 70 71
# define VIR_CGROUP_SUPPORTED
#endif

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

77 78 79 80 81 82 83 84
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 已提交
85

86 87 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
/**
 * 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 "";
        }
    }
}


124
#ifdef VIR_CGROUP_SUPPORTED
E
Eric Blake 已提交
125 126
bool
virCgroupAvailable(void)
127
{
128
    bool ret = false;
129 130 131 132 133 134 135 136 137 138 139
    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) {
140 141 142 143
        /* 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=")) {
144 145 146 147 148 149 150 151 152
            ret = true;
            break;
        }
    }

    VIR_FORCE_FCLOSE(mounts);
    return ret;
}

E
Eric Blake 已提交
153 154 155 156 157 158 159 160 161 162 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

static int
virCgroupPartitionNeedsEscaping(const char *path)
{
    FILE *fp = NULL;
    int ret = 0;
    char *line = NULL;
    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;
    }

218
 cleanup:
E
Eric Blake 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
    return ret;
}


static int
virCgroupPartitionEscape(char **path)
{
    size_t len = strlen(*path) + 1;
    int rc;
    char escape = '_';

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

    if (VIR_INSERT_ELEMENT(*path, 0, len, escape) < 0)
        return -1;

    return 0;
}
E
Eric Blake 已提交
240 241


242
static bool
243 244 245
virCgroupValidateMachineGroup(virCgroupPtr group,
                              const char *name,
                              const char *drivername,
246
                              const char *partition,
247
                              bool stripEmulatorSuffix)
248 249 250 251
{
    size_t i;
    bool valid = false;
    char *partname;
252
    char *scopename;
253 254 255 256 257 258 259 260

    if (virAsprintf(&partname, "%s.libvirt-%s",
                    name, drivername) < 0)
        goto cleanup;

    if (virCgroupPartitionEscape(&partname) < 0)
        goto cleanup;

261 262 263 264 265 266 267 268 269
    if (!partition)
        partition = "/machine";

    if (!(scopename = virSystemdMakeScopeName(name, drivername, partition)))
        goto cleanup;

    if (virCgroupPartitionEscape(&scopename) < 0)
        goto cleanup;

270 271 272
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
        char *tmp;

273 274 275
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD)
            continue;

276 277 278 279 280 281
        if (!group->controllers[i].placement)
            continue;

        tmp = strrchr(group->controllers[i].placement, '/');
        if (!tmp)
            goto cleanup;
282 283 284 285 286 287 288 289 290 291 292 293

        if (stripEmulatorSuffix &&
            (i == VIR_CGROUP_CONTROLLER_CPU ||
             i == VIR_CGROUP_CONTROLLER_CPUACCT ||
             i == VIR_CGROUP_CONTROLLER_CPUSET)) {
            if (STREQ(tmp, "/emulator"))
                *tmp = '\0';
            tmp = strrchr(group->controllers[i].placement, '/');
            if (!tmp)
                goto cleanup;
        }

294 295 296
        tmp++;

        if (STRNEQ(tmp, name) &&
297 298
            STRNEQ(tmp, partname) &&
            STRNEQ(tmp, scopename)) {
E
Eric Blake 已提交
299 300 301 302
            VIR_DEBUG("Name '%s' for controller '%s' does not match "
                      "'%s', '%s' or '%s'",
                      tmp, virCgroupControllerTypeToString(i),
                      name, partname, scopename);
303
            goto cleanup;
304
        }
305 306 307 308 309 310
    }

    valid = true;

 cleanup:
    VIR_FREE(partname);
311
    VIR_FREE(scopename);
312 313
    return valid;
}
E
Eric Blake 已提交
314

L
Lai Jiangshan 已提交
315

E
Eric Blake 已提交
316 317 318
static int
virCgroupCopyMounts(virCgroupPtr group,
                    virCgroupPtr parent)
319
{
320
    size_t i;
321
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
322 323 324
        if (!parent->controllers[i].mountPoint)
            continue;

325 326 327
        if (VIR_STRDUP(group->controllers[i].mountPoint,
                       parent->controllers[i].mountPoint) < 0)
            return -1;
328

329 330 331
        if (VIR_STRDUP(group->controllers[i].linkPoint,
                       parent->controllers[i].linkPoint) < 0)
            return -1;
332 333 334 335
    }
    return 0;
}

E
Eric Blake 已提交
336

337 338 339 340
/*
 * Process /proc/mounts figuring out what controllers are
 * mounted and where
 */
E
Eric Blake 已提交
341 342
static int
virCgroupDetectMounts(virCgroupPtr group)
343
{
344
    size_t i;
345
    FILE *mounts = NULL;
346 347 348 349 350
    struct mntent entry;
    char buf[CGROUP_MAX_VAL];

    mounts = fopen("/proc/mounts", "r");
    if (mounts == NULL) {
351 352 353
        virReportSystemError(errno, "%s",
                             _("Unable to open /proc/mounts"));
        return -1;
354 355 356
    }

    while (getmntent_r(mounts, &entry, buf, sizeof(buf)) != NULL) {
357 358
        if (STRNEQ(entry.mnt_type, "cgroup"))
            continue;
359

360
        for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
361 362 363 364 365 366 367 368 369 370 371 372
            const char *typestr = virCgroupControllerTypeToString(i);
            int typelen = strlen(typestr);
            char *tmp = entry.mnt_opts;
            while (tmp) {
                char *next = strchr(tmp, ',');
                int len;
                if (next) {
                    len = next-tmp;
                    next++;
                } else {
                    len = strlen(tmp);
                }
373 374 375 376
                /* NB, the same controller can appear >1 time in mount list
                 * due to bind mounts from one location to another. Pick the
                 * first entry only
                 */
377
                if (typelen == len && STREQLEN(typestr, tmp, len) &&
378 379 380 381 382
                    !group->controllers[i].mountPoint) {
                    char *linksrc;
                    struct stat sb;
                    char *tmp2;

383 384
                    if (VIR_STRDUP(group->controllers[i].mountPoint,
                                   entry.mnt_dir) < 0)
385
                        goto error;
386 387 388

                    tmp2 = strrchr(entry.mnt_dir, '/');
                    if (!tmp2) {
389 390 391
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("Missing '/' separator in cgroup mount '%s'"),
                                       entry.mnt_dir);
392 393
                        goto error;
                    }
394

395 396 397
                    /* If it is a co-mount it has a filename like "cpu,cpuacct"
                     * and we must identify the symlink path */
                    if (strchr(tmp2 + 1, ',')) {
398
                        *tmp2 = '\0';
399 400
                        if (virAsprintf(&linksrc, "%s/%s",
                                        entry.mnt_dir, typestr) < 0)
401
                            goto error;
402 403 404 405 406 407 408 409
                        *tmp2 = '/';

                        if (lstat(linksrc, &sb) < 0) {
                            if (errno == ENOENT) {
                                VIR_WARN("Controller %s co-mounted at %s is missing symlink at %s",
                                         typestr, entry.mnt_dir, linksrc);
                                VIR_FREE(linksrc);
                            } else {
410
                                virReportSystemError(errno,
E
Eric Blake 已提交
411 412
                                                     _("Cannot stat %s"),
                                                     linksrc);
413 414 415 416 417 418 419 420 421 422 423 424
                                goto error;
                            }
                        } else {
                            if (!S_ISLNK(sb.st_mode)) {
                                VIR_WARN("Expecting a symlink at %s for controller %s",
                                         linksrc, typestr);
                            } else {
                                group->controllers[i].linkPoint = linksrc;
                            }
                        }
                    }
                }
425 426 427
                tmp = next;
            }
        }
428 429
    }

430
    VIR_FORCE_FCLOSE(mounts);
431

432
    return 0;
433

434
 error:
435
    VIR_FORCE_FCLOSE(mounts);
436
    return -1;
437 438
}

439

E
Eric Blake 已提交
440 441 442 443
static int
virCgroupCopyPlacement(virCgroupPtr group,
                       const char *path,
                       virCgroupPtr parent)
444
{
445
    size_t i;
446
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
447 448 449
        if (!group->controllers[i].mountPoint)
            continue;

450 451 452
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD)
            continue;

453
        if (path[0] == '/') {
454 455
            if (VIR_STRDUP(group->controllers[i].placement, path) < 0)
                return -1;
456 457
        } else {
            /*
458 459 460
             * parent == "/" + path="" => "/"
             * parent == "/libvirt.service" + path == "" => "/libvirt.service"
             * parent == "/libvirt.service" + path == "foo" => "/libvirt.service/foo"
461 462 463 464 465 466 467
             */
            if (virAsprintf(&group->controllers[i].placement,
                            "%s%s%s",
                            parent->controllers[i].placement,
                            (STREQ(parent->controllers[i].placement, "/") ||
                             STREQ(path, "") ? "" : "/"),
                            path) < 0)
468
                return -1;
469 470 471 472 473 474 475
        }
    }

    return 0;
}


476
/*
477 478 479 480
 * virCgroupDetectPlacement:
 * @group: the group to process
 * @path: the relative path to append, not starting with '/'
 *
481 482
 * Process /proc/self/cgroup figuring out what cgroup
 * sub-path the current process is assigned to. ie not
483 484 485 486 487 488 489 490 491 492 493 494 495 496
 * 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.
497
 */
E
Eric Blake 已提交
498 499 500 501
static int
virCgroupDetectPlacement(virCgroupPtr group,
                         pid_t pid,
                         const char *path)
502
{
503
    size_t i;
504 505
    FILE *mapping  = NULL;
    char line[1024];
506
    int ret = -1;
507
    char *procfile;
508

509 510
    VIR_DEBUG("Detecting placement for pid %lld path %s",
              (unsigned long long)pid, path);
511 512 513 514 515 516 517 518 519 520
    if (pid == -1) {
        if (VIR_STRDUP(procfile, "/proc/self/cgroup") < 0)
            goto cleanup;
    } else {
        if (virAsprintf(&procfile, "/proc/%llu/cgroup",
                        (unsigned long long)pid) < 0)
            goto cleanup;
    }

    mapping = fopen(procfile, "r");
521
    if (mapping == NULL) {
522 523 524 525
        virReportSystemError(errno,
                             _("Unable to open '%s'"),
                             procfile);
        goto cleanup;
526 527
    }

528 529
    while (fgets(line, sizeof(line), mapping) != NULL) {
        char *controllers = strchr(line, ':');
530 531
        char *selfpath = controllers ? strchr(controllers + 1, ':') : NULL;
        char *nl = selfpath ? strchr(selfpath, '\n') : NULL;
532

533
        if (!controllers || !selfpath)
534 535 536 537 538
            continue;

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

539
        *selfpath = '\0';
540
        controllers++;
541
        selfpath++;
542

543
        for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
544 545 546
            const char *typestr = virCgroupControllerTypeToString(i);
            int typelen = strlen(typestr);
            char *tmp = controllers;
547

548 549 550 551
            while (tmp) {
                char *next = strchr(tmp, ',');
                int len;
                if (next) {
552
                    len = next - tmp;
553 554 555 556
                    next++;
                } else {
                    len = strlen(tmp);
                }
557 558

                /*
559 560 561
                 * selfpath == "/" + path="" -> "/"
                 * selfpath == "/libvirt.service" + path == "" -> "/libvirt.service"
                 * selfpath == "/libvirt.service" + path == "foo" -> "/libvirt.service/foo"
562
                 */
563
                if (typelen == len && STREQLEN(typestr, tmp, len) &&
564 565 566 567 568 569 570 571 572 573 574 575 576 577
                    group->controllers[i].mountPoint != NULL &&
                    group->controllers[i].placement == NULL) {
                    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;
                    }
578
                }
579 580 581 582 583 584

                tmp = next;
            }
        }
    }

585
    ret = 0;
586

587
 cleanup:
588
    VIR_FREE(procfile);
589
    VIR_FORCE_FCLOSE(mapping);
590

591
    return ret;
592 593
}

E
Eric Blake 已提交
594 595 596 597 598 599 600

static int
virCgroupDetect(virCgroupPtr group,
                pid_t pid,
                int controllers,
                const char *path,
                virCgroupPtr parent)
601
{
602 603
    size_t i;
    size_t j;
604 605
    VIR_DEBUG("group=%p controllers=%d path=%s parent=%p",
              group, controllers, path, parent);
606

607 608 609 610 611 612
    if (parent) {
        if (virCgroupCopyMounts(group, parent) < 0)
            return -1;
    } else {
        if (virCgroupDetectMounts(group) < 0)
            return -1;
613 614
    }

615
    if (controllers >= 0) {
616
        VIR_DEBUG("Filtering controllers %d", controllers);
617
        for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
618
            VIR_DEBUG("Controller '%s' wanted=%s, mount='%s'",
619
                      virCgroupControllerTypeToString(i),
620 621
                      (1 << i) & controllers ? "yes" : "no",
                      NULLSTR(group->controllers[i].mountPoint));
622
            if (((1 << i) & controllers)) {
623
                /* Remove non-existent controllers  */
624
                if (!group->controllers[i].mountPoint) {
625
                    VIR_DEBUG("Requested controller '%s' not mounted, ignoring",
626
                              virCgroupControllerTypeToString(i));
627
                    controllers &= ~(1 << i);
628 629 630 631
                }
            } else {
                /* Check whether a request to disable a controller
                 * clashes with co-mounting of controllers */
632
                for (j = 0; j < VIR_CGROUP_CONTROLLER_LAST; j++) {
633 634 635 636 637 638 639
                    if (j == i)
                        continue;
                    if (!((1 << j) & controllers))
                        continue;

                    if (STREQ_NULLABLE(group->controllers[i].mountPoint,
                                       group->controllers[j].mountPoint)) {
640 641 642 643 644
                        virReportSystemError(EINVAL,
                                             _("Controller '%s' is not wanted, but '%s' is co-mounted"),
                                             virCgroupControllerTypeToString(i),
                                             virCgroupControllerTypeToString(j));
                        return -1;
645 646 647 648 649 650 651 652
                    }
                }
                VIR_FREE(group->controllers[i].mountPoint);
            }
        }
    } else {
        VIR_DEBUG("Auto-detecting controllers");
        controllers = 0;
653
        for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
654 655 656 657 658 659 660
            VIR_DEBUG("Controller '%s' present=%s",
                      virCgroupControllerTypeToString(i),
                      group->controllers[i].mountPoint ? "yes" : "no");
            if (group->controllers[i].mountPoint == NULL)
                continue;
            controllers |= (1 << i);
        }
661
    }
662

663
    /* Check that at least 1 controller is available */
664
    if (!controllers) {
665 666 667
        virReportSystemError(ENXIO, "%s",
                             _("At least one cgroup controller is required"));
        return -1;
668
    }
669

670 671 672 673 674 675 676 677 678 679
    /* 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;
680

681 682 683 684
    /* Check that for every mounted controller, we found our placement */
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
        if (!group->controllers[i].mountPoint)
            continue;
685

686 687 688 689 690 691
        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;
692
        }
693

694
        VIR_DEBUG("Detected mount/mapping %zu:%s at %s in %s for pid %llu", i,
695 696
                  virCgroupControllerTypeToString(i),
                  group->controllers[i].mountPoint,
697 698
                  group->controllers[i].placement,
                  (unsigned long long)pid);
699 700
    }

701
    return 0;
702 703
}

704

E
Eric Blake 已提交
705 706 707 708 709
static int
virCgroupSetValueStr(virCgroupPtr group,
                     int controller,
                     const char *key,
                     const char *value)
710
{
711
    int ret = -1;
712
    char *keypath = NULL;
713
    char *tmp = NULL;
714

715 716
    if (virCgroupPathOfController(group, controller, key, &keypath) < 0)
        return -1;
717

718
    VIR_DEBUG("Set value '%s' to '%s'", keypath, value);
719
    if (virFileWriteStr(keypath, value, 0) < 0) {
720 721 722 723 724 725 726
        if (errno == EINVAL &&
            (tmp = strrchr(keypath, '/'))) {
            virReportSystemError(errno,
                                 _("Invalid value '%s' for '%s'"),
                                 value, tmp + 1);
            goto cleanup;
        }
727 728 729
        virReportSystemError(errno,
                             _("Unable to write to '%s'"), keypath);
        goto cleanup;
730 731
    }

732
    ret = 0;
733

734
 cleanup:
735 736
    VIR_FREE(keypath);
    return ret;
737 738
}

E
Eric Blake 已提交
739 740 741 742 743 744

static int
virCgroupGetValueStr(virCgroupPtr group,
                     int controller,
                     const char *key,
                     char **value)
745 746
{
    char *keypath = NULL;
747
    int ret = -1, rc;
748

749
    *value = NULL;
750

751 752
    if (virCgroupPathOfController(group, controller, key, &keypath) < 0)
        return -1;
753

754
    VIR_DEBUG("Get value %s", keypath);
755

756 757 758 759
    if ((rc = virFileReadAll(keypath, 1024*1024, value)) < 0) {
        virReportSystemError(errno,
                             _("Unable to read from '%s'"), keypath);
        goto cleanup;
760 761
    }

762 763 764
    /* Terminated with '\n' has sometimes harmful effects to the caller */
    if (rc > 0 && (*value)[rc - 1] == '\n')
        (*value)[rc - 1] = '\0';
765

766 767
    ret = 0;

768
 cleanup:
769 770
    VIR_FREE(keypath);
    return ret;
771 772
}

E
Eric Blake 已提交
773 774 775 776 777 778

static int
virCgroupSetValueU64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     unsigned long long int value)
779 780
{
    char *strval = NULL;
781
    int ret;
782

783 784
    if (virAsprintf(&strval, "%llu", value) < 0)
        return -1;
785

786
    ret = virCgroupSetValueStr(group, controller, key, strval);
787 788 789

    VIR_FREE(strval);

790
    return ret;
791 792 793
}


E
Eric Blake 已提交
794 795 796 797 798
static int
virCgroupSetValueI64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     long long int value)
799 800
{
    char *strval = NULL;
801
    int ret;
802

803 804
    if (virAsprintf(&strval, "%lld", value) < 0)
        return -1;
805

806
    ret = virCgroupSetValueStr(group, controller, key, strval);
807 808 809

    VIR_FREE(strval);

810
    return ret;
811 812
}

E
Eric Blake 已提交
813 814 815 816 817 818

static int
virCgroupGetValueI64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     long long int *value)
819 820
{
    char *strval = NULL;
821
    int ret = -1;
822

823 824
    if (virCgroupGetValueStr(group, controller, key, &strval) < 0)
        goto cleanup;
825

826 827 828 829 830 831
    if (virStrToLong_ll(strval, NULL, 10, value) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       strval);
        goto cleanup;
    }
832

833 834
    ret = 0;

835
 cleanup:
836 837
    VIR_FREE(strval);
    return ret;
838 839
}

E
Eric Blake 已提交
840 841 842 843 844 845

static int
virCgroupGetValueU64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     unsigned long long int *value)
846 847
{
    char *strval = NULL;
848
    int ret = -1;
849

850 851
    if (virCgroupGetValueStr(group, controller, key, &strval) < 0)
        goto cleanup;
852

853 854 855 856 857 858
    if (virStrToLong_ull(strval, NULL, 10, value) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       strval);
        goto cleanup;
    }
859

860 861
    ret = 0;

862
 cleanup:
863 864
    VIR_FREE(strval);
    return ret;
865 866 867
}


E
Eric Blake 已提交
868 869
static int
virCgroupCpuSetInherit(virCgroupPtr parent, virCgroupPtr group)
870
{
871
    size_t i;
872 873 874 875 876
    const char *inherit_values[] = {
        "cpuset.cpus",
        "cpuset.mems",
    };

877
    VIR_DEBUG("Setting up inheritance %s -> %s", parent->path, group->path);
878
    for (i = 0; i < ARRAY_CARDINALITY(inherit_values); i++) {
879
        char *value;
880

881 882 883 884
        if (virCgroupGetValueStr(parent,
                                 VIR_CGROUP_CONTROLLER_CPUSET,
                                 inherit_values[i],
                                 &value) < 0)
885
            return -1;
886 887 888

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

889 890 891 892 893
        if (virCgroupSetValueStr(group,
                                 VIR_CGROUP_CONTROLLER_CPUSET,
                                 inherit_values[i],
                                 value) < 0) {
            VIR_FREE(value);
894
            return -1;
895
        }
896
        VIR_FREE(value);
897 898
    }

899
    return 0;
900 901
}

E
Eric Blake 已提交
902 903 904

static int
virCgroupSetMemoryUseHierarchy(virCgroupPtr group)
905 906 907 908
{
    unsigned long long value;
    const char *filename = "memory.use_hierarchy";

909 910 911
    if (virCgroupGetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             filename, &value) < 0)
912
        return -1;
913 914 915 916 917 918

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

    VIR_DEBUG("Setting up %s/%s", group->path, filename);
919 920 921
    if (virCgroupSetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             filename, 1) < 0)
922
        return -1;
923

924
    return 0;
925 926
}

E
Eric Blake 已提交
927 928 929 930 931 932

static int
virCgroupMakeGroup(virCgroupPtr parent,
                   virCgroupPtr group,
                   bool create,
                   unsigned int flags)
933
{
934
    size_t i;
935
    int ret = -1;
936

937
    VIR_DEBUG("Make group %s", group->path);
938
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
939 940
        char *path = NULL;

941 942 943 944 945 946
        /* We must never mkdir() in systemd's hierarchy */
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD) {
            VIR_DEBUG("Not creating systemd controller group");
            continue;
        }

947
        /* Skip over controllers that aren't mounted */
948 949 950
        if (!group->controllers[i].mountPoint) {
            VIR_DEBUG("Skipping unmounted controller %s",
                      virCgroupControllerTypeToString(i));
951
            continue;
952
        }
953

954
        if (virCgroupPathOfController(group, i, "", &path) < 0)
955
            return -1;
956

957 958 959
        /* As of Feb 2011, clang can't see that the above function
         * call did not modify group. */
        sa_assert(group->controllers[i].mountPoint);
960

961
        VIR_DEBUG("Make controller %s", path);
962
        if (!virFileExists(path)) {
963 964
            if (!create ||
                mkdir(path, 0755) < 0) {
965 966 967 968
                if (errno == EEXIST) {
                    VIR_FREE(path);
                    continue;
                }
969 970 971 972 973
                /* 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) {
974
                    VIR_DEBUG("Ignoring mkdir failure with blkio controller. Kernel probably too old");
975 976 977 978
                    VIR_FREE(group->controllers[i].mountPoint);
                    VIR_FREE(path);
                    continue;
                } else {
979 980 981
                    virReportSystemError(errno,
                                         _("Failed to create controller %s for group"),
                                         virCgroupControllerTypeToString(i));
982
                    VIR_FREE(path);
983
                    goto cleanup;
984
                }
985
            }
986 987
            if (group->controllers[VIR_CGROUP_CONTROLLER_CPUSET].mountPoint != NULL &&
                (i == VIR_CGROUP_CONTROLLER_CPUSET ||
E
Eric Blake 已提交
988 989
                 STREQ(group->controllers[i].mountPoint,
                       group->controllers[VIR_CGROUP_CONTROLLER_CPUSET].mountPoint))) {
990
                if (virCgroupCpuSetInherit(parent, group) < 0) {
991
                    VIR_FREE(path);
992
                    goto cleanup;
993
                }
994
            }
995 996 997 998
            /*
             * Note that virCgroupSetMemoryUseHierarchy should always be
             * called prior to creating subcgroups and attaching tasks.
             */
999 1000
            if ((flags & VIR_CGROUP_MEM_HIERACHY) &&
                (group->controllers[VIR_CGROUP_CONTROLLER_MEMORY].mountPoint != NULL) &&
1001
                (i == VIR_CGROUP_CONTROLLER_MEMORY ||
E
Eric Blake 已提交
1002 1003
                 STREQ(group->controllers[i].mountPoint,
                       group->controllers[VIR_CGROUP_CONTROLLER_MEMORY].mountPoint))) {
1004
                if (virCgroupSetMemoryUseHierarchy(group) < 0) {
1005
                    VIR_FREE(path);
1006
                    goto cleanup;
1007 1008
                }
            }
1009 1010 1011 1012 1013
        }

        VIR_FREE(path);
    }

1014
    VIR_DEBUG("Done making controllers for group");
1015 1016
    ret = 0;

1017
 cleanup:
1018
    return ret;
1019 1020
}

1021

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
/**
 * 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.
 *
1036
 * Returns 0 on success, -1 on error
1037
 */
E
Eric Blake 已提交
1038 1039 1040 1041 1042 1043
static int
virCgroupNew(pid_t pid,
             const char *path,
             virCgroupPtr parent,
             int controllers,
             virCgroupPtr *group)
1044
{
1045 1046
    VIR_DEBUG("parent=%p path=%s controllers=%d",
              parent, path, controllers);
1047
    *group = NULL;
1048

1049 1050
    if (VIR_ALLOC((*group)) < 0)
        goto error;
1051

1052
    if (path[0] == '/' || !parent) {
1053 1054
        if (VIR_STRDUP((*group)->path, path) < 0)
            goto error;
1055 1056 1057 1058
    } else {
        if (virAsprintf(&(*group)->path, "%s%s%s",
                        parent->path,
                        STREQ(parent->path, "") ? "" : "/",
1059 1060
                        path) < 0)
            goto error;
1061 1062
    }

1063
    if (virCgroupDetect(*group, pid, controllers, path, parent) < 0)
1064
        goto error;
1065

1066 1067
    return 0;

1068
 error:
1069 1070
    virCgroupFree(group);
    *group = NULL;
1071

1072
    return -1;
1073
}
1074

1075

1076 1077 1078 1079 1080 1081
/**
 * virCgroupAddTask:
 *
 * @group: The cgroup to add a task to
 * @pid: The pid of the task to add
 *
1082
 * Returns: 0 on success, -1 on error
1083
 */
E
Eric Blake 已提交
1084 1085
int
virCgroupAddTask(virCgroupPtr group, pid_t pid)
1086
{
1087
    int ret = -1;
1088
    size_t i;
1089

1090
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
1091 1092 1093
        /* Skip over controllers not mounted */
        if (!group->controllers[i].mountPoint)
            continue;
1094

1095 1096 1097 1098
        /* We must never add tasks in systemd's hierarchy */
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD)
            continue;

E
Eric Blake 已提交
1099
        if (virCgroupSetValueU64(group, i, "tasks", pid) < 0)
1100
            goto cleanup;
1101 1102
    }

1103
    ret = 0;
1104
 cleanup:
1105
    return ret;
1106 1107
}

E
Eric Blake 已提交
1108

1109 1110 1111 1112 1113 1114 1115
/**
 * virCgroupAddTaskController:
 *
 * @group: The cgroup to add a task to
 * @pid: The pid of the task to add
 * @controller: The cgroup controller to be operated on
 *
1116
 * Returns: 0 on success or -1 on error
1117
 */
E
Eric Blake 已提交
1118 1119
int
virCgroupAddTaskController(virCgroupPtr group, pid_t pid, int controller)
1120
{
1121 1122 1123 1124 1125
    if (controller < 0 || controller >= VIR_CGROUP_CONTROLLER_LAST) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Controller %d out of range"), controller);
        return -1;
    }
1126

1127 1128 1129 1130 1131 1132
    if (!group->controllers[controller].mountPoint) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Controller '%s' not mounted"),
                       virCgroupControllerTypeToString(controller));
        return -1;
    }
1133 1134 1135 1136 1137 1138

    return virCgroupSetValueU64(group, controller, "tasks",
                                (unsigned long long)pid);
}


E
Eric Blake 已提交
1139 1140 1141 1142
static int
virCgroupAddTaskStrController(virCgroupPtr group,
                              const char *pidstr,
                              int controller)
1143 1144 1145 1146 1147 1148
{
    char *str = NULL, *cur = NULL, *next = NULL;
    unsigned long long p = 0;
    int rc = 0;
    char *endp;

1149 1150
    if (VIR_STRDUP(str, pidstr) < 0)
        return -1;
1151 1152 1153

    cur = str;
    while (*cur != '\0') {
1154 1155 1156
        if (virStrToLong_ull(cur, &endp, 10, &p) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot parse '%s' as an integer"), cur);
1157
            goto cleanup;
1158
        }
1159

1160 1161 1162 1163 1164 1165 1166 1167
        if (virCgroupAddTaskController(group, p, controller) < 0) {
            /* A thread that exits between when we first read the source
             * tasks and now is not fatal.  */
            if (virLastErrorIsSystemErrno(ESRCH))
                virResetLastError();
            else
                goto cleanup;
        }
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177

        next = strchr(cur, '\n');
        if (next) {
            cur = next + 1;
            *next = '\0';
        } else {
            break;
        }
    }

1178
 cleanup:
1179 1180 1181 1182
    VIR_FREE(str);
    return rc;
}

E
Eric Blake 已提交
1183

1184 1185 1186 1187 1188 1189
/**
 * virCgroupMoveTask:
 *
 * @src_group: The source cgroup where all tasks are removed from
 * @dest_group: The destination where all tasks are added to
 *
1190
 * Returns: 0 on success or -1 on failure
1191
 */
E
Eric Blake 已提交
1192 1193
int
virCgroupMoveTask(virCgroupPtr src_group, virCgroupPtr dest_group)
1194
{
1195
    int ret = -1;
1196
    char *content = NULL;
1197
    size_t i;
1198

1199
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
1200 1201 1202
        if (!src_group->controllers[i].mountPoint ||
            !dest_group->controllers[i].mountPoint)
            continue;
1203

1204 1205 1206 1207
        /* We must never move tasks in systemd's hierarchy */
        if (i == VIR_CGROUP_CONTROLLER_SYSTEMD)
            continue;

1208 1209 1210 1211 1212
        /* New threads are created in the same group as their parent;
         * but if a thread is created after we first read we aren't
         * aware that it needs to move.  Therefore, we must iterate
         * until content is empty.  */
        while (1) {
J
Ján Tomko 已提交
1213
            VIR_FREE(content);
1214 1215 1216
            if (virCgroupGetValueStr(src_group, i, "tasks", &content) < 0)
                return -1;

1217 1218
            if (!*content)
                break;
1219

1220
            if (virCgroupAddTaskStrController(dest_group, content, i) < 0)
1221 1222
                goto cleanup;
        }
1223
    }
1224

1225
    ret = 0;
1226
 cleanup:
1227
    VIR_FREE(content);
1228
    return ret;
1229
}
1230

1231

E
Eric Blake 已提交
1232 1233
static int
virCgroupSetPartitionSuffix(const char *path, char **res)
1234
{
1235
    char **tokens;
1236
    size_t i;
1237
    int ret = -1;
1238

1239
    if (!(tokens = virStringSplit(path, "/", 0)))
1240
        return ret;
1241

1242
    for (i = 0; tokens[i] != NULL; i++) {
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
        /* 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],
1258
                              strlen(tokens[i]) + strlen(".partition") + 1) < 0)
1259 1260 1261
                goto cleanup;
            strcat(tokens[i], ".partition");
        }
1262

1263
        if (virCgroupPartitionEscape(&(tokens[i])) < 0)
1264
            goto cleanup;
1265 1266
    }

1267
    if (!(*res = virStringJoin((const char **)tokens, "/")))
1268
        goto cleanup;
1269 1270

    ret = 0;
1271

1272
 cleanup:
1273 1274 1275 1276
    virStringFreeList(tokens);
    return ret;
}

E
Eric Blake 已提交
1277

1278 1279 1280 1281 1282 1283 1284 1285 1286
/**
 * 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
 * partition path identified by @name.
 *
1287
 * Returns 0 on success, -1 on failure
1288
 */
E
Eric Blake 已提交
1289 1290 1291 1292 1293
int
virCgroupNewPartition(const char *path,
                      bool create,
                      int controllers,
                      virCgroupPtr *group)
1294
{
1295
    int ret = -1;
1296 1297
    char *parentPath = NULL;
    virCgroupPtr parent = NULL;
1298
    char *newPath = NULL;
1299 1300 1301
    VIR_DEBUG("path=%s create=%d controllers=%x",
              path, create, controllers);

1302 1303 1304 1305 1306 1307
    if (path[0] != '/') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Partition path '%s' must start with '/'"),
                       path);
        return -1;
    }
1308

1309
    if (virCgroupSetPartitionSuffix(path, &newPath) < 0)
1310 1311
        goto cleanup;

1312
    if (virCgroupNew(-1, newPath, NULL, controllers, group) < 0)
1313 1314
        goto cleanup;

1315
    if (STRNEQ(newPath, "/")) {
1316
        char *tmp;
1317
        if (VIR_STRDUP(parentPath, newPath) < 0)
1318 1319 1320 1321 1322 1323
            goto cleanup;

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

1324
        if (virCgroupNew(-1, parentPath, NULL, controllers, &parent) < 0)
1325 1326
            goto cleanup;

1327
        if (virCgroupMakeGroup(parent, *group, create, VIR_CGROUP_NONE) < 0) {
1328 1329 1330 1331 1332
            virCgroupRemove(*group);
            goto cleanup;
        }
    }

1333
    ret = 0;
1334
 cleanup:
1335
    if (ret != 0)
1336 1337 1338
        virCgroupFree(group);
    virCgroupFree(&parent);
    VIR_FREE(parentPath);
1339
    VIR_FREE(newPath);
1340
    return ret;
1341 1342
}

1343

G
Gao feng 已提交
1344
/**
1345
* virCgroupNewSelf:
G
Gao feng 已提交
1346 1347 1348
*
* @group: Pointer to returned virCgroupPtr
*
1349 1350 1351
* Obtain a cgroup representing the config of the
* current process
*
1352
* Returns 0 on success, or -1 on error
G
Gao feng 已提交
1353
*/
E
Eric Blake 已提交
1354 1355
int
virCgroupNewSelf(virCgroupPtr *group)
G
Gao feng 已提交
1356
{
1357
    return virCgroupNewDetect(-1, -1, group);
G
Gao feng 已提交
1358
}
1359

1360

1361 1362 1363 1364 1365 1366 1367 1368
/**
 * virCgroupNewDomainPartition:
 *
 * @partition: partition holding the domain
 * @driver: name of the driver
 * @name: name of the domain
 * @group: Pointer to returned virCgroupPtr
 *
1369
 * Returns 0 on success, or -1 on error
1370
 */
E
Eric Blake 已提交
1371 1372 1373 1374 1375 1376
int
virCgroupNewDomainPartition(virCgroupPtr partition,
                            const char *driver,
                            const char *name,
                            bool create,
                            virCgroupPtr *group)
1377
{
1378
    int ret = -1;
1379
    char *grpname = NULL;
1380

1381
    if (virAsprintf(&grpname, "%s.libvirt-%s",
1382
                    name, driver) < 0)
1383
        goto cleanup;
1384

1385 1386
    if (virCgroupPartitionEscape(&grpname) < 0)
        goto cleanup;
1387

1388
    if (virCgroupNew(-1, grpname, partition, -1, group) < 0)
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
        goto cleanup;

    /*
     * 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 已提交
1401 1402
    if (virCgroupMakeGroup(partition, *group, create,
                           VIR_CGROUP_MEM_HIERACHY) < 0) {
1403 1404 1405
        virCgroupRemove(*group);
        virCgroupFree(group);
        goto cleanup;
1406 1407
    }

1408 1409
    ret = 0;

1410
 cleanup:
1411
    VIR_FREE(grpname);
1412
    return ret;
1413
}
1414

E
Eric Blake 已提交
1415

1416
/**
1417
 * virCgroupNewVcpu:
1418
 *
1419
 * @domain: group for the domain
1420
 * @vcpuid: id of the vcpu
1421
 * @create: true to create if not already existing
1422 1423
 * @group: Pointer to returned virCgroupPtr
 *
1424
 * Returns 0 on success, or -1 on error
1425
 */
E
Eric Blake 已提交
1426 1427 1428 1429 1430
int
virCgroupNewVcpu(virCgroupPtr domain,
                 int vcpuid,
                 bool create,
                 virCgroupPtr *group)
1431
{
1432 1433
    int ret = -1;
    char *name = NULL;
1434
    int controllers;
1435

1436
    if (virAsprintf(&name, "vcpu%d", vcpuid) < 0)
1437
        goto cleanup;
1438

1439 1440 1441 1442
    controllers = ((1 << VIR_CGROUP_CONTROLLER_CPU) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUACCT) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUSET));

1443
    if (virCgroupNew(-1, name, domain, controllers, group) < 0)
1444
        goto cleanup;
1445

1446 1447 1448 1449
    if (virCgroupMakeGroup(domain, *group, create, VIR_CGROUP_NONE) < 0) {
        virCgroupRemove(*group);
        virCgroupFree(group);
        goto cleanup;
1450 1451
    }

1452
    ret = 0;
1453
 cleanup:
1454 1455
    VIR_FREE(name);
    return ret;
1456 1457
}

E
Eric Blake 已提交
1458

1459
/**
1460
 * virCgroupNewEmulator:
1461
 *
1462 1463
 * @domain: group for the domain
 * @create: true to create if not already existing
1464 1465
 * @group: Pointer to returned virCgroupPtr
 *
1466
 * Returns: 0 on success or -1 on error
1467
 */
E
Eric Blake 已提交
1468 1469 1470 1471
int
virCgroupNewEmulator(virCgroupPtr domain,
                     bool create,
                     virCgroupPtr *group)
1472
{
1473
    int ret = -1;
1474
    int controllers;
1475

1476 1477 1478 1479
    controllers = ((1 << VIR_CGROUP_CONTROLLER_CPU) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUACCT) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUSET));

1480
    if (virCgroupNew(-1, "emulator", domain, controllers, group) < 0)
1481
        goto cleanup;
1482

1483 1484 1485 1486
    if (virCgroupMakeGroup(domain, *group, create, VIR_CGROUP_NONE) < 0) {
        virCgroupRemove(*group);
        virCgroupFree(group);
        goto cleanup;
1487 1488
    }

1489
    ret = 0;
1490
 cleanup:
1491
    return ret;
1492
}
1493

1494

E
Eric Blake 已提交
1495 1496 1497 1498
int
virCgroupNewDetect(pid_t pid,
                   int controllers,
                   virCgroupPtr *group)
1499
{
1500
    return virCgroupNew(pid, "", NULL, controllers, group);
1501 1502
}

E
Eric Blake 已提交
1503

1504 1505 1506
/*
 * Returns 0 on success (but @group may be NULL), -1 on fatal error
 */
E
Eric Blake 已提交
1507 1508 1509 1510 1511 1512 1513
int
virCgroupNewDetectMachine(const char *name,
                          const char *drivername,
                          pid_t pid,
                          const char *partition,
                          int controllers,
                          virCgroupPtr *group)
1514
{
1515
    if (virCgroupNewDetect(pid, controllers, group) < 0) {
1516 1517 1518 1519 1520
        if (virCgroupNewIgnoreError())
            return 0;
        return -1;
    }

E
Eric Blake 已提交
1521 1522
    if (!virCgroupValidateMachineGroup(*group, name, drivername, partition,
                                       true)) {
1523 1524
        VIR_DEBUG("Failed to validate machine name for '%s' driver '%s'",
                  name, drivername);
1525 1526 1527 1528 1529 1530 1531
        virCgroupFree(group);
        return 0;
    }

    return 0;
}

E
Eric Blake 已提交
1532

1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
/*
 * Returns 0 on success, -1 on fatal error, -2 on systemd not available
 */
static int
virCgroupNewMachineSystemd(const char *name,
                           const char *drivername,
                           bool privileged,
                           const unsigned char *uuid,
                           const char *rootdir,
                           pid_t pidleader,
                           bool isContainer,
                           const char *partition,
                           int controllers,
                           virCgroupPtr *group)
1547 1548
{
    int ret = -1;
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
    int rv;
    virCgroupPtr init, parent = NULL;
    char *path = NULL;
    char *offset;

    VIR_DEBUG("Trying to setup machine '%s' via systemd", name);
    if ((rv = virSystemdCreateMachine(name,
                                      drivername,
                                      privileged,
                                      uuid,
                                      rootdir,
                                      pidleader,
                                      isContainer,
                                      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;
1573

1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    path = init->controllers[VIR_CGROUP_CONTROLLER_SYSTEMD].placement;
    init->controllers[VIR_CGROUP_CONTROLLER_SYSTEMD].placement = NULL;
    virCgroupFree(&init);

    if (!path || STREQ(path, "/") || path[0] != '/') {
        VIR_DEBUG("Systemd didn't setup its controller");
        ret = -2;
        goto cleanup;
    }

    offset = path;

    if (virCgroupNew(pidleader,
                     "",
                     NULL,
                     controllers,
                     &parent) < 0)
        goto cleanup;


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

    if (virCgroupAddTask(*group, pidleader) < 0) {
        virErrorPtr saved = virSaveLastError();
        virCgroupRemove(*group);
        virCgroupFree(group);
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
    }

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

E
Eric Blake 已提交
1639

1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
static int
virCgroupNewMachineManual(const char *name,
                          const char *drivername,
                          pid_t pidleader,
                          const char *partition,
                          int controllers,
                          virCgroupPtr *group)
{
    virCgroupPtr parent = NULL;
    int ret = -1;

    VIR_DEBUG("Fallback to non-systemd setup");
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
    if (virCgroupNewPartition(partition,
                              STREQ(partition, "/machine"),
                              controllers,
                              &parent) < 0) {
        if (virCgroupNewIgnoreError())
            goto done;

        goto cleanup;
    }

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

    if (virCgroupAddTask(*group, pidleader) < 0) {
        virErrorPtr saved = virSaveLastError();
        virCgroupRemove(*group);
        virCgroupFree(group);
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
    }

1679
 done:
1680 1681
    ret = 0;

1682
 cleanup:
1683 1684 1685 1686
    virCgroupFree(&parent);
    return ret;
}

E
Eric Blake 已提交
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698

int
virCgroupNewMachine(const char *name,
                    const char *drivername,
                    bool privileged,
                    const unsigned char *uuid,
                    const char *rootdir,
                    pid_t pidleader,
                    bool isContainer,
                    const char *partition,
                    int controllers,
                    virCgroupPtr *group)
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
{
    int rv;

    *group = NULL;

    if ((rv = virCgroupNewMachineSystemd(name,
                                         drivername,
                                         privileged,
                                         uuid,
                                         rootdir,
                                         pidleader,
                                         isContainer,
                                         partition,
                                         controllers,
                                         group)) == 0)
        return 0;

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

    return virCgroupNewMachineManual(name,
                                     drivername,
                                     pidleader,
                                     partition,
                                     controllers,
                                     group);
}

E
Eric Blake 已提交
1727 1728 1729

bool
virCgroupNewIgnoreError(void)
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
{
    if (virLastErrorIsSystemErrno(ENXIO) ||
        virLastErrorIsSystemErrno(EPERM) ||
        virLastErrorIsSystemErrno(EACCES)) {
        virResetLastError();
        VIR_DEBUG("No cgroups present/configured/accessible, ignoring error");
        return true;
    }
    return false;
}

E
Eric Blake 已提交
1741

E
Eric Blake 已提交
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
/**
 * virCgroupFree:
 *
 * @group: The group structure to free
 */
void
virCgroupFree(virCgroupPtr *group)
{
    size_t i;

    if (*group == NULL)
        return;

    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
        VIR_FREE((*group)->controllers[i].mountPoint);
        VIR_FREE((*group)->controllers[i].linkPoint);
        VIR_FREE((*group)->controllers[i].placement);
    }

    VIR_FREE((*group)->path);
    VIR_FREE(*group);
}


/**
 * 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,
                          int controller,
                          const char *key,
                          char **path)
{
    if (controller == -1) {
        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, "/")) {
                controller = i;
                break;
            }
        }
    }
    if (controller == -1) {
        virReportSystemError(ENOSYS, "%s",
                             _("No controllers are mounted"));
        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;
}


1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
/**
 * 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;
    char *str1 = NULL, *str2 = NULL, *p1, *p2;
    size_t i;
    int ret = -1;

    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)
        goto cleanup;

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "blkio.throttle.io_serviced", &str2) < 0)
        goto cleanup;

    /* 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);
                goto cleanup;
            }

            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]);
                goto cleanup;
            }
            *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);
                goto cleanup;
            }

            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]);
                goto cleanup;
            }
            *requests_ptrs[i] += stats_val;
        }
    }

    ret = 0;

1938
 cleanup:
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
    VIR_FREE(str2);
    VIR_FREE(str1);
    return ret;
}


/**
 * 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)
{
    char *str1 = NULL, *str2 = NULL, *str3 = NULL, *p1, *p2;
    struct stat sb;
    size_t i;
    int ret = -1;

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

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

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

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "blkio.throttle.io_service_bytes", &str1) < 0)
        goto cleanup;

    if (virCgroupGetValueStr(group,
                             VIR_CGROUP_CONTROLLER_BLKIO,
                             "blkio.throttle.io_serviced", &str2) < 0)
        goto cleanup;

    if (virAsprintf(&str3, "%d:%d ", major(sb.st_rdev), minor(sb.st_rdev)) < 0)
        goto cleanup;

    if (!(p1 = strstr(str1, str3))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot find byte stats for block device '%s'"),
                       str3);
        goto cleanup;
    }

    if (!(p2 = strstr(str2, str3))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot find request stats for block device '%s'"),
                       str3);
        goto cleanup;
    }

    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);
            goto cleanup;
        }

        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]));
            goto cleanup;
        }

        if (!(p2 = strstr(p2, value_names[i]))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot find request %sstats for block device '%s'"),
                           value_names[i], str3);
            goto cleanup;
        }

        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]));
            goto cleanup;
        }
    }

    ret = 0;

2056
 cleanup:
2057 2058 2059 2060 2061 2062 2063
    VIR_FREE(str3);
    VIR_FREE(str2);
    VIR_FREE(str1);
    return ret;
}


2064 2065 2066 2067 2068 2069
/**
 * virCgroupSetBlkioWeight:
 *
 * @group: The cgroup to change io weight for
 * @weight: The Weight for this cgroup
 *
2070
 * Returns: 0 on success, -1 on error
2071
 */
E
Eric Blake 已提交
2072 2073
int
virCgroupSetBlkioWeight(virCgroupPtr group, unsigned int weight)
2074 2075 2076 2077 2078 2079 2080
{
    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "blkio.weight",
                                weight);
}

E
Eric Blake 已提交
2081

2082 2083 2084 2085 2086 2087
/**
 * virCgroupGetBlkioWeight:
 *
 * @group: The cgroup to get weight for
 * @Weight: Pointer to returned weight
 *
2088
 * Returns: 0 on success, -1 on error
2089
 */
E
Eric Blake 已提交
2090 2091
int
virCgroupGetBlkioWeight(virCgroupPtr group, unsigned int *weight)
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
{
    unsigned long long tmp;
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_BLKIO,
                               "blkio.weight", &tmp);
    if (ret == 0)
        *weight = tmp;
    return ret;
}

2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
/**
 * 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)
{
    char *str;
    struct stat sb;
    int ret;

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

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

    if (virAsprintf(&str, "%d:%d %u", major(sb.st_rdev),
                    minor(sb.st_rdev), riops) < 0)
        return -1;

    ret = virCgroupSetValueStr(group,
                               VIR_CGROUP_CONTROLLER_BLKIO,
                               "blkio.throttle.read_iops_device",
                               str);

    VIR_FREE(str);
    return ret;
}

E
Eric Blake 已提交
2147

2148
/**
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
 * 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)
{
    char *str;
    struct stat sb;
    int ret;

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

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

    if (virAsprintf(&str, "%d:%d %u", major(sb.st_rdev),
                    minor(sb.st_rdev), wiops) < 0)
        return -1;

    ret = virCgroupSetValueStr(group,
                               VIR_CGROUP_CONTROLLER_BLKIO,
                               "blkio.throttle.write_iops_device",
                               str);

    VIR_FREE(str);
    return ret;
}


/**
 * 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)
{
    char *str;
    struct stat sb;
    int ret;

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

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

    if (virAsprintf(&str, "%d:%d %llu", major(sb.st_rdev),
                    minor(sb.st_rdev), rbps) < 0)
        return -1;

    ret = virCgroupSetValueStr(group,
                               VIR_CGROUP_CONTROLLER_BLKIO,
                               "blkio.throttle.read_bps_device",
                               str);

    VIR_FREE(str);
    return ret;
}

/**
 * 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
2242
 *
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
 * Returns: 0 on success, -1 on error
 */
int
virCgroupSetBlkioDeviceWriteBps(virCgroupPtr group,
                                const char *path,
                                unsigned long long wbps)
{
    char *str;
    struct stat sb;
    int ret;

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

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

    if (virAsprintf(&str, "%d:%d %llu", major(sb.st_rdev),
                    minor(sb.st_rdev), wbps) < 0)
        return -1;

    ret = virCgroupSetValueStr(group,
                               VIR_CGROUP_CONTROLLER_BLKIO,
                               "blkio.throttle.write_bps_device",
                               str);

    VIR_FREE(str);
    return ret;
}


/**
 * virCgroupSetBlkioDeviceWeight:
 * @group: The cgroup to change block io setting for
 * @path: The path of device
2286 2287
 * @weight: The new device weight (100-1000),
 * (10-1000) after kernel 2.6.39, or 0 to clear
2288 2289 2290 2291
 *
 * device_weight is treated as a write-only parameter, so
 * there isn't a getter counterpart.
 *
2292
 * Returns: 0 on success, -1 on error
2293
 */
E
Eric Blake 已提交
2294 2295 2296 2297
int
virCgroupSetBlkioDeviceWeight(virCgroupPtr group,
                              const char *path,
                              unsigned int weight)
2298 2299 2300 2301 2302
{
    char *str;
    struct stat sb;
    int ret;

2303 2304 2305 2306 2307 2308
    if (stat(path, &sb) < 0) {
        virReportSystemError(errno,
                             _("Path '%s' is not accessible"),
                             path);
        return -1;
    }
2309

2310 2311 2312 2313 2314 2315
    if (!S_ISBLK(sb.st_mode)) {
        virReportSystemError(EINVAL,
                             _("Path '%s' must be a block device"),
                             path);
        return -1;
    }
2316 2317 2318

    if (virAsprintf(&str, "%d:%d %d", major(sb.st_rdev), minor(sb.st_rdev),
                    weight) < 0)
2319
        return -1;
2320 2321 2322 2323 2324 2325 2326 2327

    ret = virCgroupSetValueStr(group,
                               VIR_CGROUP_CONTROLLER_BLKIO,
                               "blkio.weight_device",
                               str);
    VIR_FREE(str);
    return ret;
}
2328

2329

2330 2331 2332 2333 2334 2335 2336 2337
/**
 * virCgroupSetMemory:
 *
 * @group: The cgroup to change memory for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2338 2339
int
virCgroupSetMemory(virCgroupPtr group, unsigned long long kb)
2340
{
2341 2342
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2343 2344 2345 2346 2347 2348 2349 2350
    if (kb > maxkb) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Memory '%llu' must be less than %llu"),
                       kb, maxkb);
        return -1;
    }

    if (kb == maxkb)
2351 2352 2353 2354 2355 2356 2357 2358 2359
        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);
2360 2361
}

E
Eric Blake 已提交
2362

R
Ryota Ozaki 已提交
2363 2364 2365 2366 2367 2368 2369 2370
/**
 * virCgroupGetMemoryUsage:
 *
 * @group: The cgroup to change memory for
 * @kb: Pointer to returned used memory in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2371 2372
int
virCgroupGetMemoryUsage(virCgroupPtr group, unsigned long *kb)
R
Ryota Ozaki 已提交
2373
{
C
Cole Robinson 已提交
2374
    long long unsigned int usage_in_bytes;
R
Ryota Ozaki 已提交
2375 2376 2377 2378 2379 2380 2381 2382 2383
    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 已提交
2384

2385 2386 2387 2388 2389 2390 2391 2392
/**
 * virCgroupSetMemoryHardLimit:
 *
 * @group: The cgroup to change memory hard limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2393 2394
int
virCgroupSetMemoryHardLimit(virCgroupPtr group, unsigned long long kb)
2395 2396 2397 2398
{
    return virCgroupSetMemory(group, kb);
}

E
Eric Blake 已提交
2399

2400 2401 2402 2403 2404 2405 2406 2407
/**
 * virCgroupGetMemoryHardLimit:
 *
 * @group: The cgroup to get the memory hard limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2408 2409
int
virCgroupGetMemoryHardLimit(virCgroupPtr group, unsigned long long *kb)
2410 2411
{
    long long unsigned int limit_in_bytes;
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
    int ret = -1;

    if (virCgroupGetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.limit_in_bytes", &limit_in_bytes) < 0)
        goto cleanup;

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

    ret = 0;
 cleanup:
2425 2426 2427
    return ret;
}

E
Eric Blake 已提交
2428

2429 2430 2431 2432 2433 2434 2435 2436
/**
 * virCgroupSetMemorySoftLimit:
 *
 * @group: The cgroup to change memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2437 2438
int
virCgroupSetMemorySoftLimit(virCgroupPtr group, unsigned long long kb)
2439
{
2440 2441
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2442 2443 2444 2445 2446 2447 2448 2449
    if (kb > maxkb) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Memory '%llu' must be less than %llu"),
                       kb, maxkb);
        return -1;
    }

    if (kb == maxkb)
2450 2451 2452 2453 2454 2455 2456 2457 2458
        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);
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
}


/**
 * virCgroupGetMemorySoftLimit:
 *
 * @group: The cgroup to get the memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2470 2471
int
virCgroupGetMemorySoftLimit(virCgroupPtr group, unsigned long long *kb)
2472 2473
{
    long long unsigned int limit_in_bytes;
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
    int ret = -1;

    if (virCgroupGetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.soft_limit_in_bytes", &limit_in_bytes) < 0)
        goto cleanup;

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

    ret = 0;
 cleanup:
2487 2488 2489
    return ret;
}

E
Eric Blake 已提交
2490

2491
/**
2492
 * virCgroupSetMemSwapHardLimit:
2493
 *
2494 2495
 * @group: The cgroup to change mem+swap hard limit for
 * @kb: The mem+swap amount in kilobytes
2496 2497 2498
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2499 2500
int
virCgroupSetMemSwapHardLimit(virCgroupPtr group, unsigned long long kb)
2501
{
2502 2503
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

2504 2505 2506 2507 2508 2509 2510 2511
    if (kb > maxkb) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Memory '%llu' must be less than %llu"),
                       kb, maxkb);
        return -1;
    }

    if (kb == maxkb)
2512 2513 2514 2515 2516 2517 2518 2519 2520
        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);
2521 2522
}

E
Eric Blake 已提交
2523

2524
/**
2525
 * virCgroupGetMemSwapHardLimit:
2526
 *
2527 2528
 * @group: The cgroup to get mem+swap hard limit for
 * @kb: The mem+swap amount in kilobytes
2529 2530 2531
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2532 2533
int
virCgroupGetMemSwapHardLimit(virCgroupPtr group, unsigned long long *kb)
2534 2535
{
    long long unsigned int limit_in_bytes;
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
    int ret = -1;

    if (virCgroupGetValueU64(group,
                             VIR_CGROUP_CONTROLLER_MEMORY,
                             "memory.memsw.limit_in_bytes", &limit_in_bytes) < 0)
        goto cleanup;

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

    ret = 0;
 cleanup:
2549 2550 2551
    return ret;
}

E
Eric Blake 已提交
2552

G
Gao feng 已提交
2553 2554 2555 2556 2557 2558 2559 2560
/**
 * virCgroupGetMemSwapUsage:
 *
 * @group: The cgroup to get mem+swap usage for
 * @kb: The mem+swap amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2561 2562
int
virCgroupGetMemSwapUsage(virCgroupPtr group, unsigned long long *kb)
G
Gao feng 已提交
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
{
    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 已提交
2574

2575 2576 2577 2578 2579 2580 2581 2582
/**
 * virCgroupSetCpusetMems:
 *
 * @group: The cgroup to set cpuset.mems for
 * @mems: the numa nodes to set
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2583 2584
int
virCgroupSetCpusetMems(virCgroupPtr group, const char *mems)
2585 2586 2587 2588 2589 2590 2591
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.mems",
                                mems);
}

E
Eric Blake 已提交
2592

2593 2594 2595 2596 2597 2598 2599 2600
/**
 * virCgroupGetCpusetMems:
 *
 * @group: The cgroup to get cpuset.mems for
 * @mems: the numa nodes to get
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2601 2602
int
virCgroupGetCpusetMems(virCgroupPtr group, char **mems)
2603 2604 2605 2606 2607 2608 2609
{
    return virCgroupGetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.mems",
                                mems);
}

E
Eric Blake 已提交
2610

2611 2612 2613 2614 2615 2616 2617 2618
/**
 * virCgroupSetCpusetCpus:
 *
 * @group: The cgroup to set cpuset.cpus for
 * @cpus: the cpus to set
 *
 * Retuens: 0 on success
 */
E
Eric Blake 已提交
2619 2620
int
virCgroupSetCpusetCpus(virCgroupPtr group, const char *cpus)
2621 2622 2623 2624 2625 2626 2627
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.cpus",
                                cpus);
}

E
Eric Blake 已提交
2628

2629 2630 2631 2632 2633 2634 2635 2636
/**
 * virCgroupGetCpusetCpus:
 *
 * @group: The cgroup to get cpuset.cpus for
 * @cpus: the cpus to get
 *
 * Retuens: 0 on success
 */
E
Eric Blake 已提交
2637 2638
int
virCgroupGetCpusetCpus(virCgroupPtr group, char **cpus)
2639 2640 2641 2642 2643 2644 2645
{
    return virCgroupGetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.cpus",
                                cpus);
}

E
Eric Blake 已提交
2646

2647 2648 2649
/**
 * virCgroupDenyAllDevices:
 *
2650
 * @group: The cgroup to deny all permissions, for all devices
2651 2652 2653
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2654 2655
int
virCgroupDenyAllDevices(virCgroupPtr group)
2656 2657
{
    return virCgroupSetValueStr(group,
2658 2659 2660
                                VIR_CGROUP_CONTROLLER_DEVICES,
                                "devices.deny",
                                "a");
2661 2662
}

2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
/**
 * 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 已提交
2694

2695 2696 2697 2698 2699
/**
 * virCgroupAllowDevice:
 *
 * @group: The cgroup to allow a device for
 * @type: The device type (i.e., 'c' or 'b')
2700 2701
 * @major: The major number of the device, a negative value means '*'
 * @minor: The minor number of the device, a negative value means '*'
2702
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
2703 2704 2705
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2706 2707 2708
int
virCgroupAllowDevice(virCgroupPtr group, char type, int major, int minor,
                     int perms)
2709
{
2710
    int ret = -1;
2711
    char *devstr = NULL;
2712 2713
    char *majorstr = NULL;
    char *minorstr = NULL;
2714

2715 2716 2717 2718 2719 2720 2721 2722 2723
    if ((major < 0 && VIR_STRDUP(majorstr, "*") < 0) ||
            virAsprintf(&majorstr, "%i", major) < 0)
        goto cleanup;

    if ((minor < 0 && VIR_STRDUP(minorstr, "*") < 0) ||
            virAsprintf(&minorstr, "%i", minor) < 0)
        goto cleanup;

    if (virAsprintf(&devstr, "%c %s:%s %s", type, majorstr, minorstr,
2724
                    virCgroupGetDevicePermsString(perms)) < 0)
2725
        goto cleanup;
2726

2727 2728 2729 2730 2731
    if (virCgroupSetValueStr(group,
                             VIR_CGROUP_CONTROLLER_DEVICES,
                             "devices.allow",
                             devstr) < 0)
        goto cleanup;
2732

2733 2734
    ret = 0;

2735
 cleanup:
2736
    VIR_FREE(devstr);
2737 2738
    VIR_FREE(majorstr);
    VIR_FREE(minorstr);
2739
    return ret;
2740
}
2741

E
Eric Blake 已提交
2742

2743 2744 2745 2746 2747 2748
/**
 * virCgroupAllowDeviceMajor:
 *
 * @group: The cgroup to allow an entire device major type for
 * @type: The device type (i.e., 'c' or 'b')
 * @major: The major number of the device type
2749
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
2750 2751 2752
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2753 2754 2755
int
virCgroupAllowDeviceMajor(virCgroupPtr group, char type, int major,
                          int perms)
2756
{
2757
    int ret = -1;
2758 2759
    char *devstr = NULL;

2760 2761
    if (virAsprintf(&devstr, "%c %i:* %s", type, major,
                    virCgroupGetDevicePermsString(perms)) < 0)
2762
        goto cleanup;
2763

2764 2765 2766 2767 2768
    if (virCgroupSetValueStr(group,
                             VIR_CGROUP_CONTROLLER_DEVICES,
                             "devices.allow",
                             devstr) < 0)
        goto cleanup;
2769

2770 2771
    ret = 0;

2772
 cleanup:
2773 2774
    VIR_FREE(devstr);
    return ret;
2775 2776
}

E
Eric Blake 已提交
2777

2778 2779 2780 2781 2782
/**
 * virCgroupAllowDevicePath:
 *
 * @group: The cgroup to allow the device for
 * @path: the device to allow
2783
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
2784 2785 2786 2787
 *
 * Queries the type of device and its major/minor number, and
 * adds that to the cgroup ACL
 *
2788
 * Returns: 0 on success, 1 if path exists but is not a device, or
2789
 * -1 on error
2790
 */
E
Eric Blake 已提交
2791 2792
int
virCgroupAllowDevicePath(virCgroupPtr group, const char *path, int perms)
2793 2794 2795
{
    struct stat sb;

2796 2797 2798 2799 2800 2801
    if (stat(path, &sb) < 0) {
        virReportSystemError(errno,
                             _("Path '%s' is not accessible"),
                             path);
        return -1;
    }
2802 2803

    if (!S_ISCHR(sb.st_mode) && !S_ISBLK(sb.st_mode))
2804
        return 1;
2805 2806 2807 2808

    return virCgroupAllowDevice(group,
                                S_ISCHR(sb.st_mode) ? 'c' : 'b',
                                major(sb.st_rdev),
2809 2810
                                minor(sb.st_rdev),
                                perms);
2811
}
D
Daniel P. Berrange 已提交
2812

2813 2814 2815 2816 2817 2818 2819 2820

/**
 * virCgroupDenyDevice:
 *
 * @group: The cgroup to deny a device for
 * @type: The device type (i.e., 'c' or 'b')
 * @major: The major number of the device
 * @minor: The minor number of the device
2821
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to deny
2822 2823 2824
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2825 2826 2827
int
virCgroupDenyDevice(virCgroupPtr group, char type, int major, int minor,
                    int perms)
2828
{
2829
    int ret = -1;
2830 2831
    char *devstr = NULL;

2832 2833
    if (virAsprintf(&devstr, "%c %i:%i %s", type, major, minor,
                    virCgroupGetDevicePermsString(perms)) < 0)
2834
        goto cleanup;
2835

2836 2837 2838 2839 2840
    if (virCgroupSetValueStr(group,
                             VIR_CGROUP_CONTROLLER_DEVICES,
                             "devices.deny",
                             devstr) < 0)
        goto cleanup;
2841

2842 2843
    ret = 0;

2844
 cleanup:
2845 2846
    VIR_FREE(devstr);
    return ret;
2847 2848
}

E
Eric Blake 已提交
2849

2850 2851 2852 2853 2854 2855
/**
 * virCgroupDenyDeviceMajor:
 *
 * @group: The cgroup to deny an entire device major type for
 * @type: The device type (i.e., 'c' or 'b')
 * @major: The major number of the device type
2856
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to deny
2857 2858 2859
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
2860 2861 2862
int
virCgroupDenyDeviceMajor(virCgroupPtr group, char type, int major,
                         int perms)
2863
{
2864
    int ret = -1;
2865 2866
    char *devstr = NULL;

2867 2868
    if (virAsprintf(&devstr, "%c %i:* %s", type, major,
                    virCgroupGetDevicePermsString(perms)) < 0)
2869
        goto cleanup;
2870

2871 2872 2873 2874 2875
    if (virCgroupSetValueStr(group,
                             VIR_CGROUP_CONTROLLER_DEVICES,
                             "devices.deny",
                             devstr) < 0)
        goto cleanup;
2876

2877 2878
    ret = 0;

2879
 cleanup:
2880 2881
    VIR_FREE(devstr);
    return ret;
2882 2883
}

E
Eric Blake 已提交
2884 2885 2886

int
virCgroupDenyDevicePath(virCgroupPtr group, const char *path, int perms)
2887 2888 2889
{
    struct stat sb;

2890 2891 2892 2893 2894 2895
    if (stat(path, &sb) < 0) {
        virReportSystemError(errno,
                             _("Path '%s' is not accessible"),
                             path);
        return -1;
    }
2896 2897

    if (!S_ISCHR(sb.st_mode) && !S_ISBLK(sb.st_mode))
2898
        return 1;
2899 2900 2901 2902

    return virCgroupDenyDevice(group,
                               S_ISCHR(sb.st_mode) ? 'c' : 'b',
                               major(sb.st_rdev),
2903 2904
                               minor(sb.st_rdev),
                               perms);
2905 2906
}

E
Eric Blake 已提交
2907

2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
/* 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,
                          unsigned int nvcpupids,
                          unsigned long long *sum_cpu_time,
                          unsigned int num)
{
    int ret = -1;
    size_t i;
    char *buf = NULL;
    virCgroupPtr group_vcpu = NULL;

    for (i = 0; i < nvcpupids; i++) {
        char *pos;
        unsigned long long tmp;
        size_t j;

        if (virCgroupNewVcpu(group, i, false, &group_vcpu) < 0)
            goto cleanup;

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

        pos = buf;
        for (j = 0; j < num; j++) {
            if (virStrToLong_ull(pos, &pos, 10, &tmp) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cpuacct parse error"));
                goto cleanup;
            }
            sum_cpu_time[j] += tmp;
        }

        virCgroupFree(&group_vcpu);
        VIR_FREE(buf);
    }

    ret = 0;
 cleanup:
    virCgroupFree(&group_vcpu);
    VIR_FREE(buf);
    return ret;
}


2966 2967 2968 2969 2970
int
virCgroupGetPercpuStats(virCgroupPtr group,
                        virTypedParameterPtr params,
                        unsigned int nparams,
                        int start_cpu,
2971 2972
                        unsigned int ncpus,
                        unsigned int nvcpupids)
2973 2974 2975
{
    int rv = -1;
    size_t i;
2976
    int need_cpus, total_cpus;
2977 2978
    char *pos;
    char *buf = NULL;
2979
    unsigned long long *sum_cpu_time = NULL;
2980 2981 2982 2983 2984
    virTypedParameterPtr ent;
    int param_idx;
    unsigned long long cpu_time;

    /* return the number of supported params */
2985 2986 2987 2988 2989 2990
    if (nparams == 0 && ncpus != 0) {
        if (nvcpupids == 0)
            return CGROUP_NB_PER_CPU_STAT_PARAM;
        else
            return CGROUP_NB_PER_CPU_STAT_PARAM + 1;
    }
2991 2992

    /* To parse account file, we need to know how many cpus are present.  */
J
Ján Tomko 已提交
2993
    if ((total_cpus = nodeGetCPUCount()) < 0)
2994 2995
        return rv;

J
Ján Tomko 已提交
2996 2997
    if (ncpus == 0)
        return total_cpus;
2998

2999
    if (start_cpu >= total_cpus) {
3000 3001
        virReportError(VIR_ERR_INVALID_ARG,
                       _("start_cpu %d larger than maximum of %d"),
3002
                       start_cpu, total_cpus - 1);
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
        goto cleanup;
    }

    /* we get percpu cputime accounting info. */
    if (virCgroupGetCpuacctPercpuUsage(group, &buf))
        goto cleanup;
    pos = buf;

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

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

J
Ján Tomko 已提交
3017
    for (i = 0; i < need_cpus; i++) {
3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
        if (virStrToLong_ull(pos, &pos, 10, &cpu_time) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cpuacct parse error"));
            goto cleanup;
        }
        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)
            goto cleanup;
    }

3031 3032 3033 3034 3035
    if (nvcpupids == 0 || param_idx + 1 >= nparams)
        goto success;
    /* return percpu vcputime in index 1 */
    param_idx++;

J
Ján Tomko 已提交
3036
    if (VIR_ALLOC_N(sum_cpu_time, need_cpus) < 0)
3037
        goto cleanup;
J
Ján Tomko 已提交
3038
    if (virCgroupGetPercpuVcpuSum(group, nvcpupids, sum_cpu_time, need_cpus) < 0)
3039 3040
        goto cleanup;

J
Ján Tomko 已提交
3041
    for (i = start_cpu; i < need_cpus; i++) {
3042 3043 3044 3045
        if (virTypedParameterAssign(&params[(i - start_cpu) * nparams +
                                            param_idx],
                                    VIR_DOMAIN_CPU_STATS_VCPUTIME,
                                    VIR_TYPED_PARAM_ULLONG,
J
Ján Tomko 已提交
3046
                                    sum_cpu_time[i]) < 0)
3047 3048 3049 3050
            goto cleanup;
    }

 success:
3051
    rv = param_idx + 1;
3052

3053
 cleanup:
3054
    VIR_FREE(sum_cpu_time);
3055 3056 3057 3058
    VIR_FREE(buf);
    return rv;
}

3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108

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 已提交
3109 3110
int
virCgroupSetCpuShares(virCgroupPtr group, unsigned long long shares)
3111
{
3112 3113
    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
D
Daniel P. Berrange 已提交
3114
                                "cpu.shares", shares);
3115 3116
}

E
Eric Blake 已提交
3117 3118 3119

int
virCgroupGetCpuShares(virCgroupPtr group, unsigned long long *shares)
3120
{
3121 3122
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
D
Daniel P. Berrange 已提交
3123
                                "cpu.shares", shares);
3124
}
3125

E
Eric Blake 已提交
3126

3127 3128 3129 3130 3131 3132 3133 3134
/**
 * 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 已提交
3135 3136
int
virCgroupSetCpuCfsPeriod(virCgroupPtr group, unsigned long long cfs_period)
3137
{
3138
    /* The cfs_period should be greater or equal than 1ms, and less or equal
3139 3140
     * than 1s.
     */
3141 3142 3143 3144 3145 3146
    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;
    }
3147 3148 3149 3150 3151 3152

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

E
Eric Blake 已提交
3153

3154 3155 3156 3157 3158 3159 3160 3161
/**
 * 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 已提交
3162 3163
int
virCgroupGetCpuCfsPeriod(virCgroupPtr group, unsigned long long *cfs_period)
3164 3165 3166 3167 3168 3169
{
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.cfs_period_us", cfs_period);
}

E
Eric Blake 已提交
3170

3171 3172 3173 3174 3175 3176 3177 3178 3179
/**
 * 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 已提交
3180 3181
int
virCgroupSetCpuCfsQuota(virCgroupPtr group, long long cfs_quota)
3182
{
3183 3184 3185 3186 3187 3188 3189 3190
    /* 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;
3191 3192 3193 3194 3195 3196 3197
    }

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

E
Eric Blake 已提交
3198 3199 3200

int
virCgroupGetCpuacctPercpuUsage(virCgroupPtr group, char **usage)
3201 3202 3203 3204 3205
{
    return virCgroupGetValueStr(group, VIR_CGROUP_CONTROLLER_CPUACCT,
                                "cpuacct.usage_percpu", usage);
}

E
Eric Blake 已提交
3206

E
Eric Blake 已提交
3207 3208 3209 3210 3211 3212
int
virCgroupRemoveRecursively(char *grppath)
{
    DIR *grpdir;
    struct dirent *ent;
    int rc = 0;
E
Eric Blake 已提交
3213
    int direrr;
E
Eric Blake 已提交
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223

    grpdir = opendir(grppath);
    if (grpdir == NULL) {
        if (errno == ENOENT)
            return 0;
        rc = -errno;
        VIR_ERROR(_("Unable to open %s (%d)"), grppath, errno);
        return rc;
    }

E
Eric Blake 已提交
3224 3225 3226
    /* 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) {
E
Eric Blake 已提交
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
        char *path;

        if (ent->d_name[0] == '.') continue;
        if (ent->d_type != DT_DIR) continue;

        if (virAsprintf(&path, "%s/%s", grppath, ent->d_name) == -1) {
            rc = -ENOMEM;
            break;
        }
        rc = virCgroupRemoveRecursively(path);
        VIR_FREE(path);
        if (rc != 0)
            break;
    }
E
Eric Blake 已提交
3241 3242 3243 3244 3245
    if (direrr < 0) {
        rc = -errno;
        VIR_ERROR(_("Failed to readdir for %s (%d)"), grppath, errno);
    }

E
Eric Blake 已提交
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 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307
    closedir(grpdir);

    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;
    char *grppath = NULL;

    VIR_DEBUG("Removing cgroup %s", group->path);
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
        /* 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_FREE(grppath);
    }
    VIR_DEBUG("Done removing cgroup %s", group->path);

    return rc;
}


3308 3309 3310
/*
 * Returns 1 if some PIDs are killed, 0 if none are killed, or -1 on error
 */
E
Eric Blake 已提交
3311 3312
static int
virCgroupKillInternal(virCgroupPtr group, int signum, virHashTablePtr pids)
3313
{
3314
    int ret = -1;
3315
    bool killedAny = false;
3316 3317
    char *keypath = NULL;
    bool done = false;
E
Eric Blake 已提交
3318 3319 3320
    FILE *fp = NULL;
    VIR_DEBUG("group=%p path=%s signum=%d pids=%p",
              group, group->path, signum, pids);
3321

3322
    if (virCgroupPathOfController(group, -1, "tasks", &keypath) < 0)
3323
        return -1;
3324 3325 3326 3327 3328 3329 3330

    /* 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"))) {
3331 3332 3333 3334 3335 3336
            if (errno == ENOENT) {
                VIR_DEBUG("No file %s, assuming done", keypath);
                killedAny = false;
                goto done;
            }

3337 3338 3339
            virReportSystemError(errno,
                                 _("Failed to read %s"),
                                 keypath);
3340 3341 3342
            goto cleanup;
        } else {
            while (!feof(fp)) {
3343 3344
                unsigned long pid_value;
                if (fscanf(fp, "%lu", &pid_value) != 1) {
3345 3346
                    if (feof(fp))
                        break;
3347 3348 3349
                    virReportSystemError(errno,
                                         _("Failed to read %s"),
                                         keypath);
E
Eric Blake 已提交
3350
                    goto cleanup;
3351
                }
3352
                if (virHashLookup(pids, (void*)pid_value))
3353 3354
                    continue;

3355 3356 3357
                VIR_DEBUG("pid=%lu", pid_value);
                /* Cgroups is a Linux concept, so this cast is safe.  */
                if (kill((pid_t)pid_value, signum) < 0) {
3358
                    if (errno != ESRCH) {
3359 3360 3361
                        virReportSystemError(errno,
                                             _("Failed to kill process %lu"),
                                             pid_value);
3362 3363 3364 3365
                        goto cleanup;
                    }
                    /* Leave RC == 0 since we didn't kill one */
                } else {
3366
                    killedAny = true;
3367 3368 3369
                    done = false;
                }

3370
                ignore_value(virHashAddEntry(pids, (void*)pid_value, (void*)1));
3371 3372 3373 3374 3375
            }
            VIR_FORCE_FCLOSE(fp);
        }
    }

3376
 done:
3377
    ret = killedAny ? 1 : 0;
3378

3379
 cleanup:
3380
    VIR_FREE(keypath);
E
Eric Blake 已提交
3381
    VIR_FORCE_FCLOSE(fp);
3382

3383
    return ret;
3384 3385 3386
}


E
Eric Blake 已提交
3387 3388
static uint32_t
virCgroupPidCode(const void *name, uint32_t seed)
3389
{
3390 3391
    unsigned long pid_value = (unsigned long)(intptr_t)name;
    return virHashCodeGen(&pid_value, sizeof(pid_value), seed);
3392
}
E
Eric Blake 已提交
3393 3394 3395 3396


static bool
virCgroupPidEqual(const void *namea, const void *nameb)
3397 3398 3399
{
    return namea == nameb;
}
E
Eric Blake 已提交
3400 3401 3402 3403


static void *
virCgroupPidCopy(const void *name)
3404 3405 3406 3407
{
    return (void*)name;
}

E
Eric Blake 已提交
3408

3409
/*
3410
 * Returns 1 if some PIDs are killed, 0 if none are killed, or -1 on error
3411
 */
E
Eric Blake 已提交
3412 3413
int
virCgroupKill(virCgroupPtr group, int signum)
3414 3415
{
    VIR_DEBUG("group=%p path=%s signum=%d", group, group->path, signum);
3416
    int ret;
3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427
    /* The 'tasks' file in cgroups can contain duplicated
     * pids, so we use a hash to track which we've already
     * killed.
     */
    virHashTablePtr pids = virHashCreateFull(100,
                                             NULL,
                                             virCgroupPidCode,
                                             virCgroupPidEqual,
                                             virCgroupPidCopy,
                                             NULL);

3428
    ret = virCgroupKillInternal(group, signum, pids);
3429 3430 3431

    virHashFree(pids);

3432
    return ret;
3433 3434 3435
}


E
Eric Blake 已提交
3436 3437 3438 3439 3440
static int
virCgroupKillRecursiveInternal(virCgroupPtr group,
                               int signum,
                               virHashTablePtr pids,
                               bool dormdir)
3441
{
3442
    int ret = -1;
3443
    int rc;
3444
    bool killedAny = false;
3445
    char *keypath = NULL;
3446
    DIR *dp = NULL;
3447 3448
    virCgroupPtr subgroup = NULL;
    struct dirent *ent;
E
Eric Blake 已提交
3449
    int direrr;
E
Eric Blake 已提交
3450 3451
    VIR_DEBUG("group=%p path=%s signum=%d pids=%p",
              group, group->path, signum, pids);
3452

3453
    if (virCgroupPathOfController(group, -1, "", &keypath) < 0)
3454
        return -1;
3455

3456
    if ((rc = virCgroupKillInternal(group, signum, pids)) < 0)
3457
        goto cleanup;
3458 3459
    if (rc == 1)
        killedAny = true;
3460

3461
    VIR_DEBUG("Iterate over children of %s (killedAny=%d)", keypath, killedAny);
3462
    if (!(dp = opendir(keypath))) {
3463 3464 3465 3466 3467
        if (errno == ENOENT) {
            VIR_DEBUG("Path %s does not exist, assuming done", keypath);
            killedAny = false;
            goto done;
        }
3468 3469
        virReportSystemError(errno,
                             _("Cannot open %s"), keypath);
3470
        goto cleanup;
3471 3472
    }

E
Eric Blake 已提交
3473
    while ((direrr = virDirRead(dp, &ent, keypath)) > 0) {
3474 3475 3476 3477 3478 3479 3480 3481 3482
        if (STREQ(ent->d_name, "."))
            continue;
        if (STREQ(ent->d_name, ".."))
            continue;
        if (ent->d_type != DT_DIR)
            continue;

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

3483
        if (virCgroupNew(-1, ent->d_name, group, -1, &subgroup) < 0)
3484 3485
            goto cleanup;

E
Eric Blake 已提交
3486 3487
        if ((rc = virCgroupKillRecursiveInternal(subgroup, signum, pids,
                                                 true)) < 0)
3488 3489
            goto cleanup;
        if (rc == 1)
3490
            killedAny = true;
3491 3492 3493 3494 3495 3496

        if (dormdir)
            virCgroupRemove(subgroup);

        virCgroupFree(&subgroup);
    }
E
Eric Blake 已提交
3497 3498
    if (direrr < 0)
        goto cleanup;
3499

3500
 done:
3501
    ret = killedAny ? 1 : 0;
3502

3503
 cleanup:
3504
    virCgroupFree(&subgroup);
3505 3506 3507
    VIR_FREE(keypath);
    if (dp)
        closedir(dp);
3508

3509
    return ret;
3510 3511
}

E
Eric Blake 已提交
3512 3513 3514

int
virCgroupKillRecursive(virCgroupPtr group, int signum)
3515
{
3516
    int ret;
3517 3518 3519 3520 3521 3522 3523 3524
    VIR_DEBUG("group=%p path=%s signum=%d", group, group->path, signum);
    virHashTablePtr pids = virHashCreateFull(100,
                                             NULL,
                                             virCgroupPidCode,
                                             virCgroupPidEqual,
                                             virCgroupPidCopy,
                                             NULL);

3525
    ret = virCgroupKillRecursiveInternal(group, signum, pids, false);
3526 3527 3528

    virHashFree(pids);

3529
    return ret;
3530 3531 3532
}


E
Eric Blake 已提交
3533 3534
int
virCgroupKillPainfully(virCgroupPtr group)
3535
{
3536
    size_t i;
3537
    int ret;
3538
    VIR_DEBUG("cgroup=%p path=%s", group, group->path);
3539
    for (i = 0; i < 15; i++) {
3540 3541 3542 3543 3544 3545
        int signum;
        if (i == 0)
            signum = SIGTERM;
        else if (i == 8)
            signum = SIGKILL;
        else
J
Ján Tomko 已提交
3546
            signum = 0; /* Just check for existence */
3547

3548 3549 3550 3551
        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)
3552 3553 3554 3555
            break;

        usleep(200 * 1000);
    }
3556 3557
    VIR_DEBUG("Complete %d", ret);
    return ret;
3558
}
3559

E
Eric Blake 已提交
3560 3561 3562

static char *
virCgroupIdentifyRoot(virCgroupPtr group)
3563 3564 3565 3566
{
    char *ret = NULL;
    size_t i;

3567
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
        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;
        }

3578 3579 3580
        if (VIR_STRNDUP(ret, group->controllers[i].mountPoint,
                        tmp - group->controllers[i].mountPoint) < 0)
            return NULL;
3581 3582 3583 3584 3585 3586 3587 3588 3589
        return ret;
    }

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


3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659
/**
 * 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)
{
    char *str;
    char *p;
    int ret = -1;
    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);
        goto cleanup;
    }
    if (!(p = STRSKIP(p, "\nsystem ")) ||
        virStrToLong_ull(p, NULL, 10, sys) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Cannot parse sys stat '%s'"),
                       p);
        goto cleanup;
    }
    /* 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"));
            goto cleanup;
        }
        scale = 1000000000.0 / ticks_per_sec;
    }
    *user *= scale;
    *sys *= scale;

    ret = 0;
3660
 cleanup:
3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
    VIR_FREE(str);
    return ret;
}


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 已提交
3684 3685 3686
int
virCgroupIsolateMount(virCgroupPtr group, const char *oldroot,
                      const char *mountopts)
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705
{
    int ret = -1;
    size_t i;
    char *opts = NULL;
    char *root = NULL;

    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);
        goto cleanup;
    }

    if (virAsprintf(&opts,
3706
                    "mode=755,size=65536%s", mountopts) < 0)
3707 3708 3709 3710 3711 3712 3713 3714 3715
        goto cleanup;

    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");
        goto cleanup;
    }

3716
    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
3717 3718 3719 3720 3721 3722 3723 3724
        if (!group->controllers[i].mountPoint)
            continue;

        if (!virFileExists(group->controllers[i].mountPoint)) {
            char *src;
            if (virAsprintf(&src, "%s%s%s",
                            oldroot,
                            group->controllers[i].mountPoint,
3725
                            group->controllers[i].placement) < 0)
3726 3727
                goto cleanup;

E
Eric Blake 已提交
3728 3729
            VIR_DEBUG("Create mount point '%s'",
                      group->controllers[i].mountPoint);
3730 3731 3732 3733 3734 3735 3736 3737
            if (virFileMakePath(group->controllers[i].mountPoint) < 0) {
                virReportSystemError(errno,
                                     _("Unable to create directory %s"),
                                     group->controllers[i].mountPoint);
                VIR_FREE(src);
                goto cleanup;
            }

E
Eric Blake 已提交
3738 3739
            if (mount(src, group->controllers[i].mountPoint, NULL, MS_BIND,
                      NULL) < 0) {
3740 3741 3742
                virReportSystemError(errno,
                                     _("Failed to bind cgroup '%s' on '%s'"),
                                     src, group->controllers[i].mountPoint);
3743
                VIR_FREE(src);
3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765
                goto cleanup;
            }

            VIR_FREE(src);
        }

        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);
                return -1;
            }
        }
    }
    ret = 0;

3766
 cleanup:
3767 3768 3769 3770
    VIR_FREE(root);
    VIR_FREE(opts);
    return ret;
}
3771 3772


3773 3774 3775 3776 3777 3778 3779 3780 3781
int virCgroupSetOwner(virCgroupPtr cgroup,
                      uid_t uid,
                      gid_t gid,
                      int controllers)
{
    int ret = -1;
    size_t i;
    char *base = NULL, *entry = NULL;
    DIR *dh = NULL;
E
Eric Blake 已提交
3782
    int direrr;
3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802

    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
        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;

        if (!(dh = opendir(base))) {
            virReportSystemError(errno,
                                 _("Unable to open dir '%s'"), base);
            goto cleanup;
        }

E
Eric Blake 已提交
3803
        while ((direrr = virDirRead(dh, &de, base)) > 0) {
3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819
            if (STREQ(de->d_name, ".") ||
                STREQ(de->d_name, ".."))
                continue;

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

            VIR_FREE(entry);
        }
E
Eric Blake 已提交
3820 3821
        if (direrr < 0)
            goto cleanup;
3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845

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

        VIR_FREE(base);
        closedir(dh);
        dh = NULL;
    }

    ret = 0;

 cleanup:
    if (dh)
        closedir(dh);
    VIR_FREE(entry);
    VIR_FREE(base);
    return ret;
}


3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
/**
 * 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)
{
    char *path = NULL;
    int ret = false;

    if (!cgroup)
        return false;

    if (virCgroupPathOfController(cgroup, VIR_CGROUP_CONTROLLER_CPU,
                                  "cpu.cfs_period_us", &path) < 0) {
        virResetLastError();
        goto cleanup;
    }

    ret = virFileExists(path);

3870
 cleanup:
3871 3872 3873 3874 3875
    VIR_FREE(path);
    return ret;
}


3876 3877
#else /* !VIR_CGROUP_SUPPORTED */

3878 3879 3880 3881 3882 3883 3884
bool
virCgroupAvailable(void)
{
    return false;
}


3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952
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;
}


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


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


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


3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
int
virCgroupNewDetectMachine(const char *name ATTRIBUTE_UNUSED,
                          const char *drivername ATTRIBUTE_UNUSED,
                          pid_t pid ATTRIBUTE_UNUSED,
                          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;
}

3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990
int
virCgroupNewMachine(const char *name ATTRIBUTE_UNUSED,
                    const char *drivername ATTRIBUTE_UNUSED,
                    bool privileged ATTRIBUTE_UNUSED,
                    const unsigned char *uuid ATTRIBUTE_UNUSED,
                    const char *rootdir ATTRIBUTE_UNUSED,
                    pid_t pidleader ATTRIBUTE_UNUSED,
                    bool isContainer ATTRIBUTE_UNUSED,
                    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;
}

3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007

void
virCgroupFree(virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
}


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


4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019
int
virCgroupPathOfController(virCgroupPtr group ATTRIBUTE_UNUSED,
                          int controller ATTRIBUTE_UNUSED,
                          const char *key ATTRIBUTE_UNUSED,
                          char **path ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
int
virCgroupAddTask(virCgroupPtr group ATTRIBUTE_UNUSED,
                 pid_t pid ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


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


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


4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077
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;
}


4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
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;
}


4098 4099 4100 4101 4102 4103 4104 4105 4106 4107
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;
}

4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147
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;
}

4148

4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 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 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277
int
virCgroupSetMemory(virCgroupPtr group ATTRIBUTE_UNUSED,
                   unsigned long long kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


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


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

4278 4279 4280 4281 4282 4283 4284 4285
int
virCgroupAllowAllDevices(virCgroupPtr group ATTRIBUTE_UNUSED,
                         int perms ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}
4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320

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


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


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


4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356
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;
}


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


4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367
int
virCgroupDenyDevicePath(virCgroupPtr group ATTRIBUTE_UNUSED,
                        const char *path ATTRIBUTE_UNUSED,
                        int perms ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 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
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;
}


4418 4419 4420 4421 4422 4423 4424 4425 4426
int
virCgroupRemoveRecursively(char *grppath ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


4427 4428 4429 4430 4431 4432 4433 4434 4435
int
virCgroupRemove(virCgroupPtr group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


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
int
virCgroupKill(virCgroupPtr group ATTRIBUTE_UNUSED,
              int signum ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


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


4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505
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;
}


4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516
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;
}


4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
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 已提交
4537 4538 4539 4540
int
virCgroupIsolateMount(virCgroupPtr group ATTRIBUTE_UNUSED,
                      const char *oldroot ATTRIBUTE_UNUSED,
                      const char *mountopts ATTRIBUTE_UNUSED)
4541
{
4542 4543 4544
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
4545
}
4546

4547 4548 4549 4550 4551 4552 4553 4554

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

E
Eric Blake 已提交
4555 4556 4557 4558 4559 4560

int
virCgroupGetPercpuStats(virCgroupPtr group ATTRIBUTE_UNUSED,
                        virTypedParameterPtr params ATTRIBUTE_UNUSED,
                        unsigned int nparams ATTRIBUTE_UNUSED,
                        int start_cpu ATTRIBUTE_UNUSED,
J
Ján Tomko 已提交
4561 4562
                        unsigned int ncpus ATTRIBUTE_UNUSED,
                        unsigned int nvcpupids ATTRIBUTE_UNUSED)
E
Eric Blake 已提交
4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580
{
    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;
}

4581
#endif /* !VIR_CGROUP_SUPPORTED */