qemu_cgroup.c 34.6 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
const char *const defaultDeviceACL[] = {
46 47 48
    "/dev/null", "/dev/full", "/dev/zero",
    "/dev/random", "/dev/urandom",
    "/dev/ptmx", "/dev/kvm", "/dev/kqemu",
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
    int ret;
64

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

68
    if (!readonly)
69
        perms |= VIR_CGROUP_DEVICE_WRITE;
70

71
    VIR_DEBUG("Allow path %s, perms: %s",
72
              path, virCgroupGetDevicePermsString(perms));
73

74
    ret = virCgroupAllowDevicePath(priv->cgroup, path, perms, true);
75

76
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path,
77 78
                             virCgroupGetDevicePermsString(perms),
                             ret == 0);
79 80

    return ret;
81 82 83
}


84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
static int
qemuSetupImageCgroupInternal(virDomainObjPtr vm,
                             virStorageSourcePtr src,
                             bool forceReadonly)
{
    if (!src->path || !virStorageSourceIsLocalStorage(src)) {
        VIR_DEBUG("Not updating cgroups for disk path '%s', type: %s",
                  NULLSTR(src->path), virStorageTypeToString(src->type));
        return 0;
    }

    return qemuSetupImagePathCgroup(vm, src->path, src->readonly || forceReadonly);
}


99
int
100 101
qemuSetupImageCgroup(virDomainObjPtr vm,
                     virStorageSourcePtr src)
102
{
103
    return qemuSetupImageCgroupInternal(vm, src, false);
104 105 106 107 108 109 110
}


int
qemuTeardownImageCgroup(virDomainObjPtr vm,
                        virStorageSourcePtr src)
{
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    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;
135 136 137
}


138 139 140
int
qemuSetupDiskCgroup(virDomainObjPtr vm,
                    virDomainDiskDefPtr disk)
141
{
142
    virStorageSourcePtr next;
143
    bool forceReadonly = false;
144

145
    for (next = disk->src; next; next = next->backingStore) {
146
        if (qemuSetupImageCgroupInternal(vm, next, forceReadonly) < 0)
147
            return -1;
148 149 150

        /* setup only the top level image for read-write */
        forceReadonly = true;
151
    }
152 153

    return 0;
154 155 156
}


157 158 159
int
qemuTeardownDiskCgroup(virDomainObjPtr vm,
                       virDomainDiskDefPtr disk)
160
{
161
    virStorageSourcePtr next;
162

163
    for (next = disk->src; next; next = next->backingStore) {
164
        if (qemuTeardownImageCgroup(vm, next) < 0)
165 166
            return -1;
    }
167

168
    return 0;
169 170
}

171

172
static int
173
qemuSetupChrSourceCgroup(virDomainObjPtr vm,
174
                         virDomainChrSourceDefPtr source)
175
{
176
    qemuDomainObjPrivatePtr priv = vm->privateData;
177
    int ret;
178

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

182
    if (source->type != VIR_DOMAIN_CHR_TYPE_DEV)
183 184
        return 0;

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

187
    ret = virCgroupAllowDevicePath(priv->cgroup, source->data.file.path,
188
                                   VIR_CGROUP_DEVICE_RW, false);
189
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
190
                             source->data.file.path, "rw", ret == 0);
191

192
    return ret;
193 194
}

195 196 197 198 199 200 201 202

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

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

206 207 208 209 210 211 212 213 214 215 216 217 218 219
    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",
                             source->data.file.path, "rw", ret == 0);

    return ret;
}


220
static int
221 222 223
qemuSetupChardevCgroupCB(virDomainDefPtr def ATTRIBUTE_UNUSED,
                         virDomainChrDefPtr dev,
                         void *opaque)
224
{
225 226
    virDomainObjPtr vm = opaque;

227
    return qemuSetupChrSourceCgroup(vm, dev->source);
228 229 230 231
}


