qemu_cgroup.c 32.4 KB
Newer Older
1 2 3
/*
 * qemu_cgroup.c: QEMU cgroup management
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2006-2013 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * 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
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include "qemu_cgroup.h"
27
#include "qemu_domain.h"
28
#include "qemu_process.h"
29
#include "vircgroup.h"
30
#include "virlog.h"
31
#include "viralloc.h"
32
#include "virerror.h"
33
#include "virutil.h"
34
#include "domain_audit.h"
35 36 37 38 39 40 41

#define VIR_FROM_THIS VIR_FROM_QEMU

static const char *const defaultDeviceACL[] = {
    "/dev/null", "/dev/full", "/dev/zero",
    "/dev/random", "/dev/urandom",
    "/dev/ptmx", "/dev/kvm", "/dev/kqemu",
42
    "/dev/rtc", "/dev/hpet", "/dev/vfio/vfio",
43 44 45 46 47
    NULL,
};
#define DEVICE_PTY_MAJOR 136
#define DEVICE_SND_MAJOR 116

48
static int
49
qemuSetupDiskPathAllow(virDomainDiskDefPtr disk,
50 51 52
                       const char *path,
                       size_t depth ATTRIBUTE_UNUSED,
                       void *opaque)
53
{
54 55
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
56 57 58
    int rc;

    VIR_DEBUG("Process path %s for disk", path);
59
    rc = virCgroupAllowDevicePath(priv->cgroup, path,
60 61
                                  (disk->readonly ? VIR_CGROUP_DEVICE_READ
                                   : VIR_CGROUP_DEVICE_RW));
62
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path,
63
                             disk->readonly ? "r" : "rw", rc);
64 65
    if (rc < 0) {
        if (rc == -EACCES) { /* Get this for root squash NFS */
66 67 68 69 70 71 72 73 74 75 76 77
            VIR_DEBUG("Ignoring EACCES for %s", path);
        } else {
            virReportSystemError(-rc,
                                 _("Unable to allow access for disk path %s"),
                                 path);
            return -1;
        }
    }
    return 0;
}


78
int qemuSetupDiskCgroup(virDomainObjPtr vm,
79 80
                        virDomainDiskDefPtr disk)
{
81 82 83 84 85 86
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (!virCgroupHasController(priv->cgroup,
                                VIR_CGROUP_CONTROLLER_DEVICES))
        return 0;

87 88 89
    return virDomainDiskDefForeachPath(disk,
                                       true,
                                       qemuSetupDiskPathAllow,
90
                                       vm);
91 92 93
}


94 95 96 97 98
static int
qemuTeardownDiskPathDeny(virDomainDiskDefPtr disk ATTRIBUTE_UNUSED,
                         const char *path,
                         size_t depth ATTRIBUTE_UNUSED,
                         void *opaque)
99
{
100 101
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
102 103 104
    int rc;

    VIR_DEBUG("Process path %s for disk", path);
105
    rc = virCgroupDenyDevicePath(priv->cgroup, path,
106
                                 VIR_CGROUP_DEVICE_RWM);
107
    virDomainAuditCgroupPath(vm, priv->cgroup, "deny", path, "rwm", rc);
108 109
    if (rc < 0) {
        if (rc == -EACCES) { /* Get this for root squash NFS */
110 111 112 113 114 115 116 117 118 119 120 121
            VIR_DEBUG("Ignoring EACCES for %s", path);
        } else {
            virReportSystemError(-rc,
                                 _("Unable to deny access for disk path %s"),
                                 path);
            return -1;
        }
    }
    return 0;
}


122
int qemuTeardownDiskCgroup(virDomainObjPtr vm,
123 124
                           virDomainDiskDefPtr disk)
{
125 126 127 128 129 130
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (!virCgroupHasController(priv->cgroup,
                                VIR_CGROUP_CONTROLLER_DEVICES))
        return 0;

131 132 133
    return virDomainDiskDefForeachPath(disk,
                                       true,
                                       qemuTeardownDiskPathDeny,
134
                                       vm);
135 136
}

137
static int
138 139
qemuSetupChrSourceCgroup(virDomainDefPtr def,
                         virDomainChrSourceDefPtr dev,
140
                         void *opaque)
