qemu_cgroup.c 33.1 KB
Newer Older
1 2 3
/*
 * qemu_cgroup.c: QEMU cgroup management
 *
4
 * Copyright (C) 2006-2015 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 "domain_audit.h"
34
#include "virscsi.h"
35
#include "virstring.h"
36
#include "virfile.h"
37
#include "virtypedparam.h"
38
#include "virnuma.h"
39
#include "virsystemd.h"
40 41 42

#define VIR_FROM_THIS VIR_FROM_QEMU

43 44
VIR_LOG_INIT("qemu.qemu_cgroup");

45 46 47 48
static const char *const defaultDeviceACL[] = {
    "/dev/null", "/dev/full", "/dev/zero",
    "/dev/random", "/dev/urandom",
    "/dev/ptmx", "/dev/kvm", "/dev/kqemu",
49
    "/dev/rtc", "/dev/hpet", "/dev/vfio/vfio",
50 51 52 53 54
    NULL,
};
#define DEVICE_PTY_MAJOR 136
#define DEVICE_SND_MAJOR 116

55
static int
56 57 58
qemuSetupImageCgroupInternal(virDomainObjPtr vm,
                             virStorageSourcePtr src,
                             bool forceReadonly)
59
{
60
    qemuDomainObjPrivatePtr priv = vm->privateData;
61
    int perms = VIR_CGROUP_DEVICE_READ;
62
    int ret;
63

64 65 66 67 68 69 70 71 72 73
    if (!virCgroupHasController(priv->cgroup,
                                VIR_CGROUP_CONTROLLER_DEVICES))
        return 0;

    if (!src->path || !virStorageSourceIsLocalStorage(src)) {
        VIR_DEBUG("Not updating cgroups for disk path '%s', type: %s",
                  NULLSTR(src->path), virStorageTypeToString(src->type));
        return 0;
    }

74 75
    if (!src->readonly && !forceReadonly)
        perms |= VIR_CGROUP_DEVICE_WRITE;
76

77 78
    VIR_DEBUG("Allow path %s, perms: %s",
              src->path, virCgroupGetDevicePermsString(perms));
79

80
    ret = virCgroupAllowDevicePath(priv->cgroup, src->path, perms, true);
81

82
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", src->path,
83 84
                             virCgroupGetDevicePermsString(perms),
                             ret == 0);
85 86

    return ret;
87 88 89
}


90
int
91 92
qemuSetupImageCgroup(virDomainObjPtr vm,
                     virStorageSourcePtr src)
93
{
94
    return qemuSetupImageCgroupInternal(vm, src, false);
95 96 97 98 99 100 101
}


int
qemuTeardownImageCgroup(virDomainObjPtr vm,
                        virStorageSourcePtr src)
{
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int perms = VIR_CGROUP_DEVICE_READ |
                VIR_CGROUP_DEVICE_WRITE |
                VIR_CGROUP_DEVICE_MKNOD;
    int ret;

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

    if (!src->path || !virStorageSourceIsLocalStorage(src)) {
        VIR_DEBUG("Not updating cgroups for disk path '%s', type: %s",
                  NULLSTR(src->path), virStorageTypeToString(src->type));
        return 0;
    }

    VIR_DEBUG("Deny path %s", src->path);

    ret = virCgroupDenyDevicePath(priv->cgroup, src->path, perms, true);

    virDomainAuditCgroupPath(vm, priv->cgroup, "deny", src->path,
                             virCgroupGetDevicePermsString(perms), ret == 0);

    return ret;
126 127 128
}


129 130 131
int
qemuSetupDiskCgroup(virDomainObjPtr vm,
                    virDomainDiskDefPtr disk)
132
{
133
    virStorageSourcePtr next;
134
    bool forceReadonly = false;
135

136
    for (next = disk->src; next; next = next->backingStore) {
137
        if (qemuSetupImageCgroupInternal(vm, next, forceReadonly) < 0)
138
            return -1;
139 140 141

        /* setup only the top level image for read-write */
        forceReadonly = true;
142
    }
143 144

    return 0;
145 146 147
}


148 149 150
int
qemuTeardownDiskCgroup(virDomainObjPtr vm,
                       virDomainDiskDefPtr disk)
151
{
152
    virStorageSourcePtr next;
153

154
    for (next = disk->src; next; next = next->backingStore) {
155
        if (qemuTeardownImageCgroup(vm, next) < 0)
156 157
            return -1;
    }
158

159
    return 0;
160 161
}

