vircgroup.c 88.3 KB
Newer Older
1
/*
2
 * vircgroup.c: methods for managing control cgroups
3
 *
4
 * Copyright (C) 2010-2015 Red Hat, Inc.
5 6
 * Copyright IBM Corp. 2008
 *
O
Osier Yang 已提交
7 8 9 10 11 12 13 14 15 16 17
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25
 *
 * Authors:
 *  Dan Smith <danms@us.ibm.com>
 */
#include <config.h>

26
#ifdef __linux__
27
# include <mntent.h>
28
# include <sys/mount.h>
29 30
# include <fcntl.h>
# include <sys/stat.h>
31

32 33 34 35 36
# ifdef MAJOR_IN_MKDEV
#  include <sys/mkdev.h>
# elif MAJOR_IN_SYSMACROS
#  include <sys/sysmacros.h>
# endif
37

38 39 40 41 42
# include <sys/types.h>
# include <signal.h>
# include <dirent.h>
# include <unistd.h>
#endif /* __linux__ */
43

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

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

61 62
VIR_LOG_INIT("util.cgroup");

63 64
#define VIR_FROM_THIS VIR_FROM_CGROUP

65
#define CGROUP_NB_TOTAL_CPU_STAT_PARAM 3
66
#define CGROUP_NB_PER_CPU_STAT_PARAM   1
67

68
VIR_ENUM_IMPL(virCgroupController, VIR_CGROUP_CONTROLLER_LAST,
R
Ryota Ozaki 已提交
69
              "cpu", "cpuacct", "cpuset", "memory", "devices",
70 71
              "freezer", "blkio", "net_cls", "perf_event",
              "name=systemd");
72

E
Eric Blake 已提交
73

74 75 76 77 78 79 80 81 82 83 84 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
/**
 * 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 "";
        }
    }
}


112
#ifdef __linux__
E
Eric Blake 已提交
113 114
bool
virCgroupAvailable(void)
115
{
116 117
    size_t i;
    virCgroupBackendPtr *backends = virCgroupBackendGetAll();
118

119
    if (!backends)
120 121
        return false;

122 123 124
    for (i = 0; i < VIR_CGROUP_BACKEND_TYPE_LAST; i++) {
        if (backends[i] && backends[i]->available())
            return true;
125 126
    }

127
    return false;
128 129
}

E
Eric Blake 已提交
130 131 132 133 134 135

static int
virCgroupPartitionNeedsEscaping(const char *path)
{
    FILE *fp = NULL;
    int ret = 0;
136
    VIR_AUTOFREE(char *) line = NULL;
E
Eric Blake 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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
    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;
    }

195
 cleanup:
E
Eric Blake 已提交
196 197 198 199 200
    VIR_FORCE_FCLOSE(fp);
    return ret;
}


201
int
E
Eric Blake 已提交
202 203 204
virCgroupPartitionEscape(char **path)
{
    int rc;
205
    char *newstr = NULL;
E
Eric Blake 已提交
206 207 208 209

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

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

213 214 215
    VIR_FREE(*path);
    *path = newstr;

E
Eric Blake 已提交
216 217
    return 0;
}
E
Eric Blake 已提交
218 219


220 221 222 223
/*
 * Process /proc/mounts figuring out what controllers are
 * mounted and where
 */
224
static int
225
virCgroupDetectMounts(virCgroupPtr group)
226
{
227
    FILE *mounts = NULL;
228 229
    struct mntent entry;
    char buf[CGROUP_MAX_VAL];
230
    int ret = -1;
231

232
    mounts = fopen("/proc/mounts", "r");
233
    if (mounts == NULL) {
234
        virReportSystemError(errno, "%s", _("Unable to open /proc/mounts"));
235
        return -1;
236 237 238
    }

    while (getmntent_r(mounts, &entry, buf, sizeof(buf)) != NULL) {
239 240 241 242 243
        if (group->backend->detectMounts(group,
                                         entry.mnt_type,
                                         entry.mnt_opts,
                                         entry.mnt_dir) < 0) {
            goto cleanup;
244
        }
245 246
    }

247 248
    ret = 0;
 cleanup:
249
    VIR_FORCE_FCLOSE(mounts);
250
    return ret;
251 252
}

253 254

/*
255 256 257 258
 * virCgroupDetectPlacement:
 * @group: the group to process
 * @path: the relative path to append, not starting with '/'
 *
259 260
 * Process /proc/self/cgroup figuring out what cgroup
 * sub-path the current process is assigned to. ie not
261 262 263 264 265 266 267 268 269 270 271 272 273 274
 * 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.
275
 */
E
Eric Blake 已提交
276 277 278 279
static int
virCgroupDetectPlacement(virCgroupPtr group,
                         pid_t pid,
                         const char *path)
280
{
281 282
    FILE *mapping  = NULL;
    char line[1024];
283
    int ret = -1;
284
    VIR_AUTOFREE(char *) procfile = NULL;
285

286
    VIR_DEBUG("Detecting placement for pid %lld path %s",
M
Michal Privoznik 已提交
287
              (long long) pid, path);
288 289 290 291
    if (pid == -1) {
        if (VIR_STRDUP(procfile, "/proc/self/cgroup") < 0)
            goto cleanup;
    } else {
M
Michal Privoznik 已提交
292 293
        if (virAsprintf(&procfile, "/proc/%lld/cgroup",
                        (long long) pid) < 0)
294 295 296 297
            goto cleanup;
    }

    mapping = fopen(procfile, "r");
298
    if (mapping == NULL) {
299 300 301 302
        virReportSystemError(errno,
                             _("Unable to open '%s'"),
                             procfile);
        goto cleanup;
303 304
    }

305 306
    while (fgets(line, sizeof(line), mapping) != NULL) {
        char *controllers = strchr(line, ':');
307 308
        char *selfpath = controllers ? strchr(controllers + 1, ':') : NULL;
        char *nl = selfpath ? strchr(selfpath, '\n') : NULL;
309

310
        if (!controllers || !selfpath)
311 312 313 314 315
            continue;

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

316
        *selfpath = '\0';
317
        controllers++;
318
        selfpath++;
319

320 321 322
        if (group->backend->detectPlacement(group, path, controllers,
                                            selfpath) < 0) {
            goto cleanup;
323 324 325
        }
    }

326
    ret = 0;
327

328
 cleanup:
329
    VIR_FORCE_FCLOSE(mapping);
330
    return ret;
331 332
}

E
Eric Blake 已提交
333

334 335 336 337 338 339 340 341
static int
virCgroupDetect(virCgroupPtr group,
                pid_t pid,
                int controllers,
                const char *path,
                virCgroupPtr parent)
{
    int rc;
342 343
    size_t i;
    virCgroupBackendPtr *backends = virCgroupBackendGetAll();
344 345 346 347

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

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    if (!backends)
        return -1;

    for (i = 0; i < VIR_CGROUP_BACKEND_TYPE_LAST; i++) {
        if (backends[i] && backends[i]->available()) {
            group->backend = backends[i];
            break;
        }
    }

    if (!group->backend) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no cgroup backend available"));
        return -1;
    }

364
    if (parent) {
365
        if (group->backend->copyMounts(group, parent) < 0)
366 367 368 369 370 371
            return -1;
    } else {
        if (virCgroupDetectMounts(group) < 0)
            return -1;
    }

372
    rc = group->backend->detectControllers(group, controllers);
373 374 375
    if (rc < 0)
        return -1;

376
    /* Check that at least 1 controller is available */
377
    if (rc == 0) {
378 379 380
        virReportSystemError(ENXIO, "%s",
                             _("At least one cgroup controller is required"));
        return -1;
381
    }
382

383 384 385 386
    /* In some cases we can copy part of the placement info
     * based on the parent cgroup...
     */
    if ((parent || path[0] == '/') &&
387
        group->backend->copyPlacement(group, path, parent) < 0)
388 389 390 391 392
        return -1;

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

394
    /* Check that for every mounted controller, we found our placement */
395
    if (group->backend->validatePlacement(group, pid) < 0)
396
        return -1;
397

398
    return 0;
399 400
}

401

402
char *
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
virCgroupGetBlockDevString(const char *path)
{
    char *ret = NULL;
    struct stat sb;

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

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

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

    return ret;
}


431
int
E
Eric Blake 已提交
432 433 434 435
virCgroupSetValueStr(virCgroupPtr group,
                     int controller,
                     const char *key,
                     const char *value)
436
{
437
    VIR_AUTOFREE(char *) keypath = NULL;
438
    char *tmp = NULL;
439

440 441
    if (virCgroupPathOfController(group, controller, key, &keypath) < 0)
        return -1;
442

443
    VIR_DEBUG("Set value '%s' to '%s'", keypath, value);
444
    if (virFileWriteStr(keypath, value, 0) < 0) {
445 446 447 448 449
        if (errno == EINVAL &&
            (tmp = strrchr(keypath, '/'))) {
            virReportSystemError(errno,
                                 _("Invalid value '%s' for '%s'"),
                                 value, tmp + 1);
450
            return -1;
451
        }
452 453
        virReportSystemError(errno,
                             _("Unable to write to '%s'"), keypath);
454
        return -1;
455 456
    }

457
    return 0;
458 459
}

E
Eric Blake 已提交
460

461
int
E
Eric Blake 已提交
462 463 464 465
virCgroupGetValueStr(virCgroupPtr group,
                     int controller,
                     const char *key,
                     char **value)
