qemu_cgroup.c 40.2 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
 */

#include <config.h>

#include "qemu_cgroup.h"
25
#include "qemu_domain.h"
26
#include "qemu_process.h"
27
#include "qemu_extdevice.h"
28
#include "qemu_hostdev.h"
29
#include "virlog.h"
30
#include "viralloc.h"
31
#include "virerror.h"
32
#include "domain_audit.h"
33
#include "virscsi.h"
34
#include "virstring.h"
35
#include "virfile.h"
36
#include "virtypedparam.h"
37
#include "virnuma.h"
38
#include "virsystemd.h"
39
#include "virdevmapper.h"
40 41 42

#define VIR_FROM_THIS VIR_FROM_QEMU

43 44
VIR_LOG_INIT("qemu.qemu_cgroup");

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

55

56
static int
57 58 59
qemuSetupImagePathCgroup(virDomainObjPtr vm,
                         const char *path,
                         bool readonly)
60
{
61
    qemuDomainObjPrivatePtr priv = vm->privateData;
62
    int perms = VIR_CGROUP_DEVICE_READ;
63 64 65 66
    char **targetPaths = NULL;
    size_t i;
    int rv;
    int ret = -1;
67

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

71
    if (!readonly)
72
        perms |= VIR_CGROUP_DEVICE_WRITE;
73

74
    VIR_DEBUG("Allow path %s, perms: %s",
75
              path, virCgroupGetDevicePermsString(perms));
76

77
    rv = virCgroupAllowDevicePath(priv->cgroup, path, perms, true);
78

79
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path,
80
                             virCgroupGetDevicePermsString(perms),
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
                             rv);
    if (rv < 0)
        goto cleanup;

    if (rv > 0) {
        /* @path is neither character device nor block device. */
        ret = 0;
        goto cleanup;
    }

    if (virDevMapperGetTargets(path, &targetPaths) < 0 &&
        errno != ENOSYS && errno != EBADF) {
        virReportSystemError(errno,
                             _("Unable to get devmapper targets for %s"),
                             path);
        goto cleanup;
    }
98

99 100 101 102 103 104 105 106 107 108 109 110 111
    for (i = 0; targetPaths && targetPaths[i]; i++) {
        rv = virCgroupAllowDevicePath(priv->cgroup, targetPaths[i], perms, false);

        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", targetPaths[i],
                                 virCgroupGetDevicePermsString(perms),
                                 rv);
        if (rv < 0)
            goto cleanup;
    }

    ret = 0;
 cleanup:
    virStringListFree(targetPaths);
112
    return ret;
113 114 115
}


116 117 118 119 120
static int
qemuSetupImageCgroupInternal(virDomainObjPtr vm,
                             virStorageSourcePtr src,
                             bool forceReadonly)
{
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    g_autofree char *path = NULL;
    bool readonly = src->readonly || forceReadonly;

    if (src->type == VIR_STORAGE_TYPE_NVME) {
        /* Even though disk is R/O we can't make it so in
         * CGroups. QEMU will try to do some ioctl()-s over the
         * device and such operations are considered R/W by the
         * kernel */
        readonly = false;

        if (!(path = virPCIDeviceAddressGetIOMMUGroupDev(&src->nvme->pciAddr)))
            return -1;

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

        path = g_strdup(src->path);
144 145
    }

146
    if (virStoragePRDefIsManaged(src->pr) &&
147 148
        virFileExists(QEMU_DEVICE_MAPPER_CONTROL_PATH) &&
        qemuSetupImagePathCgroup(vm, QEMU_DEVICE_MAPPER_CONTROL_PATH, false) < 0)
149 150
        return -1;

151
    return qemuSetupImagePathCgroup(vm, path, readonly);
152 153 154
}


155
int
156 157
qemuSetupImageCgroup(virDomainObjPtr vm,
                     virStorageSourcePtr src)
158
{
159
    return qemuSetupImageCgroupInternal(vm, src, false);
160 161 162 163 164 165 166
}


