qemu_cgroup.c 31.0 KB
Newer Older
1 2 3
/*
 * qemu_cgroup.c: QEMU cgroup management
 *
4
 * Copyright (C) 2006-2014 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 38 39

#define VIR_FROM_THIS VIR_FROM_QEMU

40 41
VIR_LOG_INIT("qemu.qemu_cgroup");

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

52 53 54 55 56
static int
qemuSetImageCgroupInternal(virDomainObjPtr vm,
                           virStorageSourcePtr src,
                           bool deny,
                           bool forceReadonly)
57
{
58
    qemuDomainObjPrivatePtr priv = vm->privateData;
59
    int perms = VIR_CGROUP_DEVICE_READ;
60
    int ret;
61

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    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);

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

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

        ret = virCgroupAllowDevicePath(priv->cgroup, src->path, perms);
    }

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

    /* Get this for root squash NFS */
    if (ret < 0 &&
        virLastErrorIsSystemErrno(EACCES)) {
97
        VIR_DEBUG("Ignoring EACCES for %s", src->path);
98 99
        virResetLastError();
        ret = 0;
100
    }
101

102
    return ret;
103 104 105
}


106 107 108 109 110 111 112 113 114
int
qemuSetImageCgroup(virDomainObjPtr vm,
                   virStorageSourcePtr src,
                   bool deny)
{
    return qemuSetImageCgroupInternal(vm, src, deny, false);
}


115 116 117
int
qemuSetupDiskCgroup(virDomainObjPtr vm,
                    virDomainDiskDefPtr disk)
118
{
119
    virStorageSourcePtr next;
120
    bool forceReadonly = false;
121

122
    for (next = disk->src; next; next = next->backingStore) {
123
        if (qemuSetImageCgroupInternal(vm, next, false, forceReadonly) < 0)
124
            return -1;
125 126 127

        /* setup only the top level image for read-write */
        forceReadonly = true;
128
    }
129 130

    return 0;
131 132 133
}


134 135 136
int
qemuTeardownDiskCgroup(virDomainObjPtr vm,
                       virDomainDiskDefPtr disk)
137
{
138
    virStorageSourcePtr next;
139

140 141 142 143
    for (next = disk->src; next; next = next->backingStore) {
        if (qemuSetImageCgroup(vm, next, true) < 0)
            return -1;
    }
144

145
    return 0;
146 147
}

148

149
static int
150
qemuSetupChrSourceCgroup(virDomainDefPtr def ATTRIBUTE_UNUSED,
151
                         virDomainChrSourceDefPtr dev,
152
                         void *opaque)
153
{
154 155
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
156
    int ret;
157

158
    if (dev->type != VIR_DOMAIN_CHR_TYPE_DEV)
159 160
        return 0;

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

163 164
    ret = virCgroupAllowDevicePath(priv->cgroup, dev->data.file.path,
                                   VIR_CGROUP_DEVICE_RW);
165
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
166
                             dev->data.file.path, "rw", ret == 0);
167

168
    return ret;
169 170
}

171 172 173 174 175
static int
qemuSetupChardevCgroup(virDomainDefPtr def,
                       virDomainChrDefPtr dev,
                       void *opaque)
{
176
    return qemuSetupChrSourceCgroup(def, &dev->source, opaque);
177 178 179 180 181 182
}


static int
qemuSetupTPMCgroup(virDomainDefPtr def,
                   virDomainTPMDefPtr dev,
183
                   void *opaque)
184
{
185
    int ret = 0;
186 187 188

    switch (dev->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
189 190
        ret = qemuSetupChrSourceCgroup(def, &dev->data.passthrough.source,
                                       opaque);
191 192 193 194 195
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

196
    return ret;
197 198
}

199

200
static int
201
qemuSetupHostUSBDeviceCgroup(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
202 203
                             const char *path,
                             void *opaque)
204
{
205 206
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
207
    int ret;
208 209

    VIR_DEBUG("Process path '%s' for USB device", path);
210 211 212
    ret = virCgroupAllowDevicePath(priv->cgroup, path,
                                   VIR_CGROUP_DEVICE_RW);
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path, "rw", ret == 0);
213

214
    return ret;
215 216
}