466
{
467 468
    VIR_AUTOFREE(char *) keypath = NULL;
    int rc;
469

470
    *value = NULL;
471

472 473
    if (virCgroupPathOfController(group, controller, key, &keypath) < 0)
        return -1;
474

475
    VIR_DEBUG("Get value %s", keypath);
476

477 478 479
    if ((rc = virFileReadAll(keypath, 1024*1024, value)) < 0) {
        virReportSystemError(errno,
                             _("Unable to read from '%s'"), keypath);
480
        return -1;
481 482
    }

483 484 485
    /* Terminated with '\n' has sometimes harmful effects to the caller */
    if (rc > 0 && (*value)[rc - 1] == '\n')
        (*value)[rc - 1] = '\0';
486

487
    return 0;
488 489
}

E
Eric Blake 已提交
490

491
int
492 493 494 495 496 497
virCgroupGetValueForBlkDev(virCgroupPtr group,
                           int controller,
                           const char *key,
                           const char *path,
                           char **value)
{
498 499
    VIR_AUTOFREE(char *) prefix = NULL;
    VIR_AUTOFREE(char *) str = NULL;
500 501
    char **lines = NULL;
    int ret = -1;
502 503

    if (virCgroupGetValueStr(group, controller, key, &str) < 0)
504
        goto error;
505 506

    if (!(prefix = virCgroupGetBlockDevString(path)))
507
        goto error;
508 509

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

512
    if (VIR_STRDUP(*value, virStringListGetFirstWithPrefix(lines, prefix)) < 0)
513
        goto error;
514

515 516 517 518
    ret = 0;
 error:
    virStringListFree(lines);
    return ret;
519 520 521
}


522
int
E
Eric Blake 已提交
523 524 525 526
virCgroupSetValueU64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     unsigned long long int value)
527
{
528
    VIR_AUTOFREE(char *) strval = NULL;
529

530 531
    if (virAsprintf(&strval, "%llu", value) < 0)
        return -1;
532

533
    return virCgroupSetValueStr(group, controller, key, strval);
534 535 536
}


537
int
E
Eric Blake 已提交
538 539 540 541
virCgroupSetValueI64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     long long int value)
542
{
543
    VIR_AUTOFREE(char *) strval = NULL;
544

545 546
    if (virAsprintf(&strval, "%lld", value) < 0)
        return -1;
547

548
    return virCgroupSetValueStr(group, controller, key, strval);
549 550
}

E
Eric Blake 已提交
551

552
int
E
Eric Blake 已提交
553 554 555 556
virCgroupGetValueI64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     long long int *value)
557
{
558
    VIR_AUTOFREE(char *) strval = NULL;
559

560
    if (virCgroupGetValueStr(group, controller, key, &strval) < 0)
561
        return -1;
562

563 564 565 566
    if (virStrToLong_ll(strval, NULL, 10, value) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       strval);
567
        return -1;
568
    }
569

570
    return 0;
571 572
}

E
Eric Blake 已提交
573

574
int
E
Eric Blake 已提交
575 576 577 578
virCgroupGetValueU64(virCgroupPtr group,
                     int controller,
                     const char *key,
                     unsigned long long int *value)
579
{
580
    VIR_AUTOFREE(char *) strval = NULL;
581

582
    if (virCgroupGetValueStr(group, controller, key, &strval) < 0)
583
        return -1;
584

585 586 587 588
    if (virStrToLong_ull(strval, NULL, 10, value) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to parse '%s' as an integer"),
                       strval);
589
        return -1;
590
    }
591

592
    return 0;
593 594 595
}


E
Eric Blake 已提交
596 597 598 599 600
static int
virCgroupMakeGroup(virCgroupPtr parent,
                   virCgroupPtr group,
                   bool create,
                   unsigned int flags)
601
{
602 603 604
    if (group->backend->makeGroup(parent, group, create, flags) < 0) {
        virCgroupRemove(group);
        return -1;
605 606
    }

607
    return 0;
608 609
}

610

611 612 613 614 615 616 617 618 619 620 621 622 623 624
/**
 * 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.
 *
625
 * Returns 0 on success, -1 on error
626
 */
627
int
E
Eric Blake 已提交
628 629 630 631 632
virCgroupNew(pid_t pid,
             const char *path,
             virCgroupPtr parent,
             int controllers,
             virCgroupPtr *group)
633
{
634 635
    VIR_DEBUG("pid=%lld path=%s parent=%p controllers=%d group=%p",
              (long long) pid, path, parent, controllers, group);
636
    *group = NULL;
637

638 639
    if (VIR_ALLOC((*group)) < 0)
        goto error;
640

641
    if (path[0] == '/' || !parent) {
642 643
        if (VIR_STRDUP((*group)->path, path) < 0)
            goto error;
644 645 646 647
    } else {
        if (virAsprintf(&(*group)->path, "%s%s%s",
                        parent->path,
                        STREQ(parent->path, "") ? "" : "/",
648 649
                        path) < 0)
            goto error;
650 651
    }

652
    if (virCgroupDetect(*group, pid, controllers, path, parent) < 0)
653
        goto error;
654

655 656
    return 0;

657
 error:
658
    virCgroupFree(group);
659
    *group = NULL;
660

661
    return -1;
662
}
663

664

665
/**
666
 * virCgroupAddProcess:
667
 *
668 669
 * @group: The cgroup to add a process to
 * @pid: The pid of the process to add
670
 *
671
 * Will add the process to all controllers, except the
672 673 674 675 676
 * systemd unit controller.
 *
 * Returns: 0 on success, -1 on error
 */
int
677
virCgroupAddProcess(virCgroupPtr group, pid_t pid)
678
{
679
    return group->backend->addTask(group, pid, VIR_CGROUP_TASK_PROCESS);
680 681 682
}

/**
683
 * virCgroupAddMachineProcess:
684
 *
685 686
 * @group: The cgroup to add a process to
 * @pid: The pid of the process to add
687
 *
688
 * Will add the process to all controllers, including the
689 690 691 692 693
 * systemd unit controller.
 *
 * Returns: 0 on success, -1 on error
 */
int
694
virCgroupAddMachineProcess(virCgroupPtr group, pid_t pid)
695
{
696 697 698
    return group->backend->addTask(group, pid,
                                   VIR_CGROUP_TASK_PROCESS |
                                   VIR_CGROUP_TASK_SYSTEMD);
699 700
}

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
/**
 * virCgroupAddThread:
 *
 * @group: The cgroup to add a thread to
 * @pid: The pid of the thread to add
 *
 * Will add the thread to all controllers, except the
 * systemd unit controller.
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupAddThread(virCgroupPtr group,
                   pid_t pid)
{
716
    return group->backend->addTask(group, pid, VIR_CGROUP_TASK_THREAD);
717 718
}

E
Eric Blake 已提交
719 720 721

static int
virCgroupSetPartitionSuffix(const char *path, char **res)
722
{
723
    char **tokens;
724
    size_t i;
725
    int ret = -1;
726

727
    if (!(tokens = virStringSplit(path, "/", 0)))
728
        return ret;
729

730
    for (i = 0; tokens[i] != NULL; i++) {
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
        /* 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],
746
                              strlen(tokens[i]) + strlen(".partition") + 1) < 0)
747
                goto cleanup;
748 749
            strcat(tokens[i], ".partition");
        }
750

751
        if (virCgroupPartitionEscape(&(tokens[i])) < 0)
752
            goto cleanup;
753 754
    }

755
    if (!(*res = virStringListJoin((const char **)tokens, "/")))
756
        goto cleanup;
757

758 759 760 761 762
    ret = 0;

 cleanup:
    virStringListFree(tokens);
    return ret;
763 764
}

E
Eric Blake 已提交
765

766 767 768 769 770 771 772
/**
 * 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
773
 * partition path identified by @path.
774
 *
775
 * Returns 0 on success, -1 on failure
776
 */
E
Eric Blake 已提交
777 778 779 780 781
int
virCgroupNewPartition(const char *path,
                      bool create,
                      int controllers,
                      virCgroupPtr *group)
782
{
783
    int ret = -1;
784 785
    VIR_AUTOFREE(char *) parentPath = NULL;
    VIR_AUTOFREE(char *) newPath = NULL;
786
    virCgroupPtr parent = NULL;
787 788 789
    VIR_DEBUG("path=%s create=%d controllers=%x",
              path, create, controllers);

790 791 792 793 794 795
    if (path[0] != '/') {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Partition path '%s' must start with '/'"),
                       path);
        return -1;
    }
796

797
    if (virCgroupSetPartitionSuffix(path, &newPath) < 0)
798
        goto cleanup;
799

800 801
    if (virCgroupNew(-1, newPath, NULL, controllers, group) < 0)
        goto cleanup;
802

803
    if (STRNEQ(newPath, "/")) {
804
        char *tmp;
805
        if (VIR_STRDUP(parentPath, newPath) < 0)
806
            goto cleanup;
807 808 809 810 811

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

812
        if (virCgroupNew(-1, parentPath, NULL, controllers, &parent) < 0)
813
            goto cleanup;
814

815
        if (virCgroupMakeGroup(parent, *group, create, VIR_CGROUP_NONE) < 0)
816
            goto cleanup;
817 818
    }

819 820 821
    ret = 0;
 cleanup:
    if (ret != 0)
822 823
        virCgroupFree(group);
    virCgroupFree(&parent);
824
    return ret;
825 826
}

827

G
Gao feng 已提交
828
/**
829
* virCgroupNewSelf:
G
Gao feng 已提交
830 831 832
*
* @group: Pointer to returned virCgroupPtr
*
833 834 835
* Obtain a cgroup representing the config of the
* current process
*
836
* Returns 0 on success, or -1 on error
G
Gao feng 已提交
837
*/
E
Eric Blake 已提交
838 839
int
virCgroupNewSelf(virCgroupPtr *group)
G
Gao feng 已提交
840
{
841
    return virCgroupNewDetect(-1, -1, group);
G
Gao feng 已提交
842
}
843

