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

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

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

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

#define CGROUP_MAX_VAL 512

56 57
#define VIR_FROM_THIS VIR_FROM_CGROUP

58
VIR_ENUM_IMPL(virCgroupController, VIR_CGROUP_CONTROLLER_LAST,
R
Ryota Ozaki 已提交
59
              "cpu", "cpuacct", "cpuset", "memory", "devices",
60
              "freezer", "blkio");
61

62 63 64 65 66 67 68 69
typedef enum {
    VIR_CGROUP_NONE = 0, /* create subdir under each cgroup if possible. */
    VIR_CGROUP_MEM_HIERACHY = 1 << 0, /* call virCgroupSetMemoryUseHierarchy
                                       * before creating subcgroups and
                                       * attaching tasks
                                       */
} virCgroupFlags;

70 71 72 73 74 75 76
/**
 * virCgroupFree:
 *
 * @group: The group structure to free
 */
void virCgroupFree(virCgroupPtr *group)
{
77 78 79 80 81 82 83
    int i;

    if (*group == NULL)
        return;

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

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

L
Lai Jiangshan 已提交
92
/**
93
 * virCgroupHasController: query whether a cgroup controller is present
L
Lai Jiangshan 已提交
94
 *
95
 * @cgroup: The group structure to be queried, or NULL
L
Lai Jiangshan 已提交
96 97
 * @controller: cgroup subsystem id
 *
98 99
 * Returns true if a cgroup controller is mounted and is associated
 * with this cgroup object.
L
Lai Jiangshan 已提交
100
 */
101
bool virCgroupHasController(virCgroupPtr cgroup, int controller)
L
Lai Jiangshan 已提交
102
{
103 104 105 106
    if (!cgroup)
        return false;
    if (controller < 0 || controller >= VIR_CGROUP_CONTROLLER_LAST)
        return false;
L
Lai Jiangshan 已提交
107 108 109
    return cgroup->controllers[controller].mountPoint != NULL;
}

110
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
111 112 113 114 115 116 117 118 119 120 121 122 123
static int virCgroupCopyMounts(virCgroupPtr group,
                               virCgroupPtr parent)
{
    int i;
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
        if (!parent->controllers[i].mountPoint)
            continue;

        group->controllers[i].mountPoint =
            strdup(parent->controllers[i].mountPoint);

        if (!group->controllers[i].mountPoint)
            return -ENOMEM;
124 125 126 127 128 129 130 131

        if (parent->controllers[i].linkPoint) {
            group->controllers[i].linkPoint =
                strdup(parent->controllers[i].linkPoint);

            if (!group->controllers[i].linkPoint)
                return -ENOMEM;
        }
132 133 134 135
    }
    return 0;
}

136 137 138 139 140
/*
 * Process /proc/mounts figuring out what controllers are
 * mounted and where
 */
static int virCgroupDetectMounts(virCgroupPtr group)
141
{
142
    int i;
143
    FILE *mounts = NULL;
144 145 146 147 148
    struct mntent entry;
    char buf[CGROUP_MAX_VAL];

    mounts = fopen("/proc/mounts", "r");
    if (mounts == NULL) {
149
        VIR_ERROR(_("Unable to open /proc/mounts"));
150
        return -ENOENT;
151 152 153
    }

    while (getmntent_r(mounts, &entry, buf, sizeof(buf)) != NULL) {
154 155
        if (STRNEQ(entry.mnt_type, "cgroup"))
            continue;
156

157 158 159 160 161 162 163 164 165 166 167 168 169
        for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
            const char *typestr = virCgroupControllerTypeToString(i);
            int typelen = strlen(typestr);
            char *tmp = entry.mnt_opts;
            while (tmp) {
                char *next = strchr(tmp, ',');
                int len;
                if (next) {
                    len = next-tmp;
                    next++;
                } else {
                    len = strlen(tmp);
                }
170 171 172 173
                /* NB, the same controller can appear >1 time in mount list
                 * due to bind mounts from one location to another. Pick the
                 * first entry only
                 */
174
                if (typelen == len && STREQLEN(typestr, tmp, len) &&
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
                    !group->controllers[i].mountPoint) {
                    char *linksrc;
                    struct stat sb;
                    char *tmp2;

                    if (!(group->controllers[i].mountPoint = strdup(entry.mnt_dir)))
                        goto no_memory;

                    tmp2 = strrchr(entry.mnt_dir, '/');
                    if (!tmp2) {
                        errno = EINVAL;
                        goto error;
                    }
                    *tmp2 = '\0';
                    /* If it is a co-mount it has a filename like "cpu,cpuacct"
                     * and we must identify the symlink path */
                    if (strchr(tmp2 + 1, ',')) {
                        if (virAsprintf(&linksrc, "%s/%s",
                                        entry.mnt_dir, typestr) < 0)
                            goto no_memory;
                        *tmp2 = '/';

                        if (lstat(linksrc, &sb) < 0) {
                            if (errno == ENOENT) {
                                VIR_WARN("Controller %s co-mounted at %s is missing symlink at %s",
                                         typestr, entry.mnt_dir, linksrc);
                                VIR_FREE(linksrc);
                            } else {
                                goto error;
                            }
                        } else {
                            if (!S_ISLNK(sb.st_mode)) {
                                VIR_WARN("Expecting a symlink at %s for controller %s",
                                         linksrc, typestr);
                            } else {
                                group->controllers[i].linkPoint = linksrc;
                            }
                        }
                    }
                }
215 216 217
                tmp = next;
            }
        }
218 219
    }

220
    VIR_FORCE_FCLOSE(mounts);
221

222
    return 0;
223

224
no_memory:
225 226
    errno = ENOMEM;
error:
227
    VIR_FORCE_FCLOSE(mounts);
228
    return -errno;
229 230
}

231

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
static int virCgroupCopyPlacement(virCgroupPtr group,
                                  const char *path,
                                  virCgroupPtr parent)
{
    int i;
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
        if (!group->controllers[i].mountPoint)
            continue;

        if (path[0] == '/') {
            if (!(group->controllers[i].placement = strdup(path)))
                return -ENOMEM;
        } else {
            /*
             * parent=="/" + path="" => "/"
             * parent=="/libvirt.service" + path=="" => "/libvirt.service"
             * parent=="/libvirt.service" + path=="foo" => "/libvirt.service/foo"
             */
            if (virAsprintf(&group->controllers[i].placement,
                            "%s%s%s",
                            parent->controllers[i].placement,
                            (STREQ(parent->controllers[i].placement, "/") ||
                             STREQ(path, "") ? "" : "/"),
                            path) < 0)
                return -ENOMEM;
        }
    }

    return 0;
}


264
/*
265 266 267 268
 * virCgroupDetectPlacement:
 * @group: the group to process
 * @path: the relative path to append, not starting with '/'
 *
269 270
 * Process /proc/self/cgroup figuring out what cgroup
 * sub-path the current process is assigned to. ie not
271 272 273 274 275 276 277 278 279 280 281 282 283 284
 * 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.
285
 */
286 287
static int virCgroupDetectPlacement(virCgroupPtr group,
                                    const char *path)
288 289
{
    int i;
290 291
    FILE *mapping  = NULL;
    char line[1024];
292

293 294
    mapping = fopen("/proc/self/cgroup", "r");
    if (mapping == NULL) {
295
        VIR_ERROR(_("Unable to open /proc/self/cgroup"));
296
        return -ENOENT;
297 298
    }

299 300
    while (fgets(line, sizeof(line), mapping) != NULL) {
        char *controllers = strchr(line, ':');
301 302
        char *selfpath = controllers ? strchr(controllers + 1, ':') : NULL;
        char *nl = selfpath ? strchr(selfpath, '\n') : NULL;
303

304
        if (!controllers || !selfpath)
305 306 307 308 309
            continue;

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

310
        *selfpath = '\0';
311
        controllers++;
312
        selfpath++;
313 314 315 316 317 318 319 320 321

        for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
            const char *typestr = virCgroupControllerTypeToString(i);
            int typelen = strlen(typestr);
            char *tmp = controllers;
            while (tmp) {
                char *next = strchr(tmp, ',');
                int len;
                if (next) {
322
                    len = next - tmp;
323 324 325 326
                    next++;
                } else {
                    len = strlen(tmp);
                }
327 328 329 330 331 332 333 334 335 336 337 338 339 340

                /*
                 * selfpath=="/" + path="" -> "/"
                 * selfpath=="/libvirt.service" + path="" -> "/libvirt.service"
                 * selfpath=="/libvirt.service" + path="foo" -> "/libvirt.service/foo"
                 */
                if (typelen == len && STREQLEN(typestr, tmp, len)) {
                    if (virAsprintf(&group->controllers[i].placement,
                                    "%s%s%s", selfpath,
                                    (STREQ(selfpath, "/") ||
                                     STREQ(path, "") ? "" : "/"),
                                    path) < 0)
                        goto no_memory;
                }
341 342 343 344 345 346

                tmp = next;
            }
        }
    }

347
    VIR_FORCE_FCLOSE(mapping);