162

163
static int
164
qemuSetupChrSourceCgroup(virDomainObjPtr vm,
165
                         virDomainChrSourceDefPtr source)
166
{
167
    qemuDomainObjPrivatePtr priv = vm->privateData;
168
    int ret;
169

170
    if (source->type != VIR_DOMAIN_CHR_TYPE_DEV)
171 172
        return 0;

173
    VIR_DEBUG("Process path '%s' for device", source->data.file.path);
174

175
    ret = virCgroupAllowDevicePath(priv->cgroup, source->data.file.path,
176
                                   VIR_CGROUP_DEVICE_RW, false);
177
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
178
                             source->data.file.path, "rw", ret == 0);
179

180
    return ret;
181 182
}

183
static int
184
qemuSetupChardevCgroup(virDomainDefPtr def ATTRIBUTE_UNUSED,
185 186 187
                       virDomainChrDefPtr dev,
                       void *opaque)
{
188 189 190
    virDomainObjPtr vm = opaque;

    return qemuSetupChrSourceCgroup(vm, &dev->source);
191 192 193 194
}


static int
195
qemuSetupTPMCgroup(virDomainObjPtr vm)
196
{
197
    int ret = 0;
198
    virDomainTPMDefPtr dev = vm->def->tpm;
199 200 201

    switch (dev->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
202
        ret = qemuSetupChrSourceCgroup(vm, &dev->data.passthrough.source);
203 204 205 206 207
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

208
    return ret;
209 210
}

211

212 213 214 215 216 217 218 219 220 221 222
static int
qemuSetupInputCgroup(virDomainObjPtr vm,
                     virDomainInputDefPtr dev)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = 0;

    switch (dev->type) {
    case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
        VIR_DEBUG("Process path '%s' for input device", dev->source.evdev);
        ret = virCgroupAllowDevicePath(priv->cgroup, dev->source.evdev,
223
                                       VIR_CGROUP_DEVICE_RW, false);
224 225 226 227 228 229 230 231
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", dev->source.evdev, "rw", ret == 0);
        break;
    }

    return ret;
}


232
static int
233
qemuSetupHostUSBDeviceCgroup(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
234 235
                             const char *path,
                             void *opaque)
236
{
237 238
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
239
    int ret;
240 241

    VIR_DEBUG("Process path '%s' for USB device", path);
242
    ret = virCgroupAllowDevicePath(priv->cgroup, path,
243
                                   VIR_CGROUP_DEVICE_RW, false);
244
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path, "rw", ret == 0);
245

246
    return ret;
247 248
}

249
static int
250
qemuSetupHostSCSIDeviceCgroup(virSCSIDevicePtr dev ATTRIBUTE_UNUSED,
251 252 253 254 255
                              const char *path,
                              void *opaque)
{
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
256
    int ret;
257 258 259

    VIR_DEBUG("Process path '%s' for SCSI device", path);

260 261 262
    ret = virCgroupAllowDevicePath(priv->cgroup, path,
                                   virSCSIDeviceGetReadonly(dev) ?
                                   VIR_CGROUP_DEVICE_READ :
263
                                   VIR_CGROUP_DEVICE_RW, false);
264 265

    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path,
266
                             virSCSIDeviceGetReadonly(dev) ? "r" : "rw", ret == 0);
267

268
    return ret;
269
}
270

271
int
272
qemuSetupHostdevCgroup(virDomainObjPtr vm,
273 274 275 276
                       virDomainHostdevDefPtr dev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
277
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
278
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
279
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
280
    virPCIDevicePtr pci = NULL;
281
    virUSBDevicePtr usb = NULL;
282
    virSCSIDevicePtr scsi = NULL;
283 284 285 286 287 288 289 290 291 292 293 294 295 296
    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:
297
            if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
298
                int rv;
299

300 301 302 303
                pci = virPCIDeviceNew(pcisrc->addr.domain,
                                      pcisrc->addr.bus,
                                      pcisrc->addr.slot,
                                      pcisrc->addr.function);
304 305 306
                if (!pci)
                    goto cleanup;

307
                if (!(path = virPCIDeviceGetIOMMUGroupDev(pci)))
308 309 310
                    goto cleanup;

                VIR_DEBUG("Cgroup allow %s for PCI device assignment", path);
311
                rv = virCgroupAllowDevicePath(priv->cgroup, path,
312
                                              VIR_CGROUP_DEVICE_RW, false);
313
                virDomainAuditCgroupPath(vm, priv->cgroup,
314 315
                                         "allow", path, "rw", rv == 0);
                if (rv < 0)
316 317 318
                    goto cleanup;
            }
            break;