141
{
142 143
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
144 145
    int rc;

146
    if (dev->type != VIR_DOMAIN_CHR_TYPE_DEV)
147 148
        return 0;

149
    VIR_DEBUG("Process path '%s' for device", dev->data.file.path);
150

151
    rc = virCgroupAllowDevicePath(priv->cgroup, dev->data.file.path,
152
                                  VIR_CGROUP_DEVICE_RW);
153
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
154
                             dev->data.file.path, "rw", rc);
155
    if (rc < 0) {
156 157
        virReportSystemError(-rc,
                             _("Unable to allow device %s for %s"),
158
                             dev->data.file.path, def->name);
159 160 161 162 163 164
        return -1;
    }

    return 0;
}

165 166 167 168 169
static int
qemuSetupChardevCgroup(virDomainDefPtr def,
                       virDomainChrDefPtr dev,
                       void *opaque)
{
170
    return qemuSetupChrSourceCgroup(def, &dev->source, opaque);
171 172 173 174 175 176
}


static int
qemuSetupTPMCgroup(virDomainDefPtr def,
                   virDomainTPMDefPtr dev,
177
                   void *opaque)
178 179 180 181 182 183
{
    int rc = 0;

    switch (dev->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
        rc = qemuSetupChrSourceCgroup(def, &dev->data.passthrough.source,
184
                                      opaque);
185 186 187 188 189 190 191 192
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return rc;
}

193

194
int qemuSetupHostUsbDeviceCgroup(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
195 196 197
                                 const char *path,
                                 void *opaque)
{
198 199
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
200 201 202
    int rc;

    VIR_DEBUG("Process path '%s' for USB device", path);
203
    rc = virCgroupAllowDevicePath(priv->cgroup, path,
204
                                  VIR_CGROUP_DEVICE_RW);
205
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path, "rw", rc);
206
    if (rc < 0) {
207 208 209 210 211 212 213 214 215
        virReportSystemError(-rc,
                             _("Unable to allow device %s"),
                             path);
        return -1;
    }

    return 0;
}

216

217 218 219 220 221 222 223 224 225 226 227 228 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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
int
qemuSetupHostdevCGroup(virDomainObjPtr vm,
                       virDomainHostdevDefPtr dev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virPCIDevicePtr pci = NULL;
    char *path = NULL;

    /* currently this only does something for PCI devices using vfio
     * for device assignment, but it is called for *all* hostdev
     * devices.
     */

    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_DEVICES))
        return 0;

    if (dev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {

        switch (dev->source.subsys.type) {
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
            if (dev->source.subsys.u.pci.backend
                != VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
                int rc;

                pci = virPCIDeviceNew(dev->source.subsys.u.pci.addr.domain,
                                      dev->source.subsys.u.pci.addr.bus,
                                      dev->source.subsys.u.pci.addr.slot,
                                      dev->source.subsys.u.pci.addr.function);
                if (!pci)
                    goto cleanup;

                if (!(path = virPCIDeviceGetVFIOGroupDev(pci)))
                    goto cleanup;

                VIR_DEBUG("Cgroup allow %s for PCI device assignment", path);
                rc = virCgroupAllowDevicePath(priv->cgroup, path,
                                              VIR_CGROUP_DEVICE_RW);
                virDomainAuditCgroupPath(vm, priv->cgroup,
                                         "allow", path, "rw", rc);
                if (rc < 0) {
                    virReportSystemError(-rc,
                                         _("Unable to allow access "
                                           "for device path %s"),
                                         path);
                    goto cleanup;
                }
            }
            break;
        default:
            break;
        }
    }

    ret = 0;
cleanup:
    virPCIDeviceFree(pci);
    VIR_FREE(path);
    return ret;
}



