cgroup.c 32.3 KB
Newer Older
1 2 3
/*
 * cgroup.c: Tools for managing cgroups
 *
4
 * Copyright (C) 2010-2011 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15
 * Copyright IBM Corp. 2008
 *
 * See COPYING.LIB for the License of this software
 *
 * Authors:
 *  Dan Smith <danms@us.ibm.com>
 */
#include <config.h>

#include <stdio.h>
#include <stdint.h>
16
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
17
# include <mntent.h>
D
Daniel P. Berrange 已提交
18
#endif
19 20 21 22 23 24 25
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <libgen.h>
26
#include <dirent.h>
27 28 29 30 31

#include "internal.h"
#include "util.h"
#include "memory.h"
#include "cgroup.h"
32
#include "logging.h"
33
#include "files.h"
34 35 36

#define CGROUP_MAX_VAL 512

37
VIR_ENUM_IMPL(virCgroupController, VIR_CGROUP_CONTROLLER_LAST,
R
Ryota Ozaki 已提交
38
              "cpu", "cpuacct", "cpuset", "memory", "devices",
39
              "freezer", "blkio");
40 41 42 43 44 45

struct virCgroupController {
    int type;
    char *mountPoint;
    char *placement;
};
46 47 48

struct virCgroup {
    char *path;
49 50

    struct virCgroupController controllers[VIR_CGROUP_CONTROLLER_LAST];
51 52 53 54 55 56 57 58 59
};

/**
 * virCgroupFree:
 *
 * @group: The group structure to free
 */
void virCgroupFree(virCgroupPtr *group)
{
60 61 62 63 64 65 66 67
    int i;

    if (*group == NULL)
        return;

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

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

L
Lai Jiangshan 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86
/**
 * virCgroupMounted: query whether a cgroup subsystem is mounted or not
 *
 * @cgroup: The group structure to be queried
 * @controller: cgroup subsystem id
 *
 * Returns true if a cgroup is subsystem is mounted.
 */
bool virCgroupMounted(virCgroupPtr cgroup, int controller)
{
    return cgroup->controllers[controller].mountPoint != NULL;
}

87
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
88 89 90 91 92
/*
 * Process /proc/mounts figuring out what controllers are
 * mounted and where
 */
static int virCgroupDetectMounts(virCgroupPtr group)
93
{
94
    int i;
95
    FILE *mounts = NULL;
96 97 98 99 100
    struct mntent entry;
    char buf[CGROUP_MAX_VAL];

    mounts = fopen("/proc/mounts", "r");
    if (mounts == NULL) {
101
        VIR_ERROR0(_("Unable to open /proc/mounts"));
102
        return -ENOENT;
103 104 105
    }

    while (getmntent_r(mounts, &entry, buf, sizeof(buf)) != NULL) {
106 107
        if (STRNEQ(entry.mnt_type, "cgroup"))
            continue;
108

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
        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);
                }
                if (typelen == len && STREQLEN(typestr, tmp, len) &&
                    !(group->controllers[i].mountPoint = strdup(entry.mnt_dir)))
                    goto no_memory;
                tmp = next;
            }
        }
128 129
    }

130
    VIR_FORCE_FCLOSE(mounts);
131

132
    return 0;
133

134
no_memory:
135
    VIR_FORCE_FCLOSE(mounts);
136
    return -ENOMEM;
137 138
}

139 140 141 142 143

/*
 * Process /proc/self/cgroup figuring out what cgroup
 * sub-path the current process is assigned to. ie not
 * neccessarily in the root
144
 */
145
static int virCgroupDetectPlacement(virCgroupPtr group)
146 147
{
    int i;
148 149
    FILE *mapping  = NULL;
    char line[1024];
150

151 152
    mapping = fopen("/proc/self/cgroup", "r");
    if (mapping == NULL) {
153
        VIR_ERROR0(_("Unable to open /proc/self/cgroup"));
154
        return -ENOENT;
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
    while (fgets(line, sizeof(line), mapping) != NULL) {
        char *controllers = strchr(line, ':');
        char *path = controllers ? strchr(controllers+1, ':') : NULL;
        char *nl = path ? strchr(path, '\n') : NULL;

        if (!controllers || !path)
            continue;

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

        *path = '\0';
        controllers++;
        path++;

        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) {
                    len = next-tmp;
                    next++;
                } else {
                    len = strlen(tmp);
                }
                if (typelen == len && STREQLEN(typestr, tmp, len) &&
                    !(group->controllers[i].placement = strdup(STREQ(path, "/") ? "" : path)))
                    goto no_memory;

                tmp = next;
            }
        }
    }