348

349
    return 0;
350 351

no_memory:
352
    VIR_FORCE_FCLOSE(mapping);
353 354
    return -ENOMEM;

355 356
}

357
static int virCgroupDetect(virCgroupPtr group,
358 359 360
                           int controllers,
                           const char *path,
                           virCgroupPtr parent)
361
{
362 363
    int rc;
    int i;
364
    int j;
365 366
    VIR_DEBUG("group=%p controllers=%d path=%s parent=%p",
              group, controllers, path, parent);
367

368 369 370 371
    if (parent)
        rc = virCgroupCopyMounts(group, parent);
    else
        rc = virCgroupDetectMounts(group);
372
    if (rc < 0) {
373
        VIR_ERROR(_("Failed to detect mounts for %s"), group->path);
374
        return rc;
375 376
    }

377 378 379
    if (controllers >= 0) {
        VIR_DEBUG("Validating controllers %d", controllers);
        for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
380
            VIR_DEBUG("Controller '%s' wanted=%s, mount='%s'",
381
                      virCgroupControllerTypeToString(i),
382 383
                      (1 << i) & controllers ? "yes" : "no",
                      NULLSTR(group->controllers[i].mountPoint));
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
            if (((1 << i) & controllers)) {
                /* Ensure requested controller is present */
                if (!group->controllers[i].mountPoint) {
                    VIR_DEBUG("Requested controlled '%s' not mounted",
                              virCgroupControllerTypeToString(i));
                    return -ENOENT;
                }
            } else {
                /* Check whether a request to disable a controller
                 * clashes with co-mounting of controllers */
                for (j = 0 ; j < VIR_CGROUP_CONTROLLER_LAST ; j++) {
                    if (j == i)
                        continue;
                    if (!((1 << j) & controllers))
                        continue;

                    if (STREQ_NULLABLE(group->controllers[i].mountPoint,
                                       group->controllers[j].mountPoint)) {
                        VIR_DEBUG("Controller '%s' is not wanted, but '%s' is co-mounted",
                                  virCgroupControllerTypeToString(i),
                                  virCgroupControllerTypeToString(j));
                        return -EINVAL;
                    }
                }
                VIR_FREE(group->controllers[i].mountPoint);
            }
        }
    } else {
        VIR_DEBUG("Auto-detecting controllers");
        controllers = 0;
        for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
            VIR_DEBUG("Controller '%s' present=%s",
                      virCgroupControllerTypeToString(i),
                      group->controllers[i].mountPoint ? "yes" : "no");
            if (group->controllers[i].mountPoint == NULL)
                continue;
            controllers |= (1 << i);
        }
422
    }
423

424
    /* Check that at least 1 controller is available */
425 426
    if (!controllers) {
        VIR_DEBUG("No controllers set");
427
        return -ENXIO;
428
    }
429

430 431 432 433
    if (parent || path[0] == '/')
        rc = virCgroupCopyPlacement(group, path, parent);
    else
        rc = virCgroupDetectPlacement(group, path);
434

435 436 437 438 439
    if (rc == 0) {
        /* Check that for every mounted controller, we found our placement */
        for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
            if (!group->controllers[i].mountPoint)
                continue;
440

441
            if (!group->controllers[i].placement) {
442
                VIR_ERROR(_("Could not find placement for controller %s at %s"),
443 444 445 446 447
                          virCgroupControllerTypeToString(i),
                          group->controllers[i].placement);
                rc = -ENOENT;
                break;
            }
448

449 450 451 452 453 454
            VIR_DEBUG("Detected mount/mapping %i:%s at %s in %s", i,
                      virCgroupControllerTypeToString(i),
                      group->controllers[i].mountPoint,
                      group->controllers[i].placement);
        }
    } else {
455
        VIR_ERROR(_("Failed to detect mapping for %s"), group->path);
456 457 458 459
    }

    return rc;
}
D
Daniel P. Berrange 已提交
460
#endif
461

462

463 464 465 466
int virCgroupPathOfController(virCgroupPtr group,
                              int controller,
                              const char *key,
                              char **path)
467
{
468 469 470 471 472 473 474 475 476 477 478 479 480
    if (controller == -1) {
        int i;
        for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
            if (group->controllers[i].mountPoint &&
                group->controllers[i].placement) {
                controller = i;
                break;
            }
        }
    }
    if (controller == -1)
        return -ENOSYS;

481 482 483 484 485 486
    if (group->controllers[controller].mountPoint == NULL)
        return -ENOENT;

    if (group->controllers[controller].placement == NULL)
        return -ENOENT;

487
    if (virAsprintf(path, "%s%s/%s",
488 489 490 491 492 493 494 495 496
                    group->controllers[controller].mountPoint,
                    group->controllers[controller].placement,
                    key ? key : "") == -1)
        return -ENOMEM;

    return 0;
}


497
static int virCgroupSetValueStr(virCgroupPtr group,
498
                                int controller,
499 500 501 502 503 504
                                const char *key,
                                const char *value)
{
    int rc = 0;
    char *keypath = NULL;

505
    rc = virCgroupPathOfController(group, controller, key, &keypath);
506 507 508
    if (rc != 0)
        return rc;

509
    VIR_DEBUG("Set value '%s' to '%s'", keypath, value);
510
    rc = virFileWriteStr(keypath, value, 0);
511 512
    if (rc < 0) {
        rc = -errno;
513
        VIR_DEBUG("Failed to write value '%s': %m", value);
514 515
    } else {
        rc = 0;
516 517 518 519 520 521 522 523
    }

    VIR_FREE(keypath);

    return rc;
}

static int virCgroupGetValueStr(virCgroupPtr group,
524
                                int controller,
525 526 527 528 529 530
                                const char *key,
                                char **value)
{
    int rc;
    char *keypath = NULL;

531
    *value = NULL;
532

533
    rc = virCgroupPathOfController(group, controller, key, &keypath);
534
    if (rc != 0) {
535
        VIR_DEBUG("No path of %s, %s", group->path, key);
536 537 538
        return rc;
    }

539
    VIR_DEBUG("Get value %s", keypath);
540

541
    rc = virFileReadAll(keypath, 1024*1024, value);
542 543
    if (rc < 0) {
        rc = -errno;
544
        VIR_DEBUG("Failed to read %s: %m\n", keypath);
545
    } else {
546
        /* Terminated with '\n' has sometimes harmful effects to the caller */
547 548
        if ((*value)[rc - 1] == '\n')
            (*value)[rc - 1] = '\0';
549

550
        rc = 0;
551 552 553 554 555 556 557
    }

    VIR_FREE(keypath);

    return rc;
}

558
static int virCgroupSetValueU64(virCgroupPtr group,
559
                                int controller,
560
                                const char *key,
D
Daniel P. Berrange 已提交
561
                                unsigned long long int value)
562 563 564 565
{
    char *strval = NULL;
    int rc;

D
Daniel P. Berrange 已提交
566
    if (virAsprintf(&strval, "%llu", value) == -1)
567 568
        return -ENOMEM;

569
    rc = virCgroupSetValueStr(group, controller, key, strval);
570 571 572 573 574 575 576

    VIR_FREE(strval);

    return rc;
}


577 578

static int virCgroupSetValueI64(virCgroupPtr group,
579
                                int controller,
580
                                const char *key,
D
Daniel P. Berrange 已提交
581
                                long long int value)
582 583 584 585
{
    char *strval = NULL;
    int rc;

D
Daniel P. Berrange 已提交
586
    if (virAsprintf(&strval, "%lld", value) == -1)
587 588
        return -ENOMEM;

589
    rc = virCgroupSetValueStr(group, controller, key, strval);
590 591 592 593 594 595 596

    VIR_FREE(strval);

    return rc;
}

static int virCgroupGetValueI64(virCgroupPtr group,
597
                                int controller,
598
                                const char *key,
D
Daniel P. Berrange 已提交
599
                                long long int *value)
600 601 602 603
{
    char *strval = NULL;
    int rc = 0;

604
    rc = virCgroupGetValueStr(group, controller, key, &strval);
605 606 607
    if (rc != 0)
        goto out;

608
    if (virStrToLong_ll(strval, NULL, 10, value) < 0)
609 610 611 612 613 614 615
        rc = -EINVAL;
out:
    VIR_FREE(strval);

    return rc;
}

616
static int virCgroupGetValueU64(virCgroupPtr group,
617
                                int controller,
618
                                const char *key,
D
Daniel P. Berrange 已提交
619
                                unsigned long long int *value)
620 621 622 623
{
    char *strval = NULL;
    int rc = 0;

624
    rc = virCgroupGetValueStr(group, controller, key, &strval);
625 626 627
    if (rc != 0)
        goto out;

D
Daniel P. Berrange 已提交
628
    if (virStrToLong_ull(strval, NULL, 10, value) < 0)
629 630 631 632 633 634 635 636
        rc = -EINVAL;
out:
    VIR_FREE(strval);

    return rc;
}