319 320 321 322 323 324 325 326

        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            /* NB: hostdev->missing wasn't previously checked in the
             * case of hotplug, only when starting a domain. Now it is
             * always checked, and the cgroup setup skipped if true.
             */
            if (dev->missing)
                break;
327
            if ((usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device,
328 329 330 331
                                       NULL)) == NULL) {
                goto cleanup;
            }

332
            /* oddly, qemuSetupHostUSBDeviceCgroup doesn't ever
333 334
             * reference the usb object we just created
             */
335
            if (virUSBDeviceFileIterate(usb, qemuSetupHostUSBDeviceCgroup,
336 337 338 339
                                        vm) < 0) {
                goto cleanup;
            }
            break;
340

341
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
            if (scsisrc->protocol ==
                VIR_DOMAIN_HOSTDEV_SCSI_PROTOCOL_TYPE_ISCSI) {
                virDomainHostdevSubsysSCSIiSCSIPtr iscsisrc = &scsisrc->u.iscsi;
                /* Follow qemuSetupDiskCgroup() and qemuSetImageCgroupInternal()
                 * which does nothing for non local storage
                 */
                VIR_DEBUG("Not updating cgroups for hostdev iSCSI path '%s'",
                          iscsisrc->path);
            } else {
                virDomainHostdevSubsysSCSIHostPtr scsihostsrc =
                    &scsisrc->u.host;
                if ((scsi = virSCSIDeviceNew(NULL,
                                             scsihostsrc->adapter,
                                             scsihostsrc->bus,
                                             scsihostsrc->target,
                                             scsihostsrc->unit,
                                             dev->readonly,
                                             dev->shareable)) == NULL)
                    goto cleanup;
361

362 363 364 365 366
                if (virSCSIDeviceFileIterate(scsi,
                                             qemuSetupHostSCSIDeviceCgroup,
                                             vm) < 0)
                    goto cleanup;
            }
367 368
            break;
        }
369

370 371 372 373 374 375
        default:
            break;
        }
    }

    ret = 0;
376
 cleanup:
377
    virPCIDeviceFree(pci);
378
    virUSBDeviceFree(usb);
379
    virSCSIDeviceFree(scsi);
380 381 382 383 384 385 386 387 388 389
    VIR_FREE(path);
    return ret;
}

int
qemuTeardownHostdevCgroup(virDomainObjPtr vm,
                       virDomainHostdevDefPtr dev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
390
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    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:
406
            if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
407
                int rv;
408

409 410 411 412
                pci = virPCIDeviceNew(pcisrc->addr.domain,
                                      pcisrc->addr.bus,
                                      pcisrc->addr.slot,
                                      pcisrc->addr.function);
413 414 415
                if (!pci)
                    goto cleanup;

416
                if (!(path = virPCIDeviceGetIOMMUGroupDev(pci)))
417 418 419
                    goto cleanup;

                VIR_DEBUG("Cgroup deny %s for PCI device assignment", path);
420
                rv = virCgroupDenyDevicePath(priv->cgroup, path,
421
                                             VIR_CGROUP_DEVICE_RWM, false);
422
                virDomainAuditCgroupPath(vm, priv->cgroup,
423 424
                                         "deny", path, "rwm", rv == 0);
                if (rv < 0)
425 426 427
                    goto cleanup;
            }
            break;
428 429 430
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            /* nothing to tear down for USB */
            break;
431 432 433 434 435 436
        default:
            break;
        }
    }

    ret = 0;
437
 cleanup:
438 439 440 441 442
    virPCIDeviceFree(pci);
    VIR_FREE(path);
    return ret;
}

443 444 445 446
static int
qemuSetupBlkioCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
447
    size_t i;
448 449 450 451 452 453 454 455 456 457 458 459

    if (!virCgroupHasController(priv->cgroup,
                                VIR_CGROUP_CONTROLLER_BLKIO)) {
        if (vm->def->blkio.weight || vm->def->blkio.ndevices) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Block I/O tuning is not available on this host"));
            return -1;
        } else {
            return 0;
        }
    }

