qemu_cgroup.c 32.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 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 56 57 58 59
static int
qemuSetImageCgroupInternal(virDomainObjPtr vm,
                           virStorageSourcePtr src,
                           bool deny,
                           bool forceReadonly)
60
{
61
    qemuDomainObjPrivatePtr priv = vm->privateData;
62
    int perms = VIR_CGROUP_DEVICE_READ;
63
    int ret;
64

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    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;
    }

    if (deny) {
        perms |= VIR_CGROUP_DEVICE_WRITE | VIR_CGROUP_DEVICE_MKNOD;

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

80
        ret = virCgroupDenyDevicePath(priv->cgroup, src->path, perms, true);
81
    } else {
82
        if (!src->readonly && !forceReadonly)
83 84 85 86 87
            perms |= VIR_CGROUP_DEVICE_WRITE;

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

88
        ret = virCgroupAllowDevicePath(priv->cgroup, src->path, perms, true);
89 90 91 92 93 94 95
    }

    virDomainAuditCgroupPath(vm, priv->cgroup,
                             deny ? "deny" : "allow",
                             src->path,
                             virCgroupGetDevicePermsString(perms),
                             ret == 0);
96 97

    return ret;
98 99 100
}


101 102 103 104 105 106 107 108 109
int
qemuSetImageCgroup(virDomainObjPtr vm,
                   virStorageSourcePtr src,
                   bool deny)
{
    return qemuSetImageCgroupInternal(vm, src, deny, false);
}


110 111 112
int
qemuSetupDiskCgroup(virDomainObjPtr vm,
                    virDomainDiskDefPtr disk)
113
{
114
    virStorageSourcePtr next;
115
    bool forceReadonly = false;
116

117
    for (next = disk->src; next; next = next->backingStore) {
118
        if (qemuSetImageCgroupInternal(vm, next, false, forceReadonly) < 0)
119
            return -1;
120 121 122

        /* setup only the top level image for read-write */
        forceReadonly = true;
123
    }
124 125

    return 0;
126 127 128
}


129 130 131
int
qemuTeardownDiskCgroup(virDomainObjPtr vm,
                       virDomainDiskDefPtr disk)
132
{
133
    virStorageSourcePtr next;
134

135 136 137 138
    for (next = disk->src; next; next = next->backingStore) {
        if (qemuSetImageCgroup(vm, next, true) < 0)
            return -1;
    }
139

140
    return 0;
141 142
}

143

144
static int
145
qemuSetupChrSourceCgroup(virDomainObjPtr vm,
146
                         virDomainChrSourceDefPtr source)
147
{
148
    qemuDomainObjPrivatePtr priv = vm->privateData;
149
    int ret;
150

151
    if (source->type != VIR_DOMAIN_CHR_TYPE_DEV)
152 153
        return 0;

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

156
    ret = virCgroupAllowDevicePath(priv->cgroup, source->data.file.path,
157
                                   VIR_CGROUP_DEVICE_RW, false);
158
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
159
                             source->data.file.path, "rw", ret == 0);
160

161
    return ret;
162 163
}

164
static int
165
qemuSetupChardevCgroup(virDomainDefPtr def ATTRIBUTE_UNUSED,
166 167 168
                       virDomainChrDefPtr dev,
                       void *opaque)
{
169 170 171
    virDomainObjPtr vm = opaque;

    return qemuSetupChrSourceCgroup(vm, &dev->source);
172 173 174 175
}


static int
176
qemuSetupTPMCgroup(virDomainObjPtr vm)
177
{
178
    int ret = 0;
179
    virDomainTPMDefPtr dev = vm->def->tpm;
180 181 182

    switch (dev->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
183
        ret = qemuSetupChrSourceCgroup(vm, &dev->data.passthrough.source);
184 185 186 187 188
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

189
    return ret;
190 191
}

192

193 194 195 196 197 198 199 200 201 202 203
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,
204
                                       VIR_CGROUP_DEVICE_RW, false);
205 206 207 208 209 210 211 212
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", dev->source.evdev, "rw", ret == 0);
        break;
    }

    return ret;
}


