qemu_cgroup.c 29.7 KB
Newer Older
1 2 3
/*
 * qemu_cgroup.c: QEMU cgroup management
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2006-2013 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 40 41 42 43

#define VIR_FROM_THIS VIR_FROM_QEMU

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

50
static int
51
qemuSetupDiskPathAllow(virDomainDiskDefPtr disk,
52 53 54
                       const char *path,
                       size_t depth ATTRIBUTE_UNUSED,
                       void *opaque)
55
{
56 57
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
58
    int ret;
59 60

    VIR_DEBUG("Process path %s for disk", path);
61 62 63
    ret = virCgroupAllowDevicePath(priv->cgroup, path,
                                   (disk->readonly ? VIR_CGROUP_DEVICE_READ
                                    : VIR_CGROUP_DEVICE_RW));
64
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path,
65 66 67 68 69 70 71 72
                             disk->readonly ? "r" : "rw", ret == 0);

    /* Get this for root squash NFS */
    if (ret < 0 &&
        virLastErrorIsSystemErrno(EACCES)) {
        VIR_DEBUG("Ignoring EACCES for %s", path);
        virResetLastError();
        ret = 0;
73
    }
74
    return ret;
75 76 77
}


78 79 80
int
qemuSetupDiskCgroup(virDomainObjPtr vm,
                    virDomainDiskDefPtr disk)
81
{
82 83 84 85 86 87
    qemuDomainObjPrivatePtr priv = vm->privateData;

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

88
    return virDomainDiskDefForeachPath(disk, true, qemuSetupDiskPathAllow, vm);
89 90 91
}


92 93 94 95 96
static int
qemuTeardownDiskPathDeny(virDomainDiskDefPtr disk ATTRIBUTE_UNUSED,
                         const char *path,
                         size_t depth ATTRIBUTE_UNUSED,
                         void *opaque)
97
{
98 99
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
100
    int ret;
101 102

    VIR_DEBUG("Process path %s for disk", path);
103 104 105 106 107 108 109 110 111 112
    ret = virCgroupDenyDevicePath(priv->cgroup, path,
                                  VIR_CGROUP_DEVICE_RWM);
    virDomainAuditCgroupPath(vm, priv->cgroup, "deny", path, "rwm", ret == 0);

    /* Get this for root squash NFS */
    if (ret < 0 &&
        virLastErrorIsSystemErrno(EACCES)) {
        VIR_DEBUG("Ignoring EACCES for %s", path);
        virResetLastError();
        ret = 0;
113
    }
114
    return ret;
115 116 117
}


118 119 120
int
qemuTeardownDiskCgroup(virDomainObjPtr vm,
                       virDomainDiskDefPtr disk)
121
{
122 123 124 125 126 127
    qemuDomainObjPrivatePtr priv = vm->privateData;

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

128 129 130
    return virDomainDiskDefForeachPath(disk,
                                       true,
                                       qemuTeardownDiskPathDeny,
131
                                       vm);
132 133
}

134
static int
135
qemuSetupChrSourceCgroup(virDomainDefPtr def ATTRIBUTE_UNUSED,
136
                         virDomainChrSourceDefPtr dev,
137
                         void *opaque)
138
{
139 140
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
141
    int ret;
142

143
    if (dev->type != VIR_DOMAIN_CHR_TYPE_DEV)
144 145
        return 0;

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

148 149
    ret = virCgroupAllowDevicePath(priv->cgroup, dev->data.file.path,
                                   VIR_CGROUP_DEVICE_RW);
150
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow",
151
                             dev->data.file.path, "rw", ret == 0);
152

153
    return ret;
154 155
}

156 157 158 159 160
static int
qemuSetupChardevCgroup(virDomainDefPtr def,
                       virDomainChrDefPtr dev,
                       void *opaque)
{
161
    return qemuSetupChrSourceCgroup(def, &dev->source, opaque);
162 163 164 165 166 167
}


static int
qemuSetupTPMCgroup(virDomainDefPtr def,
                   virDomainTPMDefPtr dev,
168
                   void *opaque)