637
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
638
static int virCgroupCpuSetInherit(virCgroupPtr parent, virCgroupPtr group)
639 640 641 642 643 644 645 646
{
    int i;
    int rc = 0;
    const char *inherit_values[] = {
        "cpuset.cpus",
        "cpuset.mems",
    };

647 648 649
    VIR_DEBUG("Setting up inheritance %s -> %s", parent->path, group->path);
    for (i = 0; i < ARRAY_CARDINALITY(inherit_values) ; i++) {
        char *value;
650

651 652 653 654
        rc = virCgroupGetValueStr(parent,
                                  VIR_CGROUP_CONTROLLER_CPUSET,
                                  inherit_values[i],
                                  &value);
655
        if (rc != 0) {
656
            VIR_ERROR(_("Failed to get %s %d"), inherit_values[i], rc);
657 658 659 660 661 662 663 664 665
            break;
        }

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

        rc = virCgroupSetValueStr(group,
                                  VIR_CGROUP_CONTROLLER_CPUSET,
                                  inherit_values[i],
                                  value);
666
        VIR_FREE(value);
667 668

        if (rc != 0) {
669
            VIR_ERROR(_("Failed to set %s %d"), inherit_values[i], rc);
670 671 672 673 674 675 676
            break;
        }
    }

    return rc;
}

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
static int virCgroupSetMemoryUseHierarchy(virCgroupPtr group)
{
    int rc = 0;
    unsigned long long value;
    const char *filename = "memory.use_hierarchy";

    rc = virCgroupGetValueU64(group,
                              VIR_CGROUP_CONTROLLER_MEMORY,
                              filename, &value);
    if (rc != 0) {
        VIR_ERROR(_("Failed to read %s/%s (%d)"), group->path, filename, rc);
        return rc;
    }

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

    VIR_DEBUG("Setting up %s/%s", group->path, filename);
    rc = virCgroupSetValueU64(group,
                              VIR_CGROUP_CONTROLLER_MEMORY,
                              filename, 1);

    if (rc != 0) {
        VIR_ERROR(_("Failed to set %s/%s (%d)"), group->path, filename, rc);
    }

    return rc;
}

707 708 709 710
static int virCgroupMakeGroup(virCgroupPtr parent,
                              virCgroupPtr group,
                              bool create,
                              unsigned int flags)
711 712 713 714
{
    int i;
    int rc = 0;

715
    VIR_DEBUG("Make group %s", group->path);
716
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
717 718
        char *path = NULL;

719
        /* Skip over controllers that aren't mounted */
720 721 722
        if (!group->controllers[i].mountPoint) {
            VIR_DEBUG("Skipping unmounted controller %s",
                      virCgroupControllerTypeToString(i));
723
            continue;
724
        }
725

726
        rc = virCgroupPathOfController(group, i, "", &path);
727 728 729
        if (rc < 0) {
            VIR_DEBUG("Failed to find path of controller %s",
                      virCgroupControllerTypeToString(i));
730
            return rc;
731
        }
732 733 734
        /* As of Feb 2011, clang can't see that the above function
         * call did not modify group. */
        sa_assert(group->controllers[i].mountPoint);
735

736
        VIR_DEBUG("Make controller %s", path);
737
        if (access(path, F_OK) != 0) {
738 739
            if (!create ||
                mkdir(path, 0755) < 0) {
740 741 742 743 744
                /* With a kernel that doesn't support multi-level directory
                 * for blkio controller, libvirt will fail and disable all
                 * other controllers even though they are available. So
                 * treat blkio as unmounted if mkdir fails. */
                if (i == VIR_CGROUP_CONTROLLER_BLKIO) {
745
                    VIR_DEBUG("Ignoring mkdir failure with blkio controller. Kernel probably too old");
746 747 748 749 750
                    rc = 0;
                    VIR_FREE(group->controllers[i].mountPoint);
                    VIR_FREE(path);
                    continue;
                } else {
751 752
                    VIR_DEBUG("Failed to create controller %s for group",
                              virCgroupControllerTypeToString(i));
753 754 755 756
                    rc = -errno;
                    VIR_FREE(path);
                    break;
                }
757
            }
758 759 760 761
            if (group->controllers[VIR_CGROUP_CONTROLLER_CPUSET].mountPoint != NULL &&
                (i == VIR_CGROUP_CONTROLLER_CPUSET ||
                 STREQ(group->controllers[i].mountPoint, group->controllers[VIR_CGROUP_CONTROLLER_CPUSET].mountPoint))) {
                rc = virCgroupCpuSetInherit(parent, group);
762 763
                if (rc != 0) {
                    VIR_FREE(path);
764
                    break;
765
                }
766
            }
767 768 769 770
            /*
             * Note that virCgroupSetMemoryUseHierarchy should always be
             * called prior to creating subcgroups and attaching tasks.
             */
771 772
            if ((flags & VIR_CGROUP_MEM_HIERACHY) &&
                (group->controllers[VIR_CGROUP_CONTROLLER_MEMORY].mountPoint != NULL) &&
773 774 775 776 777 778 779 780
                (i == VIR_CGROUP_CONTROLLER_MEMORY ||
                 STREQ(group->controllers[i].mountPoint, group->controllers[VIR_CGROUP_CONTROLLER_MEMORY].mountPoint))) {
                rc = virCgroupSetMemoryUseHierarchy(group);
                if (rc != 0) {
                    VIR_FREE(path);
                    break;
                }
            }
781 782 783 784 785
        }

        VIR_FREE(path);
    }

786
    VIR_DEBUG("Done making controllers for group");
787 788 789
    return rc;
}

790

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
/**
 * 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.
 *
 */
806
static int virCgroupNew(const char *path,
807
                        virCgroupPtr parent,
808
                        int controllers,
809
                        virCgroupPtr *group)
810 811 812 813
{
    int rc = 0;
    char *typpath = NULL;

814 815
    VIR_DEBUG("parent=%p path=%s controllers=%d",
              parent, path, controllers);
816
    *group = NULL;
817

818
    if (VIR_ALLOC((*group)) != 0) {
819 820 821 822
        rc = -ENOMEM;
        goto err;
    }

823 824 825 826 827 828 829 830 831 832 833 834 835
    if (path[0] == '/' || !parent) {
        if (!((*group)->path = strdup(path))) {
            rc = -ENOMEM;
            goto err;
        }
    } else {
        if (virAsprintf(&(*group)->path, "%s%s%s",
                        parent->path,
                        STREQ(parent->path, "") ? "" : "/",
                        path) < 0) {
            rc = -ENOMEM;
            goto err;
        }
836 837
    }

838
    rc = virCgroupDetect(*group, controllers, path, parent);
839 840
    if (rc < 0)
        goto err;
841 842 843

    return rc;
err:
844 845
    virCgroupFree(group);
    *group = NULL;
846 847 848 849 850 851

    VIR_FREE(typpath);

    return rc;
}

852
static int virCgroupAppRoot(virCgroupPtr *group,
853 854
                            bool create,
                            int controllers)
855
{
856
    virCgroupPtr selfgrp = NULL;
857
    int rc;
858

859 860
    rc = virCgroupNewSelf(&selfgrp);

861 862
    if (rc != 0)
        return rc;
863

864
    rc = virCgroupNew("libvirt", selfgrp, controllers, group);
865
    if (rc != 0)
866
        goto cleanup;
867

868
    rc = virCgroupMakeGroup(selfgrp, *group, create, VIR_CGROUP_NONE);
869

870
cleanup:
871
    virCgroupFree(&selfgrp);
872 873
    return rc;
}
D
Daniel P. Berrange 已提交
874
#endif
875

876
#if defined _DIRENT_HAVE_D_TYPE
877
int virCgroupRemoveRecursively(char *grppath)
878 879 880 881 882 883 884
{
    DIR *grpdir;
    struct dirent *ent;
    int rc = 0;

    grpdir = opendir(grppath);
    if (grpdir == NULL) {
885 886
        if (errno == ENOENT)
            return 0;
887
        rc = -errno;
888
        VIR_ERROR(_("Unable to open %s (%d)"), grppath, errno);
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
        return rc;
    }

    for (;;) {
        char *path;

        errno = 0;
        ent = readdir(grpdir);
        if (ent == NULL) {
            if ((rc = -errno))
                VIR_ERROR(_("Failed to readdir for %s (%d)"), grppath, errno);
            break;
        }

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

        if (virAsprintf(&path, "%s/%s", grppath, ent->d_name) == -1) {
            rc = -ENOMEM;
            break;
        }
        rc = virCgroupRemoveRecursively(path);
        VIR_FREE(path);
        if (rc != 0)
            break;
    }
    closedir(grpdir);

917
    VIR_DEBUG("Removing cgroup %s", grppath);
918 919 920 921 922 923 924
    if (rmdir(grppath) != 0 && errno != ENOENT) {
        rc = -errno;
        VIR_ERROR(_("Unable to remove %s (%d)"), grppath, errno);
    }

    return rc;
}
925
#else
926
int virCgroupRemoveRecursively(char *grppath ATTRIBUTE_UNUSED)
927 928 929 930 931
{
    /* Claim no support */
    return -ENXIO;
}
#endif
932