844

845 846 847 848 849 850 851 852
/**
 * virCgroupNewDomainPartition:
 *
 * @partition: partition holding the domain
 * @driver: name of the driver
 * @name: name of the domain
 * @group: Pointer to returned virCgroupPtr
 *
853
 * Returns 0 on success, or -1 on error
854
 */
E
Eric Blake 已提交
855 856 857 858 859 860
int
virCgroupNewDomainPartition(virCgroupPtr partition,
                            const char *driver,
                            const char *name,
                            bool create,
                            virCgroupPtr *group)
861
{
862
    VIR_AUTOFREE(char *)grpname = NULL;
863

864
    if (virAsprintf(&grpname, "%s.libvirt-%s",
865
                    name, driver) < 0)
866
        return -1;
867

868
    if (virCgroupPartitionEscape(&grpname) < 0)
869
        return -1;
870

871
    if (virCgroupNew(-1, grpname, partition, -1, group) < 0)
872
        return -1;
873 874 875 876 877 878 879 880 881 882 883

    /*
     * 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 已提交
884 885
    if (virCgroupMakeGroup(partition, *group, create,
                           VIR_CGROUP_MEM_HIERACHY) < 0) {
886
        virCgroupFree(group);
887
        return -1;
888 889
    }

890
    return 0;
891
}
892

E
Eric Blake 已提交
893

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
/**
 * virCgroupNewThread:
 *
 * @domain: group for the domain
 * @name: enum to generate the name for the new thread
 * @id: id of the vcpu or iothread
 * @create: true to create if not already existing
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success, or -1 on error
 */
int
virCgroupNewThread(virCgroupPtr domain,
                   virCgroupThreadName nameval,
                   int id,
                   bool create,
                   virCgroupPtr *group)
{
912
    VIR_AUTOFREE(char *) name = NULL;
913 914 915 916 917
    int controllers;

    switch (nameval) {
    case VIR_CGROUP_THREAD_VCPU:
        if (virAsprintf(&name, "vcpu%d", id) < 0)
918
            return -1;
919 920 921
        break;
    case VIR_CGROUP_THREAD_EMULATOR:
        if (VIR_STRDUP(name, "emulator") < 0)
922
            return -1;
923 924 925
        break;
    case VIR_CGROUP_THREAD_IOTHREAD:
        if (virAsprintf(&name, "iothread%d", id) < 0)
926
            return -1;
927 928 929 930
        break;
    case VIR_CGROUP_THREAD_LAST:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected name value %d"), nameval);
931
        return -1;
932 933 934 935 936 937 938
    }

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

    if (virCgroupNew(-1, name, domain, controllers, group) < 0)
939
        return -1;
940 941

    if (virCgroupMakeGroup(domain, *group, create, VIR_CGROUP_NONE) < 0) {
942
        virCgroupFree(group);
943
        return -1;
944 945
    }

946
    return 0;
947 948 949
}


E
Eric Blake 已提交
950 951 952 953
int
virCgroupNewDetect(pid_t pid,
                   int controllers,
                   virCgroupPtr *group)
954
{
955
    return virCgroupNew(pid, "", NULL, controllers, group);
956 957
}

E
Eric Blake 已提交
958

959 960 961
/*
 * Returns 0 on success (but @group may be NULL), -1 on fatal error
 */
E
Eric Blake 已提交
962 963 964 965 966
int
virCgroupNewDetectMachine(const char *name,
                          const char *drivername,
                          pid_t pid,
                          int controllers,
967
                          char *machinename,
E
Eric Blake 已提交
968
                          virCgroupPtr *group)
969
{
970
    if (virCgroupNewDetect(pid, controllers, group) < 0) {
971 972 973 974 975
        if (virCgroupNewIgnoreError())
            return 0;
        return -1;
    }

976
    if (!(*group)->backend->validateMachineGroup(*group, name, drivername, machinename)) {
977 978
        VIR_DEBUG("Failed to validate machine name for '%s' driver '%s'",
                  name, drivername);
979
        virCgroupFree(group);
980 981 982 983 984 985
        return 0;
    }

    return 0;
}

E
Eric Blake 已提交
986

987 988 989 990 991 992 993 994 995 996 997
static int
virCgroupEnableMissingControllers(char *path,
                                  pid_t pidleader,
                                  int controllers,
                                  virCgroupPtr *group)
{
    virCgroupPtr parent = NULL;
    char *offset = path;
    int ret = -1;

    if (virCgroupNew(pidleader,
998
                     "/",
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
                     NULL,
                     controllers,
                     &parent) < 0)
        return ret;

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

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

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

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


1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
/*
 * Returns 0 on success, -1 on fatal error, -2 on systemd not available
 */
static int
virCgroupNewMachineSystemd(const char *name,
                           const char *drivername,
                           const unsigned char *uuid,
                           const char *rootdir,
                           pid_t pidleader,
                           bool isContainer,
1049 1050
                           size_t nnicindexes,
                           int *nicindexes,
1051 1052 1053
                           const char *partition,
                           int controllers,
                           virCgroupPtr *group)
1054
{
1055
    int rv;
1056
    virCgroupPtr init;
1057
    VIR_AUTOFREE(char *) path = NULL;
1058 1059 1060 1061 1062 1063 1064 1065

    VIR_DEBUG("Trying to setup machine '%s' via systemd", name);
    if ((rv = virSystemdCreateMachine(name,
                                      drivername,
                                      uuid,
                                      rootdir,
                                      pidleader,
                                      isContainer,
1066 1067
                                      nnicindexes,
                                      nicindexes,
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
                                      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;
1079

1080
    path = init->backend->stealPlacement(init);
1081
    virCgroupFree(&init);
1082 1083 1084

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

1088 1089
    if (virCgroupEnableMissingControllers(path, pidleader,
                                          controllers, group) < 0) {
1090
        return -1;
1091 1092
    }

1093 1094 1095 1096 1097 1098 1099 1100
    if (virCgroupAddProcess(*group, pidleader) < 0) {
        virErrorPtr saved = virSaveLastError();
        virCgroupRemove(*group);
        virCgroupFree(group);
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
1101 1102
    }

1103
    return 0;
1104
}
1105

E
Eric Blake 已提交
1106

1107 1108 1109
/*
 * Returns 0 on success, -1 on fatal error
 */
1110
int virCgroupTerminateMachine(const char *name)
1111
{
1112
    return virSystemdTerminateMachine(name);
1113 1114 1115
}


1116 1117 1118
static int
virCgroupNewMachineManual(const char *name,
                          const char *drivername,
1119
                          pid_t pidleader,
1120 1121 1122 1123
                          const char *partition,
                          int controllers,
                          virCgroupPtr *group)
{
1124 1125
    virCgroupPtr parent = NULL;
    int ret = -1;
1126 1127

    VIR_DEBUG("Fallback to non-systemd setup");
1128 1129 1130 1131 1132
    if (virCgroupNewPartition(partition,
                              STREQ(partition, "/machine"),
                              controllers,
                              &parent) < 0) {
        if (virCgroupNewIgnoreError())
1133
            goto done;
1134

1135
        goto cleanup;
1136 1137 1138 1139 1140 1141 1142
    }

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

1145
    if (virCgroupAddProcess(*group, pidleader) < 0) {
1146 1147
        virErrorPtr saved = virSaveLastError();
        virCgroupRemove(*group);
1148
        virCgroupFree(group);
1149 1150 1151 1152 1153 1154
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
    }

1155 1156 1157 1158
 done:
    ret = 0;

 cleanup:
1159
    virCgroupFree(&parent);
1160
    return ret;
1161 1162
}

E
Eric Blake 已提交
1163 1164 1165 1166 1167 1168 1169 1170

int
virCgroupNewMachine(const char *name,
                    const char *drivername,
                    const unsigned char *uuid,
                    const char *rootdir,
                    pid_t pidleader,
                    bool isContainer,
1171 1172
                    size_t nnicindexes,
                    int *nicindexes,
E
Eric Blake 已提交
1173 1174 1175
                    const char *partition,
                    int controllers,
                    virCgroupPtr *group)
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
{
    int rv;

    *group = NULL;

    if ((rv = virCgroupNewMachineSystemd(name,
                                         drivername,
                                         uuid,
                                         rootdir,
                                         pidleader,
                                         isContainer,
1187 1188
                                         nnicindexes,
                                         nicindexes,
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
                                         partition,
                                         controllers,
                                         group)) == 0)
        return 0;

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

    return virCgroupNewMachineManual(name,
                                     drivername,
1199
                                     pidleader,
1200 1201 1202 1203 1204
                                     partition,
                                     controllers,
                                     group);
}

E
Eric Blake 已提交
1205 1206 1207

bool
virCgroupNewIgnoreError(void)
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
{
    if (virLastErrorIsSystemErrno(ENXIO) ||
        virLastErrorIsSystemErrno(EPERM) ||
        virLastErrorIsSystemErrno(EACCES)) {
        virResetLastError();
        VIR_DEBUG("No cgroups present/configured/accessible, ignoring error");
        return true;
    }
    return false;
}

E
Eric Blake 已提交
1219

E
Eric Blake 已提交
1220 1221 1222 1223 1224 1225
/**
 * virCgroupFree:
 *
 * @group: The group structure to free
 */
void
1226
virCgroupFree(virCgroupPtr *group)
E
Eric Blake 已提交
1227 1228 1229
{
    size_t i;

1230
    if (*group == NULL)
E
Eric Blake 已提交
1231 1232 1233
        return;

    for (i = 0; i < VIR_CGROUP_CONTROLLER_LAST; i++) {
1234 1235 1236
        VIR_FREE((*group)->legacy[i].mountPoint);
        VIR_FREE((*group)->legacy[i].linkPoint);
        VIR_FREE((*group)->legacy[i].placement);
E
Eric Blake 已提交
1237 1238
    }

1239 1240
    VIR_FREE((*group)->path);
    VIR_FREE(*group);
E
Eric Blake 已提交
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
}


/**
 * 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;
1260 1261

    return cgroup->backend->hasController(cgroup, controller);
E
Eric Blake 已提交
1262 1263 1264 1265 1266
}


int
virCgroupPathOfController(virCgroupPtr group,
1267
                          unsigned int controller,
E
Eric Blake 已提交
1268 1269 1270
                          const char *key,
                          char **path)
{
1271 1272 1273
    if (controller >= VIR_CGROUP_CONTROLLER_LAST) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid controller id '%d'"), controller);
E
Eric Blake 已提交
1274 1275 1276
        return -1;
    }

1277
    return group->backend->pathOfController(group, controller, key, path);
E
Eric Blake 已提交
1278 1279 1280
}


1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
/**
 * 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)
{
1299 1300 1301
    VIR_CGROUP_BACKEND_CALL(group, getBlkioIoServiced, -1,
                            bytes_read, bytes_write,
                            requests_read, requests_write);
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
}


/**
 * 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)
{
1325 1326 1327
    VIR_CGROUP_BACKEND_CALL(group, getBlkioIoDeviceServiced, -1,
                            path, bytes_read, bytes_write,
                            requests_read, requests_write);
1328 1329 1330
}


1331 1332 1333 1334 1335 1336
/**
 * virCgroupSetBlkioWeight:
 *
 * @group: The cgroup to change io weight for
 * @weight: The Weight for this cgroup
 *
1337
 * Returns: 0 on success, -1 on error
1338
 */
E
Eric Blake 已提交
1339 1340
int
virCgroupSetBlkioWeight(virCgroupPtr group, unsigned int weight)
1341
{
1342
    VIR_CGROUP_BACKEND_CALL(group, setBlkioWeight, -1, weight);
1343 1344
}

E
Eric Blake 已提交
1345

1346 1347 1348 1349 1350 1351
/**
 * virCgroupGetBlkioWeight:
 *
 * @group: The cgroup to get weight for
 * @Weight: Pointer to returned weight
 *
1352
 * Returns: 0 on success, -1 on error
1353
 */
E
Eric Blake 已提交
1354 1355
int
virCgroupGetBlkioWeight(virCgroupPtr group, unsigned int *weight)
1356
{
1357
    VIR_CGROUP_BACKEND_CALL(group, getBlkioWeight, -1, weight);
1358 1359
}

1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
/**
 * 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)
{
1373
    VIR_CGROUP_BACKEND_CALL(group, setBlkioDeviceReadIops, -1, path, riops);
1374 1375
}

E
Eric Blake 已提交
1376

1377
/**
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
 * 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)
{
1390
    VIR_CGROUP_BACKEND_CALL(group, setBlkioDeviceWriteIops, -1, path, wiops);
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
}


/**
 * 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)
{
1407
    VIR_CGROUP_BACKEND_CALL(group, setBlkioDeviceReadBps, -1, path, rbps);
1408 1409 1410 1411 1412 1413 1414
}

/**
 * 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
1415
 *
1416 1417 1418 1419 1420 1421 1422
 * Returns: 0 on success, -1 on error
 */
int
virCgroupSetBlkioDeviceWriteBps(virCgroupPtr group,
                                const char *path,
                                unsigned long long wbps)
{
1423
    VIR_CGROUP_BACKEND_CALL(group, setBlkioDeviceWriteBps, -1, path, wbps);
1424 1425 1426 1427 1428 1429 1430
}


/**
 * virCgroupSetBlkioDeviceWeight:
 * @group: The cgroup to change block io setting for
 * @path: The path of device
1431 1432
 * @weight: The new device weight (100-1000),
 * (10-1000) after kernel 2.6.39, or 0 to clear
1433
 *
1434
 * Returns: 0 on success, -1 on error
1435
 */
E
Eric Blake 已提交
1436 1437 1438 1439
int
virCgroupSetBlkioDeviceWeight(virCgroupPtr group,
                              const char *path,
                              unsigned int weight)
1440
{
1441
    VIR_CGROUP_BACKEND_CALL(group, setBlkioDeviceWeight, -1, path, weight);
1442
}
1443

1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
/**
 * virCgroupGetBlkioDeviceReadIops:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @riops: Returned device read iops throttle, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceReadIops(virCgroupPtr group,
                                const char *path,
                                unsigned int *riops)
{
1457
    VIR_CGROUP_BACKEND_CALL(group, getBlkioDeviceReadIops, -1, path, riops);
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
}

/**
 * virCgroupGetBlkioDeviceWriteIops:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @wiops: Returned device write iops throttle, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceWriteIops(virCgroupPtr group,
                                 const char *path,
                                 unsigned int *wiops)
{
1473
    VIR_CGROUP_BACKEND_CALL(group, getBlkioDeviceWriteIops, -1, path, wiops);
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
}

/**
 * virCgroupGetBlkioDeviceReadBps:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @rbps: Returned device read bps throttle, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceReadBps(virCgroupPtr group,
                               const char *path,
                               unsigned long long *rbps)
{
1489
    VIR_CGROUP_BACKEND_CALL(group, getBlkioDeviceReadBps, -1, path, rbps);
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
}

/**
 * virCgroupGetBlkioDeviceWriteBps:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @wbps: Returned device write bps throttle, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceWriteBps(virCgroupPtr group,
                                const char *path,
                                unsigned long long *wbps)
{
1505
    VIR_CGROUP_BACKEND_CALL(group, getBlkioDeviceWriteBps, -1, path, wbps);
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
}

/**
 * virCgroupGetBlkioDeviceWeight:
 * @group: The cgroup to gather block io setting for
 * @path: The path of device
 * @weight: Returned device weight, 0 if there is none
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetBlkioDeviceWeight(virCgroupPtr group,
                              const char *path,
                              unsigned int *weight)
{
1521
    VIR_CGROUP_BACKEND_CALL(group, getBlkioDeviceWeight, -1, path, weight);
1522 1523
}

1524

1525 1526 1527 1528 1529 1530 1531 1532
/**
 * virCgroupSetMemory:
 *
 * @group: The cgroup to change memory for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1533 1534
int
virCgroupSetMemory(virCgroupPtr group, unsigned long long kb)
1535
{
1536
    VIR_CGROUP_BACKEND_CALL(group, setMemory, -1, kb);
1537 1538
}

E
Eric Blake 已提交
1539

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
/**
 * virCgroupGetMemoryStat:
 *
 * @group: The cgroup to change memory for
 * @cache: page cache memory in KiB
 * @activeAnon: anonymous and swap cache memory in KiB
 * @inactiveAnon: anonymous and swap cache memory in KiB
 * @activeFile: file-backed memory in KiB
 * @inactiveFile: file-backed memory in KiB
 * @unevictable: memory that cannot be reclaimed KiB
 *
 * Returns: 0 on success, -1 on error
 */
int
virCgroupGetMemoryStat(virCgroupPtr group,
                       unsigned long long *cache,
                       unsigned long long *activeAnon,
                       unsigned long long *inactiveAnon,
                       unsigned long long *activeFile,
                       unsigned long long *inactiveFile,
                       unsigned long long *unevictable)
{
1562 1563 1564 1565
    VIR_CGROUP_BACKEND_CALL(group, getMemoryStat, -1, cache,
                            activeAnon, inactiveAnon,
                            activeFile, inactiveFile,
                            unevictable);
1566 1567 1568
}


R
Ryota Ozaki 已提交
1569 1570 1571 1572 1573 1574 1575 1576
/**
 * virCgroupGetMemoryUsage:
 *
 * @group: The cgroup to change memory for
 * @kb: Pointer to returned used memory in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1577 1578
int
virCgroupGetMemoryUsage(virCgroupPtr group, unsigned long *kb)
R
Ryota Ozaki 已提交
1579
{
1580
    VIR_CGROUP_BACKEND_CALL(group, getMemoryUsage, -1, kb);
R
Ryota Ozaki 已提交
1581 1582
}

E
Eric Blake 已提交
1583

1584 1585 1586 1587 1588 1589 1590 1591
/**
 * virCgroupSetMemoryHardLimit:
 *
 * @group: The cgroup to change memory hard limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1592 1593
int
virCgroupSetMemoryHardLimit(virCgroupPtr group, unsigned long long kb)
1594
{
1595
    VIR_CGROUP_BACKEND_CALL(group, setMemoryHardLimit, -1, kb);
1596 1597
}

E
Eric Blake 已提交
1598

1599 1600 1601 1602 1603 1604 1605 1606
/**
 * virCgroupGetMemoryHardLimit:
 *
 * @group: The cgroup to get the memory hard limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1607 1608
int
virCgroupGetMemoryHardLimit(virCgroupPtr group, unsigned long long *kb)
1609
{
1610
    VIR_CGROUP_BACKEND_CALL(group, getMemoryHardLimit, -1, kb);
1611 1612
}

E
Eric Blake 已提交
1613

1614 1615 1616 1617 1618 1619 1620 1621
/**
 * virCgroupSetMemorySoftLimit:
 *
 * @group: The cgroup to change memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1622 1623
int
virCgroupSetMemorySoftLimit(virCgroupPtr group, unsigned long long kb)
1624
{
1625
    VIR_CGROUP_BACKEND_CALL(group, setMemorySoftLimit, -1, kb);
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
}


/**
 * virCgroupGetMemorySoftLimit:
 *
 * @group: The cgroup to get the memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1637 1638
int
virCgroupGetMemorySoftLimit(virCgroupPtr group, unsigned long long *kb)
1639
{
1640
    VIR_CGROUP_BACKEND_CALL(group, getMemorySoftLimit, -1, kb);
1641 1642
}

E
Eric Blake 已提交
1643

1644
/**
1645
 * virCgroupSetMemSwapHardLimit:
1646
 *
1647 1648
 * @group: The cgroup to change mem+swap hard limit for
 * @kb: The mem+swap amount in kilobytes
1649 1650 1651
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1652 1653
int
virCgroupSetMemSwapHardLimit(virCgroupPtr group, unsigned long long kb)
1654
{
1655
    VIR_CGROUP_BACKEND_CALL(group, setMemSwapHardLimit, -1, kb);
1656 1657
}

E
Eric Blake 已提交
1658

1659
/**
1660
 * virCgroupGetMemSwapHardLimit:
1661
 *
1662 1663
 * @group: The cgroup to get mem+swap hard limit for
 * @kb: The mem+swap amount in kilobytes
1664 1665 1666
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1667 1668
int
virCgroupGetMemSwapHardLimit(virCgroupPtr group, unsigned long long *kb)
1669
{
1670
    VIR_CGROUP_BACKEND_CALL(group, getMemSwapHardLimit, -1, kb);
1671 1672
}

E
Eric Blake 已提交
1673

G
Gao feng 已提交
1674 1675 1676 1677 1678 1679 1680 1681
/**
 * virCgroupGetMemSwapUsage:
 *
 * @group: The cgroup to get mem+swap usage for
 * @kb: The mem+swap amount in kilobytes
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1682 1683
int
virCgroupGetMemSwapUsage(virCgroupPtr group, unsigned long long *kb)
G
Gao feng 已提交
1684
{
1685
    VIR_CGROUP_BACKEND_CALL(group, getMemSwapUsage, -1, kb);
G
Gao feng 已提交
1686 1687
}

E
Eric Blake 已提交
1688

1689 1690 1691 1692 1693 1694 1695 1696
/**
 * virCgroupSetCpusetMems:
 *
 * @group: The cgroup to set cpuset.mems for
 * @mems: the numa nodes to set
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1697 1698
int
virCgroupSetCpusetMems(virCgroupPtr group, const char *mems)
1699
{
1700
    VIR_CGROUP_BACKEND_CALL(group, setCpusetMems, -1, mems);
1701 1702
}

E
Eric Blake 已提交
1703

1704 1705 1706 1707 1708 1709 1710 1711
/**
 * virCgroupGetCpusetMems:
 *
 * @group: The cgroup to get cpuset.mems for
 * @mems: the numa nodes to get
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1712 1713
int
virCgroupGetCpusetMems(virCgroupPtr group, char **mems)
1714
{
1715
    VIR_CGROUP_BACKEND_CALL(group, getCpusetMems, -1, mems);
1716 1717
}

E
Eric Blake 已提交
1718

1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
/**
 * virCgroupSetCpusetMemoryMigrate:
 *
 * @group: The cgroup to set cpuset.memory_migrate for
 * @migrate: Whether to migrate the memory on change or not
 *
 * Returns: 0 on success
 */
int
virCgroupSetCpusetMemoryMigrate(virCgroupPtr group, bool migrate)
{
1730
    VIR_CGROUP_BACKEND_CALL(group, setCpusetMemoryMigrate, -1, migrate);
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
}


/**
 * virCgroupGetCpusetMemoryMigrate:
 *
 * @group: The cgroup to get cpuset.memory_migrate for
 * @migrate: Migration setting
 *
 * Returns: 0 on success
 */
int
virCgroupGetCpusetMemoryMigrate(virCgroupPtr group, bool *migrate)
{
1745
    VIR_CGROUP_BACKEND_CALL(group, getCpusetMemoryMigrate, -1, migrate);
1746 1747 1748
}


1749 1750 1751 1752 1753 1754
/**
 * virCgroupSetCpusetCpus:
 *
 * @group: The cgroup to set cpuset.cpus for
 * @cpus: the cpus to set
 *
N
Nitesh Konkar 已提交
1755
 * Returns: 0 on success
1756
 */
E
Eric Blake 已提交
1757 1758
int
virCgroupSetCpusetCpus(virCgroupPtr group, const char *cpus)
1759
{
1760
    VIR_CGROUP_BACKEND_CALL(group, setCpusetCpus, -1, cpus);
1761 1762
}

E
Eric Blake 已提交
1763

1764 1765 1766 1767 1768 1769
/**
 * virCgroupGetCpusetCpus:
 *
 * @group: The cgroup to get cpuset.cpus for
 * @cpus: the cpus to get
 *
N
Nitesh Konkar 已提交
1770
 * Returns: 0 on success
1771
 */
E
Eric Blake 已提交
1772 1773
int
virCgroupGetCpusetCpus(virCgroupPtr group, char **cpus)
1774
{
1775
    VIR_CGROUP_BACKEND_CALL(group, getCpusetCpus, -1, cpus);
1776 1777
}

E
Eric Blake 已提交
1778

1779 1780 1781
/**
 * virCgroupDenyAllDevices:
 *
1782
 * @group: The cgroup to deny all permissions, for all devices
1783 1784 1785
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1786 1787
int
virCgroupDenyAllDevices(virCgroupPtr group)
1788
{
1789
    VIR_CGROUP_BACKEND_CALL(group, denyAllDevices, -1);
1790 1791
}

1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
/**
 * 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)
{
1809
    VIR_CGROUP_BACKEND_CALL(group, allowAllDevices, -1, perms);
1810 1811
}

E
Eric Blake 已提交
1812

1813 1814 1815 1816 1817
/**
 * virCgroupAllowDevice:
 *
 * @group: The cgroup to allow a device for
 * @type: The device type (i.e., 'c' or 'b')
1818 1819
 * @major: The major number of the device, a negative value means '*'
 * @minor: The minor number of the device, a negative value means '*'
1820
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
1821 1822 1823
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1824 1825 1826
int
virCgroupAllowDevice(virCgroupPtr group, char type, int major, int minor,
                     int perms)
1827
{
1828
    VIR_CGROUP_BACKEND_CALL(group, allowDevice, -1, type, major, minor, perms);
1829
}
1830

E
Eric Blake 已提交
1831

1832 1833 1834 1835 1836
/**
 * virCgroupAllowDevicePath:
 *
 * @group: The cgroup to allow the device for
 * @path: the device to allow
1837
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
1838
 * @ignoreEacces: Ignore lack of permission (mostly for NFS mounts)
1839 1840 1841 1842
 *
 * Queries the type of device and its major/minor number, and
 * adds that to the cgroup ACL
 *
1843 1844
 * Returns: 0 on success, 1 if path exists but is not a device or is not
 * accesible, or * -1 on error
1845
 */
E
Eric Blake 已提交
1846
int
1847 1848 1849 1850
virCgroupAllowDevicePath(virCgroupPtr group,
                         const char *path,
                         int perms,
                         bool ignoreEacces)
1851 1852 1853
{
    struct stat sb;

1854
    if (stat(path, &sb) < 0) {
1855 1856 1857
        if (errno == EACCES && ignoreEacces)
            return 1;

1858 1859 1860 1861 1862
        virReportSystemError(errno,
                             _("Path '%s' is not accessible"),
                             path);
        return -1;
    }
1863 1864

    if (!S_ISCHR(sb.st_mode) && !S_ISBLK(sb.st_mode))
1865
        return 1;
1866

1867 1868 1869 1870 1871
    VIR_CGROUP_BACKEND_CALL(group, allowDevice, -1,
                            S_ISCHR(sb.st_mode) ? 'c' : 'b',
                            major(sb.st_rdev),
                            minor(sb.st_rdev),
                            perms);
1872
}
D
Daniel P. Berrange 已提交
1873

1874 1875 1876 1877 1878 1879

/**
 * virCgroupDenyDevice:
 *
 * @group: The cgroup to deny a device for
 * @type: The device type (i.e., 'c' or 'b')
1880 1881
 * @major: The major number of the device, a negative value means '*'
 * @minor: The minor number of the device, a negative value means '*'
1882
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to deny
1883 1884 1885
 *
 * Returns: 0 on success
 */
E
Eric Blake 已提交
1886 1887 1888
int
virCgroupDenyDevice(virCgroupPtr group, char type, int major, int minor,
                    int perms)
1889
{
1890
    VIR_CGROUP_BACKEND_CALL(group, denyDevice, -1, type, major, minor, perms);
1891 1892
}

E
Eric Blake 已提交
1893

1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
/**
 * virCgroupDenyDevicePath:
 *
 * @group: The cgroup to deny the device for
 * @path: the device to deny
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
 * @ignoreEacces: Ignore lack of permission (mostly for NFS mounts)
 *
 * Queries the type of device and its major/minor number, and
 * removes it from the cgroup ACL
 *
 * Returns: 0 on success, 1 if path exists but is not a device or is not
 * accessible, or -1 on error.
 */
E
Eric Blake 已提交
1908
int
1909 1910 1911 1912
virCgroupDenyDevicePath(virCgroupPtr group,
                        const char *path,
                        int perms,
                        bool ignoreEacces)
1913 1914 1915
{
    struct stat sb;

1916
    if (stat(path, &sb) < 0) {
1917 1918 1919
        if (errno == EACCES && ignoreEacces)
            return 1;

1920 1921 1922 1923 1924
        virReportSystemError(errno,
                             _("Path '%s' is not accessible"),
                             path);
        return -1;
    }
1925 1926

    if (!S_ISCHR(sb.st_mode) && !S_ISBLK(sb.st_mode))
1927
        return 1;
1928

1929 1930 1931 1932 1933
    VIR_CGROUP_BACKEND_CALL(group, denyDevice, -1,
                            S_ISCHR(sb.st_mode) ? 'c' : 'b',
                            major(sb.st_rdev),
                            minor(sb.st_rdev),
                            perms);
1934 1935
}

E
Eric Blake 已提交
1936

1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
/* 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,
1953
                          virBitmapPtr guestvcpus,
1954
                          unsigned long long *sum_cpu_time,
1955 1956
                          size_t nsum,
                          virBitmapPtr cpumap)
1957
{
1958
    int ret = -1;
1959
    ssize_t i = -1;
1960
    virCgroupPtr group_vcpu = NULL;
1961

1962
    while ((i = virBitmapNextSetBit(guestvcpus, i)) >= 0) {
1963
        VIR_AUTOFREE(char *) buf = NULL;
1964 1965
        char *pos;
        unsigned long long tmp;
1966
        ssize_t j;
1967

J
John Ferlan 已提交
1968 1969
        if (virCgroupNewThread(group, VIR_CGROUP_THREAD_VCPU, i,
                               false, &group_vcpu) < 0)
1970
            goto cleanup;
1971 1972

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

        pos = buf;
1976 1977 1978
        for (j = virBitmapNextSetBit(cpumap, -1);
             j >= 0 && j < nsum;
             j = virBitmapNextSetBit(cpumap, j)) {
1979 1980 1981
            if (virStrToLong_ull(pos, &pos, 10, &tmp) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cpuacct parse error"));
1982
                goto cleanup;
1983 1984 1985
            }
            sum_cpu_time[j] += tmp;
        }
1986

1987
        virCgroupFree(&group_vcpu);
1988 1989
    }

1990 1991
    ret = 0;
 cleanup:
1992
    virCgroupFree(&group_vcpu);
1993
    return ret;
1994 1995 1996
}


1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
/**
 * virCgroupGetPercpuStats:
 * @cgroup: cgroup data structure
 * @params: typed parameter array where data is returned
 * @nparams: cardinality of @params
 * @start_cpu: offset of physical CPU to get data for
 * @ncpus: number of physical CPUs to get data for
 * @nvcpupids: number of vCPU threads for a domain (actual number of vcpus)
 *
 * This function is the worker that retrieves data in the appropriate format
 * for the terribly designed 'virDomainGetCPUStats' API. Sharing semantics with
 * the API, this function has two modes of operation depending on magic settings
 * of the input arguments. Please refer to docs of 'virDomainGetCPUStats' for
 * the usage patterns of the similarly named arguments.
 *
 * @nvcpupids determines the count of active vcpu threads for the vm. If the
 * threads could not be detected the percpu data is skipped.
 *
 * Please DON'T use this function anywhere else.
 */
2017 2018 2019 2020 2021
int
virCgroupGetPercpuStats(virCgroupPtr group,
                        virTypedParameterPtr params,
                        unsigned int nparams,
                        int start_cpu,
2022
                        unsigned int ncpus,
2023
                        virBitmapPtr guestvcpus)
2024
{
2025
    int ret = -1;
2026
    size_t i;
2027
    int need_cpus, total_cpus;
2028
    char *pos;
2029 2030
    VIR_AUTOFREE(char *) buf = NULL;
    VIR_AUTOFREE(unsigned long long *) sum_cpu_time = NULL;
2031 2032 2033
    virTypedParameterPtr ent;
    int param_idx;
    unsigned long long cpu_time;
2034
    virBitmapPtr cpumap = NULL;
2035 2036

    /* return the number of supported params */
2037
    if (nparams == 0 && ncpus != 0) {
2038
        if (!guestvcpus)
2039 2040 2041 2042
            return CGROUP_NB_PER_CPU_STAT_PARAM;
        else
            return CGROUP_NB_PER_CPU_STAT_PARAM + 1;
    }
2043 2044

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

2048 2049
    total_cpus = virBitmapSize(cpumap);

2050
    /* return total number of cpus */
2051 2052 2053 2054
    if (ncpus == 0) {
        ret = total_cpus;
        goto cleanup;
    }
2055

2056
    if (start_cpu >= total_cpus) {
2057 2058
        virReportError(VIR_ERR_INVALID_ARG,
                       _("start_cpu %d larger than maximum of %d"),
2059
                       start_cpu, total_cpus - 1);
2060
        goto cleanup;
2061 2062 2063 2064
    }

    /* we get percpu cputime accounting info. */
    if (virCgroupGetCpuacctPercpuUsage(group, &buf))
2065
        goto cleanup;
2066 2067 2068 2069 2070 2071
    pos = buf;

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

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

J
Ján Tomko 已提交
2074
    for (i = 0; i < need_cpus; i++) {
J
Ján Tomko 已提交
2075
        if (!virBitmapIsBitSet(cpumap, i)) {
2076 2077
            cpu_time = 0;
        } else if (virStrToLong_ull(pos, &pos, 10, &cpu_time) < 0) {
2078 2079
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cpuacct parse error"));
2080
            goto cleanup;
2081 2082 2083 2084 2085 2086
        }
        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)
2087
            goto cleanup;
2088 2089
    }

2090
    /* return percpu vcputime in index 1 */
2091
    param_idx = 1;
2092

2093
    if (guestvcpus && param_idx < nparams) {
2094
        if (VIR_ALLOC_N(sum_cpu_time, need_cpus) < 0)
2095
            goto cleanup;
2096 2097
        if (virCgroupGetPercpuVcpuSum(group, guestvcpus, sum_cpu_time,
                                      need_cpus, cpumap) < 0)
2098
            goto cleanup;
2099 2100

        for (i = start_cpu; i < need_cpus; i++) {
2101 2102
            int idx = (i - start_cpu) * nparams + param_idx;
            if (virTypedParameterAssign(&params[idx],
2103 2104 2105
                                        VIR_DOMAIN_CPU_STATS_VCPUTIME,
                                        VIR_TYPED_PARAM_ULLONG,
                                        sum_cpu_time[i]) < 0)
2106
                goto cleanup;
2107 2108 2109
        }

        param_idx++;
2110 2111
    }

2112 2113 2114 2115 2116
    ret = param_idx;

 cleanup:
    virBitmapFree(cpumap);
    return ret;
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 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168

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 已提交
2169 2170
int
virCgroupSetCpuShares(virCgroupPtr group, unsigned long long shares)
2171
{
2172
    VIR_CGROUP_BACKEND_CALL(group, setCpuShares, -1, shares);
2173 2174
}

E
Eric Blake 已提交
2175 2176 2177

int
virCgroupGetCpuShares(virCgroupPtr group, unsigned long long *shares)
2178
{
2179
    VIR_CGROUP_BACKEND_CALL(group, getCpuShares, -1, shares);
2180
}
2181

E
Eric Blake 已提交
2182

2183 2184 2185 2186 2187 2188 2189 2190
/**
 * 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 已提交
2191 2192
int
virCgroupSetCpuCfsPeriod(virCgroupPtr group, unsigned long long cfs_period)
2193
{
2194
    VIR_CGROUP_BACKEND_CALL(group, setCpuCfsPeriod, -1, cfs_period);
2195 2196
}

E
Eric Blake 已提交
2197

2198 2199 2200 2201 2202 2203 2204 2205
/**
 * 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 已提交
2206 2207
int
virCgroupGetCpuCfsPeriod(virCgroupPtr group, unsigned long long *cfs_period)
2208
{
2209
    VIR_CGROUP_BACKEND_CALL(group, getCpuCfsPeriod, -1, cfs_period);
2210 2211
}

E
Eric Blake 已提交
2212

2213 2214 2215 2216 2217 2218 2219 2220 2221
/**
 * 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 已提交
2222 2223
int
virCgroupSetCpuCfsQuota(virCgroupPtr group, long long cfs_quota)
2224
{
2225
    VIR_CGROUP_BACKEND_CALL(group, setCpuCfsQuota, -1, cfs_quota);
2226 2227
}

E
Eric Blake 已提交
2228 2229 2230

int
virCgroupGetCpuacctPercpuUsage(virCgroupPtr group, char **usage)
2231
{
2232
    VIR_CGROUP_BACKEND_CALL(group, getCpuacctPercpuUsage, -1, usage);
2233 2234
}

E
Eric Blake 已提交
2235

2236
int
E
Eric Blake 已提交
2237 2238 2239 2240 2241
virCgroupRemoveRecursively(char *grppath)
{
    DIR *grpdir;
    struct dirent *ent;
    int rc = 0;
E
Eric Blake 已提交
2242
    int direrr;
E
Eric Blake 已提交
2243

J
Ján Tomko 已提交
2244
    if (virDirOpenQuiet(&grpdir, grppath) < 0) {
E
Eric Blake 已提交
2245 2246 2247 2248 2249 2250 2251
        if (errno == ENOENT)
            return 0;
        rc = -errno;
        VIR_ERROR(_("Unable to open %s (%d)"), grppath, errno);
        return rc;
    }

E
Eric Blake 已提交
2252 2253 2254
    /* 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) {
2255
        VIR_AUTOFREE(char *) path = NULL;
E
Eric Blake 已提交
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266

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

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

J
Ján Tomko 已提交
2272
    VIR_DIR_CLOSE(grpdir);
E
Eric Blake 已提交
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298

    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)
{
2299
    return group->backend->remove(group);
E
Eric Blake 已提交
2300 2301 2302
}


2303 2304 2305 2306 2307
static int
virCgroupPathOfAnyController(virCgroupPtr group,
                             const char *name,
                             char **keypath)
{
2308
    int controller;
2309

2310 2311 2312
    controller = group->backend->getAnyController(group);
    if (controller >= 0)
        return virCgroupPathOfController(group, controller, name, keypath);
2313 2314 2315 2316 2317 2318 2319

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


2320 2321 2322
/*
 * Returns 1 if some PIDs are killed, 0 if none are killed, or -1 on error
 */
E
Eric Blake 已提交
2323 2324
static int
virCgroupKillInternal(virCgroupPtr group, int signum, virHashTablePtr pids)
2325
{
2326
    int ret = -1;
2327
    bool killedAny = false;
2328
    VIR_AUTOFREE(char *) keypath = NULL;
2329
    bool done = false;
E
Eric Blake 已提交
2330 2331 2332
    FILE *fp = NULL;
    VIR_DEBUG("group=%p path=%s signum=%d pids=%p",
              group, group->path, signum, pids);
2333

2334
    if (virCgroupPathOfAnyController(group, "tasks", &keypath) < 0)
2335
        return -1;
2336 2337 2338 2339 2340 2341 2342

    /* 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"))) {
2343 2344 2345 2346 2347 2348
            if (errno == ENOENT) {
                VIR_DEBUG("No file %s, assuming done", keypath);
                killedAny = false;
                goto done;
            }

2349 2350 2351
            virReportSystemError(errno,
                                 _("Failed to read %s"),
                                 keypath);
2352 2353 2354
            goto cleanup;
        } else {
            while (!feof(fp)) {
M
Michal Privoznik 已提交
2355 2356
                long pid_value;
                if (fscanf(fp, "%ld", &pid_value) != 1) {
2357 2358
                    if (feof(fp))
                        break;
2359 2360 2361
                    virReportSystemError(errno,
                                         _("Failed to read %s"),
                                         keypath);
E
Eric Blake 已提交
2362
                    goto cleanup;
2363
                }
2364
                if (virHashLookup(pids, (void*)pid_value))
2365 2366
                    continue;

M
Michal Privoznik 已提交
2367
                VIR_DEBUG("pid=%ld", pid_value);
2368 2369
                /* Cgroups is a Linux concept, so this cast is safe.  */
                if (kill((pid_t)pid_value, signum) < 0) {
2370
                    if (errno != ESRCH) {
2371
                        virReportSystemError(errno,
M
Michal Privoznik 已提交
2372
                                             _("Failed to kill process %ld"),
2373
                                             pid_value);
2374 2375 2376 2377
                        goto cleanup;
                    }
                    /* Leave RC == 0 since we didn't kill one */
                } else {
2378
                    killedAny = true;
2379 2380 2381
                    done = false;
                }

2382
                ignore_value(virHashAddEntry(pids, (void*)pid_value, (void*)1));
2383 2384 2385 2386 2387
            }
            VIR_FORCE_FCLOSE(fp);
        }
    }

2388
 done:
2389
    ret = killedAny ? 1 : 0;
2390

2391
 cleanup:
E
Eric Blake 已提交
2392
    VIR_FORCE_FCLOSE(fp);
2393

2394
    return ret;
2395 2396 2397
}


E
Eric Blake 已提交
2398 2399
static uint32_t
virCgroupPidCode(const void *name, uint32_t seed)
2400
{
M
Michal Privoznik 已提交
2401
    long pid_value = (long)(intptr_t)name;
2402
    return virHashCodeGen(&pid_value, sizeof(pid_value), seed);
2403
}
E
Eric Blake 已提交
2404 2405 2406 2407


static bool
virCgroupPidEqual(const void *namea, const void *nameb)
2408 2409 2410
{
    return namea == nameb;
}
E
Eric Blake 已提交
2411 2412 2413 2414


static void *
virCgroupPidCopy(const void *name)
2415 2416 2417 2418
{
    return (void*)name;
}

E
Eric Blake 已提交
2419 2420 2421 2422 2423 2424

static int
virCgroupKillRecursiveInternal(virCgroupPtr group,
                               int signum,
                               virHashTablePtr pids,
                               bool dormdir)
2425
{
2426
    int ret = -1;
2427
    int rc;
2428
    bool killedAny = false;
2429
    VIR_AUTOFREE(char *) keypath = NULL;
2430
    DIR *dp = NULL;
2431
    virCgroupPtr subgroup = NULL;
2432
    struct dirent *ent;
E
Eric Blake 已提交
2433
    int direrr;
E
Eric Blake 已提交
2434 2435
    VIR_DEBUG("group=%p path=%s signum=%d pids=%p",
              group, group->path, signum, pids);
2436

2437
    if (virCgroupPathOfAnyController(group, "", &keypath) < 0)
2438
        return -1;
2439

2440
    if ((rc = virCgroupKillInternal(group, signum, pids)) < 0)
2441
        goto cleanup;
2442 2443
    if (rc == 1)
        killedAny = true;
2444

2445
    VIR_DEBUG("Iterate over children of %s (killedAny=%d)", keypath, killedAny);
J
Ján Tomko 已提交
2446
    if ((rc = virDirOpenIfExists(&dp, keypath)) < 0)
2447
        goto cleanup;
J
Ján Tomko 已提交
2448 2449 2450 2451 2452

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

E
Eric Blake 已提交
2455
    while ((direrr = virDirRead(dp, &ent, keypath)) > 0) {
2456 2457 2458 2459 2460
        if (ent->d_type != DT_DIR)
            continue;

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

2461
        if (virCgroupNew(-1, ent->d_name, group, -1, &subgroup) < 0)
2462 2463
            goto cleanup;

E
Eric Blake 已提交
2464 2465
        if ((rc = virCgroupKillRecursiveInternal(subgroup, signum, pids,
                                                 true)) < 0)
2466 2467
            goto cleanup;
        if (rc == 1)
2468
            killedAny = true;
2469 2470 2471

        if (dormdir)
            virCgroupRemove(subgroup);
2472

2473
        virCgroupFree(&subgroup);
2474
    }
E
Eric Blake 已提交
2475 2476
    if (direrr < 0)
        goto cleanup;
2477

2478
 done:
2479
    ret = killedAny ? 1 : 0;
2480

2481
 cleanup:
2482
    virCgroupFree(&subgroup);
J
Ján Tomko 已提交
2483
    VIR_DIR_CLOSE(dp);
2484
    return ret;
2485 2486
}

E
Eric Blake 已提交
2487 2488 2489

int
virCgroupKillRecursive(virCgroupPtr group, int signum)
2490
{
2491
    int ret;
2492
    VIR_DEBUG("group=%p path=%s signum=%d", group, group->path, signum);
2493 2494 2495 2496 2497 2498
    virHashTablePtr pids = virHashCreateFull(100,
                                             NULL,
                                             virCgroupPidCode,
                                             virCgroupPidEqual,
                                             virCgroupPidCopy,
                                             NULL);
2499

2500 2501 2502 2503 2504
    ret = virCgroupKillRecursiveInternal(group, signum, pids, false);

    virHashFree(pids);

    return ret;
2505 2506 2507
}


E
Eric Blake 已提交
2508 2509
int
virCgroupKillPainfully(virCgroupPtr group)
2510
{
2511
    size_t i;
2512
    int ret;
2513
    VIR_DEBUG("cgroup=%p path=%s", group, group->path);
2514
    for (i = 0; i < 15; i++) {
2515 2516 2517 2518 2519 2520
        int signum;
        if (i == 0)
            signum = SIGTERM;
        else if (i == 8)
            signum = SIGKILL;
        else
J
Ján Tomko 已提交
2521
            signum = 0; /* Just check for existence */
2522

2523 2524 2525 2526
        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)
2527 2528 2529 2530
            break;

        usleep(200 * 1000);
    }
2531 2532
    VIR_DEBUG("Complete %d", ret);
    return ret;
2533
}
2534

E
Eric Blake 已提交
2535

2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
/**
 * 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)
{
2548
    VIR_CGROUP_BACKEND_CALL(group, getCpuCfsQuota, -1, cfs_quota);
2549 2550 2551 2552 2553 2554
}


int
virCgroupGetCpuacctUsage(virCgroupPtr group, unsigned long long *usage)
{
2555
    VIR_CGROUP_BACKEND_CALL(group, getCpuacctUsage, -1, usage);
2556 2557 2558 2559 2560 2561 2562
}


int
virCgroupGetCpuacctStat(virCgroupPtr group, unsigned long long *user,
                        unsigned long long *sys)
{
2563
    VIR_CGROUP_BACKEND_CALL(group, getCpuacctStat, -1, user, sys);
2564 2565 2566 2567 2568 2569
}


int
virCgroupSetFreezerState(virCgroupPtr group, const char *state)
{
2570
    VIR_CGROUP_BACKEND_CALL(group, setFreezerState, -1, state);
2571 2572 2573 2574 2575 2576
}


int
virCgroupGetFreezerState(virCgroupPtr group, char **state)
{
2577
    VIR_CGROUP_BACKEND_CALL(group, getFreezerState, -1, state);
2578 2579 2580
}


E
Eric Blake 已提交
2581
int
2582 2583
virCgroupBindMount(virCgroupPtr group, const char *oldroot,
                   const char *mountopts)
2584
{
2585
    return group->backend->bindMount(group, oldroot, mountopts);
2586
}
2587 2588


2589 2590 2591 2592 2593
int virCgroupSetOwner(virCgroupPtr cgroup,
                      uid_t uid,
                      gid_t gid,
                      int controllers)
{
2594
    return cgroup->backend->setOwner(cgroup, uid, gid, controllers);
2595 2596 2597
}


2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
/**
 * 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)
{
2608
    VIR_CGROUP_BACKEND_CALL(cgroup, supportsCpuBW, false);
2609 2610
}

2611 2612 2613
int
virCgroupHasEmptyTasks(virCgroupPtr cgroup, int controller)
{
2614
    return cgroup->backend->hasEmptyTasks(cgroup, controller);
2615
}
2616

2617 2618 2619
bool
virCgroupControllerAvailable(int controller)
{
2620 2621
    virCgroupPtr cgroup;
    bool ret = false;
2622 2623

    if (virCgroupNewSelf(&cgroup) < 0)
2624
        return ret;
2625

2626
    ret = virCgroupHasController(cgroup, controller);
2627
    virCgroupFree(&cgroup);
2628
    return ret;
2629 2630
}

2631
#else /* !__linux__ */
2632

2633 2634 2635 2636 2637 2638 2639
bool
virCgroupAvailable(void)
{
    return false;
}


2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
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;
}