213
static int
214
qemuSetupHostUSBDeviceCgroup(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
215 216
                             const char *path,
                             void *opaque)
217
{
218 219
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
220
    int ret;
221 222

    VIR_DEBUG("Process path '%s' for USB device", path);
223
    ret = virCgroupAllowDevicePath(priv->cgroup, path,
224
                                   VIR_CGROUP_DEVICE_RW, false);
225
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path, "rw", ret == 0);
226

227
    return ret;
228 229
}

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

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

241 242 243
    ret = virCgroupAllowDevicePath(priv->cgroup, path,
                                   virSCSIDeviceGetReadonly(dev) ?
                                   VIR_CGROUP_DEVICE_READ :
244
                                   VIR_CGROUP_DEVICE_RW, false);
245 246

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

249
    return ret;
250
}
251

252
int
253
qemuSetupHostdevCgroup(virDomainObjPtr vm,
254 255 256 257
                       virDomainHostdevDefPtr dev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
258
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
259
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
260
    virDomainHostdevSubsysSCSIPtr scsisrc = &dev->source.subsys.u.scsi;
261
    virPCIDevicePtr pci = NULL;
262
    virUSBDevicePtr usb = NULL;
263
    virSCSIDevicePtr scsi = NULL;
264 265 266 267 268 269 270 271 272 273 274 275 276 277
    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:
278
            if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
279
                int rv;
280

281 282 283 284
                pci = virPCIDeviceNew(pcisrc->addr.domain,
                                      pcisrc->addr.bus,
                                      pcisrc->addr.slot,
                                      pcisrc->addr.function);
285 286 287
                if (!pci)
                    goto cleanup;

288
                if (!(path = virPCIDeviceGetIOMMUGroupDev(pci)))
289 290 291
                    goto cleanup;

                VIR_DEBUG("Cgroup allow %s for PCI device assignment", path);
292
                rv = virCgroupAllowDevicePath(priv->cgroup, path,
293
                                              VIR_CGROUP_DEVICE_RW, false);
294
                virDomainAuditCgroupPath(vm, priv->cgroup,
295 296
                                         "allow", path, "rw", rv == 0);
                if (rv < 0)
297 298 299
                    goto cleanup;
            }
            break;
300 301 302 303 304 305 306 307

        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;
308
            if ((usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device,
309 310 311 312
                                       NULL)) == NULL) {
                goto cleanup;
            }

313
            /* oddly, qemuSetupHostUSBDeviceCgroup doesn't ever
314 315
             * reference the usb object we just created
             */
316
            if (virUSBDeviceFileIterate(usb, qemuSetupHostUSBDeviceCgroup,
317 318 319 320
                                        vm) < 0) {
                goto cleanup;
            }
            break;
321

322
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI: {
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
            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;
342

343 344 345 346 347
                if (virSCSIDeviceFileIterate(scsi,
                                             qemuSetupHostSCSIDeviceCgroup,
                                             vm) < 0)
                    goto cleanup;
            }
348 349
            break;
        }
350

351 352 353 354 355 356
        default:
            break;
        }
    }

    ret = 0;
357
 cleanup:
358
    virPCIDeviceFree(pci);
359
    virUSBDeviceFree(usb);
360
    virSCSIDeviceFree(scsi);
361 362 363 364 365 366 367 368 369 370
    VIR_FREE(path);
    return ret;
}

int
qemuTeardownHostdevCgroup(virDomainObjPtr vm,
                       virDomainHostdevDefPtr dev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
371
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    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:
387
            if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
388
                int rv;
389

390 391 392 393
                pci = virPCIDeviceNew(pcisrc->addr.domain,
                                      pcisrc->addr.bus,
                                      pcisrc->addr.slot,
                                      pcisrc->addr.function);
394 395 396
                if (!pci)
                    goto cleanup;

397
                if (!(path = virPCIDeviceGetIOMMUGroupDev(pci)))
398 399 400
                    goto cleanup;

                VIR_DEBUG("Cgroup deny %s for PCI device assignment", path);
401
                rv = virCgroupDenyDevicePath(priv->cgroup, path,
402
                                             VIR_CGROUP_DEVICE_RWM, false);
403
                virDomainAuditCgroupPath(vm, priv->cgroup,
404 405
                                         "deny", path, "rwm", rv == 0);
                if (rv < 0)
406 407 408
                    goto cleanup;
            }
            break;