static int
232
qemuSetupTPMCgroup(virDomainObjPtr vm)
233
{
234
    int ret = 0;
235
    virDomainTPMDefPtr dev = vm->def->tpm;
236 237 238

    switch (dev->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
239
        ret = qemuSetupChrSourceCgroup(vm, &dev->data.passthrough.source);
240 241 242 243 244
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

245
    return ret;
246 247
}

248

249 250 251 252 253 254 255
static int
qemuSetupInputCgroup(virDomainObjPtr vm,
                     virDomainInputDefPtr dev)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = 0;

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

259 260 261 262
    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,
263
                                       VIR_CGROUP_DEVICE_RW, false);
264 265 266 267 268 269 270 271
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", dev->source.evdev, "rw", ret == 0);
        break;
    }

    return ret;
}


272
int
273
qemuSetupHostdevCgroup(virDomainObjPtr vm,
274 275 276
                       virDomainHostdevDefPtr dev)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
277 278 279 280
    char **path = NULL;
    int *perms = NULL;
    size_t i, npaths = 0;
    int rv, ret = -1;
281

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

285
    if (qemuDomainGetHostdevPath(NULL, dev, false, &npaths, &path, &perms) < 0)
286
        goto cleanup;
287

288 289 290 291 292 293 294 295
    for (i = 0; i < npaths; i++) {
        VIR_DEBUG("Cgroup allow %s perms=%d", path[i], perms[i]);
        rv = virCgroupAllowDevicePath(priv->cgroup, path[i], perms[i], false);
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path[i],
                                 virCgroupGetDevicePermsString(perms[i]),
                                 ret == 0);
        if (rv < 0)
            goto cleanup;
296 297
    }

298
    ret = 0;
299

300
 cleanup:
301 302
    for (i = 0; i < npaths; i++)
        VIR_FREE(path[i]);
303
    VIR_FREE(path);
304
    VIR_FREE(perms);
305 306 307 308 309 310 311 312
    return ret;
}

int
qemuTeardownHostdevCgroup(virDomainObjPtr vm,
                       virDomainHostdevDefPtr dev)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
313 314 315
    char **path = NULL;
    size_t i, npaths = 0;
    int rv, ret = -1;
316 317 318 319 320 321 322 323 324

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

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    if (dev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
        dev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
        dev->source.subsys.u.pci.backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO &&
        qemuDomainGetHostdevPath(vm->def, dev, true,
                                 &npaths, &path, NULL) < 0)
        goto cleanup;

    for (i = 0; i < npaths; i++) {
        VIR_DEBUG("Cgroup deny %s", path[i]);
        rv = virCgroupDenyDevicePath(priv->cgroup, path[i],
                                     VIR_CGROUP_DEVICE_RWM, false);
        virDomainAuditCgroupPath(vm, priv->cgroup,
                                 "deny", path[i], "rwm", rv == 0);
        if (rv < 0)
            goto cleanup;
340 341 342
    }

    ret = 0;
343
 cleanup:
344 345
    for (i = 0; i < npaths; i++)
        VIR_FREE(path[i]);
346 347 348 349
    VIR_FREE(path);
    return ret;
}

350

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
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",
                             mem->nvdimmPath, "rw", rv == 0);

    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,
                             "deny", mem->nvdimmPath, "rwm", rv == 0);
    return rv;
}


395 396 397 398 399 400 401 402
static int
qemuSetupGraphicsCgroup(virDomainObjPtr vm,
                        virDomainGraphicsDefPtr gfx)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    const char *rendernode = gfx->data.spice.rendernode;
    int ret;

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

406 407 408 409 410 411 412 413 414 415 416 417 418
    if (gfx->type != VIR_DOMAIN_GRAPHICS_TYPE_SPICE ||
        gfx->data.spice.gl != VIR_TRISTATE_BOOL_YES ||
        !rendernode)
        return 0;

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


419 420 421 422
static int
qemuSetupBlkioCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
423
    size_t i;
424 425 426 427 428 429 430 431 432 433 434 435

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

436 437 438
    if (vm->def->blkio.weight != 0 &&
        virCgroupSetBlkioWeight(priv->cgroup, vm->def->blkio.weight) < 0)
        return -1;