int
qemuTeardownImageCgroup(virDomainObjPtr vm,
                        virStorageSourcePtr src)
{
167
    qemuDomainObjPrivatePtr priv = vm->privateData;
168
    g_autofree char *path = NULL;
169
    int perms = VIR_CGROUP_DEVICE_RWM;
170 171
    bool hasPR = false;
    bool hasNVMe = false;
172
    size_t i;
173 174 175 176 177 178
    int ret;

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

179 180
    for (i = 0; i < vm->def->ndisks; i++) {
        virStorageSourcePtr diskSrc = vm->def->disks[i]->src;
181

182 183
        if (src == diskSrc)
            continue;
184

185 186
        if (virStoragePRDefIsManaged(diskSrc->pr))
            hasPR = true;
187

188 189 190 191 192 193 194
        if (virStorageSourceChainHasNVMe(diskSrc))
            hasNVMe = true;
    }

    if (src->type == VIR_STORAGE_TYPE_NVME) {
        if (!(path = virPCIDeviceAddressGetIOMMUGroupDev(&src->nvme->pciAddr)))
            return -1;
195

196 197 198
        if (!hasNVMe &&
            !qemuDomainNeedsVFIO(vm->def)) {
            ret = virCgroupDenyDevicePath(priv->cgroup, QEMU_DEV_VFIO, perms, true);
199
            virDomainAuditCgroupPath(vm, priv->cgroup, "deny",
200
                                     QEMU_DEV_VFIO,
201 202
                                     virCgroupGetDevicePermsString(perms), ret);
            if (ret < 0)
203 204 205 206 207 208 209
                return -1;
        }
    } else {
        if (!src->path || !virStorageSourceIsLocalStorage(src)) {
            VIR_DEBUG("Not updating cgroups for disk path '%s', type: %s",
                      NULLSTR(src->path), virStorageTypeToString(src->type));
            return 0;
210
        }
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225

        path = g_strdup(src->path);
    }

    if (!hasPR &&
        virFileExists(QEMU_DEVICE_MAPPER_CONTROL_PATH)) {
        VIR_DEBUG("Disabling device mapper control");
        ret = virCgroupDenyDevicePath(priv->cgroup,
                                      QEMU_DEVICE_MAPPER_CONTROL_PATH,
                                      perms, true);
        virDomainAuditCgroupPath(vm, priv->cgroup, "deny",
                                 QEMU_DEVICE_MAPPER_CONTROL_PATH,
                                 virCgroupGetDevicePermsString(perms), ret);
        if (ret < 0)
            return ret;
226 227
    }

228
    VIR_DEBUG("Deny path %s", path);
229

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

232
    virDomainAuditCgroupPath(vm, priv->cgroup, "deny", path,
233
                             virCgroupGetDevicePermsString(perms), ret);
234

235 236 237 238 239 240 241
    /* If you're looking for a counter part to
     * qemuSetupImagePathCgroup you're at the right place.
     * However, we can't just blindly deny all the device mapper
     * targets of src->path because they might still be used by
     * another disk in domain. Just like we are not removing
     * disks from namespace. */

242
    return ret;
243 244 245
}


246
int
247 248
qemuSetupImageChainCgroup(virDomainObjPtr vm,
                          virStorageSourcePtr src)
249
{
250
    virStorageSourcePtr next;
251
    bool forceReadonly = false;
252

253
    for (next = src; virStorageSourceIsBacking(next); next = next->backingStore) {
254
        if (qemuSetupImageCgroupInternal(vm, next, forceReadonly) < 0)
255
            return -1;
256 257 258

        /* setup only the top level image for read-write */
        forceReadonly = true;
259
    }
260 261

    return 0;
262 263 264
}


265
int
266 267
qemuTeardownImageChainCgroup(virDomainObjPtr vm,
                             virStorageSourcePtr src)
268
{
269
    virStorageSourcePtr next;
270

271
    for (next = src; virStorageSourceIsBacking(next); next = next->backingStore) {
272
        if (qemuTeardownImageCgroup(vm, next) < 0)
273 274
            return -1;
    }
275

276
    return 0;
277 278
}

279

280
static int
281
qemuSetupChrSourceCgroup(virDomainObjPtr vm,
282
                         virDomainChrSourceDefPtr source)
283
{
284
    qemuDomainObjPrivatePtr priv = vm->privateData;
285
    int ret;
286

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

290
    if (source->type != VIR_DOMAIN_CHR_TYPE_DEV)
291 292
        return 0;

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

295
    ret = virCgroupAllowDevicePath(priv->cgroup, source->data.file.path,
296
                                   VIR_CGROUP_DEVICE_RW, false);
297
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
298
                             source->data.file.path, "rw", ret);
299

300
    return ret;
301 302
}

303 304 305 306 307 308 309 310

static int
qemuTeardownChrSourceCgroup(virDomainObjPtr vm,
                            virDomainChrSourceDefPtr source)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret;

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

314 315 316 317 318 319 320 321
    if (source->type != VIR_DOMAIN_CHR_TYPE_DEV)
        return 0;

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

    ret = virCgroupDenyDevicePath(priv->cgroup, source->data.file.path,
                                  VIR_CGROUP_DEVICE_RW, false);
    virDomainAuditCgroupPath(vm, priv->cgroup, "deny",
322
                             source->data.file.path, "rw", ret);
323 324 325 326 327

    return ret;
}


328
static int
J
Ján Tomko 已提交
329
qemuSetupChardevCgroupCB(virDomainDefPtr def G_GNUC_UNUSED,
330 331
                         virDomainChrDefPtr dev,
                         void *opaque)
332
{
333 334
    virDomainObjPtr vm = opaque;

335
    return qemuSetupChrSourceCgroup(vm, dev->source);
336 337 338 339
}


static int
340
qemuSetupTPMCgroup(virDomainObjPtr vm)
341
{
342
    int ret = 0;
343
    virDomainTPMDefPtr dev = vm->def->tpm;
344 345 346

    switch (dev->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
347
        ret = qemuSetupChrSourceCgroup(vm, &dev->data.passthrough.source);
348
        break;
349
    case VIR_DOMAIN_TPM_TYPE_EMULATOR:
350 351 352 353
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

354
    return ret;
355 356
}

357

358
int
359 360 361 362 363 364
qemuSetupInputCgroup(virDomainObjPtr vm,
                     virDomainInputDefPtr dev)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = 0;

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

368 369 370 371
    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,
372
                                       VIR_CGROUP_DEVICE_RW, false);
373
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", dev->source.evdev, "rw", ret);
374 375 376 377 378 379 380
        break;
    }

    return ret;
}