409 410 411
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            /* nothing to tear down for USB */
            break;
412 413 414 415 416 417
        default:
            break;
        }
    }

    ret = 0;
418
 cleanup:
419 420 421 422 423
    virPCIDeviceFree(pci);
    VIR_FREE(path);
    return ret;
}

424 425 426 427
static int
qemuSetupBlkioCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
428
    size_t i;
429 430 431 432 433 434 435 436 437 438 439 440

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

441 442 443
    if (vm->def->blkio.weight != 0 &&
        virCgroupSetBlkioWeight(priv->cgroup, vm->def->blkio.weight) < 0)
        return -1;
444 445 446

    if (vm->def->blkio.ndevices) {
        for (i = 0; i < vm->def->blkio.ndevices; i++) {
447
            virBlkioDevicePtr dev = &vm->def->blkio.devices[i];
448 449
            if (dev->weight &&
                (virCgroupSetBlkioDeviceWeight(priv->cgroup, dev->path,
450 451 452
                                               dev->weight) < 0 ||
                 virCgroupGetBlkioDeviceWeight(priv->cgroup, dev->path,
                                               &dev->weight) < 0))
453 454 455 456
                return -1;

            if (dev->riops &&
                (virCgroupSetBlkioDeviceReadIops(priv->cgroup, dev->path,
457 458 459
                                                 dev->riops) < 0 ||
                 virCgroupGetBlkioDeviceReadIops(priv->cgroup, dev->path,
                                                 &dev->riops) < 0))
460 461 462 463
                return -1;

            if (dev->wiops &&
                (virCgroupSetBlkioDeviceWriteIops(priv->cgroup, dev->path,
464 465 466
                                                  dev->wiops) < 0 ||
                 virCgroupGetBlkioDeviceWriteIops(priv->cgroup, dev->path,
                                                  &dev->wiops) < 0))
467 468 469 470
                return -1;

            if (dev->rbps &&
                (virCgroupSetBlkioDeviceReadBps(priv->cgroup, dev->path,
471 472 473
                                                dev->rbps) < 0 ||
                 virCgroupGetBlkioDeviceReadBps(priv->cgroup, dev->path,
                                                &dev->rbps) < 0))
474 475 476 477
                return -1;

            if (dev->wbps &&
                (virCgroupSetBlkioDeviceWriteBps(priv->cgroup, dev->path,
478 479 480
                                                 dev->wbps) < 0 ||
                 virCgroupGetBlkioDeviceWriteBps(priv->cgroup, dev->path,
                                                 &dev->wbps) < 0))
481 482 483 484 485 486 487
                return -1;
        }
    }

    return 0;
}

488

489 490 491 492 493
static int
qemuSetupMemoryCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

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

506 507 508
    if (virMemoryLimitIsSet(vm->def->mem.hard_limit))
        if (virCgroupSetMemoryHardLimit(priv->cgroup, vm->def->mem.hard_limit) < 0)
            return -1;
509

510 511 512
    if (virMemoryLimitIsSet(vm->def->mem.soft_limit))
        if (virCgroupSetMemorySoftLimit(priv->cgroup, vm->def->mem.soft_limit) < 0)
            return -1;
513

514 515 516
    if (virMemoryLimitIsSet(vm->def->mem.swap_hard_limit))
        if (virCgroupSetMemSwapHardLimit(priv->cgroup, vm->def->mem.swap_hard_limit) < 0)
            return -1;
517 518 519 520 521

    return 0;
}