194
    VIR_FORCE_FCLOSE(mapping);
195

196
    return 0;
197 198

no_memory:
199
    VIR_FORCE_FCLOSE(mapping);
200 201
    return -ENOMEM;

202 203
}

204
static int virCgroupDetect(virCgroupPtr group)
205
{
206 207 208
    int any = 0;
    int rc;
    int i;
209

210 211
    rc = virCgroupDetectMounts(group);
    if (rc < 0) {
212
        VIR_ERROR(_("Failed to detect mounts for %s"), group->path);
213
        return rc;
214 215
    }

216 217 218 219 220 221 222
    /* Check that at least 1 controller is available */
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
        if (group->controllers[i].mountPoint != NULL)
            any = 1;
    }
    if (!any)
        return -ENXIO;
223 224


225
    rc = virCgroupDetectPlacement(group);
226

227 228 229 230 231
    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;
232

233
            if (!group->controllers[i].placement) {
234
                VIR_ERROR(_("Could not find placement for controller %s at %s"),
235 236 237 238 239
                          virCgroupControllerTypeToString(i),
                          group->controllers[i].placement);
                rc = -ENOENT;
                break;
            }
240

241 242 243 244 245 246
            VIR_DEBUG("Detected mount/mapping %i:%s at %s in %s", i,
                      virCgroupControllerTypeToString(i),
                      group->controllers[i].mountPoint,
                      group->controllers[i].placement);
        }
    } else {
247
        VIR_ERROR(_("Failed to detect mapping for %s"), group->path);
248 249 250 251
    }

    return rc;
}
D
Daniel P. Berrange 已提交
252
#endif
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

static int virCgroupPathOfController(virCgroupPtr group,
                                     int controller,
                                     const char *key,
                                     char **path)
{
    if (group->controllers[controller].mountPoint == NULL)
        return -ENOENT;

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

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

    return 0;
}


277
static int virCgroupSetValueStr(virCgroupPtr group,
278
                                int controller,
279 280 281 282 283 284
                                const char *key,
                                const char *value)
{
    int rc = 0;
    char *keypath = NULL;

285
    rc = virCgroupPathOfController(group, controller, key, &keypath);
286 287 288
    if (rc != 0)
        return rc;

289
    VIR_DEBUG("Set value '%s' to '%s'", keypath, value);
290
    rc = virFileWriteStr(keypath, value, 0);
291 292
    if (rc < 0) {
        rc = -errno;
293
        VIR_DEBUG("Failed to write value '%s': %m", value);
294 295
    } else {
        rc = 0;
296 297 298 299 300 301 302 303
    }

    VIR_FREE(keypath);

    return rc;
}

static int virCgroupGetValueStr(virCgroupPtr group,
304
                                int controller,
305 306 307 308 309 310
                                const char *key,
                                char **value)
{
    int rc;
    char *keypath = NULL;

311
    *value = NULL;
312

313
    rc = virCgroupPathOfController(group, controller, key, &keypath);
314
    if (rc != 0) {
315
        VIR_DEBUG("No path of %s, %s", group->path, key);
316 317 318
        return rc;
    }

319
    VIR_DEBUG("Get value %s", keypath);
320

321
    rc = virFileReadAll(keypath, 1024, value);
322 323
    if (rc < 0) {
        rc = -errno;
324
        VIR_DEBUG("Failed to read %s: %m\n", keypath);
325
    } else {
326 327 328 329
        /* Terminated with '\n' has sometimes harmful effects to the caller */
        char *p = strchr(*value, '\n');
        if (p) *p = '\0';

330
        rc = 0;
331 332 333 334 335 336 337
    }

    VIR_FREE(keypath);

    return rc;
}