2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686
int
virCgroupNewThread(virCgroupPtr domain ATTRIBUTE_UNUSED,
                   virCgroupThreadName nameval ATTRIBUTE_UNUSED,
                   int id ATTRIBUTE_UNUSED,
                   bool create ATTRIBUTE_UNUSED,
                   virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
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;
}


2698 2699 2700 2701 2702
int
virCgroupNewDetectMachine(const char *name ATTRIBUTE_UNUSED,
                          const char *drivername ATTRIBUTE_UNUSED,
                          pid_t pid ATTRIBUTE_UNUSED,
                          int controllers ATTRIBUTE_UNUSED,
2703
                          char *machinename ATTRIBUTE_UNUSED,
2704 2705 2706 2707 2708 2709 2710
                          virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

J
Ján Tomko 已提交
2711

2712
int virCgroupTerminateMachine(const char *name ATTRIBUTE_UNUSED)
J
Ján Tomko 已提交
2713 2714 2715 2716 2717 2718 2719
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


2720 2721 2722 2723 2724 2725 2726
int
virCgroupNewMachine(const char *name ATTRIBUTE_UNUSED,
                    const char *drivername ATTRIBUTE_UNUSED,
                    const unsigned char *uuid ATTRIBUTE_UNUSED,
                    const char *rootdir ATTRIBUTE_UNUSED,
                    pid_t pidleader ATTRIBUTE_UNUSED,
                    bool isContainer ATTRIBUTE_UNUSED,
2727 2728
                    size_t nnicindexes ATTRIBUTE_UNUSED,
                    int *nicindexes ATTRIBUTE_UNUSED,
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
                    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;
}

2746 2747

void
2748
virCgroupFree(virCgroupPtr *group ATTRIBUTE_UNUSED)
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
}


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