439 440 441

    if (vm->def->blkio.ndevices) {
        for (i = 0; i < vm->def->blkio.ndevices; i++) {
442
            virBlkioDevicePtr dev = &vm->def->blkio.devices[i];
443 444
            if (dev->weight &&
                (virCgroupSetBlkioDeviceWeight(priv->cgroup, dev->path,
445 446 447
                                               dev->weight) < 0 ||
                 virCgroupGetBlkioDeviceWeight(priv->cgroup, dev->path,
                                               &dev->weight) < 0))
448 449 450 451
                return -1;

            if (dev->riops &&
                (virCgroupSetBlkioDeviceReadIops(priv->cgroup, dev->path,
452 453 454
                                                 dev->riops) < 0 ||
                 virCgroupGetBlkioDeviceReadIops(priv->cgroup, dev->path,
                                                 &dev->riops) < 0))
455 456 457 458
                return -1;

            if (dev->wiops &&
                (virCgroupSetBlkioDeviceWriteIops(priv->cgroup, dev->path,
459 460 461
                                                  dev->wiops) < 0 ||
                 virCgroupGetBlkioDeviceWriteIops(priv->cgroup, dev->path,
                                                  &dev->wiops) < 0))
462 463 464 465
                return -1;

            if (dev->rbps &&
                (virCgroupSetBlkioDeviceReadBps(priv->cgroup, dev->path,
466 467 468
                                                dev->rbps) < 0 ||
                 virCgroupGetBlkioDeviceReadBps(priv->cgroup, dev->path,
                                                &dev->rbps) < 0))
469 470 471 472
                return -1;

            if (dev->wbps &&
                (virCgroupSetBlkioDeviceWriteBps(priv->cgroup, dev->path,
473 474 475
                                                 dev->wbps) < 0 ||
                 virCgroupGetBlkioDeviceWriteBps(priv->cgroup, dev->path,
                                                 &dev->wbps) < 0))
476 477 478 479 480 481 482
                return -1;
        }
    }

    return 0;
}

483

484 485 486 487 488
static int
qemuSetupMemoryCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

E
Eric Blake 已提交
489
    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_MEMORY)) {
490 491 492
        if (virMemoryLimitIsSet(vm->def->mem.hard_limit) ||
            virMemoryLimitIsSet(vm->def->mem.soft_limit) ||
            virMemoryLimitIsSet(vm->def->mem.swap_hard_limit)) {
493 494 495
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Memory cgroup is not available on this host"));
            return -1;
O
Osier Yang 已提交
496 497
        } else {
            return 0;
498 499 500
        }
    }

501 502 503
    if (virMemoryLimitIsSet(vm->def->mem.hard_limit))
        if (virCgroupSetMemoryHardLimit(priv->cgroup, vm->def->mem.hard_limit) < 0)
            return -1;
504

505 506 507
    if (virMemoryLimitIsSet(vm->def->mem.soft_limit))
        if (virCgroupSetMemorySoftLimit(priv->cgroup, vm->def->mem.soft_limit) < 0)
            return -1;
508

509 510 511
    if (virMemoryLimitIsSet(vm->def->mem.swap_hard_limit))
        if (virCgroupSetMemSwapHardLimit(priv->cgroup, vm->def->mem.swap_hard_limit) < 0)
            return -1;
512 513 514 515 516

    return 0;
}


517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
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;
}


536 537 538 539 540 541 542
int
qemuSetupRNGCgroup(virDomainObjPtr vm,
                   virDomainRNGDefPtr rng)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int rv;

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

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    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,
                                 "rw", rv == 0);
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
            return -1;
    }

    return 0;
}


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

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

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    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,
                                 "rw", rv == 0);
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
            return -1;
    }

    return 0;
}


590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
int
qemuSetupChardevCgroup(virDomainObjPtr vm,
                       virDomainChrDefPtr dev)
{
    return qemuSetupChrSourceCgroup(vm, dev->source);
}


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