int
qemuTeardownHostdevCgroup(virDomainObjPtr vm,
                       virDomainHostdevDefPtr dev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virPCIDevicePtr pci = NULL;
    char *path = NULL;

    /* currently this only does something for PCI devices using vfio
     * for device assignment, but it is called for *all* hostdev
     * devices.
     */

    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_DEVICES))
        return 0;

    if (dev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {

        switch (dev->source.subsys.type) {
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
            if (dev->source.subsys.u.pci.backend
                != VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
                int rc;

                pci = virPCIDeviceNew(dev->source.subsys.u.pci.addr.domain,
                                      dev->source.subsys.u.pci.addr.bus,
                                      dev->source.subsys.u.pci.addr.slot,
                                      dev->source.subsys.u.pci.addr.function);
                if (!pci)
                    goto cleanup;

                if (!(path = virPCIDeviceGetVFIOGroupDev(pci)))
                    goto cleanup;

                VIR_DEBUG("Cgroup deny %s for PCI device assignment", path);
                rc = virCgroupDenyDevicePath(priv->cgroup, path,
                                             VIR_CGROUP_DEVICE_RWM);
                virDomainAuditCgroupPath(vm, priv->cgroup,
                                         "deny", path, "rwm", rc);
                if (rc < 0) {
                    virReportSystemError(-rc,
                                         _("Unable to deny access "
                                           "for device path %s"),
                                         path);
                    goto cleanup;
                }
            }
            break;
        default:
            break;
        }
    }

    ret = 0;
cleanup:
    virPCIDeviceFree(pci);
    VIR_FREE(path);
    return ret;
}


342
int qemuInitCgroup(virQEMUDriverPtr driver,
343 344
                   virDomainObjPtr vm,
                   bool startup)
345
{
346
    int rc = -1;
347
    qemuDomainObjPrivatePtr priv = vm->privateData;
348
    virCgroupPtr parent = NULL;
349 350
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

351 352 353
    if (!cfg->privileged)
        goto done;

354 355
    virCgroupFree(&priv->cgroup);

356 357 358 359 360 361
    if (!vm->def->resource && startup) {
        virDomainResourceDefPtr res;

        if (VIR_ALLOC(res) < 0) {
            virReportOOMError();
            goto cleanup;
362 363
        }

364
        if (!(res->partition = strdup("/machine"))) {
365 366 367 368 369 370
            virReportOOMError();
            VIR_FREE(res);
            goto cleanup;
        }

        vm->def->resource = res;
371 372
    }

373 374 375 376 377 378 379 380 381 382 383
    if (vm->def->resource &&
        vm->def->resource->partition) {
        if (vm->def->resource->partition[0] != '/') {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("Resource partition '%s' must start with '/'"),
                           vm->def->resource->partition);
            goto cleanup;
        }
        /* We only auto-create the default partition. In other
         * cases we expec the sysadmin/app to have done so */
        rc = virCgroupNewPartition(vm->def->resource->partition,
384
                                   STREQ(vm->def->resource->partition, "/machine"),
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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
                                   cfg->cgroupControllers,
                                   &parent);
        if (rc != 0) {
            if (rc == -ENXIO ||
                rc == -EPERM ||
                rc == -EACCES) { /* No cgroups mounts == success */
                VIR_DEBUG("No cgroups present/configured/accessible, ignoring error");
                goto done;
            }

            virReportSystemError(-rc,
                                 _("Unable to initialize %s cgroup"),
                                 vm->def->resource->partition);
            goto cleanup;
        }

        rc = virCgroupNewDomainPartition(parent,
                                         "qemu",
                                         vm->def->name,
                                         true,
                                         &priv->cgroup);
        if (rc != 0) {
            virReportSystemError(-rc,
                                 _("Unable to create cgroup for %s"),
                                 vm->def->name);
            goto cleanup;
        }
    } else {
        rc = virCgroupNewDriver("qemu",
                                true,
                                cfg->cgroupControllers,
                                &parent);
        if (rc != 0) {
            if (rc == -ENXIO ||
                rc == -EPERM ||
                rc == -EACCES) { /* No cgroups mounts == success */
                VIR_DEBUG("No cgroups present/configured/accessible, ignoring error");
                goto done;
            }

            virReportSystemError(-rc,
                                 _("Unable to create cgroup for %s"),
                                 vm->def->name);
            goto cleanup;
        }

        rc = virCgroupNewDomainDriver(parent,
                                      vm->def->name,
                                      true,
                                      &priv->cgroup);
        if (rc != 0) {
            virReportSystemError(-rc,
                                 _("Unable to create cgroup for %s"),
                                 vm->def->name);
            goto cleanup;
        }
441 442 443 444 445
    }