2763 2764
int
virCgroupPathOfController(virCgroupPtr group ATTRIBUTE_UNUSED,
2765
                          unsigned int controller ATTRIBUTE_UNUSED,
2766 2767 2768 2769 2770 2771 2772 2773 2774
                          const char *key ATTRIBUTE_UNUSED,
                          char **path ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


2775
int
2776 2777
virCgroupAddProcess(virCgroupPtr group ATTRIBUTE_UNUSED,
                    pid_t pid ATTRIBUTE_UNUSED)
2778 2779 2780 2781 2782 2783 2784
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


2785
int
2786 2787
virCgroupAddMachineProcess(virCgroupPtr group ATTRIBUTE_UNUSED,
                           pid_t pid ATTRIBUTE_UNUSED)
2788 2789 2790 2791 2792 2793 2794
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


2795 2796 2797 2798 2799 2800 2801 2802 2803 2804
int
virCgroupAddThread(virCgroupPtr group ATTRIBUTE_UNUSED,
                   pid_t pid ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENXIO, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
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;
}


2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851
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;
}


2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
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;
}

2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
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;
}

2902 2903 2904
int
virCgroupGetBlkioDeviceWeight(virCgroupPtr group ATTRIBUTE_UNUSED,
                              const char *path ATTRIBUTE_UNUSED,
2905
                              unsigned int *weight ATTRIBUTE_UNUSED)