381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
int
qemuTeardownInputCgroup(virDomainObjPtr vm,
                        virDomainInputDefPtr dev)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = 0;

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

    switch (dev->type) {
    case VIR_DOMAIN_INPUT_TYPE_PASSTHROUGH:
        VIR_DEBUG("Process path '%s' for input device", dev->source.evdev);
        ret = virCgroupDenyDevicePath(priv->cgroup, dev->source.evdev,
                                      VIR_CGROUP_DEVICE_RWM, false);
396
        virDomainAuditCgroupPath(vm, priv->cgroup, "deny", dev->source.evdev, "rwm", ret);
397 398 399 400 401 402 403
        break;
    }

    return ret;
}


404 405 406 407 408 409 410 411 412 413
/**
 * qemuSetupHostdevCgroup:
 * vm: domain object
 * @dev: device to allow
 *
 * For given host device @dev allow access to in Cgroups.
 *
 * Returns: 0 on success,
 *         -1 otherwise.
 */
414
int
415
qemuSetupHostdevCgroup(virDomainObjPtr vm,
416 417 418
                       virDomainHostdevDefPtr dev)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
419 420
    g_autofree char *path = NULL;
    int perms;
421
    int rv;
422

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

426
    if (qemuDomainGetHostdevPath(dev, &path, &perms) < 0)
427
        return -1;
428

429 430 431 432 433 434
    VIR_DEBUG("Cgroup allow %s perms=%d", path, perms);
    rv = virCgroupAllowDevicePath(priv->cgroup, path, perms, false);
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path,
                             virCgroupGetDevicePermsString(perms),
                             rv);
    if (rv < 0)
435
        return -1;
436

437 438 439 440 441 442 443
    if (qemuHostdevNeedsVFIO(dev)) {
        VIR_DEBUG("Cgroup allow %s perms=%d", QEMU_DEV_VFIO, VIR_CGROUP_DEVICE_RW);
        rv = virCgroupAllowDevicePath(priv->cgroup, QEMU_DEV_VFIO,
                                      VIR_CGROUP_DEVICE_RW, false);
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
                                 QEMU_DEV_VFIO, "rw", rv);
        if (rv < 0)
444
            return -1;
445 446
    }

447
    return 0;
448 449
}

450 451 452 453 454 455 456 457 458 459 460 461

/**
 * qemuTeardownHostdevCgroup:
 * @vm: doamin object
 * @dev: device to tear down
 *
 * For given host device @dev deny access to it in CGroups.
 * Note, @dev must not be in @vm's definition.
 *
 * Returns: 0 on success,
 *         -1 otherwise.
 */
462 463
int
qemuTeardownHostdevCgroup(virDomainObjPtr vm,
464
                          virDomainHostdevDefPtr dev)
465 466
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
467
    g_autofree char *path = NULL;
468
    int rv;
469 470 471 472

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

473
    if (qemuDomainGetHostdevPath(dev, &path, NULL) < 0)
474
        return -1;
475

476 477 478 479 480 481
    VIR_DEBUG("Cgroup deny %s", path);
    rv = virCgroupDenyDevicePath(priv->cgroup, path,
                                 VIR_CGROUP_DEVICE_RWM, false);
    virDomainAuditCgroupPath(vm, priv->cgroup,
                             "deny", path, "rwm", rv);
    if (rv < 0)
482
        return -1;
483

484 485 486 487 488 489 490 491
    if (qemuHostdevNeedsVFIO(dev) &&
        !qemuDomainNeedsVFIO(vm->def)) {
        VIR_DEBUG("Cgroup deny " QEMU_DEV_VFIO);
        rv = virCgroupDenyDevicePath(priv->cgroup, QEMU_DEV_VFIO,
                                     VIR_CGROUP_DEVICE_RWM, false);
        virDomainAuditCgroupPath(vm, priv->cgroup, "deny",
                                 QEMU_DEV_VFIO, "rwm", rv);
        if (rv < 0)
492
            return -1;
493 494
    }

495
    return 0;
496 497
}

498

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
int
qemuSetupMemoryDevicesCgroup(virDomainObjPtr vm,
                             virDomainMemoryDefPtr mem)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int rv;

    if (mem->model != VIR_DOMAIN_MEMORY_MODEL_NVDIMM)
        return 0;

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

    VIR_DEBUG("Setting devices Cgroup for NVDIMM device: %s", mem->nvdimmPath);
    rv = virCgroupAllowDevicePath(priv->cgroup, mem->nvdimmPath,
                                  VIR_CGROUP_DEVICE_RW, false);
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
516
                             mem->nvdimmPath, "rw", rv);
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

    return rv;
}


int
qemuTeardownMemoryDevicesCgroup(virDomainObjPtr vm,
                                virDomainMemoryDefPtr mem)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int rv;

    if (mem->model != VIR_DOMAIN_MEMORY_MODEL_NVDIMM)
        return 0;

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

    rv = virCgroupDenyDevicePath(priv->cgroup, mem->nvdimmPath,
                                 VIR_CGROUP_DEVICE_RWM, false);
    virDomainAuditCgroupPath(vm, priv->cgroup,
538
                             "deny", mem->nvdimmPath, "rwm", rv);
539 540 541 542
    return rv;
}


543 544 545 546 547
static int
qemuSetupGraphicsCgroup(virDomainObjPtr vm,
                        virDomainGraphicsDefPtr gfx)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