606 607 608 609 610 611 612
static int
qemuSetupDevicesCgroup(virQEMUDriverPtr driver,
                       virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = NULL;
    const char *const *deviceACL = NULL;
613
    int rv = -1;
614
    int ret = -1;
615
    size_t i;
616 617 618 619

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

620 621 622 623 624
    rv = virCgroupDenyAllDevices(priv->cgroup);
    virDomainAuditCgroup(vm, priv->cgroup, "deny", "all", rv == 0);
    if (rv < 0) {
        if (virLastErrorIsSystemErrno(EPERM)) {
            virResetLastError();
625 626 627 628 629 630 631
            VIR_WARN("Group devices ACL is not accessible, disabling whitelisting");
            return 0;
        }

        goto cleanup;
    }

632 633 634
    if (qemuSetupFirmwareCgroup(vm) < 0)
        goto cleanup;

635
    for (i = 0; i < vm->def->ndisks; i++) {
636 637 638 639
        if (qemuSetupDiskCgroup(vm, vm->def->disks[i]) < 0)
            goto cleanup;
    }

640 641
    rv = virCgroupAllowDevice(priv->cgroup, 'c', DEVICE_PTY_MAJOR, -1,
                              VIR_CGROUP_DEVICE_RW);
642
    virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_PTY_MAJOR,
643 644
                              "pty", "rw", rv == 0);
    if (rv < 0)
645 646 647 648 649 650 651 652
        goto cleanup;

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

    if (vm->def->nsounds &&
653
        ((!vm->def->ngraphics && cfg->nogfxAllowHostAudio) ||
654 655
         (vm->def->graphics &&
          ((vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
656
           cfg->vncAllowHostAudio) ||
657
           (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL))))) {
658 659
        rv = virCgroupAllowDevice(priv->cgroup, 'c', DEVICE_SND_MAJOR, -1,
                                  VIR_CGROUP_DEVICE_RW);
660
        virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_SND_MAJOR,
661 662
                                  "sound", "rw", rv == 0);
        if (rv < 0)
663 664 665
            goto cleanup;
    }

666
    for (i = 0; deviceACL[i] != NULL; i++) {
667
        if (!virFileExists(deviceACL[i])) {
N
Nehal J Wani 已提交
668
            VIR_DEBUG("Ignoring non-existent device %s", deviceACL[i]);
669 670 671
            continue;
        }

672
        rv = virCgroupAllowDevicePath(priv->cgroup, deviceACL[i],
673
                                      VIR_CGROUP_DEVICE_RW, false);
674 675 676
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", deviceACL[i], "rw", rv == 0);
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
677 678 679 680 681
            goto cleanup;
    }

    if (virDomainChrDefForeach(vm->def,
                               true,
682
                               qemuSetupChardevCgroupCB,
683 684 685
                               vm) < 0)
        goto cleanup;

686
    if (vm->def->tpm && qemuSetupTPMCgroup(vm) < 0)
687 688 689
        goto cleanup;

    for (i = 0; i < vm->def->nhostdevs; i++) {
690
        if (qemuSetupHostdevCgroup(vm, vm->def->hostdevs[i]) < 0)
691 692 693
            goto cleanup;
    }

694 695 696 697 698
    for (i = 0; i < vm->def->nmems; i++) {
        if (qemuSetupMemoryDevicesCgroup(vm, vm->def->mems[i]) < 0)
            goto cleanup;
    }

699 700 701 702 703
    for (i = 0; i < vm->def->ngraphics; i++) {
        if (qemuSetupGraphicsCgroup(vm, vm->def->graphics[i]) < 0)
            goto cleanup;
    }

704 705 706 707 708
    for (i = 0; i < vm->def->ninputs; i++) {
        if (qemuSetupInputCgroup(vm, vm->def->inputs[i]) < 0)
            goto cleanup;
    }

709
    for (i = 0; i < vm->def->nrngs; i++) {
710 711
        if (qemuSetupRNGCgroup(vm, vm->def->rngs[i]) < 0)
            goto cleanup;
712 713
    }

714
    ret = 0;
715
 cleanup:
716 717 718 719 720
    virObjectUnref(cfg);
    return ret;
}