933 934 935 936 937
/**
 * virCgroupRemove:
 *
 * @group: The group to be removed
 *
938 939 940 941 942
 * 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.
 *
943 944 945 946 947 948 949 950
 * Returns: 0 on success
 */
int virCgroupRemove(virCgroupPtr group)
{
    int rc = 0;
    int i;
    char *grppath = NULL;

951
    VIR_DEBUG("Removing cgroup %s", group->path);
952
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
953 954
        /* Skip over controllers not mounted */
        if (!group->controllers[i].mountPoint)
955 956
            continue;

957 958 959 960 961
        if (virCgroupPathOfController(group,
                                      i,
                                      NULL,
                                      &grppath) != 0)
            continue;
962

963
        VIR_DEBUG("Removing cgroup %s and all child cgroups", grppath);
964
        rc = virCgroupRemoveRecursively(grppath);
965 966
        VIR_FREE(grppath);
    }
967
    VIR_DEBUG("Done removing cgroup %s", group->path);
968 969 970 971

    return rc;
}

972

973 974 975 976 977 978 979 980 981 982 983 984 985
/**
 * virCgroupAddTask:
 *
 * @group: The cgroup to add a task to
 * @pid: The pid of the task to add
 *
 * Returns: 0 on success
 */
int virCgroupAddTask(virCgroupPtr group, pid_t pid)
{
    int rc = 0;
    int i;

986
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
987 988 989
        /* Skip over controllers not mounted */
        if (!group->controllers[i].mountPoint)
            continue;
990

991
        rc = virCgroupSetValueU64(group, i, "tasks", (unsigned long long)pid);
992 993 994 995 996 997 998
        if (rc != 0)
            break;
    }

    return rc;
}

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
/**
 * virCgroupAddTaskController:
 *
 * @group: The cgroup to add a task to
 * @pid: The pid of the task to add
 * @controller: The cgroup controller to be operated on
 *
 * Returns: 0 on success or -errno on failure
 */
int virCgroupAddTaskController(virCgroupPtr group, pid_t pid, int controller)
{
1010
    if (controller < 0 || controller >= VIR_CGROUP_CONTROLLER_LAST)
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 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
        return -EINVAL;

    if (!group->controllers[controller].mountPoint)
        return -EINVAL;

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


static int virCgroupAddTaskStrController(virCgroupPtr group,
                                        const char *pidstr,
                                        int controller)
{
    char *str = NULL, *cur = NULL, *next = NULL;
    unsigned long long p = 0;
    int rc = 0;
    char *endp;

    if (virAsprintf(&str, "%s", pidstr) < 0)
        return -1;

    cur = str;
    while (*cur != '\0') {
        rc = virStrToLong_ull(cur, &endp, 10, &p);
        if (rc != 0)
            goto cleanup;

        rc = virCgroupAddTaskController(group, p, controller);
        if (rc != 0)
            goto cleanup;

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

cleanup:
    VIR_FREE(str);
    return rc;
}

/**
 * virCgroupMoveTask:
 *
 * @src_group: The source cgroup where all tasks are removed from
 * @dest_group: The destination where all tasks are added to
 * @controller: The cgroup controller to be operated on
 *
 * Returns: 0 on success or -errno on failure
 */
1066
int virCgroupMoveTask(virCgroupPtr src_group, virCgroupPtr dest_group)
1067
{
1068
    int rc = 0;
1069
    char *content = NULL;
1070
    int i;
1071

1072 1073 1074 1075
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
        if (!src_group->controllers[i].mountPoint ||
            !dest_group->controllers[i].mountPoint)
            continue;
1076

1077 1078 1079
        rc = virCgroupGetValueStr(src_group, i, "tasks", &content);
        if (rc != 0)
            return rc;
1080

1081 1082 1083
        rc = virCgroupAddTaskStrController(dest_group, content, i);
        if (rc != 0)
            goto cleanup;
1084

1085 1086
        VIR_FREE(content);
    }
1087 1088 1089 1090 1091

cleanup:
    VIR_FREE(content);
    return rc;
}
1092

1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163

#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
/**
 * virCgroupNewPartition:
 * @path: path for the partition
 * @create: true to create the cgroup tree
 * @controllers: mask of controllers to create
 *
 * Creates a new cgroup to represent the resource
 * partition path identified by @name.
 *
 * Returns 0 on success, -errno on failure
 */
int virCgroupNewPartition(const char *path,
                          bool create,
                          int controllers,
                          virCgroupPtr *group)
{
    int rc;
    char *parentPath = NULL;
    virCgroupPtr parent = NULL;
    VIR_DEBUG("path=%s create=%d controllers=%x",
              path, create, controllers);

    if (path[0] != '/')
        return -EINVAL;

    rc = virCgroupNew(path, NULL, controllers, group);
    if (rc != 0)
        goto cleanup;

    if (STRNEQ(path, "/")) {
        char *tmp;
        if (!(parentPath = strdup(path))) {
            rc = -ENOMEM;
            goto cleanup;
        }

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

        rc = virCgroupNew(parentPath, NULL, controllers, &parent);
        if (rc != 0)
            goto cleanup;

        rc = virCgroupMakeGroup(parent, *group, create, VIR_CGROUP_NONE);
        if (rc != 0) {
            virCgroupRemove(*group);
            goto cleanup;
        }
    }

cleanup:
    if (rc != 0)
        virCgroupFree(group);
    virCgroupFree(&parent);
    VIR_FREE(parentPath);
    return rc;
}
#else
int virCgroupNewPartition(const char *path ATTRIBUTE_UNUSED,
                          bool create ATTRIBUTE_UNUSED,
                          int controllers ATTRIBUTE_UNUSED,
                          virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    /* Claim no support */
    return -ENXIO;
}
#endif

1164
/**
1165
 * virCgroupNewDriver:
1166
 *
1167
 * @name: name of this driver (e.g., xen, qemu, lxc)
1168 1169 1170 1171
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success
 */
1172
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
1173
int virCgroupNewDriver(const char *name,
1174
                       bool create,
1175 1176
                       int controllers,
                       virCgroupPtr *group)
1177 1178
{
    int rc;
1179
    virCgroupPtr rootgrp = NULL;
1180

1181
    rc = virCgroupAppRoot(&rootgrp,
1182
                          create, controllers);
1183
    if (rc != 0)
1184 1185
        goto out;

1186
    rc = virCgroupNew(name, rootgrp, -1, group);
1187
    if (rc == 0) {
1188
        rc = virCgroupMakeGroup(rootgrp, *group, create, VIR_CGROUP_NONE);
1189 1190
        if (rc != 0) {
            virCgroupRemove(*group);
1191
            virCgroupFree(group);
1192
        }
1193
    }
1194
out:
1195
    virCgroupFree(&rootgrp);
1196 1197 1198

    return rc;
}
D
Daniel P. Berrange 已提交
1199
#else
1200
int virCgroupNewDriver(const char *name ATTRIBUTE_UNUSED,
1201
                       bool create ATTRIBUTE_UNUSED,
1202 1203
                       int controllers ATTRIBUTE_UNUSED,
                       virCgroupPtr *group ATTRIBUTE_UNUSED)
D
Daniel P. Berrange 已提交
1204 1205 1206 1207 1208
{
    /* Claim no support */
    return -ENXIO;
}
#endif
1209

G
Gao feng 已提交
1210
/**
1211
* virCgroupNewSelf:
G
Gao feng 已提交
1212 1213 1214
*
* @group: Pointer to returned virCgroupPtr
*
1215 1216 1217
* Obtain a cgroup representing the config of the
* current process
*
G
Gao feng 已提交
1218 1219
* Returns 0 on success
*/
1220
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
1221
int virCgroupNewSelf(virCgroupPtr *group)
G
Gao feng 已提交
1222
{
1223
    return virCgroupNew("", NULL, -1, group);
1224
}
G
Gao feng 已提交
1225
#else
1226
int virCgroupNewSelf(virCgroupPtr *group ATTRIBUTE_UNUSED)
1227
{
G
Gao feng 已提交
1228 1229
    return -ENXIO;
}
1230
#endif
1231 1232

/**
1233
 * virCgroupNewDomainDriver:
1234 1235 1236 1237 1238 1239 1240
 *
 * @driver: group for driver owning the domain
 * @name: name of the domain
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success
 */
1241
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
1242 1243 1244 1245
int virCgroupNewDomainDriver(virCgroupPtr driver,
                             const char *name,
                             bool create,
                             virCgroupPtr *group)
1246 1247 1248
{
    int rc;

1249
    rc = virCgroupNew(name, driver, -1, group);
1250

1251
    if (rc == 0) {
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        /*
         * 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.
         */
1262
        rc = virCgroupMakeGroup(driver, *group, create, VIR_CGROUP_MEM_HIERACHY);
1263 1264
        if (rc != 0) {
            virCgroupRemove(*group);
1265
            virCgroupFree(group);
1266
        }
1267 1268 1269 1270
    }

    return rc;
}
D
Daniel P. Berrange 已提交
1271
#else
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
int virCgroupNewDomainDriver(virCgroupPtr driver ATTRIBUTE_UNUSED,
                             const char *name ATTRIBUTE_UNUSED,
                             bool create ATTRIBUTE_UNUSED,
                             virCgroupPtr *group ATTRIBUTE_UNUSED)
{
    return -ENXIO;
}
#endif

/**
 * virCgroupNewDomainPartition:
 *
 * @partition: partition holding the domain
 * @driver: name of the driver
 * @name: name of the domain
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success
 */
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
int virCgroupNewDomainPartition(virCgroupPtr partition,
                                const char *driver,
                                const char *name,
                                bool create,
                                virCgroupPtr *group)
{
    int rc;
    char *dirname = NULL;

    if (virAsprintf(&dirname, "%s.%s.libvirt",
                    name, driver) < 0)
        return -ENOMEM;

    rc = virCgroupNew(dirname, partition, -1, group);

    if (rc == 0) {
        /*
         * 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.
         */
        rc = virCgroupMakeGroup(partition, *group, create, VIR_CGROUP_MEM_HIERACHY);
        if (rc != 0) {
            virCgroupRemove(*group);
            virCgroupFree(group);
        }
    }

    VIR_FREE(dirname);
    return rc;
}
#else
int virCgroupNewDomainPartition(virCgroupPtr partition ATTRIBUTE_UNUSED,
                                const char *driver ATTRIBUTE_UNUSED,
                                const char *name ATTRIBUTE_UNUSED,
                                bool create ATTRIBUTE_UNUSED,
                                virCgroupPtr *group ATTRIBUTE_UNUSED)
D
Daniel P. Berrange 已提交
1334 1335 1336 1337
{
    return -ENXIO;
}
#endif
1338

1339
/**
1340
 * virCgroupNewVcpu:
1341
 *
1342
 * @domain: group for the domain
1343
 * @vcpuid: id of the vcpu
1344
 * @create: true to create if not already existing
1345 1346 1347 1348 1349
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success
 */
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
1350
int virCgroupNewVcpu(virCgroupPtr domain,
1351
                     int vcpuid,
1352 1353
                     bool create,
                     virCgroupPtr *group)
1354 1355
{
    int rc;
1356
    char *name;
1357
    int controllers;
1358

1359
    if (virAsprintf(&name, "vcpu%d", vcpuid) < 0)
1360 1361
        return -ENOMEM;

1362 1363 1364 1365
    controllers = ((1 << VIR_CGROUP_CONTROLLER_CPU) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUACCT) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUSET));