548
    const char *rendernode = virDomainGraphicsGetRenderNode(gfx);
549 550
    int ret;

551 552
    if (!rendernode ||
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_DEVICES))
553 554 555 556 557
        return 0;

    ret = virCgroupAllowDevicePath(priv->cgroup, rendernode,
                                   VIR_CGROUP_DEVICE_RW, false);
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", rendernode,
558
                             "rw", ret);
559 560 561 562
    return ret;
}


563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
static int
qemuSetupVideoCgroup(virDomainObjPtr vm,
                     virDomainVideoDefPtr def)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virDomainVideoAccelDefPtr accel = def->accel;
    int ret;

    if (!accel)
        return 0;

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

    ret = virCgroupAllowDevicePath(priv->cgroup, accel->rendernode,
                                   VIR_CGROUP_DEVICE_RW, false);
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", accel->rendernode,
                             "rw", ret);
    return ret;
}


586 587 588 589
static int
qemuSetupBlkioCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
590
    size_t i;
591 592 593 594 595 596 597 598 599 600 601 602

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

603 604 605
    if (vm->def->blkio.weight != 0 &&
        virCgroupSetBlkioWeight(priv->cgroup, vm->def->blkio.weight) < 0)
        return -1;
606 607 608

    if (vm->def->blkio.ndevices) {
        for (i = 0; i < vm->def->blkio.ndevices; i++) {
609
            virBlkioDevicePtr dev = &vm->def->blkio.devices[i];
610 611
            if (dev->weight &&
                (virCgroupSetBlkioDeviceWeight(priv->cgroup, dev->path,
612 613 614
                                               dev->weight) < 0 ||
                 virCgroupGetBlkioDeviceWeight(priv->cgroup, dev->path,
                                               &dev->weight) < 0))
615 616 617 618
                return -1;

            if (dev->riops &&
                (virCgroupSetBlkioDeviceReadIops(priv->cgroup, dev->path,
619 620 621
                                                 dev->riops) < 0 ||
                 virCgroupGetBlkioDeviceReadIops(priv->cgroup, dev->path,
                                                 &dev->riops) < 0))
622 623 624 625
                return -1;

            if (dev->wiops &&
                (virCgroupSetBlkioDeviceWriteIops(priv->cgroup, dev->path,
626 627 628
                                                  dev->wiops) < 0 ||
                 virCgroupGetBlkioDeviceWriteIops(priv->cgroup, dev->path,
                                                  &dev->wiops) < 0))
629 630 631 632
                return -1;

            if (dev->rbps &&
                (virCgroupSetBlkioDeviceReadBps(priv->cgroup, dev->path,
633 634 635
                                                dev->rbps) < 0 ||
                 virCgroupGetBlkioDeviceReadBps(priv->cgroup, dev->path,
                                                &dev->rbps) < 0))
636 637 638 639
                return -1;

            if (dev->wbps &&
                (virCgroupSetBlkioDeviceWriteBps(priv->cgroup, dev->path,
640 641 642
                                                 dev->wbps) < 0 ||
                 virCgroupGetBlkioDeviceWriteBps(priv->cgroup, dev->path,
                                                 &dev->wbps) < 0))
643 644 645 646 647 648 649
                return -1;
        }
    }

    return 0;
}

650

651 652 653 654 655
static int
qemuSetupMemoryCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

E
Eric Blake 已提交
656
    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_MEMORY)) {
657 658 659
        if (virMemoryLimitIsSet(vm->def->mem.hard_limit) ||
            virMemoryLimitIsSet(vm->def->mem.soft_limit) ||
            virMemoryLimitIsSet(vm->def->mem.swap_hard_limit)) {
660 661 662
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Memory cgroup is not available on this host"));
            return -1;
O
Osier Yang 已提交
663 664
        } else {
            return 0;
665 666 667
        }
    }

668 669 670
    if (virMemoryLimitIsSet(vm->def->mem.hard_limit))
        if (virCgroupSetMemoryHardLimit(priv->cgroup, vm->def->mem.hard_limit) < 0)
            return -1;
671

672 673 674
    if (virMemoryLimitIsSet(vm->def->mem.soft_limit))
        if (virCgroupSetMemorySoftLimit(priv->cgroup, vm->def->mem.soft_limit) < 0)
            return -1;
675

676 677 678
    if (virMemoryLimitIsSet(vm->def->mem.swap_hard_limit))
        if (virCgroupSetMemSwapHardLimit(priv->cgroup, vm->def->mem.swap_hard_limit) < 0)
            return -1;
679 680 681 682 683

    return 0;
}


684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
static int
qemuSetupFirmwareCgroup(virDomainObjPtr vm)
{
    if (!vm->def->os.loader)
        return 0;

    if (vm->def->os.loader->path &&
        qemuSetupImagePathCgroup(vm, vm->def->os.loader->path,
                                 vm->def->os.loader->readonly == VIR_TRISTATE_BOOL_YES) < 0)
        return -1;

    if (vm->def->os.loader->nvram &&
        qemuSetupImagePathCgroup(vm, vm->def->os.loader->nvram, false) < 0)
        return -1;

    return 0;
}


703 704 705 706 707 708 709
int
qemuSetupRNGCgroup(virDomainObjPtr vm,
                   virDomainRNGDefPtr rng)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int rv;

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