721
int
722
qemuSetupCpusetMems(virDomainObjPtr vm)
723
{
724
    virCgroupPtr cgroup_temp = NULL;
725
    qemuDomainObjPrivatePtr priv = vm->privateData;
726
    virDomainNumatuneMemMode mode;
727
    char *mem_mask = NULL;
728 729 730 731 732
    int ret = -1;

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

733 734
    if (virDomainNumatuneGetMode(vm->def->numa, -1, &mode) < 0 ||
        mode != VIR_DOMAIN_NUMATUNE_MEM_STRICT)
735 736
        return 0;

737
    if (virDomainNumatuneMaybeFormatNodeset(vm->def->numa,
738
                                            priv->autoNodeset,
739
                                            &mem_mask, -1) < 0)
740
        goto cleanup;
741

742
    if (mem_mask)
J
John Ferlan 已提交
743 744
        if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                               false, &cgroup_temp) < 0 ||
745
            virCgroupSetCpusetMems(cgroup_temp, mem_mask) < 0)
746
            goto cleanup;
747

748 749 750
    ret = 0;
 cleanup:
    VIR_FREE(mem_mask);
751
    virCgroupFree(&cgroup_temp);
752 753 754 755 756
    return ret;
}


static int
757
qemuSetupCpusetCgroup(virDomainObjPtr vm)
758 759 760 761 762 763
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

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

764 765 766
    if (virCgroupSetCpusetMemoryMigrate(priv->cgroup, true) < 0)
        return -1;

767
    return 0;
768 769 770
}


771
static int
772 773
qemuSetupCpuCgroup(virQEMUDriverPtr driver,
                   virDomainObjPtr vm)
774 775
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
776 777 778 779
    virObjectEventPtr event = NULL;
    virTypedParameterPtr eventParams = NULL;
    int eventNparams = 0;
    int eventMaxparams = 0;
780 781

    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
782
       if (vm->def->cputune.sharesSpecified) {
783 784 785 786 787 788 789 790
           virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                          _("CPU tuning is not available on this host"));
           return -1;
       } else {
           return 0;
       }
    }

791 792 793 794 795 796 797
    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;
798 799 800 801
        if (vm->def->cputune.shares != val) {
            vm->def->cputune.shares = val;
            if (virTypedParamsAddULLong(&eventParams, &eventNparams,
                                        &eventMaxparams,
802
                                        VIR_DOMAIN_TUNABLE_CPU_CPU_SHARES,
803 804 805 806 807 808
                                        val) < 0)
                return -1;

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

809
        qemuDomainEventQueue(driver, event);
810
    }
811 812 813 814 815

    return 0;
}


816
static int
817
qemuInitCgroup(virQEMUDriverPtr driver,
818 819 820
               virDomainObjPtr vm,
               size_t nnicindexes,
               int *nicindexes)
821
{
822
    int ret = -1;
823 824 825
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

826
    if (!virQEMUDriverIsPrivileged(driver))
827 828
        goto done;

829 830 831
    if (!virCgroupAvailable())
        goto done;

832 833
    virCgroupFree(&priv->cgroup);

834
    if (!vm->def->resource) {
835 836
        virDomainResourceDefPtr res;

837
        if (VIR_ALLOC(res) < 0)
838
            goto cleanup;
839

840
        if (VIR_STRDUP(res->partition, "/machine") < 0) {
841 842 843 844 845
            VIR_FREE(res);
            goto cleanup;
        }

        vm->def->resource = res;
846 847
    }

848 849 850 851 852 853
    if (vm->def->resource->partition[0] != '/') {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Resource partition '%s' must start with '/'"),
                       vm->def->resource->partition);
        goto cleanup;
    }
854

855
    if (virCgroupNewMachine(priv->machineName,
856 857 858 859 860
                            "qemu",
                            vm->def->uuid,
                            NULL,
                            vm->pid,
                            false,
861
                            nnicindexes, nicindexes,
862 863 864
                            vm->def->resource->partition,
                            cfg->cgroupControllers,
                            &priv->cgroup) < 0) {
865 866
        if (virCgroupNewIgnoreError())
            goto done;
867

868 869
        goto cleanup;
    }