338
static int virCgroupSetValueU64(virCgroupPtr group,
339
                                int controller,
340
                                const char *key,
D
Daniel P. Berrange 已提交
341
                                unsigned long long int value)
342 343 344 345
{
    char *strval = NULL;
    int rc;

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

349
    rc = virCgroupSetValueStr(group, controller, key, strval);
350 351 352 353 354 355 356

    VIR_FREE(strval);

    return rc;
}


357 358

static int virCgroupSetValueI64(virCgroupPtr group,
359
                                int controller,
360
                                const char *key,
D
Daniel P. Berrange 已提交
361
                                long long int value)
362 363 364 365
{
    char *strval = NULL;
    int rc;

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

369
    rc = virCgroupSetValueStr(group, controller, key, strval);
370 371 372 373 374 375

    VIR_FREE(strval);

    return rc;
}

376 377
#if 0
/* This is included for completeness, but not yet used */
378
static int virCgroupGetValueI64(virCgroupPtr group,
379
                                int controller,
380
                                const char *key,
D
Daniel P. Berrange 已提交
381
                                long long int *value)
382 383 384 385
{
    char *strval = NULL;
    int rc = 0;

386
    rc = virCgroupGetValueStr(group, controller, key, &strval);
387 388 389
    if (rc != 0)
        goto out;

390
    if (virStrToLong_ll(strval, NULL, 10, value) < 0)
391 392 393 394 395 396
        rc = -EINVAL;
out:
    VIR_FREE(strval);

    return rc;
}
397
#endif
398

399
static int virCgroupGetValueU64(virCgroupPtr group,
400
                                int controller,
401
                                const char *key,
D
Daniel P. Berrange 已提交
402
                                unsigned long long int *value)
403 404 405 406
{
    char *strval = NULL;
    int rc = 0;

407
    rc = virCgroupGetValueStr(group, controller, key, &strval);
408 409 410
    if (rc != 0)
        goto out;

D
Daniel P. Berrange 已提交
411
    if (virStrToLong_ull(strval, NULL, 10, value) < 0)
412 413 414 415 416 417 418 419
        rc = -EINVAL;
out:
    VIR_FREE(strval);

    return rc;
}


420
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
421
static int virCgroupCpuSetInherit(virCgroupPtr parent, virCgroupPtr group)
422 423 424 425 426 427 428 429
{
    int i;
    int rc = 0;
    const char *inherit_values[] = {
        "cpuset.cpus",
        "cpuset.mems",
    };

430 431 432
    VIR_DEBUG("Setting up inheritance %s -> %s", parent->path, group->path);
    for (i = 0; i < ARRAY_CARDINALITY(inherit_values) ; i++) {
        char *value;
433

434 435 436 437
        rc = virCgroupGetValueStr(parent,
                                  VIR_CGROUP_CONTROLLER_CPUSET,
                                  inherit_values[i],
                                  &value);
438
        if (rc != 0) {
439
            VIR_ERROR(_("Failed to get %s %d"), inherit_values[i], rc);
440 441 442 443 444 445 446 447 448
            break;
        }

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

        rc = virCgroupSetValueStr(group,
                                  VIR_CGROUP_CONTROLLER_CPUSET,
                                  inherit_values[i],
                                  value);
449
        VIR_FREE(value);
450 451

        if (rc != 0) {
452
            VIR_ERROR(_("Failed to set %s %d"), inherit_values[i], rc);
453 454 455 456 457 458 459
            break;
        }
    }

    return rc;
}

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
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;
}

static int virCgroupMakeGroup(virCgroupPtr parent, virCgroupPtr group,
                              int create, bool memory_hierarchy)