713 714 715 716 717 718 719
    if (rng->backend == VIR_DOMAIN_RNG_BACKEND_RANDOM) {
        VIR_DEBUG("Setting Cgroup ACL for RNG device");
        rv = virCgroupAllowDevicePath(priv->cgroup,
                                      rng->source.file,
                                      VIR_CGROUP_DEVICE_RW, false);
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
                                 rng->source.file,
720
                                 "rw", rv);
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
            return -1;
    }

    return 0;
}


int
qemuTeardownRNGCgroup(virDomainObjPtr vm,
                      virDomainRNGDefPtr rng)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int rv;

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

740 741 742 743 744 745 746
    if (rng->backend == VIR_DOMAIN_RNG_BACKEND_RANDOM) {
        VIR_DEBUG("Tearing down Cgroup ACL for RNG device");
        rv = virCgroupDenyDevicePath(priv->cgroup,
                                     rng->source.file,
                                     VIR_CGROUP_DEVICE_RW, false);
        virDomainAuditCgroupPath(vm, priv->cgroup, "deny",
                                 rng->source.file,
747
                                 "rw", rv);
748 749 750 751 752 753 754 755 756
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
            return -1;
    }

    return 0;
}


757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
int
qemuSetupChardevCgroup(virDomainObjPtr vm,
                       virDomainChrDefPtr dev)
{
    return qemuSetupChrSourceCgroup(vm, dev->source);
}


int
qemuTeardownChardevCgroup(virDomainObjPtr vm,
                          virDomainChrDefPtr dev)
{
    return qemuTeardownChrSourceCgroup(vm, dev->source);
}


773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
static int
qemuSetupSEVCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret;

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

    ret = virCgroupAllowDevicePath(priv->cgroup, "/dev/sev",
                                   VIR_CGROUP_DEVICE_RW, false);
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", "/dev/sev",
                             "rw", ret);
    return ret;
}

789
static int
790
qemuSetupDevicesCgroup(virDomainObjPtr vm)
791 792 793 794
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = NULL;
    const char *const *deviceACL = NULL;
795
    int rv = -1;
796
    int ret = -1;
797
    size_t i;
798 799 800 801

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

802 803 804 805 806
    rv = virCgroupDenyAllDevices(priv->cgroup);
    virDomainAuditCgroup(vm, priv->cgroup, "deny", "all", rv == 0);
    if (rv < 0) {
        if (virLastErrorIsSystemErrno(EPERM)) {
            virResetLastError();
807 808 809 810 811 812 813
            VIR_WARN("Group devices ACL is not accessible, disabling whitelisting");
            return 0;
        }

        goto cleanup;
    }

814 815 816
    if (qemuSetupFirmwareCgroup(vm) < 0)
        goto cleanup;

817
    for (i = 0; i < vm->def->ndisks; i++) {
818
        if (qemuSetupImageChainCgroup(vm, vm->def->disks[i]->src) < 0)
819 820 821
            goto cleanup;
    }

822 823
    rv = virCgroupAllowDevice(priv->cgroup, 'c', DEVICE_PTY_MAJOR, -1,
                              VIR_CGROUP_DEVICE_RW);
824
    virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_PTY_MAJOR,
825 826
                              "pty", "rw", rv == 0);
    if (rv < 0)
827 828
        goto cleanup;

829
    cfg = virQEMUDriverGetConfig(priv->driver);
830 831 832 833 834
    deviceACL = cfg->cgroupDeviceACL ?
                (const char *const *)cfg->cgroupDeviceACL :
                defaultDeviceACL;

    if (vm->def->nsounds &&
835
        ((!vm->def->ngraphics && cfg->nogfxAllowHostAudio) ||
836 837
         (vm->def->graphics &&
          ((vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
838
           cfg->vncAllowHostAudio) ||
839
           (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL))))) {
840 841
        rv = virCgroupAllowDevice(priv->cgroup, 'c', DEVICE_SND_MAJOR, -1,
                                  VIR_CGROUP_DEVICE_RW);
842
        virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_SND_MAJOR,
843 844
                                  "sound", "rw", rv == 0);
        if (rv < 0)
845 846 847
            goto cleanup;
    }

848
    for (i = 0; deviceACL[i] != NULL; i++) {
849
        if (!virFileExists(deviceACL[i])) {
N
Nehal J Wani 已提交
850
            VIR_DEBUG("Ignoring non-existent device %s", deviceACL[i]);
851 852 853
            continue;
        }

854
        rv = virCgroupAllowDevicePath(priv->cgroup, deviceACL[i],
855
                                      VIR_CGROUP_DEVICE_RW, false);
856
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", deviceACL[i], "rw", rv);
857 858
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
859 860 861 862 863
            goto cleanup;
    }

    if (virDomainChrDefForeach(vm->def,
                               true,
864
                               qemuSetupChardevCgroupCB,
865 866 867
                               vm) < 0)
        goto cleanup;

868
    if (vm->def->tpm && qemuSetupTPMCgroup(vm) < 0)
869 870 871
        goto cleanup;

    for (i = 0; i < vm->def->nhostdevs; i++) {
872 873
        /* This may allow /dev/vfio/vfio multiple times, but that
         * is not a problem. Kernel will have only one record. */
874
        if (qemuSetupHostdevCgroup(vm, vm->def->hostdevs[i]) < 0)
875 876 877
            goto cleanup;
    }