1366 1367
    rc = virCgroupNew(name, domain, controllers, group);
    VIR_FREE(name);
1368 1369

    if (rc == 0) {
1370
        rc = virCgroupMakeGroup(domain, *group, create, VIR_CGROUP_NONE);
1371 1372
        if (rc != 0) {
            virCgroupRemove(*group);
1373
            virCgroupFree(group);
1374
        }
1375 1376 1377 1378 1379
    }

    return rc;
}
#else
1380
int virCgroupNewVcpu(virCgroupPtr domain ATTRIBUTE_UNUSED,
1381
                     int vcpuid ATTRIBUTE_UNUSED,
1382 1383
                     bool create ATTRIBUTE_UNUSED,
                     virCgroupPtr *group ATTRIBUTE_UNUSED)
1384 1385 1386 1387 1388
{
    return -ENXIO;
}
#endif

1389
/**
1390
 * virCgroupNewEmulator:
1391
 *
1392 1393
 * @domain: group for the domain
 * @create: true to create if not already existing
1394 1395 1396 1397 1398
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns: 0 on success or -errno on failure
 */
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
1399 1400 1401
int virCgroupNewEmulator(virCgroupPtr domain,
                         bool create,
                         virCgroupPtr *group)
1402 1403
{
    int rc;
1404
    int controllers;
1405

1406 1407 1408 1409
    controllers = ((1 << VIR_CGROUP_CONTROLLER_CPU) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUACCT) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUSET));

1410
    rc = virCgroupNew("emulator", domain, controllers, group);
1411 1412

    if (rc == 0) {
1413
        rc = virCgroupMakeGroup(domain, *group, create, VIR_CGROUP_NONE);
1414 1415
        if (rc != 0) {
            virCgroupRemove(*group);
1416
            virCgroupFree(group);
1417
        }
1418 1419 1420 1421 1422
    }

    return rc;
}
#else
1423 1424 1425
int virCgroupNewEmulator(virCgroupPtr domain ATTRIBUTE_UNUSED,
                         bool create ATTRIBUTE_UNUSED,
                         virCgroupPtr *group ATTRIBUTE_UNUSED)
1426 1427 1428 1429 1430
{
    return -ENXIO;
}

#endif
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
/**
 * virCgroupSetBlkioWeight:
 *
 * @group: The cgroup to change io weight for
 * @weight: The Weight for this cgroup
 *
 * Returns: 0 on success
 */
int virCgroupSetBlkioWeight(virCgroupPtr group, unsigned int weight)
{
    if (weight > 1000 || weight < 100)
        return -EINVAL;

    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_BLKIO,
                                "blkio.weight",
                                weight);
}

/**
 * virCgroupGetBlkioWeight:
 *
 * @group: The cgroup to get weight for
 * @Weight: Pointer to returned weight
 *
 * Returns: 0 on success
 */
int virCgroupGetBlkioWeight(virCgroupPtr group, unsigned int *weight)
{
    unsigned long long tmp;
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_BLKIO,
                               "blkio.weight", &tmp);
    if (ret == 0)
        *weight = tmp;
    return ret;
}

1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
/**
 * virCgroupSetBlkioDeviceWeight:
 *
 * @group: The cgroup to change io device weight device for
 * @path: The device with a weight to alter
 * @weight: The new device weight (100-1000), or 0 to clear
 *
 * device_weight is treated as a write-only parameter, so
 * there isn't a getter counterpart.
 *
 * Returns: 0 on success, -errno on failure
 */
#if defined(major) && defined(minor)
int virCgroupSetBlkioDeviceWeight(virCgroupPtr group,
                                  const char *path,
                                  unsigned int weight)
{
    char *str;
    struct stat sb;
    int ret;

    if (weight && (weight > 1000 || weight < 100))
        return -EINVAL;

    if (stat(path, &sb) < 0)
        return -errno;

    if (!S_ISBLK(sb.st_mode))
        return -EINVAL;

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

    ret = virCgroupSetValueStr(group,
                               VIR_CGROUP_CONTROLLER_BLKIO,
                               "blkio.weight_device",
                               str);
    VIR_FREE(str);
    return ret;
}
#else
O
Osier Yang 已提交
1512 1513 1514 1515
int
virCgroupSetBlkioDeviceWeight(virCgroupPtr group ATTRIBUTE_UNUSED,
                              const char *path ATTRIBUTE_UNUSED,
                              unsigned int weight ATTRIBUTE_UNUSED)
1516 1517 1518 1519 1520
{
    return -ENOSYS;
}
#endif

1521 1522 1523 1524 1525 1526 1527 1528
/**
 * virCgroupSetMemory:
 *
 * @group: The cgroup to change memory for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
1529
int virCgroupSetMemory(virCgroupPtr group, unsigned long long kb)
1530
{
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

    if (kb > maxkb)
        return -EINVAL;
    else if (kb == maxkb)
        return virCgroupSetValueI64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.limit_in_bytes",
                                    -1);
    else
        return virCgroupSetValueU64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.limit_in_bytes",
                                    kb << 10);
1545 1546
}

R
Ryota Ozaki 已提交
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
/**
 * virCgroupGetMemoryUsage:
 *
 * @group: The cgroup to change memory for
 * @kb: Pointer to returned used memory in kilobytes
 *
 * Returns: 0 on success
 */
int virCgroupGetMemoryUsage(virCgroupPtr group, unsigned long *kb)
{
C
Cole Robinson 已提交
1557
    long long unsigned int usage_in_bytes;
R
Ryota Ozaki 已提交
1558 1559 1560 1561 1562 1563 1564 1565 1566
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_MEMORY,
                               "memory.usage_in_bytes", &usage_in_bytes);
    if (ret == 0)
        *kb = (unsigned long) usage_in_bytes >> 10;
    return ret;
}