522 523 524 525 526 527 528
static int
qemuSetupDevicesCgroup(virQEMUDriverPtr driver,
                       virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = NULL;
    const char *const *deviceACL = NULL;
529
    int rv = -1;
530
    int ret = -1;
531
    size_t i;
532 533 534 535

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

536 537 538 539 540
    rv = virCgroupDenyAllDevices(priv->cgroup);
    virDomainAuditCgroup(vm, priv->cgroup, "deny", "all", rv == 0);
    if (rv < 0) {
        if (virLastErrorIsSystemErrno(EPERM)) {
            virResetLastError();
541 542 543 544 545 546 547
            VIR_WARN("Group devices ACL is not accessible, disabling whitelisting");
            return 0;
        }

        goto cleanup;
    }

548
    for (i = 0; i < vm->def->ndisks; i++) {
549 550 551 552
        if (qemuSetupDiskCgroup(vm, vm->def->disks[i]) < 0)
            goto cleanup;
    }

553 554
    rv = virCgroupAllowDevice(priv->cgroup, 'c', DEVICE_PTY_MAJOR, -1,
                              VIR_CGROUP_DEVICE_RW);
555
    virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_PTY_MAJOR,
556 557
                              "pty", "rw", rv == 0);
    if (rv < 0)
558 559 560 561 562 563 564 565
        goto cleanup;

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

    if (vm->def->nsounds &&
566
        ((!vm->def->ngraphics && cfg->nogfxAllowHostAudio) ||
567 568
         (vm->def->graphics &&
          ((vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
569
           cfg->vncAllowHostAudio) ||
570
           (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL))))) {
571 572
        rv = virCgroupAllowDevice(priv->cgroup, 'c', DEVICE_SND_MAJOR, -1,
                                  VIR_CGROUP_DEVICE_RW);
573
        virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_SND_MAJOR,
574 575
                                  "sound", "rw", rv == 0);
        if (rv < 0)
576 577 578
            goto cleanup;
    }

579
    for (i = 0; deviceACL[i] != NULL; i++) {
580
        if (!virFileExists(deviceACL[i])) {
N
Nehal J Wani 已提交
581
            VIR_DEBUG("Ignoring non-existent device %s", deviceACL[i]);
582 583 584
            continue;
        }

585
        rv = virCgroupAllowDevicePath(priv->cgroup, deviceACL[i],
586
                                      VIR_CGROUP_DEVICE_RW, false);
587 588 589
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", deviceACL[i], "rw", rv == 0);
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
590 591 592 593 594 595 596 597 598
            goto cleanup;
    }

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

599
    if (vm->def->tpm && qemuSetupTPMCgroup(vm) < 0)
600 601 602
        goto cleanup;

    for (i = 0; i < vm->def->nhostdevs; i++) {
603
        if (qemuSetupHostdevCgroup(vm, vm->def->hostdevs[i]) < 0)
604 605 606
            goto cleanup;
    }

607 608 609 610 611
    for (i = 0; i < vm->def->ninputs; i++) {
        if (qemuSetupInputCgroup(vm, vm->def->inputs[i]) < 0)
            goto cleanup;
    }

612 613 614
    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");
615 616
            rv = virCgroupAllowDevicePath(priv->cgroup,
                                          vm->def->rngs[i]->source.file,
617
                                          VIR_CGROUP_DEVICE_RW, false);
618
            virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
619 620
                                     vm->def->rngs[i]->source.file,
                                     "rw", rv == 0);
621 622 623 624
            if (rv < 0 &&
                !virLastErrorIsSystemErrno(ENOENT))
                goto cleanup;
        }
625 626
    }

627
    ret = 0;
628
 cleanup:
629 630 631 632 633
    virObjectUnref(cfg);
    return ret;
}


634
int
635
qemuSetupCpusetMems(virDomainObjPtr vm)
636
{
637
    virCgroupPtr cgroup_temp = NULL;
638
    qemuDomainObjPrivatePtr priv = vm->privateData;
639
    virDomainNumatuneMemMode mode;
640
    char *mem_mask = NULL;
641 642 643 644 645
    int ret = -1;

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

646 647
    if (virDomainNumatuneGetMode(vm->def->numa, -1, &mode) < 0 ||
        mode != VIR_DOMAIN_NUMATUNE_MEM_STRICT)
648 649
        return 0;

650
    if (virDomainNumatuneMaybeFormatNodeset(vm->def->numa,
651
                                            priv->autoNodeset,
652
                                            &mem_mask, -1) < 0)
653
        goto cleanup;
654

655
    if (mem_mask)
J
John Ferlan 已提交
656 657
        if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                               false, &cgroup_temp) < 0 ||