169
{
170
    int ret = 0;
171 172 173

    switch (dev->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
174 175
        ret = qemuSetupChrSourceCgroup(def, &dev->data.passthrough.source,
                                       opaque);
176 177 178 179 180
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

181
    return ret;
182 183
}

184

185 186 187 188
static int
qemuSetupHostUsbDeviceCgroup(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
                             const char *path,
                             void *opaque)
189
{
190 191
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
192
    int ret;
193 194

    VIR_DEBUG("Process path '%s' for USB device", path);
195 196 197
    ret = virCgroupAllowDevicePath(priv->cgroup, path,
                                   VIR_CGROUP_DEVICE_RW);
    virDomainAuditCgroupPath(vm, priv->cgroup, "allow", path, "rw", ret == 0);
198

199
    return ret;
200 201
}

202 203 204 205 206 207 208
static int
qemuSetupHostScsiDeviceCgroup(virSCSIDevicePtr dev ATTRIBUTE_UNUSED,
                              const char *path,
                              void *opaque)
{
    virDomainObjPtr vm = opaque;
    qemuDomainObjPrivatePtr priv = vm->privateData;
209
    int ret;
210 211 212

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

213 214 215 216
    ret = virCgroupAllowDevicePath(priv->cgroup, path,
                                   virSCSIDeviceGetReadonly(dev) ?
                                   VIR_CGROUP_DEVICE_READ :
                                   VIR_CGROUP_DEVICE_RW);
217 218

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

221
    return ret;
222
}
223

224 225 226 227 228 229 230
int
qemuSetupHostdevCGroup(virDomainObjPtr vm,
                       virDomainHostdevDefPtr dev)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virPCIDevicePtr pci = NULL;
231
    virUSBDevicePtr usb = NULL;
232
    virSCSIDevicePtr scsi = NULL;
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    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:
            if (dev->source.subsys.u.pci.backend
248
                == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
249
                int rv;
250 251 252 253 254 255 256 257

                pci = virPCIDeviceNew(dev->source.subsys.u.pci.addr.domain,
                                      dev->source.subsys.u.pci.addr.bus,
                                      dev->source.subsys.u.pci.addr.slot,
                                      dev->source.subsys.u.pci.addr.function);
                if (!pci)
                    goto cleanup;

258
                if (!(path = virPCIDeviceGetIOMMUGroupDev(pci)))
259 260 261
                    goto cleanup;

                VIR_DEBUG("Cgroup allow %s for PCI device assignment", path);
262
                rv = virCgroupAllowDevicePath(priv->cgroup, path,
263 264
                                              VIR_CGROUP_DEVICE_RW);
                virDomainAuditCgroupPath(vm, priv->cgroup,
265 266
                                         "allow", path, "rw", rv == 0);
                if (rv < 0)
267 268 269
                    goto cleanup;
            }
            break;
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

        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;
            if ((usb = virUSBDeviceNew(dev->source.subsys.u.usb.bus,
                                       dev->source.subsys.u.usb.device,
                                       NULL)) == NULL) {
                goto cleanup;
            }

            /* oddly, qemuSetupHostUsbDeviceCgroup doesn't ever
             * reference the usb object we just created
             */
            if (virUSBDeviceFileIterate(usb, qemuSetupHostUsbDeviceCgroup,
                                        vm) < 0) {
                goto cleanup;
            }
            break;
292 293 294 295 296 297

        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
            if ((scsi = virSCSIDeviceNew(dev->source.subsys.u.scsi.adapter,
                                         dev->source.subsys.u.scsi.bus,
                                         dev->source.subsys.u.scsi.target,
                                         dev->source.subsys.u.scsi.unit,
298 299
                                         dev->readonly,
                                         dev->shareable)) == NULL)
300 301 302 303 304 305 306
                goto cleanup;

            if (virSCSIDeviceFileIterate(scsi,
                                         qemuSetupHostScsiDeviceCgroup,
                                         vm) < 0)
                goto cleanup;

307 308 309 310 311 312 313 314
        default:
            break;
        }
    }

    ret = 0;
cleanup:
    virPCIDeviceFree(pci);
315
    virUSBDeviceFree(usb);