1567 1568 1569 1570 1571 1572 1573 1574
/**
 * virCgroupSetMemoryHardLimit:
 *
 * @group: The cgroup to change memory hard limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
1575
int virCgroupSetMemoryHardLimit(virCgroupPtr group, unsigned long long kb)
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
{
    return virCgroupSetMemory(group, kb);
}

/**
 * virCgroupGetMemoryHardLimit:
 *
 * @group: The cgroup to get the memory hard limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
1588
int virCgroupGetMemoryHardLimit(virCgroupPtr group, unsigned long long *kb)
1589 1590 1591 1592 1593 1594 1595
{
    long long unsigned int limit_in_bytes;
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_MEMORY,
                               "memory.limit_in_bytes", &limit_in_bytes);
    if (ret == 0)
1596
        *kb = limit_in_bytes >> 10;
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
    return ret;
}

/**
 * virCgroupSetMemorySoftLimit:
 *
 * @group: The cgroup to change memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
1608
int virCgroupSetMemorySoftLimit(virCgroupPtr group, unsigned long long kb)
1609
{
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

    if (kb > maxkb)
        return -EINVAL;
    else if (kb == maxkb)
        return virCgroupSetValueI64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.soft_limit_in_bytes",
                                    -1);
    else
        return virCgroupSetValueU64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.soft_limit_in_bytes",
                                    kb << 10);
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
}


/**
 * virCgroupGetMemorySoftLimit:
 *
 * @group: The cgroup to get the memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
1635
int virCgroupGetMemorySoftLimit(virCgroupPtr group, unsigned long long *kb)
1636 1637 1638 1639 1640 1641 1642
{
    long long unsigned int limit_in_bytes;
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_MEMORY,
                               "memory.soft_limit_in_bytes", &limit_in_bytes);
    if (ret == 0)
1643
        *kb = limit_in_bytes >> 10;
1644 1645 1646 1647
    return ret;
}

/**
1648
 * virCgroupSetMemSwapHardLimit:
1649
 *
1650 1651
 * @group: The cgroup to change mem+swap hard limit for
 * @kb: The mem+swap amount in kilobytes
1652 1653 1654
 *
 * Returns: 0 on success
 */
1655
int virCgroupSetMemSwapHardLimit(virCgroupPtr group, unsigned long long kb)
1656
{
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    unsigned long long maxkb = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;

    if (kb > maxkb)
        return -EINVAL;
    else if (kb == maxkb)
        return virCgroupSetValueI64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.memsw.limit_in_bytes",
                                    -1);
    else
        return virCgroupSetValueU64(group,
                                    VIR_CGROUP_CONTROLLER_MEMORY,
                                    "memory.memsw.limit_in_bytes",
                                    kb << 10);
1671 1672 1673
}

/**
1674
 * virCgroupGetMemSwapHardLimit:
1675
 *
1676 1677
 * @group: The cgroup to get mem+swap hard limit for
 * @kb: The mem+swap amount in kilobytes
1678 1679 1680
 *
 * Returns: 0 on success
 */
1681
int virCgroupGetMemSwapHardLimit(virCgroupPtr group, unsigned long long *kb)
1682 1683 1684 1685 1686 1687 1688
{
    long long unsigned int limit_in_bytes;
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_MEMORY,
                               "memory.memsw.limit_in_bytes", &limit_in_bytes);
    if (ret == 0)
1689
        *kb = limit_in_bytes >> 10;
1690 1691 1692
    return ret;
}

G
Gao feng 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
/**
 * virCgroupGetMemSwapUsage:
 *
 * @group: The cgroup to get mem+swap usage for
 * @kb: The mem+swap amount in kilobytes
 *
 * Returns: 0 on success
 */
int virCgroupGetMemSwapUsage(virCgroupPtr group, unsigned long long *kb)
{
    long long unsigned int usage_in_bytes;
    int ret;
    ret = virCgroupGetValueU64(group,
                               VIR_CGROUP_CONTROLLER_MEMORY,
                               "memory.memsw.usage_in_bytes", &usage_in_bytes);
    if (ret == 0)
        *kb = usage_in_bytes >> 10;
    return ret;
}

1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
/**
 * virCgroupSetCpusetMems:
 *
 * @group: The cgroup to set cpuset.mems for
 * @mems: the numa nodes to set
 *
 * Returns: 0 on success
 */
int virCgroupSetCpusetMems(virCgroupPtr group, const char *mems)
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.mems",
                                mems);
}

/**
 * virCgroupGetCpusetMems:
 *
 * @group: The cgroup to get cpuset.mems for
 * @mems: the numa nodes to get
 *
 * Returns: 0 on success
 */
int virCgroupGetCpusetMems(virCgroupPtr group, char **mems)
{
    return virCgroupGetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.mems",
                                mems);
}

1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
/**
 * virCgroupSetCpusetCpus:
 *
 * @group: The cgroup to set cpuset.cpus for
 * @cpus: the cpus to set
 *
 * Retuens: 0 on success
 */
int virCgroupSetCpusetCpus(virCgroupPtr group, const char *cpus)
{
    return virCgroupSetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.cpus",
                                cpus);
}

/**
 * virCgroupGetCpusetCpus:
 *
 * @group: The cgroup to get cpuset.cpus for
 * @cpus: the cpus to get
 *
 * Retuens: 0 on success
 */
int virCgroupGetCpusetCpus(virCgroupPtr group, char **cpus)
{
    return virCgroupGetValueStr(group,
                                VIR_CGROUP_CONTROLLER_CPUSET,
                                "cpuset.cpus",
                                cpus);
}

1777 1778 1779
/**
 * virCgroupDenyAllDevices:
 *
1780
 * @group: The cgroup to deny all permissions, for all devices
1781 1782 1783 1784 1785 1786
 *
 * Returns: 0 on success
 */
int virCgroupDenyAllDevices(virCgroupPtr group)
{
    return virCgroupSetValueStr(group,
1787 1788 1789
                                VIR_CGROUP_CONTROLLER_DEVICES,
                                "devices.deny",
                                "a");
1790 1791 1792 1793 1794 1795 1796 1797 1798
}

/**
 * virCgroupAllowDevice:
 *
 * @group: The cgroup to allow a device for
 * @type: The device type (i.e., 'c' or 'b')
 * @major: The major number of the device
 * @minor: The minor number of the device
1799
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
1800 1801 1802
 *
 * Returns: 0 on success
 */
1803 1804
int virCgroupAllowDevice(virCgroupPtr group, char type, int major, int minor,
                         int perms)
1805 1806 1807 1808
{
    int rc;
    char *devstr = NULL;

1809 1810 1811 1812
    if (virAsprintf(&devstr, "%c %i:%i %s%s%s", type, major, minor,
                    perms & VIR_CGROUP_DEVICE_READ ? "r" : "",
                    perms & VIR_CGROUP_DEVICE_WRITE ? "w" : "",
                    perms & VIR_CGROUP_DEVICE_MKNOD ? "m" : "") == -1) {
1813 1814 1815 1816 1817
        rc = -ENOMEM;
        goto out;
    }

    rc = virCgroupSetValueStr(group,
1818
                              VIR_CGROUP_CONTROLLER_DEVICES,
1819 1820 1821 1822 1823 1824 1825
                              "devices.allow",
                              devstr);
out:
    VIR_FREE(devstr);

    return rc;
}
1826

1827 1828 1829 1830 1831 1832
/**
 * virCgroupAllowDeviceMajor:
 *
 * @group: The cgroup to allow an entire device major type for
 * @type: The device type (i.e., 'c' or 'b')
 * @major: The major number of the device type
1833
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
1834 1835 1836
 *
 * Returns: 0 on success
 */
1837 1838
int virCgroupAllowDeviceMajor(virCgroupPtr group, char type, int major,
                              int perms)
1839 1840 1841 1842
{
    int rc;
    char *devstr = NULL;

1843 1844 1845 1846
    if (virAsprintf(&devstr, "%c %i:* %s%s%s", type, major,
                    perms & VIR_CGROUP_DEVICE_READ ? "r" : "",
                    perms & VIR_CGROUP_DEVICE_WRITE ? "w" : "",
                    perms & VIR_CGROUP_DEVICE_MKNOD ? "m" : "") == -1) {
1847 1848 1849 1850 1851
        rc = -ENOMEM;
        goto out;
    }

    rc = virCgroupSetValueStr(group,
1852
                              VIR_CGROUP_CONTROLLER_DEVICES,
1853 1854 1855 1856 1857 1858 1859 1860
                              "devices.allow",
                              devstr);
 out:
    VIR_FREE(devstr);

    return rc;
}

1861 1862 1863 1864 1865
/**
 * virCgroupAllowDevicePath:
 *
 * @group: The cgroup to allow the device for
 * @path: the device to allow
1866
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to allow
1867 1868 1869 1870
 *
 * Queries the type of device and its major/minor number, and
 * adds that to the cgroup ACL
 *
1871 1872
 * Returns: 0 on success, 1 if path exists but is not a device, or
 * negative errno value on failure
1873
 */
D
Daniel P. Berrange 已提交
1874
#if defined(major) && defined(minor)
1875
int virCgroupAllowDevicePath(virCgroupPtr group, const char *path, int perms)
1876 1877 1878 1879 1880 1881 1882
{
    struct stat sb;

    if (stat(path, &sb) < 0)
        return -errno;

    if (!S_ISCHR(sb.st_mode) && !S_ISBLK(sb.st_mode))
1883
        return 1;
1884 1885 1886 1887

    return virCgroupAllowDevice(group,
                                S_ISCHR(sb.st_mode) ? 'c' : 'b',
                                major(sb.st_rdev),
1888 1889
                                minor(sb.st_rdev),
                                perms);
1890
}
D
Daniel P. Berrange 已提交
1891 1892
#else
int virCgroupAllowDevicePath(virCgroupPtr group ATTRIBUTE_UNUSED,
1893 1894
                             const char *path ATTRIBUTE_UNUSED,
                             int perms ATTRIBUTE_UNUSED)