460 461 462
    if (vm->def->blkio.weight != 0 &&
        virCgroupSetBlkioWeight(priv->cgroup, vm->def->blkio.weight) < 0)
        return -1;
463 464 465

    if (vm->def->blkio.ndevices) {
        for (i = 0; i < vm->def->blkio.ndevices; i++) {
466
            virBlkioDevicePtr dev = &vm->def->blkio.devices[i];
467 468
            if (dev->weight &&
                (virCgroupSetBlkioDeviceWeight(priv->cgroup, dev->path,
469 470 471
                                               dev->weight) < 0 ||
                 virCgroupGetBlkioDeviceWeight(priv->cgroup, dev->path,
                                               &dev->weight) < 0))
472 473 474 475
                return -1;

            if (dev->riops &&
                (virCgroupSetBlkioDeviceReadIops(priv->cgroup, dev->path,
476 477 478
                                                 dev->riops) < 0 ||
                 virCgroupGetBlkioDeviceReadIops(priv->cgroup, dev->path,
                                                 &dev->riops) < 0))
479 480 481 482
                return -1;

            if (dev->wiops &&
                (virCgroupSetBlkioDeviceWriteIops(priv->cgroup, dev->path,
483 484 485
                                                  dev->wiops) < 0 ||
                 virCgroupGetBlkioDeviceWriteIops(priv->cgroup, dev->path,
                                                  &dev->wiops) < 0))
486 487 488 489
                return -1;

            if (dev->rbps &&
                (virCgroupSetBlkioDeviceReadBps(priv->cgroup, dev->path,
490 491 492
                                                dev->rbps) < 0 ||
                 virCgroupGetBlkioDeviceReadBps(priv->cgroup, dev->path,
                                                &dev->rbps) < 0))
493 494 495 496
                return -1;

            if (dev->wbps &&
                (virCgroupSetBlkioDeviceWriteBps(priv->cgroup, dev->path,
497 498 499
                                                 dev->wbps) < 0 ||
                 virCgroupGetBlkioDeviceWriteBps(priv->cgroup, dev->path,
                                                 &dev->wbps) < 0))
500 501 502 503 504 505 506
                return -1;
        }
    }

    return 0;
}

507

508 509 510 511 512
static int
qemuSetupMemoryCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

E
Eric Blake 已提交
513
    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_MEMORY)) {
514 515 516
        if (virMemoryLimitIsSet(vm->def->mem.hard_limit) ||
            virMemoryLimitIsSet(vm->def->mem.soft_limit) ||
            virMemoryLimitIsSet(vm->def->mem.swap_hard_limit)) {
517 518 519
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Memory cgroup is not available on this host"));
            return -1;
O
Osier Yang 已提交
520 521
        } else {
            return 0;
522 523 524
        }
    }

525 526 527
    if (virMemoryLimitIsSet(vm->def->mem.hard_limit))
        if (virCgroupSetMemoryHardLimit(priv->cgroup, vm->def->mem.hard_limit) < 0)
            return -1;
528

529 530 531
    if (virMemoryLimitIsSet(vm->def->mem.soft_limit))
        if (virCgroupSetMemorySoftLimit(priv->cgroup, vm->def->mem.soft_limit) < 0)
            return -1;
532

533 534 535
    if (virMemoryLimitIsSet(vm->def->mem.swap_hard_limit))
        if (virCgroupSetMemSwapHardLimit(priv->cgroup, vm->def->mem.swap_hard_limit) < 0)
            return -1;
536 537 538 539 540

    return 0;
}


541 542 543 544 545 546 547
static int
qemuSetupDevicesCgroup(virQEMUDriverPtr driver,
                       virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = NULL;
    const char *const *deviceACL = NULL;
548
    int rv = -1;
549
    int ret = -1;
550
    size_t i;
551 552 553 554

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

555 556 557 558 559
    rv = virCgroupDenyAllDevices(priv->cgroup);
    virDomainAuditCgroup(vm, priv->cgroup, "deny", "all", rv == 0);
    if (rv < 0) {
        if (virLastErrorIsSystemErrno(EPERM)) {
            virResetLastError();
560 561 562 563 564 565 566
            VIR_WARN("Group devices ACL is not accessible, disabling whitelisting");
            return 0;
        }

        goto cleanup;
    }

567
    for (i = 0; i < vm->def->ndisks; i++) {
568 569 570 571
        if (qemuSetupDiskCgroup(vm, vm->def->disks[i]) < 0)
            goto cleanup;
    }

572 573
    rv = virCgroupAllowDevice(priv->cgroup, 'c', DEVICE_PTY_MAJOR, -1,
                              VIR_CGROUP_DEVICE_RW);
574
    virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_PTY_MAJOR,
575 576
                              "pty", "rw", rv == 0);
    if (rv < 0)