492 493 494 495
{
    int i;
    int rc = 0;

496
    VIR_DEBUG("Make group %s", group->path);
497
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
498 499
        char *path = NULL;

500 501
        /* Skip over controllers that aren't mounted */
        if (!group->controllers[i].mountPoint)
502 503
            continue;

504 505 506
        rc = virCgroupPathOfController(group, i, "", &path);
        if (rc < 0)
            return rc;
507 508 509
        /* As of Feb 2011, clang can't see that the above function
         * call did not modify group. */
        sa_assert(group->controllers[i].mountPoint);
510

511
        VIR_DEBUG("Make controller %s", path);
512
        if (access(path, F_OK) != 0) {
513 514
            if (!create ||
                mkdir(path, 0755) < 0) {
515 516 517 518
                rc = -errno;
                VIR_FREE(path);
                break;
            }
519 520 521 522
            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);
523 524
                if (rc != 0) {
                    VIR_FREE(path);
525
                    break;
526
                }
527
            }
528 529 530 531 532 533 534 535 536 537 538 539 540 541
            /*
             * Note that virCgroupSetMemoryUseHierarchy should always be
             * called prior to creating subcgroups and attaching tasks.
             */
            if (memory_hierarchy &&
                group->controllers[VIR_CGROUP_CONTROLLER_MEMORY].mountPoint != NULL &&
                (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;
                }
            }
542 543 544 545 546 547 548 549
        }

        VIR_FREE(path);
    }

    return rc;
}

550 551 552

static int virCgroupNew(const char *path,
                        virCgroupPtr *group)
553 554 555 556
{
    int rc = 0;
    char *typpath = NULL;

557 558
    VIR_DEBUG("New group %s", path);
    *group = NULL;
559

560
    if (VIR_ALLOC((*group)) != 0) {
561 562 563 564
        rc = -ENOMEM;
        goto err;
    }

565
    if (!((*group)->path = strdup(path))) {
566 567 568 569
        rc = -ENOMEM;
        goto err;
    }

570 571 572
    rc = virCgroupDetect(*group);
    if (rc < 0)
        goto err;
573 574 575

    return rc;
err:
576 577
    virCgroupFree(group);
    *group = NULL;
578 579 580 581 582 583

    VIR_FREE(typpath);

    return rc;
}

584
static int virCgroupAppRoot(int privileged,
585 586
                            virCgroupPtr *group,
                            int create)
587
{
588 589
    virCgroupPtr rootgrp = NULL;
    int rc;
590

591 592 593
    rc = virCgroupNew("/", &rootgrp);
    if (rc != 0)
        return rc;
594

595 596 597 598 599
    if (privileged) {
        rc = virCgroupNew("/libvirt", group);
    } else {
        char *rootname;
        char *username;
600
        username = virGetUserName(getuid());
601 602 603 604 605 606 607 608 609 610
        if (!username) {
            rc = -ENOMEM;
            goto cleanup;
        }
        rc = virAsprintf(&rootname, "/libvirt-%s", username);
        VIR_FREE(username);
        if (rc < 0) {
            rc = -ENOMEM;
            goto cleanup;
        }
611

612 613
        rc = virCgroupNew(rootname, group);
        VIR_FREE(rootname);
614 615
    }
    if (rc != 0)
616
        goto cleanup;
617

618
    rc = virCgroupMakeGroup(rootgrp, *group, create, false);
619

620 621
cleanup:
    virCgroupFree(&rootgrp);
622 623
    return rc;
}
D
Daniel P. Berrange 已提交
624
#endif
625

626
#if defined _DIRENT_HAVE_D_TYPE
627 628 629 630 631 632 633 634
static int virCgroupRemoveRecursively(char *grppath)
{
    DIR *grpdir;
    struct dirent *ent;
    int rc = 0;

    grpdir = opendir(grppath);
    if (grpdir == NULL) {
635 636
        if (errno == ENOENT)
            return 0;
637
        rc = -errno;
638
        VIR_ERROR(_("Unable to open %s (%d)"), grppath, errno);
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
        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);

667
    VIR_DEBUG("Removing cgroup %s", grppath);
668 669 670 671 672 673 674
    if (rmdir(grppath) != 0 && errno != ENOENT) {
        rc = -errno;
        VIR_ERROR(_("Unable to remove %s (%d)"), grppath, errno);
    }

    return rc;
}
675 676 677 678 679 680 681
#else
static int virCgroupRemoveRecursively(char *grppath ATTRIBUTE_UNUSED)
{
    /* Claim no support */
    return -ENXIO;
}
#endif
682