316
    virSCSIDeviceFree(scsi);
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 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;
    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:
            if (dev->source.subsys.u.pci.backend
343
                == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
344
                int rv;
345 346 347 348 349 350 351 352

                pci = virPCIDeviceNew(dev->source.subsys.u.pci.addr.domain,
                                      dev->source.subsys.u.pci.addr.bus,
                                      dev->source.subsys.u.pci.addr.slot,
                                      dev->source.subsys.u.pci.addr.function);
                if (!pci)
                    goto cleanup;

353
                if (!(path = virPCIDeviceGetIOMMUGroupDev(pci)))
354 355 356
                    goto cleanup;

                VIR_DEBUG("Cgroup deny %s for PCI device assignment", path);
357
                rv = virCgroupDenyDevicePath(priv->cgroup, path,
358 359
                                             VIR_CGROUP_DEVICE_RWM);
                virDomainAuditCgroupPath(vm, priv->cgroup,
360 361
                                         "deny", path, "rwm", rv == 0);
                if (rv < 0)
362 363 364
                    goto cleanup;
            }
            break;
365 366 367
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            /* nothing to tear down for USB */
            break;
368 369 370 371 372 373 374 375 376 377 378 379
        default:
            break;
        }
    }

    ret = 0;
cleanup:
    virPCIDeviceFree(pci);
    VIR_FREE(path);
    return ret;
}

380 381 382 383
static int
qemuSetupBlkioCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
384
    size_t i;
385 386 387 388 389 390 391 392 393 394 395 396

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

397 398 399
    if (vm->def->blkio.weight != 0 &&
        virCgroupSetBlkioWeight(priv->cgroup, vm->def->blkio.weight) < 0)
        return -1;
400 401 402

    if (vm->def->blkio.ndevices) {
        for (i = 0; i < vm->def->blkio.ndevices; i++) {
403
            virBlkioDevicePtr dev = &vm->def->blkio.devices[i];
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
            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))
427 428 429 430 431 432 433
                return -1;
        }
    }

    return 0;
}

434

435 436 437 438 439
static int
qemuSetupMemoryCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

E
Eric Blake 已提交
440
    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_MEMORY)) {
441 442 443 444 445 446
        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 已提交
447 448
        } else {
            return 0;
449 450 451
        }
    }

452 453
    if (vm->def->mem.hard_limit != 0 &&
        virCgroupSetMemoryHardLimit(priv->cgroup, vm->def->mem.hard_limit) < 0)
454 455
        return -1;

456 457 458 459 460 461 462
    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;
463 464 465 466 467

    return 0;
}


468 469 470 471 472 473 474
static int
qemuSetupDevicesCgroup(virQEMUDriverPtr driver,
                       virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = NULL;
    const char *const *deviceACL = NULL;
475
    int rv = -1;
476
    int ret = -1;
477
    size_t i;
478 479 480 481

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

482 483 484 485 486
    rv = virCgroupDenyAllDevices(priv->cgroup);
    virDomainAuditCgroup(vm, priv->cgroup, "deny", "all", rv == 0);
    if (rv < 0) {
        if (virLastErrorIsSystemErrno(EPERM)) {
            virResetLastError();
487 488 489 490 491 492 493
            VIR_WARN("Group devices ACL is not accessible, disabling whitelisting");
            return 0;
        }

        goto cleanup;
    }

494
    for (i = 0; i < vm->def->ndisks; i++) {
495 496 497 498
        if (qemuSetupDiskCgroup(vm, vm->def->disks[i]) < 0)
            goto cleanup;
    }

499
    rv = virCgroupAllowDeviceMajor(priv->cgroup, 'c', DEVICE_PTY_MAJOR,
500 501
                                   VIR_CGROUP_DEVICE_RW);
    virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_PTY_MAJOR,
502 503
                              "pty", "rw", rv == 0);
    if (rv < 0)
504 505 506 507 508 509 510 511
        goto cleanup;

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

    if (vm->def->nsounds &&
512
        ((!vm->def->ngraphics && cfg->nogfxAllowHostAudio) ||
513 514
         (vm->def->graphics &&
          ((vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
515
           cfg->vncAllowHostAudio) ||
516
           (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL))))) {
517
        rv = virCgroupAllowDeviceMajor(priv->cgroup, 'c', DEVICE_SND_MAJOR,
518 519
                                       VIR_CGROUP_DEVICE_RW);
        virDomainAuditCgroupMajor(vm, priv->cgroup, "allow", DEVICE_SND_MAJOR,
520 521
                                  "sound", "rw", rv == 0);
        if (rv < 0)
522 523 524
            goto cleanup;
    }