577 578 579 580 581 582 583 584
        goto cleanup;

    cfg = virQEMUDriverGetConfig(driver);
    deviceACL = cfg->cgroupDeviceACL ?
                (const char *const *)cfg->cgroupDeviceACL :
                defaultDeviceACL;

    if (vm->def->nsounds &&
585
        ((!vm->def->ngraphics && cfg->nogfxAllowHostAudio) ||
586 587
         (vm->def->graphics &&
          ((vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
588
           cfg->vncAllowHostAudio) ||
589
           (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL))))) {
590 591
        rv = virCgroupAllowDevice(priv->cgroup, 'c', DEVICE_SND_MAJOR, -1,
                                  VIR_CGROUP_DEVICE_RW);
592
        virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_SND_MAJOR,
593 594
                                  "sound", "rw", rv == 0);
        if (rv < 0)
595 596 597
            goto cleanup;
    }

598
    for (i = 0; deviceACL[i] != NULL; i++) {
599
        if (!virFileExists(deviceACL[i])) {
N
Nehal J Wani 已提交
600
            VIR_DEBUG("Ignoring non-existent device %s", deviceACL[i]);
601 602 603
            continue;
        }

604
        rv = virCgroupAllowDevicePath(priv->cgroup, deviceACL[i],
605
                                      VIR_CGROUP_DEVICE_RW, false);
606 607 608
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", deviceACL[i], "rw", rv == 0);
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
609 610 611 612 613 614 615 616 617
            goto cleanup;
    }

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

618
    if (vm->def->tpm && qemuSetupTPMCgroup(vm) < 0)
619 620 621
        goto cleanup;

    for (i = 0; i < vm->def->nhostdevs; i++) {
622
        if (qemuSetupHostdevCgroup(vm, vm->def->hostdevs[i]) < 0)
623 624 625
            goto cleanup;
    }

626 627 628 629 630
    for (i = 0; i < vm->def->ninputs; i++) {
        if (qemuSetupInputCgroup(vm, vm->def->inputs[i]) < 0)
            goto cleanup;
    }

631 632 633
    for (i = 0; i < vm->def->nrngs; i++) {
        if (vm->def->rngs[i]->backend == VIR_DOMAIN_RNG_BACKEND_RANDOM) {
            VIR_DEBUG("Setting Cgroup ACL for RNG device");
634 635
            rv = virCgroupAllowDevicePath(priv->cgroup,
                                          vm->def->rngs[i]->source.file,
636
                                          VIR_CGROUP_DEVICE_RW, false);
637
            virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
638 639
                                     vm->def->rngs[i]->source.file,
                                     "rw", rv == 0);
640 641 642 643
            if (rv < 0 &&
                !virLastErrorIsSystemErrno(ENOENT))
                goto cleanup;
        }
644 645
    }

646
    ret = 0;
647
 cleanup:
648 649 650 651 652
    virObjectUnref(cfg);
    return ret;
}


653
int
654
qemuSetupCpusetMems(virDomainObjPtr vm)
655
{
656
    virCgroupPtr cgroup_temp = NULL;
657
    qemuDomainObjPrivatePtr priv = vm->privateData;
658
    virDomainNumatuneMemMode mode;
659
    char *mem_mask = NULL;
660 661 662 663 664
    int ret = -1;

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

665 666
    if (virDomainNumatuneGetMode(vm->def->numa, -1, &mode) < 0 ||
        mode != VIR_DOMAIN_NUMATUNE_MEM_STRICT)
667 668
        return 0;

669
    if (virDomainNumatuneMaybeFormatNodeset(vm->def->numa,
670
                                            priv->autoNodeset,
671
                                            &mem_mask, -1) < 0)
672
        goto cleanup;
673

674
    if (mem_mask)
J
John Ferlan 已提交
675 676
        if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                               false, &cgroup_temp) < 0 ||
677
            virCgroupSetCpusetMems(cgroup_temp, mem_mask) < 0)
678
            goto cleanup;
679

680 681 682
    ret = 0;
 cleanup:
    VIR_FREE(mem_mask);