2906 2907 2908 2909 2910 2911 2912 2913 2914
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupGetBlkioDeviceReadIops(virCgroupPtr group ATTRIBUTE_UNUSED,
                                const char *path ATTRIBUTE_UNUSED,
2915
                                unsigned int *riops ATTRIBUTE_UNUSED)
2916 2917 2918 2919 2920 2921 2922 2923 2924
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupGetBlkioDeviceWriteIops(virCgroupPtr group ATTRIBUTE_UNUSED,
                                 const char *path ATTRIBUTE_UNUSED,
2925
                                 unsigned int *wiops ATTRIBUTE_UNUSED)
2926 2927 2928 2929 2930 2931 2932 2933 2934
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupGetBlkioDeviceReadBps(virCgroupPtr group ATTRIBUTE_UNUSED,
                               const char *path ATTRIBUTE_UNUSED,
2935
                               unsigned long long *rbps ATTRIBUTE_UNUSED)
2936 2937 2938 2939 2940 2941 2942 2943 2944
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

int
virCgroupGetBlkioDeviceWriteBps(virCgroupPtr group ATTRIBUTE_UNUSED,
                                const char *path ATTRIBUTE_UNUSED,
2945
                                unsigned long long *wbps ATTRIBUTE_UNUSED)
2946 2947 2948 2949 2950
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}
2951