658
            virCgroupSetCpusetMems(cgroup_temp, mem_mask) < 0)
659
            goto cleanup;
660

661 662 663
    ret = 0;
 cleanup:
    VIR_FREE(mem_mask);
664
    virCgroupFree(&cgroup_temp);
665 666 667 668 669
    return ret;
}


static int
670
qemuSetupCpusetCgroup(virDomainObjPtr vm)
671 672 673 674 675 676
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

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

677 678 679
    if (virCgroupSetCpusetMemoryMigrate(priv->cgroup, true) < 0)
        return -1;

680
    return 0;
681 682 683
}


684
static int
685 686
qemuSetupCpuCgroup(virQEMUDriverPtr driver,
                   virDomainObjPtr vm)
687 688
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
689 690 691 692
    virObjectEventPtr event = NULL;
    virTypedParameterPtr eventParams = NULL;
    int eventNparams = 0;
    int eventMaxparams = 0;
693 694

    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
695
       if (vm->def->cputune.sharesSpecified) {
696 697 698 699 700 701 702 703
           virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                          _("CPU tuning is not available on this host"));
           return -1;
       } else {
           return 0;
       }
    }

704 705 706 707 708 709 710
    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;
711 712 713 714
        if (vm->def->cputune.shares != val) {
            vm->def->cputune.shares = val;
            if (virTypedParamsAddULLong(&eventParams, &eventNparams,
                                        &eventMaxparams,
715
                                        VIR_DOMAIN_TUNABLE_CPU_CPU_SHARES,
716 717 718 719 720 721
                                        val) < 0)
                return -1;

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

722
        qemuDomainEventQueue(driver, event);
723
    }
724 725 726 727 728

    return 0;
}


729
static int
730
qemuInitCgroup(virQEMUDriverPtr driver,
731 732 733
               virDomainObjPtr vm,
               size_t nnicindexes,
               int *nicindexes)
734
{
735
    int ret = -1;
736 737 738
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

739
    if (!virQEMUDriverIsPrivileged(driver))
740 741
        goto done;

742 743 744
    if (!virCgroupAvailable())
        goto done;

745 746
    virCgroupFree(&priv->cgroup);

747
    if (!vm->def->resource) {
748 749
        virDomainResourceDefPtr res;

750
        if (VIR_ALLOC(res) < 0)
751
            goto cleanup;
752

753
        if (VIR_STRDUP(res->partition, "/machine") < 0) {
754 755 756 757 758
            VIR_FREE(res);
            goto cleanup;
        }

        vm->def->resource = res;
759 760
    }

761 762 763 764 765 766
    if (vm->def->resource->partition[0] != '/') {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Resource partition '%s' must start with '/'"),
                       vm->def->resource->partition);
        goto cleanup;
    }
767