done:
    rc = 0;
cleanup:
446
    virCgroupFree(&parent);
447 448 449 450 451
    virObjectUnref(cfg);
    return rc;
}


452
int qemuSetupCgroup(virQEMUDriverPtr driver,
453
                    virDomainObjPtr vm,
454
                    virBitmapPtr nodemask)
455
{
456
    int rc = -1;
457
    unsigned int i;
458
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
459
    qemuDomainObjPrivatePtr priv = vm->privateData;
460
    const char *const *deviceACL =
461 462
        cfg->cgroupDeviceACL ?
        (const char *const *)cfg->cgroupDeviceACL :
463 464
        defaultDeviceACL;

465
    if (qemuInitCgroup(driver, vm, true) < 0)
466
        return -1;
467

468 469
    if (!priv->cgroup)
        goto done;
470

471 472 473
    if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_DEVICES)) {
        rc = virCgroupDenyAllDevices(priv->cgroup);
        virDomainAuditCgroup(vm, priv->cgroup, "deny", "all", rc == 0);
474 475
        if (rc != 0) {
            if (rc == -EPERM) {
476
                VIR_WARN("Group devices ACL is not accessible, disabling whitelisting");
477 478 479 480 481 482 483 484 485
                goto done;
            }

            virReportSystemError(-rc,
                                 _("Unable to deny all devices for %s"), vm->def->name);
            goto cleanup;
        }

        for (i = 0; i < vm->def->ndisks ; i++) {
486
            if (qemuSetupDiskCgroup(vm, vm->def->disks[i]) < 0)
487 488 489
                goto cleanup;
        }

490
        rc = virCgroupAllowDeviceMajor(priv->cgroup, 'c', DEVICE_PTY_MAJOR,
491
                                       VIR_CGROUP_DEVICE_RW);
492
        virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_PTY_MAJOR,
493
                                  "pty", "rw", rc == 0);
494 495 496 497 498 499
        if (rc != 0) {
            virReportSystemError(-rc, "%s",
                                 _("unable to allow /dev/pts/ devices"));
            goto cleanup;
        }

500 501 502
        if (vm->def->nsounds &&
            (!vm->def->ngraphics ||
             ((vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
503
               cfg->vncAllowHostAudio) ||
504
              (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL)))) {
505
            rc = virCgroupAllowDeviceMajor(priv->cgroup, 'c', DEVICE_SND_MAJOR,
506
                                           VIR_CGROUP_DEVICE_RW);
507
            virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_SND_MAJOR,
508
                                      "sound", "rw", rc == 0);
509 510 511 512 513 514 515 516
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to allow /dev/snd/ devices"));
                goto cleanup;
            }
        }

        for (i = 0; deviceACL[i] != NULL ; i++) {
517 518 519 520 521 522
            if (access(deviceACL[i], F_OK) < 0) {
                VIR_DEBUG("Ignoring non-existant device %s",
                          deviceACL[i]);
                continue;
            }

523
            rc = virCgroupAllowDevicePath(priv->cgroup, deviceACL[i],
524
                                          VIR_CGROUP_DEVICE_RW);
525
            virDomainAuditCgroupPath(vm, priv->cgroup, "allow", deviceACL[i], "rw", rc);
526 527 528 529 530 531 532 533 534 535 536 537
            if (rc < 0 &&
                rc != -ENOENT) {
                virReportSystemError(-rc,
                                     _("unable to allow device %s"),
                                     deviceACL[i]);
                goto cleanup;
            }
        }

        if (virDomainChrDefForeach(vm->def,
                                   true,
                                   qemuSetupChardevCgroup,
538
                                   vm) < 0)
539 540
            goto cleanup;

541 542
        if (vm->def->tpm &&
            (qemuSetupTPMCgroup(vm->def,
543
                               vm->def->tpm,
544 545
                                vm) < 0))
            goto cleanup;
546