878 879 880 881 882
    for (i = 0; i < vm->def->nmems; i++) {
        if (qemuSetupMemoryDevicesCgroup(vm, vm->def->mems[i]) < 0)
            goto cleanup;
    }

883 884 885
    for (i = 0; i < vm->def->ngraphics; i++) {
        if (qemuSetupGraphicsCgroup(vm, vm->def->graphics[i]) < 0)
            goto cleanup;
886 887 888 889 890
    }

    for (i = 0; i < vm->def->nvideos; i++) {
        if (qemuSetupVideoCgroup(vm, vm->def->videos[i]) < 0)
            goto cleanup;
891 892
    }

893 894 895 896 897
    for (i = 0; i < vm->def->ninputs; i++) {
        if (qemuSetupInputCgroup(vm, vm->def->inputs[i]) < 0)
            goto cleanup;
    }

898
    for (i = 0; i < vm->def->nrngs; i++) {
899 900
        if (qemuSetupRNGCgroup(vm, vm->def->rngs[i]) < 0)
            goto cleanup;
901 902
    }

903 904 905
    if (vm->def->sev && qemuSetupSEVCgroup(vm) < 0)
        goto cleanup;

906
    ret = 0;
907
 cleanup:
908 909 910 911 912
    virObjectUnref(cfg);
    return ret;
}


913
static int
914
qemuSetupCpusetCgroup(virDomainObjPtr vm)
915 916 917 918 919 920
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

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

921 922 923
    if (virCgroupSetCpusetMemoryMigrate(priv->cgroup, true) < 0)
        return -1;

924
    return 0;
925 926 927
}


928
static int
929
qemuSetupCpuCgroup(virDomainObjPtr vm)
930 931
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
932 933 934 935
    virObjectEventPtr event = NULL;
    virTypedParameterPtr eventParams = NULL;
    int eventNparams = 0;
    int eventMaxparams = 0;
936 937

    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
938
       if (vm->def->cputune.sharesSpecified) {
939 940 941 942 943 944 945 946
           virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                          _("CPU tuning is not available on this host"));
           return -1;
       } else {
           return 0;
       }
    }

947 948 949 950 951 952 953
    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;
954 955 956 957
        if (vm->def->cputune.shares != val) {
            vm->def->cputune.shares = val;
            if (virTypedParamsAddULLong(&eventParams, &eventNparams,
                                        &eventMaxparams,
958
                                        VIR_DOMAIN_TUNABLE_CPU_CPU_SHARES,
959 960 961 962 963 964
                                        val) < 0)
                return -1;

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

965
        virObjectEventStateQueue(priv->driver->domainEventState, event);
966
    }
967 968 969 970 971

    return 0;
}


972
static int
973
qemuInitCgroup(virDomainObjPtr vm,
974 975
               size_t nnicindexes,
               int *nicindexes)
976
{
977
    int ret = -1;
978
    qemuDomainObjPrivatePtr priv = vm->privateData;
979
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(priv->driver);
980

981
    if (!virQEMUDriverIsPrivileged(priv->driver))
982 983
        goto done;

984 985 986
    if (!virCgroupAvailable())
        goto done;

987
    virCgroupFree(&priv->cgroup);
988

989
    if (!vm->def->resource) {
990 991
        virDomainResourceDefPtr res;

992
        if (VIR_ALLOC(res) < 0)
993
            goto cleanup;
994

995
        res->partition = g_strdup("/machine");
996 997

        vm->def->resource = res;
998 999
    }

1000 1001 1002 1003 1004 1005
    if (vm->def->resource->partition[0] != '/') {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Resource partition '%s' must start with '/'"),
                       vm->def->resource->partition);
        goto cleanup;
    }
1006

1007
    if (virCgroupNewMachine(priv->machineName,
1008 1009 1010 1011 1012
                            "qemu",
                            vm->def->uuid,
                            NULL,
                            vm->pid,
                            false,
1013
                            nnicindexes, nicindexes,
1014 1015
                            vm->def->resource->partition,
                            cfg->cgroupControllers,
1016
                            cfg->maxThreadsPerProc,
1017
                            &priv->cgroup) < 0) {
1018 1019
        if (virCgroupNewIgnoreError())
            goto done;
1020

1021 1022
        goto cleanup;
    }
1023

1024
 done:
1025
    ret = 0;
1026
 cleanup:
1027 1028 1029
    virObjectUnref(cfg);
    return ret;
}
1030

1031 1032 1033
static void
qemuRestoreCgroupState(virDomainObjPtr vm)
{
1034
    char *mem_mask = NULL;
1035
    char *nodeset = NULL;
1036 1037
    int empty = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
1038
    size_t i = 0;
1039
    virBitmapPtr all_nodes;
1040
    virCgroupPtr cgroup_temp = NULL;
1041

1042 1043 1044 1045
    if (!virNumaIsAvailable() ||
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET))
        return;

1046
    if (!(all_nodes = virNumaGetHostMemoryNodeset()))
1047 1048 1049 1050 1051 1052
        goto error;

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

    if ((empty = virCgroupHasEmptyTasks(priv->cgroup,
1053
                                        VIR_CGROUP_CONTROLLER_CPUSET)) <= 0)