768 769 770 771 772 773 774 775 776 777 778 779
    /*
     * 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,
780 781 782 783 784
                            "qemu",
                            vm->def->uuid,
                            NULL,
                            vm->pid,
                            false,
785
                            nnicindexes, nicindexes,
786 787 788
                            vm->def->resource->partition,
                            cfg->cgroupControllers,
                            &priv->cgroup) < 0) {
789 790
        if (virCgroupNewIgnoreError())
            goto done;
791

792 793
        goto cleanup;
    }
794

795
 done:
796
    ret = 0;
797
 cleanup:
798 799 800
    virObjectUnref(cfg);
    return ret;
}
801

802 803 804
static void
qemuRestoreCgroupState(virDomainObjPtr vm)
{
805
    char *mem_mask = NULL;
806
    char *nodeset = NULL;
807 808
    int empty = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
809
    size_t i = 0;
810
    virBitmapPtr all_nodes;
811
    virCgroupPtr cgroup_temp = NULL;
812 813 814 815 816 817 818 819

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

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

    if ((empty = virCgroupHasEmptyTasks(priv->cgroup,
820
                                        VIR_CGROUP_CONTROLLER_CPUSET)) <= 0)
821 822 823 824 825
        goto error;

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

826 827 828 829 830 831
    for (i = 0; i < virDomainDefGetVcpusMax(vm->def); i++) {
        virDomainVcpuInfoPtr vcpu = virDomainDefGetVcpu(vm->def, i);

        if (!vcpu->online)
            continue;

J
John Ferlan 已提交
832 833
        if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_VCPU, i,
                               false, &cgroup_temp) < 0 ||
834 835 836 837 838
            virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
            virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
            virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
            goto cleanup;

839
        VIR_FREE(nodeset);
840 841 842
        virCgroupFree(&cgroup_temp);
    }

843 844 845
    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 已提交
846
                               false, &cgroup_temp) < 0 ||
847 848 849 850 851
            virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
            virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
            virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
            goto cleanup;

852
        VIR_FREE(nodeset);
853 854 855
        virCgroupFree(&cgroup_temp);
    }

J
John Ferlan 已提交
856 857
    if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                           false, &cgroup_temp) < 0 ||
858 859 860 861 862
        virCgroupSetCpusetMemoryMigrate(cgroup_temp, true) < 0 ||
        virCgroupGetCpusetMems(cgroup_temp, &nodeset) < 0 ||
        virCgroupSetCpusetMems(cgroup_temp, nodeset) < 0)
        goto cleanup;

863 864
 cleanup:
    VIR_FREE(mem_mask);
865
    VIR_FREE(nodeset);
866
    virBitmapFree(all_nodes);
867
    virCgroupFree(&cgroup_temp);
868 869 870 871 872 873 874
    return;

 error:
    virResetLastError();
    VIR_DEBUG("Couldn't restore cgroups to meaningful state");
    goto cleanup;
}
875 876 877 878 879 880 881 882 883

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

884
    if (!virQEMUDriverIsPrivileged(driver))
885 886 887 888 889 890 891
        goto done;

    if (!virCgroupAvailable())
        goto done;

    virCgroupFree(&priv->cgroup);

892 893
    if (virCgroupNewDetectMachine(vm->def->name,
                                  "qemu",
894 895
                                  vm->def->id,
                                  virQEMUDriverIsPrivileged(driver),
896
                                  vm->pid,
897
                                  cfg->cgroupControllers,
898
                                  &priv->cgroup) < 0)
899
        goto cleanup;
900

901 902 903 904
    priv->machineName = virSystemdGetMachineNameByPID(vm->pid);
    if (!priv->machineName)
        virResetLastError();

905 906
    qemuRestoreCgroupState(vm);

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

914 915
int
qemuSetupCgroup(virQEMUDriverPtr driver,
916 917 918
                virDomainObjPtr vm,
                size_t nnicindexes,
                int *nicindexes)
919
{
920
    qemuDomainObjPrivatePtr priv = vm->privateData;
921
    int ret = -1;
922

923 924 925 926 927 928
    if (!vm->pid) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot setup cgroups until process is started"));
        return -1;
    }

929
    if (qemuInitCgroup(driver, vm, nnicindexes, nicindexes) < 0)
930
        return -1;
931

932
    if (!priv->cgroup)
933
        return 0;
934

935 936
    if (qemuSetupDevicesCgroup(driver, vm) < 0)
        goto cleanup;
937

938 939
    if (qemuSetupBlkioCgroup(vm) < 0)
        goto cleanup;
940

941 942
    if (qemuSetupMemoryCgroup(vm) < 0)
        goto cleanup;
943

944
    if (qemuSetupCpuCgroup(driver, vm) < 0)
945
        goto cleanup;
946

947
    if (qemuSetupCpusetCgroup(vm) < 0)
948
        goto cleanup;
949

950
    ret = 0;
951
 cleanup:
952
    return ret;
953 954
}

955 956 957 958
int
qemuSetupCgroupVcpuBW(virCgroupPtr cgroup,
                      unsigned long long period,
                      long long quota)
959 960 961 962 963 964 965 966
{
    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 */