525
    for (i = 0; deviceACL[i] != NULL; i++) {
526 527
        if (!virFileExists(deviceACL[i])) {
            VIR_DEBUG("Ignoring non-existant device %s", deviceACL[i]);
528 529 530
            continue;
        }

531
        rv = virCgroupAllowDevicePath(priv->cgroup, deviceACL[i],
532
                                      VIR_CGROUP_DEVICE_RW);
533 534 535
        virDomainAuditCgroupPath(vm, priv->cgroup, "allow", deviceACL[i], "rw", rv == 0);
        if (rv < 0 &&
            !virLastErrorIsSystemErrno(ENOENT))
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
            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;
    }

    ret = 0;
cleanup:
    virObjectUnref(cfg);
    return ret;
}


563 564
static int
qemuSetupCpusetCgroup(virDomainObjPtr vm,
565 566
                      virBitmapPtr nodemask,
                      virCapsPtr caps)
567 568
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
569 570
    char *mem_mask = NULL;
    char *cpu_mask = NULL;
571 572 573 574 575 576 577 578 579 580 581 582
    int ret = -1;

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

    if ((vm->def->numatune.memory.nodemask ||
         (vm->def->numatune.memory.placement_mode ==
          VIR_NUMA_TUNE_MEM_PLACEMENT_MODE_AUTO)) &&
        vm->def->numatune.memory.mode == VIR_DOMAIN_NUMATUNE_MEM_STRICT) {

        if (vm->def->numatune.memory.placement_mode ==
            VIR_NUMA_TUNE_MEM_PLACEMENT_MODE_AUTO)
583
            mem_mask = virBitmapFormat(nodemask);
584
        else
585
            mem_mask = virBitmapFormat(vm->def->numatune.memory.nodemask);
586

587
        if (!mem_mask) {
588 589 590 591 592
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to convert memory nodemask"));
            goto cleanup;
        }

593
        if (virCgroupSetCpusetMems(priv->cgroup, mem_mask) < 0)
594 595 596
            goto cleanup;
    }

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
    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);
        }

        if (!cpu_mask) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to convert cpu mask"));
            goto cleanup;
        }

616
        if (virCgroupSetCpusetCpus(priv->cgroup, cpu_mask) < 0)
617 618 619
            goto cleanup;
    }

620 621
    ret = 0;
cleanup:
622 623
    VIR_FREE(mem_mask);
    VIR_FREE(cpu_mask);
624 625 626 627
    return ret;
}


628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
static int
qemuSetupCpuCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
       if (vm->def->cputune.shares) {
           virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                          _("CPU tuning is not available on this host"));
           return -1;
       } else {
           return 0;
       }
    }

643 644 645
    if (vm->def->cputune.shares &&
        virCgroupSetCpuShares(priv->cgroup, vm->def->cputune.shares) < 0)
        return -1;
646 647 648 649 650

    return 0;
}


651
static int
652
qemuInitCgroup(virQEMUDriverPtr driver,
653
               virDomainObjPtr vm)
654
{
655
    int ret = -1;
656 657 658
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

659 660 661
    if (!cfg->privileged)
        goto done;

662 663 664
    if (!virCgroupAvailable())
        goto done;

665 666
    virCgroupFree(&priv->cgroup);

667
    if (!vm->def->resource) {
668 669
        virDomainResourceDefPtr res;

670
        if (VIR_ALLOC(res) < 0)
671
            goto cleanup;
672

673
        if (VIR_STRDUP(res->partition, "/machine") < 0) {
674 675 676 677 678
            VIR_FREE(res);
            goto cleanup;
        }

        vm->def->resource = res;
679 680
    }

681 682 683 684 685 686
    if (vm->def->resource->partition[0] != '/') {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Resource partition '%s' must start with '/'"),
                       vm->def->resource->partition);
        goto cleanup;
    }
687 688 689 690 691 692 693 694 695 696 697

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

701 702
        goto cleanup;
    }
703

704 705 706 707 708 709
done:
    ret = 0;
cleanup:
    virObjectUnref(cfg);
    return ret;
}
710

711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

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

728 729 730
    if (virCgroupNewDetectMachine(vm->def->name,
                                  "qemu",
                                  vm->pid,
731 732 733
                                  vm->def->resource ?
                                  vm->def->resource->partition :
                                  NULL,
734
                                  cfg->cgroupControllers,
735
                                  &priv->cgroup) < 0)