547 548
        for (i = 0; i < vm->def->nhostdevs; i++) {
            virDomainHostdevDefPtr hostdev = vm->def->hostdevs[i];
549
            virUSBDevicePtr usb;
550

551 552 553 554 555 556
            if (qemuSetupHostdevCGroup(vm, hostdev) < 0)
                goto cleanup;

            /* NB: the code below here should be moved into
             * qemuSetupHostdevCGroup()
             */
557 558 559 560
            if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
                continue;
            if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
                continue;
561 562
            if (hostdev->missing)
                continue;
563

564 565 566
            if ((usb = virUSBDeviceNew(hostdev->source.subsys.u.usb.bus,
                                       hostdev->source.subsys.u.usb.device,
                                       NULL)) == NULL)
567 568
                goto cleanup;

569
            if (virUSBDeviceFileIterate(usb, qemuSetupHostUsbDeviceCgroup,
570
                                        vm) < 0) {
571
                virUSBDeviceFree(usb);
572
                goto cleanup;
573
            }
574
            virUSBDeviceFree(usb);
575 576 577
        }
    }

578
    if (vm->def->blkio.weight != 0) {
579 580
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_BLKIO)) {
            rc = virCgroupSetBlkioWeight(priv->cgroup, vm->def->blkio.weight);
581
            if (rc != 0) {
582 583 584 585 586
                virReportSystemError(-rc,
                                     _("Unable to set io weight for domain %s"),
                                     vm->def->name);
                goto cleanup;
            }
587
        } else {
588 589
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Block I/O tuning is not available on this host"));
590 591 592 593 594
            goto cleanup;
        }
    }

    if (vm->def->blkio.ndevices) {
595
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_BLKIO)) {
596 597
            for (i = 0; i < vm->def->blkio.ndevices; i++) {
                virBlkioDeviceWeightPtr dw = &vm->def->blkio.devices[i];
598 599
                if (!dw->weight)
                    continue;
600
                rc = virCgroupSetBlkioDeviceWeight(priv->cgroup, dw->path,
601 602 603 604 605 606 607 608 609 610
                                                   dw->weight);
                if (rc != 0) {
                    virReportSystemError(-rc,
                                         _("Unable to set io device weight "
                                           "for domain %s"),
                                         vm->def->name);
                    goto cleanup;
                }
            }
        } else {
611
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
612
                           _("Block I/O tuning is not available on this host"));
613
            goto cleanup;
614 615 616
        }
    }

617
    if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_MEMORY)) {
618 619 620
        unsigned long long hard_limit = vm->def->mem.hard_limit;

        if (!hard_limit) {
M
Michal Privoznik 已提交
621
            /* If there is no hard_limit set, set a reasonable one to avoid
E
Eric Blake 已提交
622 623
             * system thrashing caused by exploited qemu.  A 'reasonable
             * limit' has been chosen:
M
Michal Privoznik 已提交
624 625 626 627
             *     (1 + k) * (domain memory + total video memory) + (32MB for
             *     cache per each disk) + F
             * where k = 0.5 and F = 200MB.  The cache for disks is important as
             * kernel cache on the host side counts into the RSS limit. */
628 629 630
            hard_limit = vm->def->mem.max_balloon;
            for (i = 0; i < vm->def->nvideos; i++)
                hard_limit += vm->def->videos[i]->vram;
M
Michal Privoznik 已提交
631 632
            hard_limit = hard_limit * 1.5 + 204800;
            hard_limit += vm->def->ndisks * 32768;
633 634
        }

635
        rc = virCgroupSetMemoryHardLimit(priv->cgroup, hard_limit);
636 637 638 639 640 641 642
        if (rc != 0) {
            virReportSystemError(-rc,
                                 _("Unable to set memory hard limit for domain %s"),
                                 vm->def->name);
            goto cleanup;
        }
        if (vm->def->mem.soft_limit != 0) {
643
            rc = virCgroupSetMemorySoftLimit(priv->cgroup, vm->def->mem.soft_limit);
644 645 646 647 648
            if (rc != 0) {
                virReportSystemError(-rc,
                                     _("Unable to set memory soft limit for domain %s"),
                                     vm->def->name);
                goto cleanup;
649
            }
650
        }
651

652
        if (vm->def->mem.swap_hard_limit != 0) {
653
            rc = virCgroupSetMemSwapHardLimit(priv->cgroup, vm->def->mem.swap_hard_limit);
654 655 656 657 658
            if (rc != 0) {
                virReportSystemError(-rc,
                                     _("Unable to set swap hard limit for domain %s"),
                                     vm->def->name);
                goto cleanup;
659 660
            }
        }
661 662 663 664 665 666 667
    } else if (vm->def->mem.hard_limit != 0 ||
               vm->def->mem.soft_limit != 0 ||
               vm->def->mem.swap_hard_limit != 0) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Memory cgroup is not available on this host"));
    } else {
        VIR_WARN("Could not autoset a RSS limit for domain %s", vm->def->name);
668 669
    }