967
        if (virCgroupGetCpuCfsPeriod(cgroup, &old_period) < 0)
968 969
            return -1;

970
        if (virCgroupSetCpuCfsPeriod(cgroup, period) < 0)
971 972 973
            return -1;
    }

974 975 976
    if (quota &&
        virCgroupSetCpuCfsQuota(cgroup, quota) < 0)
        goto error;
977 978 979

    return 0;

980
 error:
981
    if (period) {
982 983 984 985 986 987
        virErrorPtr saved = virSaveLastError();
        ignore_value(virCgroupSetCpuCfsPeriod(cgroup, old_period));
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
988 989 990 991 992
    }

    return -1;
}

993

994
int
995 996
qemuSetupCgroupCpusetCpus(virCgroupPtr cgroup,
                          virBitmapPtr cpumask)
997
{
998
    int ret = -1;
999 1000
    char *new_cpus = NULL;

1001
    if (!(new_cpus = virBitmapFormat(cpumask)))
1002 1003
        goto cleanup;

1004
    if (virCgroupSetCpusetCpus(cgroup, new_cpus) < 0)
1005 1006
        goto cleanup;

1007
    ret = 0;
1008
 cleanup:
1009
    VIR_FREE(new_cpus);
1010
    return ret;
1011 1012
}

1013

1014
int
1015
qemuSetupCgroupForEmulator(virDomainObjPtr vm)
1016
{
1017
    virBitmapPtr cpumask = NULL;
1018
    virCgroupPtr cgroup_emulator = NULL;
1019
    virDomainDefPtr def = vm->def;
1020
    qemuDomainObjPrivatePtr priv = vm->privateData;
1021 1022
    unsigned long long period = vm->def->cputune.emulator_period;
    long long quota = vm->def->cputune.emulator_quota;
1023

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

1031 1032 1033 1034 1035 1036 1037 1038 1039
    /*
     * 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 已提交
1040 1041
    if (virCgroupNewThread(priv->cgroup, VIR_CGROUP_THREAD_EMULATOR, 0,
                           true, &cgroup_emulator) < 0)
1042 1043
        goto cleanup;

1044
    if (virCgroupMoveTask(priv->cgroup, cgroup_emulator) < 0)
1045
        goto cleanup;
1046

1047
    if (def->cputune.emulatorpin)
1048
        cpumask = def->cputune.emulatorpin;
1049 1050
    else if (def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO)
        cpumask = priv->autoCpuset;
1051
    else if (def->cpumask)
1052 1053 1054
        cpumask = def->cpumask;

    if (cpumask) {
1055
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET) &&
1056
            qemuSetupCgroupCpusetCpus(cgroup_emulator, cpumask) < 0)
1057
            goto cleanup;
H
Hu Tao 已提交
1058
    }
1059

1060
    if (period || quota) {
1061 1062 1063 1064
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU) &&
            qemuSetupCgroupVcpuBW(cgroup_emulator, period,
                                  quota) < 0)
            goto cleanup;
1065 1066
    }

1067 1068 1069
    virCgroupFree(&cgroup_emulator);
    return 0;

1070
 cleanup:
1071 1072 1073 1074 1075
    if (cgroup_emulator) {
        virCgroupRemove(cgroup_emulator);
        virCgroupFree(&cgroup_emulator);
    }

1076
    return -1;
1077
}
1078

1079

1080
int
1081
qemuRemoveCgroup(virDomainObjPtr vm)
1082
{
1083
    qemuDomainObjPrivatePtr priv = vm->privateData;
1084

1085
    if (priv->cgroup == NULL)
1086 1087
        return 0; /* Not supported, so claim success */

1088
    if (virCgroupTerminateMachine(priv->machineName) < 0) {
1089 1090 1091 1092
        if (!virCgroupNewIgnoreError())
            VIR_DEBUG("Failed to terminate cgroup for %s", vm->def->name);
    }

1093
    return virCgroupRemove(priv->cgroup);
1094
}