217
static int
218
qemuSetupHostSCSIDeviceCgroup(virSCSIDevicePtr dev ATTRIBUTE_UNUSED,
219 220 221 222 223
                              const char *path,
                              void *opaque)
{
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
224
    int ret;
225 226 227

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

228 229 230 231
    ret = virCgroupAllowDevicePath(priv->cgroup, path,
                                   virSCSIDeviceGetReadonly(dev) ?
                                   VIR_CGROUP_DEVICE_READ :
                                   VIR_CGROUP_DEVICE_RW);
232 233

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

236
    return ret;
237
}
238

239 240 241 242 243 244
int
qemuSetupHostdevCGroup(virDomainObjPtr vm,
                       virDomainHostdevDefPtr dev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
245
    virDomainHostdevSubsysUSBPtr usbsrc = &dev->source.subsys.u.usb;
246
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
247
    virPCIDevicePtr pci = NULL;
248
    virUSBDevicePtr usb = NULL;
249
    virSCSIDevicePtr scsi = NULL;
250 251 252 253 254 255 256 257 258 259 260 261 262 263
    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:
264
            if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
265
                int rv;
266

267 268 269 270
                pci = virPCIDeviceNew(pcisrc->addr.domain,
                                      pcisrc->addr.bus,
                                      pcisrc->addr.slot,
                                      pcisrc->addr.function);
271 272 273
                if (!pci)
                    goto cleanup;

274
                if (!(path = virPCIDeviceGetIOMMUGroupDev(pci)))
275 276 277
                    goto cleanup;

                VIR_DEBUG("Cgroup allow %s for PCI device assignment", path);
278
                rv = virCgroupAllowDevicePath(priv->cgroup, path,
279 280
                                              VIR_CGROUP_DEVICE_RW);
                virDomainAuditCgroupPath(vm, priv->cgroup,
281 282
                                         "allow", path, "rw", rv == 0);
                if (rv < 0)
283 284 285
                    goto cleanup;
            }
            break;
286 287 288 289 290 291 292 293

        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;
294
            if ((usb = virUSBDeviceNew(usbsrc->bus, usbsrc->device,
295 296 297 298
                                       NULL)) == NULL) {
                goto cleanup;
            }

299
            /* oddly, qemuSetupHostUSBDeviceCgroup doesn't ever
300 301
             * reference the usb object we just created
             */
302
            if (virUSBDeviceFileIterate(usb, qemuSetupHostUSBDeviceCgroup,
303 304 305 306
                                        vm) < 0) {
                goto cleanup;
            }
            break;
307 308

        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
309 310
            if ((scsi = virSCSIDeviceNew(NULL,
                                         dev->source.subsys.u.scsi.adapter,
311 312 313
                                         dev->source.subsys.u.scsi.bus,
                                         dev->source.subsys.u.scsi.target,
                                         dev->source.subsys.u.scsi.unit,
314 315
                                         dev->readonly,
                                         dev->shareable)) == NULL)
316 317 318
                goto cleanup;

            if (virSCSIDeviceFileIterate(scsi,
319
                                         qemuSetupHostSCSIDeviceCgroup,
320 321 322
                                         vm) < 0)
                goto cleanup;

323 324 325 326 327 328
        default:
            break;
        }
    }

    ret = 0;
329
 cleanup:
330
    virPCIDeviceFree(pci);
331
    virUSBDeviceFree(usb);
332
    virSCSIDeviceFree(scsi);
333 334 335 336 337 338 339 340 341 342
    VIR_FREE(path);
    return ret;
}