670
    if (vm->def->cputune.shares != 0) {
671 672
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
            rc = virCgroupSetCpuShares(priv->cgroup, vm->def->cputune.shares);
673
            if (rc != 0) {
674 675 676 677 678
                virReportSystemError(-rc,
                                     _("Unable to set io cpu shares for domain %s"),
                                     vm->def->name);
                goto cleanup;
            }
679
        } else {
680 681
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("CPU tuning is not available on this host"));
682 683 684
        }
    }

685 686
    if ((vm->def->numatune.memory.nodemask ||
         (vm->def->numatune.memory.placement_mode ==
G
Gao feng 已提交
687
          VIR_NUMA_TUNE_MEM_PLACEMENT_MODE_AUTO)) &&
H
Hu Tao 已提交
688
        vm->def->numatune.memory.mode == VIR_DOMAIN_NUMATUNE_MEM_STRICT &&
689
        virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET)) {
690 691
        char *mask = NULL;
        if (vm->def->numatune.memory.placement_mode ==
G
Gao feng 已提交
692
            VIR_NUMA_TUNE_MEM_PLACEMENT_MODE_AUTO)
693
            mask = virBitmapFormat(nodemask);
694
        else
695
            mask = virBitmapFormat(vm->def->numatune.memory.nodemask);
H
Hu Tao 已提交
696
        if (!mask) {
697 698
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to convert memory nodemask"));
H
Hu Tao 已提交
699 700 701
            goto cleanup;
        }

702
        rc = virCgroupSetCpusetMems(priv->cgroup, mask);
H
Hu Tao 已提交
703 704 705 706 707 708 709 710
        VIR_FREE(mask);
        if (rc != 0) {
            virReportSystemError(-rc,
                                 _("Unable to set cpuset.mems for domain %s"),
                                 vm->def->name);
            goto cleanup;
        }
    }
711

712 713
done:
    rc = 0;
714
cleanup:
715
    virObjectUnref(cfg);
716
    return rc == 0 ? 0 : -1;
717 718
}

719 720 721 722 723 724 725 726 727 728 729 730 731 732
int qemuSetupCgroupVcpuBW(virCgroupPtr cgroup, unsigned long long period,
                          long long quota)
{
    int rc;
    unsigned long long old_period;

    if (period == 0 && quota == 0)
        return 0;

    if (period) {
        /* get old period, and we can rollback if set quota failed */
        rc = virCgroupGetCpuCfsPeriod(cgroup, &old_period);
        if (rc < 0) {
            virReportSystemError(-rc,
W
Wen Congyang 已提交
733
                                 "%s", _("Unable to get cpu bandwidth period"));
734 735 736 737 738 739
            return -1;
        }

        rc = virCgroupSetCpuCfsPeriod(cgroup, period);
        if (rc < 0) {
            virReportSystemError(-rc,
W
Wen Congyang 已提交
740
                                 "%s", _("Unable to set cpu bandwidth period"));
741 742 743 744 745 746 747 748
            return -1;
        }
    }

    if (quota) {
        rc = virCgroupSetCpuCfsQuota(cgroup, quota);
        if (rc < 0) {
            virReportSystemError(-rc,
W
Wen Congyang 已提交
749
                                 "%s", _("Unable to set cpu bandwidth quota"));
750 751 752 753 754 755 756 757 758 759
            goto cleanup;
        }
    }

    return 0;

cleanup:
    if (period) {
        rc = virCgroupSetCpuCfsPeriod(cgroup, old_period);
        if (rc < 0)
760
            virReportSystemError(-rc, "%s",
761
                                 _("Unable to rollback cpu bandwidth period"));
762 763 764 765 766
    }

    return -1;
}