683 684 685 686 687
/**
 * virCgroupRemove:
 *
 * @group: The group to be removed
 *
688 689 690 691 692
 * 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.
 *
693 694 695 696 697 698 699 700
 * Returns: 0 on success
 */
int virCgroupRemove(virCgroupPtr group)
{
    int rc = 0;
    int i;
    char *grppath = NULL;

701
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
702 703
        /* Skip over controllers not mounted */
        if (!group->controllers[i].mountPoint)
704 705
            continue;

706 707 708 709 710
        if (virCgroupPathOfController(group,
                                      i,
                                      NULL,
                                      &grppath) != 0)
            continue;
711

712
        VIR_DEBUG("Removing cgroup %s and all child cgroups", grppath);
713
        rc = virCgroupRemoveRecursively(grppath);
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
        VIR_FREE(grppath);
    }

    return rc;
}

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

733
    for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) {
734 735 736
        /* Skip over controllers not mounted */
        if (!group->controllers[i].mountPoint)
            continue;
737

738
        rc = virCgroupSetValueU64(group, i, "tasks", (unsigned long long)pid);
739 740 741 742 743 744 745
        if (rc != 0)
            break;
    }

    return rc;
}

746

747
/**
748
 * virCgroupForDriver:
749
 *
750
 * @name: name of this driver (e.g., xen, qemu, lxc)
751 752 753 754
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success
 */
755
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
756 757 758 759
int virCgroupForDriver(const char *name,
                       virCgroupPtr *group,
                       int privileged,
                       int create)
760 761
{
    int rc;
762
    char *path = NULL;
763
    virCgroupPtr rootgrp = NULL;
764

765
    rc = virCgroupAppRoot(privileged, &rootgrp, create);
766
    if (rc != 0)
767 768
        goto out;

769 770
    if (virAsprintf(&path, "%s/%s", rootgrp->path, name) < 0) {
        rc = -ENOMEM;
771
        goto out;
772
    }
773

774 775 776
    rc = virCgroupNew(path, group);
    VIR_FREE(path);

777
    if (rc == 0) {
778
        rc = virCgroupMakeGroup(rootgrp, *group, create, false);
779 780 781
        if (rc != 0)
            virCgroupFree(group);
    }
782

783
out:
784
    virCgroupFree(&rootgrp);
785 786 787

    return rc;
}
D
Daniel P. Berrange 已提交
788 789 790 791 792 793 794 795 796 797
#else
int virCgroupForDriver(const char *name ATTRIBUTE_UNUSED,
                       virCgroupPtr *group ATTRIBUTE_UNUSED,
                       int privileged ATTRIBUTE_UNUSED,
                       int create ATTRIBUTE_UNUSED)
{
    /* Claim no support */
    return -ENXIO;
}
#endif
798

799 800 801 802 803 804 805 806 807 808

/**
 * virCgroupForDomain:
 *
 * @driver: group for driver owning the domain
 * @name: name of the domain
 * @group: Pointer to returned virCgroupPtr
 *
 * Returns 0 on success
 */