int
qemuTeardownHostdevCgroup(virDomainObjPtr vm,
                       virDomainHostdevDefPtr dev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
343
    virDomainHostdevSubsysPCIPtr pcisrc = &dev->source.subsys.u.pci;
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    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:
359
            if (pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
360
                int rv;
361

362 363 364 365
                pci = virPCIDeviceNew(pcisrc->addr.domain,
                                      pcisrc->addr.bus,
                                      pcisrc->addr.slot,
                                      pcisrc->addr.function);
366 367 368
                if (!pci)
                    goto cleanup;

369
                if (!(path = virPCIDeviceGetIOMMUGroupDev(pci)))
370 371 372
                    goto cleanup;

                VIR_DEBUG("Cgroup deny %s for PCI device assignment", path);
373
                rv = virCgroupDenyDevicePath(priv->cgroup, path,
374 375
                                             VIR_CGROUP_DEVICE_RWM);
                virDomainAuditCgroupPath(vm, priv->cgroup,
376 377
                                         "deny", path, "rwm", rv == 0);
                if (rv < 0)
378 379 380
                    goto cleanup;
            }
            break;
381 382 383
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            /* nothing to tear down for USB */
            break;
384 385 386 387 388 389
        default:
            break;
        }
    }

    ret = 0;
390
 cleanup:
391 392 393 394 395
    virPCIDeviceFree(pci);
    VIR_FREE(path);
    return ret;
}

396 397 398 399
static int
qemuSetupBlkioCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
400
    size_t i;
401 402 403 404 405 406 407 408 409 410 411 412

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

413 414 415
    if (vm->def->blkio.weight != 0 &&
        virCgroupSetBlkioWeight(priv->cgroup, vm->def->blkio.weight) < 0)
        return -1;
416 417 418

    if (vm->def->blkio.ndevices) {
        for (i = 0; i < vm->def->blkio.ndevices; i++) {
419
            virBlkioDevicePtr dev = &vm->def->blkio.devices[i];
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
            if (dev->weight &&
                (virCgroupSetBlkioDeviceWeight(priv->cgroup, dev->path,
                                               dev->weight) < 0))
                return -1;

            if (dev->riops &&
                (virCgroupSetBlkioDeviceReadIops(priv->cgroup, dev->path,
                                                 dev->riops) < 0))
                return -1;

            if (dev->wiops &&
                (virCgroupSetBlkioDeviceWriteIops(priv->cgroup, dev->path,
                                                  dev->wiops) < 0))
                return -1;

            if (dev->rbps &&
                (virCgroupSetBlkioDeviceReadBps(priv->cgroup, dev->path,
                                                dev->rbps) < 0))
                return -1;

            if (dev->wbps &&
                (virCgroupSetBlkioDeviceWriteBps(priv->cgroup, dev->path,
                                                 dev->wbps) < 0))
443 444 445 446 447 448 449
                return -1;
        }
    }

    return 0;
}

450

451 452 453 454 455
static int
qemuSetupMemoryCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

E
Eric Blake 已提交
456
    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_MEMORY)) {
457 458 459 460 461 462
        if (vm->def->mem.hard_limit != 0 ||
            vm->def->mem.soft_limit != 0 ||
            vm->def->mem.swap_hard_limit != 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Memory cgroup is not available on this host"));
            return -1;
O
Osier Yang 已提交
463 464
        } else {
            return 0;
465 466 467
        }
    }

468 469
    if (vm->def->mem.hard_limit != 0 &&
        virCgroupSetMemoryHardLimit(priv->cgroup, vm->def->mem.hard_limit) < 0)
470 471
        return -1;

472 473 474 475 476 477 478
    if (vm->def->mem.soft_limit != 0 &&
        virCgroupSetMemorySoftLimit(priv->cgroup, vm->def->mem.soft_limit) < 0)
        return -1;

    if (vm->def->mem.swap_hard_limit != 0 &&
        virCgroupSetMemSwapHardLimit(priv->cgroup, vm->def->mem.swap_hard_limit) < 0)
        return -1;
479 480 481 482 483

    return 0;
}