683
    virCgroupFree(&cgroup_temp);
684 685 686 687 688
    return ret;
}


static int
689
qemuSetupCpusetCgroup(virDomainObjPtr vm)
690 691 692 693 694 695
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

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

696 697 698
    if (virCgroupSetCpusetMemoryMigrate(priv->cgroup, true) < 0)
        return -1;

699
    return 0;
700 701 702
}


703
static int
704 705
qemuSetupCpuCgroup(virQEMUDriverPtr driver,
                   virDomainObjPtr vm)
706 707
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
708 709 710 711
    virObjectEventPtr event = NULL;
    virTypedParameterPtr eventParams = NULL;
    int eventNparams = 0;
    int eventMaxparams = 0;
712 713

    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
714
       if (vm->def->cputune.sharesSpecified) {
715 716 717 718 719 720 721 722
           virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                          _("CPU tuning is not available on this host"));
           return -1;
       } else {
           return 0;
       }
    }

723 724 725 726 727 728 729
    if (vm->def->cputune.sharesSpecified) {
        unsigned long long val;
        if (virCgroupSetCpuShares(priv->cgroup, vm->def->cputune.shares) < 0)
            return -1;

        if (virCgroupGetCpuShares(priv->cgroup, &val) < 0)
            return -1;
730 731 732 733
        if (vm->def->cputune.shares != val) {
            vm->def->cputune.shares = val;
            if (virTypedParamsAddULLong(&eventParams, &eventNparams,
                                        &eventMaxparams,
734
                                        VIR_DOMAIN_TUNABLE_CPU_CPU_SHARES,
735 736 737 738 739 740
                                        val) < 0)
                return -1;

            event = virDomainEventTunableNewFromObj(vm, eventParams, eventNparams);
        }

741
        qemuDomainEventQueue(driver, event);
742
    }
743 744 745 746 747

    return 0;
}


748
static int
749
qemuInitCgroup(virQEMUDriverPtr driver,
750 751 752
               virDomainObjPtr vm,
               size_t nnicindexes,
               int *nicindexes)
753
{
754
    int ret = -1;
755 756 757
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

758
    if (!virQEMUDriverIsPrivileged(driver))
759 760
        goto done;

761 762 763
    if (!virCgroupAvailable())
        goto done;

764 765
    virCgroupFree(&priv->cgroup);

766
    if (!vm->def->resource) {
767 768
        virDomainResourceDefPtr res;

769
        if (VIR_ALLOC(res) < 0)
770
            goto cleanup;
771

772
        if (VIR_STRDUP(res->partition, "/machine") < 0) {
773 774 775 776 777
            VIR_FREE(res);
            goto cleanup;
        }

        vm->def->resource = res;
778 779
    }

780 781 782 783 784 785
    if (vm->def->resource->partition[0] != '/') {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Resource partition '%s' must start with '/'"),
                       vm->def->resource->partition);
        goto cleanup;
    }
786

787 788 789 790 791 792 793 794 795 796 797 798
    /*
     * We need to do this because of systemd-machined, because
     * CreateMachine requires the name to be a valid hostname.
     */
    priv->machineName = virSystemdMakeMachineName("qemu",
                                                  vm->def->id,
                                                  vm->def->name,
                                                  virQEMUDriverIsPrivileged(driver));
    if (!priv->machineName)
        goto cleanup;

    if (virCgroupNewMachine(priv->machineName,
799 800 801 802 803
                            "qemu",
                            vm->def->uuid,
                            NULL,
                            vm->pid,
                            false,
804
                            nnicindexes, nicindexes,
805 806 807
                            vm->def->resource->partition,
                            cfg->cgroupControllers,
                            &priv->cgroup) < 0) {
808 809
        if (virCgroupNewIgnoreError())
            goto done;
810

811 812
        goto cleanup;
    }
813

814
 done:
815
    ret = 0;
816
 cleanup:
817 818 819
    virObjectUnref(cfg);
    return ret;
}
820