736
        goto cleanup;
737 738

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

745 746 747 748
int
qemuSetupCgroup(virQEMUDriverPtr driver,
                virDomainObjPtr vm,
                virBitmapPtr nodemask)
749
{
750
    qemuDomainObjPrivatePtr priv = vm->privateData;
751
    virCapsPtr caps = NULL;
752
    int ret = -1;
753

754 755 756 757 758 759
    if (!vm->pid) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot setup cgroups until process is started"));
        return -1;
    }

760
    if (qemuInitCgroup(driver, vm) < 0)
761
        return -1;
762

763
    if (!priv->cgroup)
764
        return 0;
765

766 767 768
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

769 770
    if (qemuSetupDevicesCgroup(driver, vm) < 0)
        goto cleanup;
771

772 773
    if (qemuSetupBlkioCgroup(vm) < 0)
        goto cleanup;
774

775 776
    if (qemuSetupMemoryCgroup(vm) < 0)
        goto cleanup;
777

778 779
    if (qemuSetupCpuCgroup(vm) < 0)
        goto cleanup;
780

781
    if (qemuSetupCpusetCgroup(vm, nodemask, caps) < 0)
782
        goto cleanup;
783

784
    ret = 0;
785
cleanup:
786
    virObjectUnref(caps);
787
    return ret;
788 789
}

790 791 792 793
int
qemuSetupCgroupVcpuBW(virCgroupPtr cgroup,
                      unsigned long long period,
                      long long quota)
794 795 796 797 798 799 800 801
{
    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 */
802
        if (virCgroupGetCpuCfsPeriod(cgroup, &old_period) < 0)
803 804
            return -1;

805
        if (virCgroupSetCpuCfsPeriod(cgroup, period) < 0)
806 807 808
            return -1;
    }

809 810 811
    if (quota &&
        virCgroupSetCpuCfsQuota(cgroup, quota) < 0)
        goto error;
812 813 814

    return 0;

815
error:
816
    if (period) {
817 818 819 820 821 822
        virErrorPtr saved = virSaveLastError();
        ignore_value(virCgroupSetCpuCfsPeriod(cgroup, old_period));
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
823 824 825 826 827
    }

    return -1;
}

828 829 830 831 832
int
qemuSetupCgroupVcpuPin(virCgroupPtr cgroup,
                       virDomainVcpuPinDefPtr *vcpupin,
                       int nvcpupin,
                       int vcpuid)
833
{
834
    size_t i;
835 836 837

    for (i = 0; i < nvcpupin; i++) {
        if (vcpuid == vcpupin[i]->vcpuid) {
838
            return qemuSetupCgroupEmulatorPin(cgroup, vcpupin[i]->cpumask);
839 840 841
        }
    }

842 843 844
    return -1;
}

845 846 847
int
qemuSetupCgroupEmulatorPin(virCgroupPtr cgroup,
                           virBitmapPtr cpumask)
848
{
849
    int ret = -1;
850 851
    char *new_cpus = NULL;

852
    new_cpus = virBitmapFormat(cpumask);
853 854 855 856 857 858
    if (!new_cpus) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to convert cpu mask"));
        goto cleanup;
    }

859
    if (virCgroupSetCpusetCpus(cgroup, new_cpus) < 0)
860 861
        goto cleanup;

862
    ret = 0;
863 864
cleanup:
    VIR_FREE(new_cpus);
865
    return ret;
866 867
}

868 869
int
qemuSetupCgroupForVcpu(virDomainObjPtr vm)
870 871 872
{
    virCgroupPtr cgroup_vcpu = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
873
    virDomainDefPtr def = vm->def;
874
    size_t i, j;
875 876 877
    unsigned long long period = vm->def->cputune.period;
    long long quota = vm->def->cputune.quota;

878
    if ((period || quota) &&
879
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
880 881
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("cgroup cpu is required for scheduler tuning"));
H
Hu Tao 已提交
882 883 884
        return -1;
    }

885 886 887 888
    /* We are trying to setup cgroups for CPU pinning, which can also be done
     * with virProcessInfoSetAffinity, thus the lack of cgroups is not fatal
     * here.
     */
889
    if (priv->cgroup == NULL)