484 485 486 487 488 489 490
static int
qemuSetupDevicesCgroup(virQEMUDriverPtr driver,
                       virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = NULL;
    const char *const *deviceACL = NULL;
491
    int rv = -1;
492
    int ret = -1;
493
    size_t i;
494 495 496 497

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

498 499 500 501 502
    rv = virCgroupDenyAllDevices(priv->cgroup);
    virDomainAuditCgroup(vm, priv->cgroup, "deny", "all", rv == 0);
    if (rv < 0) {
        if (virLastErrorIsSystemErrno(EPERM)) {
            virResetLastError();
503 504 505 506 507 508 509
            VIR_WARN("Group devices ACL is not accessible, disabling whitelisting");
            return 0;
        }

        goto cleanup;
    }

510
    for (i = 0; i < vm->def->ndisks; i++) {
511 512 513 514
        if (qemuSetupDiskCgroup(vm, vm->def->disks[i]) < 0)
            goto cleanup;
    }

515
    rv = virCgroupAllowDeviceMajor(priv->cgroup, 'c', DEVICE_PTY_MAJOR,
516 517
                                   VIR_CGROUP_DEVICE_RW);
    virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_PTY_MAJOR,
518 519
                              "pty", "rw", rv == 0);
    if (rv < 0)
520 521 522 523 524 525 526 527
        goto cleanup;

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

    if (vm->def->nsounds &&
528
        ((!vm->def->ngraphics && cfg->nogfxAllowHostAudio) ||
529 530
         (vm->def->graphics &&
          ((vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
531
           cfg->vncAllowHostAudio) ||
532
           (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL))))) {
533
        rv = virCgroupAllowDeviceMajor(priv->cgroup, 'c', DEVICE_SND_MAJOR,
534 535
                                       VIR_CGROUP_DEVICE_RW);
        virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_SND_MAJOR,
536 537
                                  "sound", "rw", rv == 0);
        if (rv < 0)
538 539 540
            goto cleanup;
    }

541
    for (i = 0; deviceACL[i] != NULL; i++) {
542
        if (!virFileExists(deviceACL[i])) {
N
Nehal J Wani 已提交
543
            VIR_DEBUG("Ignoring non-existent device %s", deviceACL[i]);
544 545 546
            continue;
        }

547
        rv = virCgroupAllowDevicePath(priv->cgroup, deviceACL[i],
548
                                      VIR_CGROUP_DEVICE_RW);
549 550 551
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", deviceACL[i], "rw", rv == 0);
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
            goto cleanup;
    }

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

    if (vm->def->tpm &&
        (qemuSetupTPMCgroup(vm->def,
                            vm->def->tpm,
                            vm) < 0))
        goto cleanup;

    for (i = 0; i < vm->def->nhostdevs; i++) {
        if (qemuSetupHostdevCGroup(vm, vm->def->hostdevs[i]) < 0)
            goto cleanup;
    }

572 573 574 575 576 577 578 579 580 581 582 583
    if (vm->def->rng &&
        (vm->def->rng->backend == VIR_DOMAIN_RNG_BACKEND_RANDOM)) {
        VIR_DEBUG("Setting Cgroup ACL for RNG device");
        rv = virCgroupAllowDevicePath(priv->cgroup, vm->def->rng->source.file,
                                      VIR_CGROUP_DEVICE_RW);
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
                                 vm->def->rng->source.file, "rw", rv == 0);
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
            goto cleanup;
    }

584
    ret = 0;
585
 cleanup:
586 587 588 589 590
    virObjectUnref(cfg);
    return ret;
}


591
static int
592 593
qemuSetupCpusetMems(virDomainObjPtr vm,
                    virBitmapPtr nodemask)
594 595
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
596
    char *mem_mask = NULL;
597 598 599 600 601
    int ret = -1;

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

602 603
    if (virDomainNumatuneMaybeFormatNodeset(vm->def->numatune,
                                            nodemask,
604
                                            &mem_mask, -1) < 0)
605
        goto cleanup;
606

607 608 609
    if (mem_mask &&
        virCgroupSetCpusetMems(priv->cgroup, mem_mask) < 0)
        goto cleanup;
610

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
    ret = 0;
 cleanup:
    VIR_FREE(mem_mask);
    return ret;
}


static int
qemuSetupCpusetCgroup(virDomainObjPtr vm,
                      virBitmapPtr nodemask,
                      virCapsPtr caps)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *cpu_mask = NULL;
    int ret = -1;

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