809
#if defined HAVE_MNTENT_H && defined HAVE_GETMNTENT_R
810 811 812 813 814 815 816 817
int virCgroupForDomain(virCgroupPtr driver,
                       const char *name,
                       virCgroupPtr *group,
                       int create)
{
    int rc;
    char *path;

818 819 820
    if (driver == NULL)
        return -EINVAL;

821 822 823 824 825 826
    if (virAsprintf(&path, "%s/%s", driver->path, name) < 0)
        return -ENOMEM;

    rc = virCgroupNew(path, group);
    VIR_FREE(path);

827
    if (rc == 0) {
828 829 830 831 832 833 834 835 836 837 838
        /*
         * 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(driver, *group, create, true);
839 840 841 842 843 844
        if (rc != 0)
            virCgroupFree(group);
    }

    return rc;
}
D
Daniel P. Berrange 已提交
845 846 847 848 849 850 851 852 853
#else
int virCgroupForDomain(virCgroupPtr driver ATTRIBUTE_UNUSED,
                       const char *name ATTRIBUTE_UNUSED,
                       virCgroupPtr *group ATTRIBUTE_UNUSED,
                       int create ATTRIBUTE_UNUSED)
{
    return -ENXIO;
}
#endif
854

855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
/**
 * 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;
}

894 895 896 897 898 899 900 901
/**
 * virCgroupSetMemory:
 *
 * @group: The cgroup to change memory for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
902
int virCgroupSetMemory(virCgroupPtr group, unsigned long long kb)
903
{
904 905 906 907 908 909 910 911 912 913 914 915 916 917
    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);
918 919
}

R
Ryota Ozaki 已提交
920 921 922 923 924 925 926 927 928 929
/**
 * 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 已提交
930
    long long unsigned int usage_in_bytes;
R
Ryota Ozaki 已提交
931 932 933 934 935 936 937 938 939
    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;
}

940 941 942 943 944 945 946 947
/**
 * virCgroupSetMemoryHardLimit:
 *
 * @group: The cgroup to change memory hard limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
948
int virCgroupSetMemoryHardLimit(virCgroupPtr group, unsigned long long kb)
949 950 951 952 953 954 955 956 957 958 959 960
{
    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
 */
961
int virCgroupGetMemoryHardLimit(virCgroupPtr group, unsigned long long *kb)
962 963 964 965 966 967 968
{
    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)
969
        *kb = limit_in_bytes >> 10;
970 971 972 973 974 975 976 977 978 979 980
    return ret;
}

/**
 * virCgroupSetMemorySoftLimit:
 *
 * @group: The cgroup to change memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
981
int virCgroupSetMemorySoftLimit(virCgroupPtr group, unsigned long long kb)
982
{
983 984 985 986 987 988 989 990 991 992 993 994 995 996
    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);
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
}


/**
 * virCgroupGetMemorySoftLimit:
 *
 * @group: The cgroup to get the memory soft limit for
 * @kb: The memory amount in kilobytes
 *
 * Returns: 0 on success
 */
1008
int virCgroupGetMemorySoftLimit(virCgroupPtr group, unsigned long long *kb)
1009 1010 1011 1012 1013 1014 1015
{
    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)
1016
        *kb = limit_in_bytes >> 10;
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    return ret;
}

/**
 * virCgroupSetSwapHardLimit:
 *
 * @group: The cgroup to change swap hard limit for
 * @kb: The swap amount in kilobytes
 *
 * Returns: 0 on success
 */
1028
int virCgroupSetSwapHardLimit(virCgroupPtr group, unsigned long long kb)
1029
{
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
    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);
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
}

/**
 * virCgroupGetSwapHardLimit:
 *
 * @group: The cgroup to get swap hard limit for
 * @kb: The swap amount in kilobytes
 *
 * Returns: 0 on success
 */
1054
int virCgroupGetSwapHardLimit(virCgroupPtr group, unsigned long long *kb)
1055 1056 1057 1058 1059 1060 1061
{
    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)
1062
        *kb = limit_in_bytes >> 10;
1063 1064 1065
    return ret;
}

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
/**
 * virCgroupDenyAllDevices:
 *
 * @group: The cgroup to deny devices for
 *
 * Returns: 0 on success
 */
int virCgroupDenyAllDevices(virCgroupPtr group)
{
    return virCgroupSetValueStr(group,
1076 1077 1078
                                VIR_CGROUP_CONTROLLER_DEVICES,
                                "devices.deny",
                                "a");
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
}

/**
 * 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
 *
 * Returns: 0 on success
 */
1091
int virCgroupAllowDevice(virCgroupPtr group, char type, int major, int minor)
1092 1093 1094 1095
{
    int rc;
    char *devstr = NULL;

1096
    if (virAsprintf(&devstr, "%c %i:%i rwm", type, major, minor) == -1) {
1097 1098 1099 1100 1101
        rc = -ENOMEM;
        goto out;
    }

    rc = virCgroupSetValueStr(group,
1102
                              VIR_CGROUP_CONTROLLER_DEVICES,
1103 1104 1105 1106 1107 1108 1109
                              "devices.allow",
                              devstr);
out:
    VIR_FREE(devstr);

    return rc;
}
1110

1111 1112 1113 1114 1115 1116 1117 1118 1119
/**
 * 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
 *
 * Returns: 0 on success
 */