870

871
 done:
872
    ret = 0;
873
 cleanup:
874 875 876
    virObjectUnref(cfg);
    return ret;
}
877

878 879 880
static void
qemuRestoreCgroupState(virDomainObjPtr vm)
{
881
    char *mem_mask = NULL;
882
    char *nodeset = NULL;
883 884
    int empty = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
885
    size_t i = 0;
886
    virBitmapPtr all_nodes;
887
    virCgroupPtr cgroup_temp = NULL;
888

889 890 891 892
    if (!virNumaIsAvailable() ||
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET))
        return;

893
    if (!(all_nodes = virNumaGetHostMemoryNodeset()))
894 895 896 897 898 899
        goto error;

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

    if ((empty = virCgroupHasEmptyTasks(priv->cgroup,
900
                                        VIR_CGROUP_CONTROLLER_CPUSET)) <= 0)
901 902 903 904 905
        goto error;

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

906
    for (i = 0; i < virDomainDefGetVcpusMax(vm->def); i++) {
907
        virDomainVcpuDefPtr vcpu = virDomainDefGetVcpu(vm->def, i);
908 909 910 911

        if (!vcpu->online)
            continue;

J
John Ferlan 已提交
912 913
        if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_VCPU, i,
                               false, &cgroup_temp) < 0 ||
914 915 916 917 918
            virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
            virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
            virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
            goto cleanup;

919
        VIR_FREE(nodeset);
920 921 922
        virCgroupFree(&cgroup_temp);
    }

923 924 925
    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 已提交
926
                               false, &cgroup_temp) < 0 ||
927 928 929 930 931
            virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
            virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
            virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
            goto cleanup;

932
        VIR_FREE(nodeset);
933 934 935
        virCgroupFree(&cgroup_temp);
    }

J
John Ferlan 已提交
936 937
    if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                           false, &cgroup_temp) < 0 ||
938 939 940 941 942
        virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
        virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
        virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
        goto cleanup;

943 944
 cleanup:
    VIR_FREE(mem_mask);
945
    VIR_FREE(nodeset);
946
    virBitmapFree(all_nodes);
947
    virCgroupFree(&cgroup_temp);
948 949 950 951 952 953 954
    return;

 error:
    virResetLastError();
    VIR_DEBUG("Couldn't restore cgroups to meaningful state");
    goto cleanup;
}
955 956 957 958 959 960 961 962 963

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

964
    if (!virQEMUDriverIsPrivileged(driver))
965 966 967 968 969
        goto done;

    if (!virCgroupAvailable())
        goto done;

970 971 972 973
    priv->machineName = qemuDomainGetMachineName(vm);
    if (!priv->machineName)
            goto cleanup;

974 975
    virCgroupFree(&priv->cgroup);

976 977 978
    if (virCgroupNewDetectMachine(vm->def->name,
                                  "qemu",
                                  vm->pid,
979
                                  cfg->cgroupControllers,
980
                                  priv->machineName,
981
                                  &priv->cgroup) < 0)
982
        goto cleanup;
983

984 985
    qemuRestoreCgroupState(vm);

986
 done:
987
    ret = 0;
988
 cleanup:
989
    virObjectUnref(cfg);
990
    return ret;
991 992
}

993 994
int
qemuSetupCgroup(virQEMUDriverPtr driver,
995 996 997
                virDomainObjPtr vm,
                size_t nnicindexes,
                int *nicindexes)
998
{
999
    qemuDomainObjPrivatePtr priv = vm->privateData;
1000
    int ret = -1;
1001

1002 1003 1004 1005 1006 1007
    if (!vm->pid) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot setup cgroups until process is started"));
        return -1;
    }

1008
    if (qemuInitCgroup(driver, vm, nnicindexes, nicindexes) < 0)
1009
        return -1;
1010

1011
    if (!priv->cgroup)
1012
        return 0;
1013