D
Daniel P. Berrange 已提交
1895 1896 1897 1898 1899
{
    return -ENOSYS;
}
#endif

1900 1901 1902 1903 1904 1905 1906 1907

/**
 * virCgroupDenyDevice:
 *
 * @group: The cgroup to deny a device for
 * @type: The device type (i.e., 'c' or 'b')
 * @major: The major number of the device
 * @minor: The minor number of the device
1908
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to deny
1909 1910 1911
 *
 * Returns: 0 on success
 */
1912 1913
int virCgroupDenyDevice(virCgroupPtr group, char type, int major, int minor,
                        int perms)
1914 1915 1916 1917
{
    int rc;
    char *devstr = NULL;

1918 1919 1920 1921
    if (virAsprintf(&devstr, "%c %i:%i %s%s%s", type, major, minor,
                    perms & VIR_CGROUP_DEVICE_READ ? "r" : "",
                    perms & VIR_CGROUP_DEVICE_WRITE ? "w" : "",
                    perms & VIR_CGROUP_DEVICE_MKNOD ? "m" : "") == -1) {
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
        rc = -ENOMEM;
        goto out;
    }

    rc = virCgroupSetValueStr(group,
                              VIR_CGROUP_CONTROLLER_DEVICES,
                              "devices.deny",
                              devstr);
out:
    VIR_FREE(devstr);

    return rc;
}

/**
 * virCgroupDenyDeviceMajor:
 *
 * @group: The cgroup to deny an entire device major type for
 * @type: The device type (i.e., 'c' or 'b')
 * @major: The major number of the device type
1942
 * @perms: Bitwise or of VIR_CGROUP_DEVICE permission bits to deny
1943 1944 1945
 *
 * Returns: 0 on success
 */
1946 1947
int virCgroupDenyDeviceMajor(virCgroupPtr group, char type, int major,
                             int perms)
1948 1949 1950 1951
{
    int rc;
    char *devstr = NULL;

1952 1953 1954 1955
    if (virAsprintf(&devstr, "%c %i:* %s%s%s", type, major,
                    perms & VIR_CGROUP_DEVICE_READ ? "r" : "",
                    perms & VIR_CGROUP_DEVICE_WRITE ? "w" : "",
                    perms & VIR_CGROUP_DEVICE_MKNOD ? "m" : "") == -1) {
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
        rc = -ENOMEM;
        goto out;
    }

    rc = virCgroupSetValueStr(group,
                              VIR_CGROUP_CONTROLLER_DEVICES,
                              "devices.deny",
                              devstr);
 out:
    VIR_FREE(devstr);

    return rc;
}

D
Daniel P. Berrange 已提交
1970
#if defined(major) && defined(minor)
1971
int virCgroupDenyDevicePath(virCgroupPtr group, const char *path, int perms)
1972 1973 1974 1975 1976 1977 1978
{
    struct stat sb;

    if (stat(path, &sb) < 0)
        return -errno;

    if (!S_ISCHR(sb.st_mode) && !S_ISBLK(sb.st_mode))
1979
        return 1;
1980 1981 1982 1983

    return virCgroupDenyDevice(group,
                               S_ISCHR(sb.st_mode) ? 'c' : 'b',
                               major(sb.st_rdev),
1984 1985
                               minor(sb.st_rdev),
                               perms);
1986
}
D
Daniel P. Berrange 已提交
1987 1988
#else
int virCgroupDenyDevicePath(virCgroupPtr group ATTRIBUTE_UNUSED,
1989 1990
                            const char *path ATTRIBUTE_UNUSED,
                            int perms ATTRIBUTE_UNUSED)
D
Daniel P. Berrange 已提交
1991 1992 1993 1994
{
    return -ENOSYS;
}
#endif
1995

1996
int virCgroupSetCpuShares(virCgroupPtr group, unsigned long long shares)
1997
{
1998 1999
    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
D
Daniel P. Berrange 已提交
2000
                                "cpu.shares", shares);
2001 2002
}

2003
int virCgroupGetCpuShares(virCgroupPtr group, unsigned long long *shares)
2004
{
2005 2006
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
D
Daniel P. Berrange 已提交
2007
                                "cpu.shares", shares);
2008
}
2009

2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
/**
 * virCgroupSetCpuCfsPeriod:
 *
 * @group: The cgroup to change cpu.cfs_period_us for
 * @cfs_period: The bandwidth period in usecs
 *
 * Returns: 0 on success
 */
int virCgroupSetCpuCfsPeriod(virCgroupPtr group, unsigned long long cfs_period)
{
    /* The cfs_period shoule be greater or equal than 1ms, and less or equal
     * than 1s.
     */
    if (cfs_period < 1000 || cfs_period > 1000000)
        return -EINVAL;

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

/**
 * 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
 */
int virCgroupGetCpuCfsPeriod(virCgroupPtr group, unsigned long long *cfs_period)
{
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.cfs_period_us", cfs_period);
}

/**
 * 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
 */
int virCgroupSetCpuCfsQuota(virCgroupPtr group, long long cfs_quota)
{
    if (cfs_quota >= 0) {
        /* The cfs_quota shoule be greater or equal than 1ms */
        if (cfs_quota < 1000)
            return -EINVAL;

        /* check overflow */
        if (cfs_quota > ULLONG_MAX / 1000)
            return -EINVAL;
    }

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

/**
 * virCgroupGetCpuCfsQuota:
 *
 * @group: The cgroup to get cpu.cfs_quota_us for
 * @cfs_quota: Pointer to the returned cpu bandwidth (in usecs) that this tg
 *             will be allowed to consume over period
 *
 * Returns: 0 on success
 */
int virCgroupGetCpuCfsQuota(virCgroupPtr group, long long *cfs_quota)
{
    return virCgroupGetValueI64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
                                "cpu.cfs_quota_us", cfs_quota);
}

2088 2089
int virCgroupGetCpuacctUsage(virCgroupPtr group, unsigned long long *usage)
{
2090 2091
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPUACCT,
D
Daniel P. Berrange 已提交
2092
                                "cpuacct.usage", usage);
2093
}
R
Ryota Ozaki 已提交
2094

2095 2096 2097 2098 2099 2100
int virCgroupGetCpuacctPercpuUsage(virCgroupPtr group, char **usage)
{
    return virCgroupGetValueStr(group, VIR_CGROUP_CONTROLLER_CPUACCT,
                                "cpuacct.usage_percpu", usage);
}

2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
#ifdef _SC_CLK_TCK
int virCgroupGetCpuacctStat(virCgroupPtr group, unsigned long long *user,
                            unsigned long long *sys)
{
    char *str;
    char *p;
    int ret;
    static double scale = -1.0;

    if ((ret = virCgroupGetValueStr(group, VIR_CGROUP_CONTROLLER_CPUACCT,
                                    "cpuacct.stat", &str)) < 0)
        return ret;
    if (!(p = STRSKIP(str, "user ")) ||
        virStrToLong_ull(p, &p, 10, user) < 0 ||
        !(p = STRSKIP(p, "\nsystem ")) ||
        virStrToLong_ull(p, NULL, 10, sys) < 0) {
        ret = -EINVAL;
        goto cleanup;
    }
    /* times reported are in system ticks (generally 100 Hz), but that
     * rate can theoretically vary between machines.  Scale things
     * into approximate nanoseconds.  */
    if (scale < 0) {
        long ticks_per_sec = sysconf(_SC_CLK_TCK);
        if (ticks_per_sec == -1) {
            ret = -errno;
            goto cleanup;
        }
        scale = 1000000000.0 / ticks_per_sec;
    }
    *user *= scale;
    *sys *= scale;

    ret = 0;
cleanup:
    VIR_FREE(str);
    return ret;
}
#else
int virCgroupGetCpuacctStat(virCgroupPtr group ATTRIBUTE_UNUSED,
                            unsigned long long *user ATTRIBUTE_UNUSED,
                            unsigned long long *sys ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}
#endif

R
Ryota Ozaki 已提交
2148 2149 2150
int virCgroupSetFreezerState(virCgroupPtr group, const char *state)
{
    return virCgroupSetValueStr(group,
2151
                                VIR_CGROUP_CONTROLLER_FREEZER,
R
Ryota Ozaki 已提交
2152 2153 2154 2155 2156
                                "freezer.state", state);
}

int virCgroupGetFreezerState(virCgroupPtr group, char **state)
{
2157
    return virCgroupGetValueStr(group,
2158
                                VIR_CGROUP_CONTROLLER_FREEZER,
R
Ryota Ozaki 已提交
2159 2160
                                "freezer.state", state);
}
2161

2162