2952 2953 2954 2955 2956 2957 2958 2959 2960 2961
int
virCgroupSetMemory(virCgroupPtr group ATTRIBUTE_UNUSED,
                   unsigned long long kb ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


P
Pavel Hrdina 已提交
2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
int
virCgroupGetMemoryStat(virCgroupPtr group ATTRIBUTE_UNUSED,
                       unsigned long long *cache ATTRIBUTE_UNUSED,
                       unsigned long long *activeAnon ATTRIBUTE_UNUSED,
                       unsigned long long *inactiveAnon ATTRIBUTE_UNUSED,
                       unsigned long long *activeFile ATTRIBUTE_UNUSED,
                       unsigned long long *inactiveFile ATTRIBUTE_UNUSED,
                       unsigned long long *unevictable ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075
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;
}

3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095

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


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

3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115

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

3116 3117 3118 3119 3120 3121 3122 3123
int
virCgroupAllowAllDevices(virCgroupPtr group ATTRIBUTE_UNUSED,
                         int perms ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}
3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146

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


3147 3148 3149
int
virCgroupAllowDevicePath(virCgroupPtr group ATTRIBUTE_UNUSED,
                         const char *path ATTRIBUTE_UNUSED,
3150 3151
                         int perms ATTRIBUTE_UNUSED,
                         bool ignoreEaccess ATTRIBUTE_UNUSED)
3152 3153 3154 3155 3156 3157 3158
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171
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;
}