630 631 632 633 634 635 636 637 638 639 640 641 642
    if (vm->def->cpumask ||
        (vm->def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO)) {

        if (vm->def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
            virBitmapPtr cpumap;
            if (!(cpumap = virCapabilitiesGetCpusForNodemask(caps, nodemask)))
                goto cleanup;
            cpu_mask = virBitmapFormat(cpumap);
            virBitmapFree(cpumap);
        } else {
            cpu_mask = virBitmapFormat(vm->def->cpumask);
        }

643
        if (!cpu_mask)
644 645
            goto cleanup;

646
        if (virCgroupSetCpusetCpus(priv->cgroup, cpu_mask) < 0)
647 648 649
            goto cleanup;
    }

650
    ret = 0;
651
 cleanup:
652
    VIR_FREE(cpu_mask);
653 654 655 656
    return ret;
}


657 658 659 660 661 662
static int
qemuSetupCpuCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
663
       if (vm->def->cputune.sharesSpecified) {
664 665 666 667 668 669 670 671
           virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                          _("CPU tuning is not available on this host"));
           return -1;
       } else {
           return 0;
       }
    }

672 673 674 675 676 677 678 679 680
    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;
        vm->def->cputune.shares = val;
    }
681 682 683 684 685

    return 0;
}


686
static int
687
qemuInitCgroup(virQEMUDriverPtr driver,
688
               virDomainObjPtr vm)
689
{
690
    int ret = -1;
691 692 693
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

694 695 696
    if (!cfg->privileged)
        goto done;

697 698 699
    if (!virCgroupAvailable())
        goto done;

700 701
    virCgroupFree(&priv->cgroup);

702
    if (!vm->def->resource) {
703 704
        virDomainResourceDefPtr res;

705
        if (VIR_ALLOC(res) < 0)
706
            goto cleanup;
707

708
        if (VIR_STRDUP(res->partition, "/machine") < 0) {
709 710 711 712 713
            VIR_FREE(res);
            goto cleanup;
        }

        vm->def->resource = res;
714 715
    }

716 717 718 719 720 721
    if (vm->def->resource->partition[0] != '/') {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Resource partition '%s' must start with '/'"),
                       vm->def->resource->partition);
        goto cleanup;
    }
722 723 724 725 726 727 728 729 730 731 732

    if (virCgroupNewMachine(vm->def->name,
                            "qemu",
                            cfg->privileged,
                            vm->def->uuid,
                            NULL,
                            vm->pid,
                            false,
                            vm->def->resource->partition,
                            cfg->cgroupControllers,
                            &priv->cgroup) < 0) {
733 734
        if (virCgroupNewIgnoreError())
            goto done;
735

736 737
        goto cleanup;
    }
738

739
 done:
740
    ret = 0;
741
 cleanup:
742 743 744
    virObjectUnref(cfg);
    return ret;
}
745

746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762

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

    if (!cfg->privileged)
        goto done;

    if (!virCgroupAvailable())
        goto done;

    virCgroupFree(&priv->cgroup);

763 764 765
    if (virCgroupNewDetectMachine(vm->def->name,
                                  "qemu",
                                  vm->pid,
766 767 768
                                  vm->def->resource ?
                                  vm->def->resource->partition :
                                  NULL,
769
                                  cfg->cgroupControllers,
770
                                  &priv->cgroup) < 0)
771
        goto cleanup;
772

773
 done:
774
    ret = 0;
775
 cleanup:
776
    virObjectUnref(cfg);
777
    return ret;
778 779
}

780 781 782 783
int
qemuSetupCgroup(virQEMUDriverPtr driver,
                virDomainObjPtr vm,
                virBitmapPtr nodemask)
784
{
785
    qemuDomainObjPrivatePtr priv = vm->privateData;
786
    virCapsPtr caps = NULL;
787
    int ret = -1;
788

789 790 791 792 793 794
    if (!vm->pid) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot setup cgroups until process is started"));
        return -1;
    }

795
    if (qemuInitCgroup(driver, vm) < 0)
796
        return -1;
797

798
    if (!priv->cgroup)
799
        return 0;
800

801 802 803
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

804 805
    if (qemuSetupDevicesCgroup(driver, vm) < 0)
        goto cleanup;
806