E
Eric Blake 已提交
2163
#if defined HAVE_KILL && defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
2164 2165 2166 2167 2168 2169
static int virCgroupKillInternal(virCgroupPtr group, int signum, virHashTablePtr pids)
{
    int rc;
    int killedAny = 0;
    char *keypath = NULL;
    bool done = false;
E
Eric Blake 已提交
2170 2171 2172
    FILE *fp = NULL;
    VIR_DEBUG("group=%p path=%s signum=%d pids=%p",
              group, group->path, signum, pids);
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190

    rc = virCgroupPathOfController(group, -1, "tasks", &keypath);
    if (rc != 0) {
        VIR_DEBUG("No path of %s, tasks", group->path);
        return rc;
    }

    /* 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"))) {
            rc = -errno;
            VIR_DEBUG("Failed to read %s: %m\n", keypath);
            goto cleanup;
        } else {
            while (!feof(fp)) {
2191 2192
                unsigned long pid_value;
                if (fscanf(fp, "%lu", &pid_value) != 1) {
2193 2194 2195
                    if (feof(fp))
                        break;
                    rc = -errno;
E
Eric Blake 已提交
2196 2197
                    VIR_DEBUG("Failed to read %s: %m\n", keypath);
                    goto cleanup;
2198
                }
2199
                if (virHashLookup(pids, (void*)pid_value))
2200 2201
                    continue;

2202 2203 2204
                VIR_DEBUG("pid=%lu", pid_value);
                /* Cgroups is a Linux concept, so this cast is safe.  */
                if (kill((pid_t)pid_value, signum) < 0) {
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
                    if (errno != ESRCH) {
                        rc = -errno;
                        goto cleanup;
                    }
                    /* Leave RC == 0 since we didn't kill one */
                } else {
                    killedAny = 1;
                    done = false;
                }

2215
                ignore_value(virHashAddEntry(pids, (void*)pid_value, (void*)1));
2216 2217 2218 2219 2220 2221 2222 2223 2224
            }
            VIR_FORCE_FCLOSE(fp);
        }
    }

    rc = killedAny ? 1 : 0;

cleanup:
    VIR_FREE(keypath);
E
Eric Blake 已提交
2225
    VIR_FORCE_FCLOSE(fp);
2226 2227 2228 2229 2230

    return rc;
}


2231
static uint32_t virCgroupPidCode(const void *name, uint32_t seed)
2232
{
2233 2234
    unsigned long pid_value = (unsigned long)(intptr_t)name;
    return virHashCodeGen(&pid_value, sizeof(pid_value), seed);
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
}
static bool virCgroupPidEqual(const void *namea, const void *nameb)
{
    return namea == nameb;
}
static void *virCgroupPidCopy(const void *name)
{
    return (void*)name;
}

/*
 * Returns
 *   < 0 : errno that occurred
 *     0 : no PIDs killed
 *     1 : at least one PID killed
 */
int virCgroupKill(virCgroupPtr group, int signum)
{
    VIR_DEBUG("group=%p path=%s signum=%d", group, group->path, signum);
    int rc;
    /* The 'tasks' file in cgroups can contain duplicated
     * pids, so we use a hash to track which we've already
     * killed.
     */
    virHashTablePtr pids = virHashCreateFull(100,
                                             NULL,
                                             virCgroupPidCode,
                                             virCgroupPidEqual,
                                             virCgroupPidCopy,
                                             NULL);

    rc = virCgroupKillInternal(group, signum, pids);

    virHashFree(pids);

    return rc;
}


static int virCgroupKillRecursiveInternal(virCgroupPtr group, int signum, virHashTablePtr pids, bool dormdir)
{
    int rc;
    int killedAny = 0;
    char *keypath = NULL;
    DIR *dp;
    virCgroupPtr subgroup = NULL;
    struct dirent *ent;
    VIR_DEBUG("group=%p path=%s signum=%d pids=%p", group, group->path, signum, pids);

    rc = virCgroupPathOfController(group, -1, "", &keypath);
    if (rc != 0) {
        VIR_DEBUG("No path of %s, tasks", group->path);
        return rc;
    }

    if ((rc = virCgroupKillInternal(group, signum, pids)) != 0)
        return rc;

    VIR_DEBUG("Iterate over children of %s", keypath);
    if (!(dp = opendir(keypath))) {
        rc = -errno;
        return rc;
    }

    while ((ent = readdir(dp))) {
        if (STREQ(ent->d_name, "."))
            continue;
        if (STREQ(ent->d_name, ".."))
            continue;
        if (ent->d_type != DT_DIR)
            continue;

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

2309
        if ((rc = virCgroupNew(ent->d_name, group, -1, &subgroup)) != 0)
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
            goto cleanup;

        if ((rc = virCgroupKillRecursiveInternal(subgroup, signum, pids, true)) < 0)
            goto cleanup;
        if (rc == 1)
            killedAny = 1;

        if (dormdir)
            virCgroupRemove(subgroup);

        virCgroupFree(&subgroup);
    }

    rc = killedAny;

cleanup:
    virCgroupFree(&subgroup);
    closedir(dp);

    return rc;
}

int virCgroupKillRecursive(virCgroupPtr group, int signum)
{
    int rc;
    VIR_DEBUG("group=%p path=%s signum=%d", group, group->path, signum);
    virHashTablePtr pids = virHashCreateFull(100,
                                             NULL,
                                             virCgroupPidCode,
                                             virCgroupPidEqual,
                                             virCgroupPidCopy,
                                             NULL);

    rc = virCgroupKillRecursiveInternal(group, signum, pids, false);

    virHashFree(pids);

    return rc;
}


int virCgroupKillPainfully(virCgroupPtr group)
{
    int i;
    int rc;
    VIR_DEBUG("cgroup=%p path=%s", group, group->path);
    for (i = 0 ; i < 15 ; i++) {
        int signum;
        if (i == 0)
            signum = SIGTERM;
        else if (i == 8)
            signum = SIGKILL;
        else
J
Ján Tomko 已提交
2363
            signum = 0; /* Just check for existence */
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375

        rc = virCgroupKillRecursive(group, signum);
        VIR_DEBUG("Iteration %d rc=%d", i, rc);
        /* If rc == -1 we hit error, if 0 we ran out of PIDs */
        if (rc <= 0)
            break;

        usleep(200 * 1000);
    }
    VIR_DEBUG("Complete %d", rc);
    return rc;
}
2376

E
Eric Blake 已提交
2377
#else /* !(HAVE_KILL, HAVE_MNTENT_H, HAVE_GETMNTENT_R) */
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
int virCgroupKill(virCgroupPtr group ATTRIBUTE_UNUSED,
                  int signum ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}
int virCgroupKillRecursive(virCgroupPtr group ATTRIBUTE_UNUSED,
                           int signum ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}

int virCgroupKillPainfully(virCgroupPtr group ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}
E
Eric Blake 已提交
2393
#endif /* HAVE_KILL, HAVE_MNTENT_H, HAVE_GETMNTENT_R */
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523

#ifdef __linux__
static char *virCgroupIdentifyRoot(virCgroupPtr group)
{
    char *ret = NULL;
    size_t i;

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

        tmp[0] = '\0';
        ret = strdup(group->controllers[i].mountPoint);
        tmp[0] = '/';
        if (!ret) {
            virReportOOMError();
            return NULL;
        }
        return ret;
    }

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


int virCgroupIsolateMount(virCgroupPtr group, const char *oldroot,
                          const char *mountopts)
{
    int ret = -1;
    size_t i;
    char *opts = NULL;
    char *root = NULL;

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

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

    if (virFileMakePath(root) < 0) {
        virReportSystemError(errno,
                             _("Unable to create directory %s"),
                             root);
        goto cleanup;
    }

    if (virAsprintf(&opts,
                    "mode=755,size=65536%s", mountopts) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (mount("tmpfs", root, "tmpfs", MS_NOSUID|MS_NODEV|MS_NOEXEC, opts) < 0) {
        virReportSystemError(errno,
                             _("Failed to mount %s on %s type %s"),
                             "tmpfs", root, "tmpfs");
        goto cleanup;
    }

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

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

            VIR_DEBUG("Create mount point '%s'", group->controllers[i].mountPoint);
            if (virFileMakePath(group->controllers[i].mountPoint) < 0) {
                virReportSystemError(errno,
                                     _("Unable to create directory %s"),
                                     group->controllers[i].mountPoint);
                VIR_FREE(src);
                goto cleanup;
            }

            if (mount(src, group->controllers[i].mountPoint, NULL, MS_BIND, NULL) < 0) {
                virReportSystemError(errno,
                                     _("Failed to bind cgroup '%s' on '%s'"),
                                     src, group->controllers[i].mountPoint);
            VIR_FREE(src);
                goto cleanup;
            }

            VIR_FREE(src);
        }

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

cleanup:
    VIR_FREE(root);
    VIR_FREE(opts);
    return ret;
}
#else /* __linux__ */
int virCgroupIsolateMount(virCgroupPtr group ATTRIBUTE_UNUSED,
                          const char *oldroot ATTRIBUTE_UNUSED,
                          const char *mountopts ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}
#endif /* __linux__ */