890 891
        return 0;

892
    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
893
        /* If we don't know VCPU<->PID mapping or all vcpu runs in the same
W
Wen Congyang 已提交
894
         * thread, we cannot control each vcpu.
895
         */
896 897
        VIR_WARN("Unable to get vcpus' pids.");
        return 0;
898 899 900
    }

    for (i = 0; i < priv->nvcpupids; i++) {
901
        if (virCgroupNewVcpu(priv->cgroup, i, true, &cgroup_vcpu) < 0)
902 903 904
            goto cleanup;

        /* move the thread for vcpu to sub dir */
905
        if (virCgroupAddTask(cgroup_vcpu, priv->vcpupids[i]) < 0)
906 907 908
            goto cleanup;

        if (period || quota) {
H
Hu Tao 已提交
909 910
            if (qemuSetupCgroupVcpuBW(cgroup_vcpu, period, quota) < 0)
                goto cleanup;
911 912
        }

913
        /* Set vcpupin in cgroup if vcpupin xml is provided */
914
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET)) {
M
Martin Kletzander 已提交
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
            /* 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;
            }
        }
930

931 932 933 934 935 936
        virCgroupFree(&cgroup_vcpu);
    }

    return 0;

cleanup:
937 938 939 940 941
    if (cgroup_vcpu) {
        virCgroupRemove(cgroup_vcpu);
        virCgroupFree(&cgroup_vcpu);
    }

942 943 944
    return -1;
}

945 946 947 948
int
qemuSetupCgroupForEmulator(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           virBitmapPtr nodemask)
949
{
950
    virBitmapPtr cpumask = NULL;
951
    virBitmapPtr cpumap = NULL;
952
    virCgroupPtr cgroup_emulator = NULL;
953
    virDomainDefPtr def = vm->def;
954
    qemuDomainObjPrivatePtr priv = vm->privateData;
955 956
    unsigned long long period = vm->def->cputune.emulator_period;
    long long quota = vm->def->cputune.emulator_quota;
957

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

965
    if (priv->cgroup == NULL)
966 967
        return 0; /* Not supported, so claim success */

968
    if (virCgroupNewEmulator(priv->cgroup, true, &cgroup_emulator) < 0)
969 970
        goto cleanup;

971
    if (virCgroupMoveTask(priv->cgroup, cgroup_emulator) < 0)
972
        goto cleanup;
973

974 975 976 977 978
    if (def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
        if (!(cpumap = qemuPrepareCpumap(driver, nodemask)))
            goto cleanup;
        cpumask = cpumap;
    } else if (def->cputune.emulatorpin) {
979
        cpumask = def->cputune.emulatorpin->cpumask;
980
    } else if (def->cpumask) {
981
        cpumask = def->cpumask;
982
    }
983 984

    if (cpumask) {
985 986 987
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET) &&
            qemuSetupCgroupEmulatorPin(cgroup_emulator, cpumask) < 0)
            goto cleanup;
H
Hu Tao 已提交
988
    }
989

990
    if (period || quota) {
991 992 993 994
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU) &&
            qemuSetupCgroupVcpuBW(cgroup_emulator, period,
                                  quota) < 0)
            goto cleanup;
995 996
    }

997
    virCgroupFree(&cgroup_emulator);
998
    virBitmapFree(cpumap);
999 1000 1001
    return 0;

cleanup:
1002 1003
    virBitmapFree(cpumap);

1004 1005 1006 1007 1008
    if (cgroup_emulator) {
        virCgroupRemove(cgroup_emulator);
        virCgroupFree(&cgroup_emulator);
    }

1009
    return -1;
1010
}
1011

1012 1013
int
qemuRemoveCgroup(virDomainObjPtr vm)
1014
{
1015
    qemuDomainObjPrivatePtr priv = vm->privateData;
1016

1017
    if (priv->cgroup == NULL)
1018 1019
        return 0; /* Not supported, so claim success */

1020
    return virCgroupRemove(priv->cgroup);
1021 1022
}

1023 1024
int
qemuAddToCgroup(virDomainObjPtr vm)
1025
{
1026
    qemuDomainObjPrivatePtr priv = vm->privateData;
1027

1028
    if (priv->cgroup == NULL)
1029 1030
        return 0; /* Not supported, so claim success */

1031
    return 0;
1032
}