821 822 823
static void
qemuRestoreCgroupState(virDomainObjPtr vm)
{
824
    char *mem_mask = NULL;
825
    char *nodeset = NULL;
826 827
    int empty = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
828
    size_t i = 0;
829
    virBitmapPtr all_nodes;
830
    virCgroupPtr cgroup_temp = NULL;
831 832 833 834 835 836 837 838

    if (!(all_nodes = virNumaGetHostNodeset()))
        goto error;

    if (!(mem_mask = virBitmapFormat(all_nodes)))
        goto error;

    if ((empty = virCgroupHasEmptyTasks(priv->cgroup,
839
                                        VIR_CGROUP_CONTROLLER_CPUSET)) <= 0)
840 841 842 843 844
        goto error;

    if (virCgroupSetCpusetMems(priv->cgroup, mem_mask) < 0)
        goto error;

845 846 847 848 849 850
    for (i = 0; i < virDomainDefGetVcpusMax(vm->def); i++) {
        virDomainVcpuInfoPtr vcpu = virDomainDefGetVcpu(vm->def, i);

        if (!vcpu->online)
            continue;

J
John Ferlan 已提交
851 852
        if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_VCPU, i,
                               false, &cgroup_temp) < 0 ||
853 854 855 856 857
            virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
            virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
            virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
            goto cleanup;

858
        VIR_FREE(nodeset);
859 860 861
        virCgroupFree(&cgroup_temp);
    }

862 863 864
    for (i = 0; i < vm->def->niothreadids; i++) {
        if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_IOTHREAD,
                               vm->def->iothreadids[i]->iothread_id,
J
John Ferlan 已提交
865
                               false, &cgroup_temp) < 0 ||
866 867 868 869 870
            virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
            virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
            virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
            goto cleanup;

871
        VIR_FREE(nodeset);
872 873 874
        virCgroupFree(&cgroup_temp);
    }

J
John Ferlan 已提交
875 876
    if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                           false, &cgroup_temp) < 0 ||
877 878 879 880 881
        virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
        virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
        virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
        goto cleanup;

882 883
 cleanup:
    VIR_FREE(mem_mask);
884
    VIR_FREE(nodeset);
885
    virBitmapFree(all_nodes);
886
    virCgroupFree(&cgroup_temp);
887 888 889 890 891 892 893
    return;

 error:
    virResetLastError();
    VIR_DEBUG("Couldn't restore cgroups to meaningful state");
    goto cleanup;
}
894 895 896 897 898 899 900 901 902

int
qemuConnectCgroup(virQEMUDriverPtr driver,
                  virDomainObjPtr vm)
{
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = -1;

903
    if (!virQEMUDriverIsPrivileged(driver))
904 905 906 907 908 909 910
        goto done;

    if (!virCgroupAvailable())
        goto done;

    virCgroupFree(&priv->cgroup);

911 912
    if (virCgroupNewDetectMachine(vm->def->name,
                                  "qemu",
913 914
                                  vm->def->id,
                                  virQEMUDriverIsPrivileged(driver),
915
                                  vm->pid,
916
                                  cfg->cgroupControllers,
917
                                  &priv->cgroup) < 0)
918
        goto cleanup;
919

920 921 922 923
    priv->machineName = virSystemdGetMachineNameByPID(vm->pid);
    if (!priv->machineName)
        virResetLastError();

924 925
    qemuRestoreCgroupState(vm);

926
 done:
927
    ret = 0;
928
 cleanup:
929
    virObjectUnref(cfg);
930
    return ret;
931 932
}

933 934
int
qemuSetupCgroup(virQEMUDriverPtr driver,
935 936 937
                virDomainObjPtr vm,
                size_t nnicindexes,
                int *nicindexes)
938
{
939
    qemuDomainObjPrivatePtr priv = vm->privateData;
940
    int ret = -1;
941

942 943 944 945 946 947
    if (!vm->pid) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot setup cgroups until process is started"));
        return -1;
    }

948
    if (qemuInitCgroup(driver, vm, nnicindexes, nicindexes) < 0)
949
        return -1;
950

951
    if (!priv->cgroup)
952
        return 0;
953

954 955
    if (qemuSetupDevicesCgroup(driver, vm) < 0)
        goto cleanup;
956

957 958
    if (qemuSetupBlkioCgroup(vm) < 0)
        goto cleanup;
959

960 961
    if (qemuSetupMemoryCgroup(vm) < 0)
        goto cleanup;
962

963
    if (qemuSetupCpuCgroup(driver, vm) < 0)
964
        goto cleanup;
965

966
    if (qemuSetupCpusetCgroup(vm) < 0)
967
        goto cleanup;
968

969
    ret = 0;
970
 cleanup:
971
    return ret;
972 973
}

974 975 976 977
int
qemuSetupCgroupVcpuBW(virCgroupPtr cgroup,
                      unsigned long long period,
                      long long quota)