807 808
    if (qemuSetupBlkioCgroup(vm) < 0)
        goto cleanup;
809

810 811
    if (qemuSetupMemoryCgroup(vm) < 0)
        goto cleanup;
812

813 814
    if (qemuSetupCpuCgroup(vm) < 0)
        goto cleanup;
815

816
    if (qemuSetupCpusetCgroup(vm, nodemask, caps) < 0)
817
        goto cleanup;
818

819
    ret = 0;
820
 cleanup:
821
    virObjectUnref(caps);
822
    return ret;
823 824
}

825 826 827 828 829 830 831
int
qemuSetupCgroupPostInit(virDomainObjPtr vm,
                        virBitmapPtr nodemask)
{
    return qemuSetupCpusetMems(vm, nodemask);
}

832 833 834 835
int
qemuSetupCgroupVcpuBW(virCgroupPtr cgroup,
                      unsigned long long period,
                      long long quota)
836 837 838 839 840 841 842 843
{
    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 */
844
        if (virCgroupGetCpuCfsPeriod(cgroup, &old_period) < 0)
845 846
            return -1;

847
        if (virCgroupSetCpuCfsPeriod(cgroup, period) < 0)
848 849 850
            return -1;
    }

851 852 853
    if (quota &&
        virCgroupSetCpuCfsQuota(cgroup, quota) < 0)
        goto error;
854 855 856

    return 0;

857
 error:
858
    if (period) {
859 860 861 862 863 864
        virErrorPtr saved = virSaveLastError();
        ignore_value(virCgroupSetCpuCfsPeriod(cgroup, old_period));
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
865 866 867 868 869
    }

    return -1;
}

870 871 872 873 874
int
qemuSetupCgroupVcpuPin(virCgroupPtr cgroup,
                       virDomainVcpuPinDefPtr *vcpupin,
                       int nvcpupin,
                       int vcpuid)
875
{
876
    size_t i;
877 878 879

    for (i = 0; i < nvcpupin; i++) {
        if (vcpuid == vcpupin[i]->vcpuid) {
880
            return qemuSetupCgroupEmulatorPin(cgroup, vcpupin[i]->cpumask);
881 882 883
        }
    }

884 885 886
    return -1;
}

887 888 889
int
qemuSetupCgroupEmulatorPin(virCgroupPtr cgroup,
                           virBitmapPtr cpumask)
890
{
891
    int ret = -1;
892 893
    char *new_cpus = NULL;

894
    if (!(new_cpus = virBitmapFormat(cpumask)))
895 896
        goto cleanup;

897
    if (virCgroupSetCpusetCpus(cgroup, new_cpus) < 0)
898 899
        goto cleanup;

900
    ret = 0;
901
 cleanup:
902
    VIR_FREE(new_cpus);
903
    return ret;
904 905
}

906 907
int
qemuSetupCgroupForVcpu(virDomainObjPtr vm)
908 909 910
{
    virCgroupPtr cgroup_vcpu = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
911
    virDomainDefPtr def = vm->def;
912
    size_t i, j;
913 914 915
    unsigned long long period = vm->def->cputune.period;
    long long quota = vm->def->cputune.quota;

916
    if ((period || quota) &&
917
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
918 919
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("cgroup cpu is required for scheduler tuning"));
H
Hu Tao 已提交
920 921 922
        return -1;
    }

923 924 925 926 927 928 929 930 931
    /*
     * 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;

932
    /* We are trying to setup cgroups for CPU pinning, which can also be done
933
     * with virProcessSetAffinity, thus the lack of cgroups is not fatal here.
934
     */
935
    if (priv->cgroup == NULL)
936 937
        return 0;

938
    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
939
        /* If we don't know VCPU<->PID mapping or all vcpu runs in the same
W
Wen Congyang 已提交
940
         * thread, we cannot control each vcpu.
941
         */
942 943
        VIR_WARN("Unable to get vcpus' pids.");
        return 0;