767 768 769 770 771
int qemuSetupCgroupVcpuPin(virCgroupPtr cgroup,
                           virDomainVcpuPinDefPtr *vcpupin,
                           int nvcpupin,
                           int vcpuid)
{
772
    int i;
773 774 775

    for (i = 0; i < nvcpupin; i++) {
        if (vcpuid == vcpupin[i]->vcpuid) {
776
            return qemuSetupCgroupEmulatorPin(cgroup, vcpupin[i]->cpumask);
777 778 779
        }
    }

780 781 782 783
    return -1;
}

int qemuSetupCgroupEmulatorPin(virCgroupPtr cgroup,
784
                               virBitmapPtr cpumask)
785 786 787 788
{
    int rc = 0;
    char *new_cpus = NULL;

789
    new_cpus = virBitmapFormat(cpumask);
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
    if (!new_cpus) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to convert cpu mask"));
        rc = -1;
        goto cleanup;
    }

    rc = virCgroupSetCpusetCpus(cgroup, new_cpus);
    if (rc < 0) {
        virReportSystemError(-rc,
                             "%s",
                             _("Unable to set cpuset.cpus"));
        goto cleanup;
    }

805 806 807 808 809
cleanup:
    VIR_FREE(new_cpus);
    return rc;
}

810
int qemuSetupCgroupForVcpu(virDomainObjPtr vm)
811 812 813
{
    virCgroupPtr cgroup_vcpu = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
814
    virDomainDefPtr def = vm->def;
815
    int rc;
M
Martin Kletzander 已提交
816
    unsigned int i, j;
817 818 819
    unsigned long long period = vm->def->cputune.period;
    long long quota = vm->def->cputune.quota;

820
    if ((period || quota) &&
821
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
822 823
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("cgroup cpu is required for scheduler tuning"));
H
Hu Tao 已提交
824 825 826
        return -1;
    }

827 828 829 830
    /* We are trying to setup cgroups for CPU pinning, which can also be done
     * with virProcessInfoSetAffinity, thus the lack of cgroups is not fatal
     * here.
     */
831
    if (priv->cgroup == NULL)
832 833
        return 0;

834
    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
835
        /* If we don't know VCPU<->PID mapping or all vcpu runs in the same
W
Wen Congyang 已提交
836
         * thread, we cannot control each vcpu.
837
         */
838 839
        VIR_WARN("Unable to get vcpus' pids.");
        return 0;
840 841 842
    }

    for (i = 0; i < priv->nvcpupids; i++) {
843
        rc = virCgroupNewVcpu(priv->cgroup, i, true, &cgroup_vcpu);
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
        if (rc < 0) {
            virReportSystemError(-rc,
                                 _("Unable to create vcpu cgroup for %s(vcpu:"
                                   " %d)"),
                                 vm->def->name, i);
            goto cleanup;
        }

        /* move the thread for vcpu to sub dir */
        rc = virCgroupAddTask(cgroup_vcpu, priv->vcpupids[i]);
        if (rc < 0) {
            virReportSystemError(-rc,
                                 _("unable to add vcpu %d task %d to cgroup"),
                                 i, priv->vcpupids[i]);
            goto cleanup;
        }

        if (period || quota) {
H
Hu Tao 已提交
862 863
            if (qemuSetupCgroupVcpuBW(cgroup_vcpu, period, quota) < 0)
                goto cleanup;
864 865
        }

866
        /* Set vcpupin in cgroup if vcpupin xml is provided */
867
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET)) {
M
Martin Kletzander 已提交
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
            /* find the right CPU to pin, otherwise
             * qemuSetupCgroupVcpuPin will fail. */
            for (j = 0; j < def->cputune.nvcpupin; j++) {
                if (def->cputune.vcpupin[j]->vcpuid != i)
                    continue;

                if (qemuSetupCgroupVcpuPin(cgroup_vcpu,
                                           def->cputune.vcpupin,
                                           def->cputune.nvcpupin,
                                           i) < 0)
                    goto cleanup;

                break;
            }
        }