1120
int virCgroupAllowDeviceMajor(virCgroupPtr group, char type, int major)
1121 1122 1123 1124
{
    int rc;
    char *devstr = NULL;

1125
    if (virAsprintf(&devstr, "%c %i:* rwm", type, major) == -1) {
1126 1127 1128 1129 1130
        rc = -ENOMEM;
        goto out;
    }

    rc = virCgroupSetValueStr(group,
1131
                              VIR_CGROUP_CONTROLLER_DEVICES,
1132 1133 1134 1135 1136 1137 1138 1139
                              "devices.allow",
                              devstr);
 out:
    VIR_FREE(devstr);

    return rc;
}

1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
/**
 * virCgroupAllowDevicePath:
 *
 * @group: The cgroup to allow the device for
 * @path: the device to allow
 *
 * Queries the type of device and its major/minor number, and
 * adds that to the cgroup ACL
 *
 * Returns: 0 on success
 */
D
Daniel P. Berrange 已提交
1151
#if defined(major) && defined(minor)
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
int virCgroupAllowDevicePath(virCgroupPtr group, const char *path)
{
    struct stat sb;

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

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

    return virCgroupAllowDevice(group,
                                S_ISCHR(sb.st_mode) ? 'c' : 'b',
                                major(sb.st_rdev),
                                minor(sb.st_rdev));
}
D
Daniel P. Berrange 已提交
1167 1168 1169 1170 1171 1172 1173 1174
#else
int virCgroupAllowDevicePath(virCgroupPtr group ATTRIBUTE_UNUSED,
                             const char *path ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}
#endif

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

/**
 * 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
 *
 * Returns: 0 on success
 */
int virCgroupDenyDevice(virCgroupPtr group, char type, int major, int minor)
{
    int rc;
    char *devstr = NULL;

    if (virAsprintf(&devstr, "%c %i:%i rwm", type, major, minor) == -1) {
        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
 *
 * Returns: 0 on success
 */
int virCgroupDenyDeviceMajor(virCgroupPtr group, char type, int major)
{
    int rc;
    char *devstr = NULL;

    if (virAsprintf(&devstr, "%c %i:* rwm", type, major) == -1) {
        rc = -ENOMEM;
        goto out;
    }

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

    return rc;
}

D
Daniel P. Berrange 已提交
1235
#if defined(major) && defined(minor)
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
int virCgroupDenyDevicePath(virCgroupPtr group, const char *path)
{
    struct stat sb;

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

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

    return virCgroupDenyDevice(group,
                               S_ISCHR(sb.st_mode) ? 'c' : 'b',
                               major(sb.st_rdev),
                               minor(sb.st_rdev));
}
D
Daniel P. Berrange 已提交
1251 1252 1253 1254 1255 1256 1257
#else
int virCgroupDenyDevicePath(virCgroupPtr group ATTRIBUTE_UNUSED,
                            const char *path ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}
#endif
1258

1259
int virCgroupSetCpuShares(virCgroupPtr group, unsigned long long shares)
1260
{
1261 1262
    return virCgroupSetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
D
Daniel P. Berrange 已提交
1263
                                "cpu.shares", shares);
1264 1265
}

1266
int virCgroupGetCpuShares(virCgroupPtr group, unsigned long long *shares)
1267
{
1268 1269
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPU,
D
Daniel P. Berrange 已提交
1270
                                "cpu.shares", shares);
1271
}
1272 1273 1274

int virCgroupGetCpuacctUsage(virCgroupPtr group, unsigned long long *usage)
{
1275 1276
    return virCgroupGetValueU64(group,
                                VIR_CGROUP_CONTROLLER_CPUACCT,
D
Daniel P. Berrange 已提交
1277
                                "cpuacct.usage", usage);
1278
}
R
Ryota Ozaki 已提交
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288

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

int virCgroupGetFreezerState(virCgroupPtr group, char **state)
{
1289
    return virCgroupGetValueStr(group,
R
Ryota Ozaki 已提交
1290 1291 1292
                                VIR_CGROUP_CONTROLLER_CPU,
                                "freezer.state", state);
}