1054 1055 1056 1057 1058
        goto error;

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

1059
    for (i = 0; i < virDomainDefGetVcpusMax(vm->def); i++) {
1060
        virDomainVcpuDefPtr vcpu = virDomainDefGetVcpu(vm->def, i);
1061 1062 1063 1064

        if (!vcpu->online)
            continue;

J
John Ferlan 已提交
1065 1066
        if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_VCPU, i,
                               false, &cgroup_temp) < 0 ||
1067 1068 1069 1070 1071
            virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
            virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
            virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
            goto cleanup;

1072
        VIR_FREE(nodeset);
1073
        virCgroupFree(&cgroup_temp);
1074 1075
    }

1076 1077 1078
    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 已提交
1079
                               false, &cgroup_temp) < 0 ||
1080 1081 1082 1083 1084
            virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
            virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
            virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
            goto cleanup;

1085
        VIR_FREE(nodeset);
1086
        virCgroupFree(&cgroup_temp);
1087 1088
    }

J
John Ferlan 已提交
1089 1090
    if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                           false, &cgroup_temp) < 0 ||
1091 1092 1093 1094 1095
        virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
        virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
        virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
        goto cleanup;

1096 1097
 cleanup:
    VIR_FREE(mem_mask);
1098
    VIR_FREE(nodeset);
1099
    virBitmapFree(all_nodes);
1100
    virCgroupFree(&cgroup_temp);
1101 1102 1103 1104 1105 1106 1107
    return;

 error:
    virResetLastError();
    VIR_DEBUG("Couldn't restore cgroups to meaningful state");
    goto cleanup;
}
1108 1109

int
1110
qemuConnectCgroup(virDomainObjPtr vm)
1111 1112
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
1113
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(priv->driver);
1114 1115
    int ret = -1;

1116
    if (!virQEMUDriverIsPrivileged(priv->driver))
1117 1118 1119 1120 1121
        goto done;

    if (!virCgroupAvailable())
        goto done;

1122
    virCgroupFree(&priv->cgroup);
1123

1124 1125 1126
    if (virCgroupNewDetectMachine(vm->def->name,
                                  "qemu",
                                  vm->pid,
1127
                                  cfg->cgroupControllers,
1128
                                  priv->machineName,
1129
                                  &priv->cgroup) < 0)
1130
        goto cleanup;
1131

1132 1133
    qemuRestoreCgroupState(vm);

1134
 done:
1135
    ret = 0;
1136
 cleanup:
1137
    virObjectUnref(cfg);
1138
    return ret;
1139 1140
}

1141
int
1142
qemuSetupCgroup(virDomainObjPtr vm,
1143 1144
                size_t nnicindexes,
                int *nicindexes)
1145
{
1146
    qemuDomainObjPrivatePtr priv = vm->privateData;
1147

1148 1149 1150 1151 1152 1153
    if (!vm->pid) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot setup cgroups until process is started"));
        return -1;
    }

1154
    if (qemuInitCgroup(vm, nnicindexes, nicindexes) < 0)
1155
        return -1;
1156

1157
    if (!priv->cgroup)
1158
        return 0;
1159

1160
    if (qemuSetupDevicesCgroup(vm) < 0)
1161
        return -1;
1162

1163
    if (qemuSetupBlkioCgroup(vm) < 0)
1164
        return -1;
1165

1166
    if (qemuSetupMemoryCgroup(vm) < 0)
1167
        return -1;
1168

1169
    if (qemuSetupCpuCgroup(vm) < 0)
1170
        return -1;
1171

1172
    if (qemuSetupCpusetCgroup(vm) < 0)
1173
        return -1;
1174

1175
    return 0;
1176 1177
}

1178 1179 1180 1181
int
qemuSetupCgroupVcpuBW(virCgroupPtr cgroup,
                      unsigned long long period,
                      long long quota)
1182 1183 1184 1185 1186 1187 1188 1189
{
    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 */
1190
        if (virCgroupGetCpuCfsPeriod(cgroup, &old_period) < 0)
1191 1192
            return -1;

1193
        if (virCgroupSetCpuCfsPeriod(cgroup, period) < 0)
1194 1195 1196
            return -1;
    }

1197 1198 1199
    if (quota &&
        virCgroupSetCpuCfsQuota(cgroup, quota) < 0)
        goto error;
1200 1201 1202

    return 0;

1203
 error:
1204
    if (period) {
1205 1206 1207
        virErrorPtr saved;

        virErrorPreserveLast(&saved);
1208
        ignore_value(virCgroupSetCpuCfsPeriod(cgroup, old_period));
1209
        virErrorRestore(&saved);
1210 1211 1212 1213 1214
    }

    return -1;
}

1215

1216
int
1217 1218
qemuSetupCgroupCpusetCpus(virCgroupPtr cgroup,
                          virBitmapPtr cpumask)
1219
{
1220
    int ret = -1;
1221 1222
    char *new_cpus = NULL;

1223
    if (!(new_cpus = virBitmapFormat(cpumask)))
1224 1225
        goto cleanup;

1226
    if (virCgroupSetCpusetCpus(cgroup, new_cpus) < 0)
1227 1228
        goto cleanup;

1229
    ret = 0;
1230
 cleanup:
1231
    VIR_FREE(new_cpus);
1232
    return ret;
1233 1234
}