883

884 885 886 887 888 889
        virCgroupFree(&cgroup_vcpu);
    }

    return 0;

cleanup:
890 891 892 893 894
    if (cgroup_vcpu) {
        virCgroupRemove(cgroup_vcpu);
        virCgroupFree(&cgroup_vcpu);
    }

895 896 897
    return -1;
}

898
int qemuSetupCgroupForEmulator(virQEMUDriverPtr driver,
899 900
                               virDomainObjPtr vm,
                               virBitmapPtr nodemask)
901
{
902
    virBitmapPtr cpumask = NULL;
903
    virBitmapPtr cpumap = NULL;
904
    virCgroupPtr cgroup_emulator = NULL;
905
    virDomainDefPtr def = vm->def;
906
    qemuDomainObjPrivatePtr priv = vm->privateData;
907 908
    unsigned long long period = vm->def->cputune.emulator_period;
    long long quota = vm->def->cputune.emulator_quota;
909
    int rc;
910

911
    if ((period || quota) &&
912
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
913 914 915 916 917
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("cgroup cpu is required for scheduler tuning"));
        return -1;
    }

918
    if (priv->cgroup == NULL)
919 920
        return 0; /* Not supported, so claim success */

921
    rc = virCgroupNewEmulator(priv->cgroup, true, &cgroup_emulator);
922 923 924 925 926 927 928
    if (rc < 0) {
        virReportSystemError(-rc,
                             _("Unable to create emulator cgroup for %s"),
                             vm->def->name);
        goto cleanup;
    }

929
    rc = virCgroupMoveTask(priv->cgroup, cgroup_emulator);
930 931 932 933 934 935
    if (rc < 0) {
        virReportSystemError(-rc,
                             _("Unable to move tasks from domain cgroup to "
                               "emulator cgroup for %s"),
                             vm->def->name);
        goto cleanup;
936 937
    }

938 939 940 941 942
    if (def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
        if (!(cpumap = qemuPrepareCpumap(driver, nodemask)))
            goto cleanup;
        cpumask = cpumap;
    } else if (def->cputune.emulatorpin) {
943
        cpumask = def->cputune.emulatorpin->cpumask;
944
    } else if (def->cpumask) {
945
        cpumask = def->cpumask;
946
    }
947 948

    if (cpumask) {
949
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET)) {
950 951 952 953 954
            rc = qemuSetupCgroupEmulatorPin(cgroup_emulator, cpumask);
            if (rc < 0)
                goto cleanup;
        }
        cpumask = NULL; /* sanity */
H
Hu Tao 已提交
955
    }
956

957
    if (period || quota) {
958
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
H
Hu Tao 已提交
959 960
            if ((rc = qemuSetupCgroupVcpuBW(cgroup_emulator, period,
                                            quota)) < 0)
961 962 963 964
                goto cleanup;
        }
    }

965
    virCgroupFree(&cgroup_emulator);
966
    virBitmapFree(cpumap);
967 968 969
    return 0;

cleanup:
970 971
    virBitmapFree(cpumap);

972 973 974 975 976 977 978
    if (cgroup_emulator) {
        virCgroupRemove(cgroup_emulator);
        virCgroupFree(&cgroup_emulator);
    }

    return rc;
}
979

980
int qemuRemoveCgroup(virDomainObjPtr vm)
981
{
982
    qemuDomainObjPrivatePtr priv = vm->privateData;
983

984
    if (priv->cgroup == NULL)
985 986
        return 0; /* Not supported, so claim success */

987
    return virCgroupRemove(priv->cgroup);
988 989
}

990
int qemuAddToCgroup(virDomainObjPtr vm)
991
{
992
    qemuDomainObjPrivatePtr priv = vm->privateData;
993 994
    int rc;

995
    if (priv->cgroup == NULL)
996 997
        return 0; /* Not supported, so claim success */

998
    rc = virCgroupAddTask(priv->cgroup, getpid());
999 1000 1001
    if (rc != 0) {
        virReportSystemError(-rc,
                             _("unable to add domain %s task %d to cgroup"),
1002 1003
                             vm->def->name, getpid());
        return -1;
1004 1005
    }

1006
    return 0;
1007
}