3172 3173 3174
int
virCgroupDenyDevicePath(virCgroupPtr group ATTRIBUTE_UNUSED,
                        const char *path ATTRIBUTE_UNUSED,
3175 3176
                        int perms ATTRIBUTE_UNUSED,
                        bool ignoreEacces ATTRIBUTE_UNUSED)
3177 3178 3179 3180 3181 3182 3183
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
int
virCgroupSetCpuShares(virCgroupPtr group ATTRIBUTE_UNUSED,
                      unsigned long long shares ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}


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


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


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


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


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


3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
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;
}


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


3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
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;
}


3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333
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 已提交
3334
int
3335 3336 3337
virCgroupBindMount(virCgroupPtr group ATTRIBUTE_UNUSED,
                   const char *oldroot ATTRIBUTE_UNUSED,
                   const char *mountopts ATTRIBUTE_UNUSED)
3338
{
3339 3340 3341
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
3342
}
3343

3344 3345 3346 3347 3348 3349 3350 3351

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

E
Eric Blake 已提交
3352 3353 3354 3355 3356 3357

int
virCgroupGetPercpuStats(virCgroupPtr group ATTRIBUTE_UNUSED,
                        virTypedParameterPtr params ATTRIBUTE_UNUSED,
                        unsigned int nparams ATTRIBUTE_UNUSED,
                        int start_cpu ATTRIBUTE_UNUSED,
J
Ján Tomko 已提交
3358
                        unsigned int ncpus ATTRIBUTE_UNUSED,
3359
                        virBitmapPtr guestvcpus ATTRIBUTE_UNUSED)
E
Eric Blake 已提交
3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377
{
    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;
}

3378 3379 3380 3381 3382 3383 3384 3385 3386
int
virCgroupHasEmptyTasks(virCgroupPtr cgroup ATTRIBUTE_UNUSED,
                       int controller ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("Control groups not supported on this platform"));
    return -1;
}

3387 3388 3389 3390 3391
bool
virCgroupControllerAvailable(int controller ATTRIBUTE_UNUSED)
{
    return false;
}
3392
#endif /* !__linux__ */
3393 3394 3395 3396 3397 3398 3399


int
virCgroupDelThread(virCgroupPtr cgroup,
                   virCgroupThreadName nameval,
                   int idx)
{
3400
    virCgroupPtr new_cgroup = NULL;
3401 3402 3403 3404 3405 3406 3407

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

        /* Remove the offlined cgroup */
        virCgroupRemove(new_cgroup);
3408
        virCgroupFree(&new_cgroup);
3409 3410 3411 3412
    }

    return 0;
}