978 979 980 981 982 983 984 985
{
    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 */
986
        if (virCgroupGetCpuCfsPeriod(cgroup, &old_period) < 0)
987 988
            return -1;

989
        if (virCgroupSetCpuCfsPeriod(cgroup, period) < 0)
990 991 992
            return -1;
    }

993 994 995
    if (quota &&
        virCgroupSetCpuCfsQuota(cgroup, quota) < 0)
        goto error;
996 997 998

    return 0;

999
 error:
1000
    if (period) {
1001 1002 1003 1004 1005 1006
        virErrorPtr saved = virSaveLastError();
        ignore_value(virCgroupSetCpuCfsPeriod(cgroup, old_period));
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
1007 1008 1009 1010 1011
    }

    return -1;
}

1012

1013
int
1014 1015
qemuSetupCgroupCpusetCpus(virCgroupPtr cgroup,
                          virBitmapPtr cpumask)
1016
{
1017
    int ret = -1;
1018 1019
    char *new_cpus = NULL;

1020
    if (!(new_cpus = virBitmapFormat(cpumask)))
1021 1022
        goto cleanup;

1023
    if (virCgroupSetCpusetCpus(cgroup, new_cpus) < 0)
1024 1025
        goto cleanup;

1026
    ret = 0;
1027
 cleanup:
1028
    VIR_FREE(new_cpus);
1029
    return ret;
1030 1031
}

1032

1033
int
1034
qemuSetupCgroupForEmulator(virDomainObjPtr vm)
1035
{
1036
    virBitmapPtr cpumask = NULL;
1037
    virCgroupPtr cgroup_emulator = NULL;
1038
    virDomainDefPtr def = vm->def;
1039
    qemuDomainObjPrivatePtr priv = vm->privateData;
1040 1041
    unsigned long long period = vm->def->cputune.emulator_period;
    long long quota = vm->def->cputune.emulator_quota;
1042

1043
    if ((period || quota) &&
1044
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
1045 1046 1047 1048 1049
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("cgroup cpu is required for scheduler tuning"));
        return -1;
    }

1050 1051 1052 1053 1054 1055 1056 1057 1058
    /*
     * If CPU cgroup controller is not initialized here, then we need
     * neither period nor quota settings.  And if CPUSET controller is
     * not initialized either, then there's nothing to do anyway.
     */
    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU) &&
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET))
        return 0;

J
John Ferlan 已提交
1059 1060
    if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                           true, &cgroup_emulator) < 0)
1061 1062
        goto cleanup;

1063
    if (virCgroupMoveTask(priv->cgroup, cgroup_emulator) < 0)
1064
        goto cleanup;
1065

1066
    if (def->cputune.emulatorpin)
1067
        cpumask = def->cputune.emulatorpin;
1068 1069
    else if (def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO)
        cpumask = priv->autoCpuset;
1070
    else if (def->cpumask)
1071 1072 1073
        cpumask = def->cpumask;

    if (cpumask) {
1074
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET) &&
1075
            qemuSetupCgroupCpusetCpus(cgroup_emulator, cpumask) < 0)
1076
            goto cleanup;
H
Hu Tao 已提交
1077
    }
1078

1079
    if (period || quota) {
1080 1081 1082 1083
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU) &&
            qemuSetupCgroupVcpuBW(cgroup_emulator, period,
                                  quota) < 0)
            goto cleanup;
1084 1085
    }

1086 1087 1088
    virCgroupFree(&cgroup_emulator);
    return 0;

1089
 cleanup:
1090 1091 1092 1093 1094
    if (cgroup_emulator) {
        virCgroupRemove(cgroup_emulator);
        virCgroupFree(&cgroup_emulator);
    }

1095
    return -1;
1096
}
1097

1098

1099
int
1100
qemuRemoveCgroup(virDomainObjPtr vm)
1101
{
1102
    qemuDomainObjPrivatePtr priv = vm->privateData;
1103

1104
    if (priv->cgroup == NULL)
1105 1106
        return 0; /* Not supported, so claim success */

1107
    if (virCgroupTerminateMachine(priv->machineName) < 0) {
1108 1109 1110 1111
        if (!virCgroupNewIgnoreError())
            VIR_DEBUG("Failed to terminate cgroup for %s", vm->def->name);
    }

1112
    return virCgroupRemove(priv->cgroup);
1113
}