944 945 946
    }

    for (i = 0; i < priv->nvcpupids; i++) {
947
        if (virCgroupNewVcpu(priv->cgroup, i, true, &cgroup_vcpu) < 0)
948 949 950
            goto cleanup;

        /* move the thread for vcpu to sub dir */
951
        if (virCgroupAddTask(cgroup_vcpu, priv->vcpupids[i]) < 0)
952 953 954
            goto cleanup;

        if (period || quota) {
H
Hu Tao 已提交
955 956
            if (qemuSetupCgroupVcpuBW(cgroup_vcpu, period, quota) < 0)
                goto cleanup;
957 958
        }

959
        /* Set vcpupin in cgroup if vcpupin xml is provided */
960
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET)) {
M
Martin Kletzander 已提交
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
            /* find the right CPU to pin, otherwise
             * qemuSetupCgroupVcpuPin will fail. */
            for (j = 0; j < def->cputune.nvcpupin; j++) {
                if (def->cputune.vcpupin[j]->vcpuid != i)
                    continue;

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

                break;
            }
        }
976

977 978 979 980 981
        virCgroupFree(&cgroup_vcpu);
    }

    return 0;

982
 cleanup:
983 984 985 986 987
    if (cgroup_vcpu) {
        virCgroupRemove(cgroup_vcpu);
        virCgroupFree(&cgroup_vcpu);
    }

988 989 990
    return -1;
}

991 992 993 994
int
qemuSetupCgroupForEmulator(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           virBitmapPtr nodemask)
995
{
996
    virBitmapPtr cpumask = NULL;
997
    virBitmapPtr cpumap = NULL;
998
    virCgroupPtr cgroup_emulator = NULL;
999
    virDomainDefPtr def = vm->def;
1000
    qemuDomainObjPrivatePtr priv = vm->privateData;
1001 1002
    unsigned long long period = vm->def->cputune.emulator_period;
    long long quota = vm->def->cputune.emulator_quota;
1003

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

1011 1012 1013 1014 1015 1016 1017 1018 1019
    /*
     * 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;

1020
    if (priv->cgroup == NULL)
1021 1022
        return 0; /* Not supported, so claim success */

1023
    if (virCgroupNewEmulator(priv->cgroup, true, &cgroup_emulator) < 0)
1024 1025
        goto cleanup;

1026
    if (virCgroupMoveTask(priv->cgroup, cgroup_emulator) < 0)
1027
        goto cleanup;
1028

1029 1030 1031 1032 1033
    if (def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
        if (!(cpumap = qemuPrepareCpumap(driver, nodemask)))
            goto cleanup;
        cpumask = cpumap;
    } else if (def->cputune.emulatorpin) {
1034
        cpumask = def->cputune.emulatorpin->cpumask;
1035
    } else if (def->cpumask) {
1036
        cpumask = def->cpumask;
1037
    }
1038 1039

    if (cpumask) {
1040 1041 1042
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET) &&
            qemuSetupCgroupEmulatorPin(cgroup_emulator, cpumask) < 0)
            goto cleanup;
H
Hu Tao 已提交
1043
    }
1044

1045
    if (period || quota) {
1046 1047 1048 1049
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU) &&
            qemuSetupCgroupVcpuBW(cgroup_emulator, period,
                                  quota) < 0)
            goto cleanup;
1050 1051
    }

1052
    virCgroupFree(&cgroup_emulator);
1053
    virBitmapFree(cpumap);
1054 1055
    return 0;

1056
 cleanup:
1057 1058
    virBitmapFree(cpumap);

1059 1060 1061 1062 1063
    if (cgroup_emulator) {
        virCgroupRemove(cgroup_emulator);
        virCgroupFree(&cgroup_emulator);
    }

1064
    return -1;
1065
}
1066

1067 1068
int
qemuRemoveCgroup(virDomainObjPtr vm)
1069
{
1070
    qemuDomainObjPrivatePtr priv = vm->privateData;
1071

1072
    if (priv->cgroup == NULL)
1073 1074
        return 0; /* Not supported, so claim success */

1075
    return virCgroupRemove(priv->cgroup);
1076 1077
}

1078 1079
int
qemuAddToCgroup(virDomainObjPtr vm)
1080
{
1081
    qemuDomainObjPrivatePtr priv = vm->privateData;
1082

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

1086
    return 0;
1087
}