1235

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
int
qemuSetupCgroupForExtDevices(virDomainObjPtr vm,
                             virQEMUDriverPtr driver)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virCgroupPtr cgroup_temp = NULL;
    int ret = -1;

    if (!qemuExtDevicesHasDevice(vm->def) ||
        priv->cgroup == NULL)
        return 0; /* Not supported, so claim success */

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

    if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                           false, &cgroup_temp) < 0)
        goto cleanup;

    ret = qemuExtDevicesSetupCgroup(driver, vm->def, cgroup_temp);

 cleanup:
1264
    virCgroupFree(&cgroup_temp);
1265 1266 1267 1268 1269

    return ret;
}


1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
int
qemuSetupGlobalCpuCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    unsigned long long period = vm->def->cputune.global_period;
    long long quota = vm->def->cputune.global_quota;
    char *mem_mask = NULL;
    virDomainNumatuneMemMode mem_mode;

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

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


    if (virDomainNumatuneGetMode(vm->def->numa, -1, &mem_mode) == 0 &&
        mem_mode == VIR_DOMAIN_NUMATUNE_MEM_STRICT &&
        virDomainNumatuneMaybeFormatNodeset(vm->def->numa,
                                            priv->autoNodeset,
                                            &mem_mask, -1) < 0)
        goto cleanup;

    if (period || quota) {
        if (qemuSetupCgroupVcpuBW(priv->cgroup, period, quota) < 0)
            goto cleanup;
    }

    VIR_FREE(mem_mask);

    return 0;

 cleanup:
    VIR_FREE(mem_mask);

    return -1;
}


1319
int
1320
qemuRemoveCgroup(virDomainObjPtr vm)
1321
{
1322
    qemuDomainObjPrivatePtr priv = vm->privateData;
1323

1324
    if (priv->cgroup == NULL)
1325 1326
        return 0; /* Not supported, so claim success */

1327
    if (virCgroupTerminateMachine(priv->machineName) < 0) {
1328 1329 1330 1331
        if (!virCgroupNewIgnoreError())
            VIR_DEBUG("Failed to terminate cgroup for %s", vm->def->name);
    }

1332
    return virCgroupRemove(priv->cgroup);
1333
}
1334 1335 1336 1337 1338 1339 1340 1341


static void
qemuCgroupEmulatorAllNodesDataFree(qemuCgroupEmulatorAllNodesDataPtr data)
{
    if (!data)
        return;

1342
    virCgroupFree(&data->emulatorCgroup);
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    VIR_FREE(data->emulatorMemMask);
    VIR_FREE(data);
}


/**
 * qemuCgroupEmulatorAllNodesAllow:
 * @cgroup: domain cgroup pointer
 * @retData: filled with structure used to roll back the operation
 *
 * Allows all NUMA nodes for the qemu emulator thread temporarily. This is
 * necessary when hotplugging cpus since it requires memory allocated in the
 * DMA region. Afterwards the operation can be reverted by
1356
 * qemuCgroupEmulatorAllNodesRestore.
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
 *
 * Returns 0 on success -1 on error
 */
int
qemuCgroupEmulatorAllNodesAllow(virCgroupPtr cgroup,
                                qemuCgroupEmulatorAllNodesDataPtr *retData)
{
    qemuCgroupEmulatorAllNodesDataPtr data = NULL;
    char *all_nodes_str = NULL;
    virBitmapPtr all_nodes = NULL;
    int ret = -1;

    if (!virNumaIsAvailable() ||
        !virCgroupHasController(cgroup, VIR_CGROUP_CONTROLLER_CPUSET))
        return 0;

1373
    if (!(all_nodes = virNumaGetHostMemoryNodeset()))
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
        goto cleanup;

    if (!(all_nodes_str = virBitmapFormat(all_nodes)))
        goto cleanup;

    if (VIR_ALLOC(data) < 0)
        goto cleanup;

    if (virCgroupNewThread(cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                           false, &data->emulatorCgroup) < 0)
        goto cleanup;

    if (virCgroupGetCpusetMems(data->emulatorCgroup, &data->emulatorMemMask) < 0 ||
        virCgroupSetCpusetMems(data->emulatorCgroup, all_nodes_str) < 0)
        goto cleanup;

1390
    *retData = g_steal_pointer(&data);
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    ret = 0;

 cleanup:
    VIR_FREE(all_nodes_str);
    virBitmapFree(all_nodes);
    qemuCgroupEmulatorAllNodesDataFree(data);

    return ret;
}


/**
1403
 * qemuCgroupEmulatorAllNodesRestore:
1404 1405 1406 1407 1408 1409
 * @data: data structure created by qemuCgroupEmulatorAllNodesAllow
 *
 * Rolls back the setting done by qemuCgroupEmulatorAllNodesAllow and frees the
 * associated data.
 */
void
1410
qemuCgroupEmulatorAllNodesRestore(qemuCgroupEmulatorAllNodesDataPtr data)
1411 1412 1413 1414 1415 1416
{
    virErrorPtr err;

    if (!data)
        return;

1417
    virErrorPreserveLast(&err);
1418
    virCgroupSetCpusetMems(data->emulatorCgroup, data->emulatorMemMask);
1419
    virErrorRestore(&err);
1420 1421 1422

    qemuCgroupEmulatorAllNodesDataFree(data);
}