1014 1015
    if (qemuSetupDevicesCgroup(driver, vm) < 0)
        goto cleanup;
1016

1017 1018
    if (qemuSetupBlkioCgroup(vm) < 0)
        goto cleanup;
1019

1020 1021
    if (qemuSetupMemoryCgroup(vm) < 0)
        goto cleanup;
1022

1023
    if (qemuSetupCpuCgroup(driver, vm) < 0)
1024
        goto cleanup;
1025

1026
    if (qemuSetupCpusetCgroup(vm) < 0)
1027
        goto cleanup;
1028

1029
    ret = 0;
1030
 cleanup:
1031
    return ret;
1032 1033
}

1034 1035 1036 1037
int
qemuSetupCgroupVcpuBW(virCgroupPtr cgroup,
                      unsigned long long period,
                      long long quota)
1038 1039 1040 1041 1042 1043 1044 1045
{
    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 */
1046
        if (virCgroupGetCpuCfsPeriod(cgroup, &old_period) < 0)
1047 1048
            return -1;

1049
        if (virCgroupSetCpuCfsPeriod(cgroup, period) < 0)
1050 1051 1052
            return -1;
    }

1053 1054 1055
    if (quota &&
        virCgroupSetCpuCfsQuota(cgroup, quota) < 0)
        goto error;
1056 1057 1058

    return 0;

1059
 error:
1060
    if (period) {
1061 1062 1063 1064 1065 1066
        virErrorPtr saved = virSaveLastError();
        ignore_value(virCgroupSetCpuCfsPeriod(cgroup, old_period));
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
1067 1068 1069 1070 1071
    }

    return -1;
}

1072

1073
int
1074 1075
qemuSetupCgroupCpusetCpus(virCgroupPtr cgroup,
                          virBitmapPtr cpumask)
1076
{
1077
    int ret = -1;
1078 1079
    char *new_cpus = NULL;

1080
    if (!(new_cpus = virBitmapFormat(cpumask)))
1081 1082
        goto cleanup;

1083
    if (virCgroupSetCpusetCpus(cgroup, new_cpus) < 0)
1084 1085
        goto cleanup;

1086
    ret = 0;
1087
 cleanup:
1088
    VIR_FREE(new_cpus);
1089
    return ret;
1090 1091
}

1092

1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
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;
}


1142
int
1143
qemuRemoveCgroup(virDomainObjPtr vm)
1144
{
1145
    qemuDomainObjPrivatePtr priv = vm->privateData;
1146

1147
    if (priv->cgroup == NULL)
1148 1149
        return 0; /* Not supported, so claim success */

1150
    if (virCgroupTerminateMachine(priv->machineName) < 0) {
1151 1152 1153 1154
        if (!virCgroupNewIgnoreError())
            VIR_DEBUG("Failed to terminate cgroup for %s", vm->def->name);
    }

1155
    return virCgroupRemove(priv->cgroup);
1156
}
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178


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

    virCgroupFree(&data->emulatorCgroup);
    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
1179
 * qemuCgroupEmulatorAllNodesRestore.
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
 *
 * 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;

1196
    if (!(all_nodes = virNumaGetHostMemoryNodeset()))
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
        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;

    VIR_STEAL_PTR(*retData, data);
    ret = 0;

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

    return ret;
}


/**
1226
 * qemuCgroupEmulatorAllNodesRestore:
1227 1228 1229 1230 1231 1232
 * @data: data structure created by qemuCgroupEmulatorAllNodesAllow
 *
 * Rolls back the setting done by qemuCgroupEmulatorAllNodesAllow and frees the
 * associated data.
 */
void
1233
qemuCgroupEmulatorAllNodesRestore(qemuCgroupEmulatorAllNodesDataPtr data)
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
{
    virErrorPtr err;

    if (!data)
        return;

    err = virSaveLastError();
    virCgroupSetCpusetMems(data->emulatorCgroup, data->emulatorMemMask);
    virSetError(err);
    virFreeError(err);

    qemuCgroupEmulatorAllNodesDataFree(data);
}