qemu_cgroup.c 29.7 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
int
qemuSetImageCgroup(virDomainObjPtr vm,
                   virStorageSourcePtr src,
                   bool deny)
56
{
57
    qemuDomainObjPrivatePtr priv = vm->privateData;
58
    int perms = VIR_CGROUP_DEVICE_READ;
59
    int ret;
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    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 {
        if (!src->readonly)
            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);
92 93 94 95

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

101
    return ret;
102 103 104
}


105 106 107
int
qemuSetupDiskCgroup(virDomainObjPtr vm,
                    virDomainDiskDefPtr disk)
108
{
109
    virStorageSourcePtr next;
110

111 112 113
    for (next = disk->src; next; next = next->backingStore) {
        if (qemuSetImageCgroup(vm, next, false) < 0)
            return -1;
114
    }
115 116

    return 0;
117 118 119
}


120 121 122
int
qemuTeardownDiskCgroup(virDomainObjPtr vm,
                       virDomainDiskDefPtr disk)
123
{
124
    virStorageSourcePtr next;
125

126 127 128 129
    for (next = disk->src; next; next = next->backingStore) {
        if (qemuSetImageCgroup(vm, next, true) < 0)
            return -1;
    }
130

131
    return 0;
132 133
}

134

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

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

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

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

154
    return ret;
155 156
}

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


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

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

182
    return ret;
183 184
}

185

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

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

200
    return ret;
201 202
}

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

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

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

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

222
    return ret;
223
}
224

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

                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;

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

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

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

285
            /* oddly, qemuSetupHostUSBDeviceCgroup doesn't ever
286 287
             * reference the usb object we just created
             */
288
            if (virUSBDeviceFileIterate(usb, qemuSetupHostUSBDeviceCgroup,
289 290 291 292
                                        vm) < 0) {
                goto cleanup;
            }
            break;
293 294

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

            if (virSCSIDeviceFileIterate(scsi,
305
                                         qemuSetupHostSCSIDeviceCgroup,
306 307 308
                                         vm) < 0)
                goto cleanup;

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

    ret = 0;
315
 cleanup:
316
    virPCIDeviceFree(pci);
317
    virUSBDeviceFree(usb);
318
    virSCSIDeviceFree(scsi);
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    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
345
                == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_VFIO) {
346
                int rv;
347 348 349 350 351 352 353 354

                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;

355
                if (!(path = virPCIDeviceGetIOMMUGroupDev(pci)))
356 357 358
                    goto cleanup;

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

    ret = 0;
376
 cleanup:
377 378 379 380 381
    virPCIDeviceFree(pci);
    VIR_FREE(path);
    return ret;
}

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

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

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

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

    return 0;
}

436

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

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

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

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

    return 0;
}


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

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

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

        goto cleanup;
    }

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

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

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

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

527
    for (i = 0; deviceACL[i] != NULL; i++) {
528
        if (!virFileExists(deviceACL[i])) {
N
Nehal J Wani 已提交
529
            VIR_DEBUG("Ignoring non-existent device %s", deviceACL[i]);
530 531 532
            continue;
        }

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

558 559 560 561 562 563 564 565 566 567 568 569
    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;
    }

570
    ret = 0;
571
 cleanup:
572 573 574 575 576
    virObjectUnref(cfg);
    return ret;
}


577 578
static int
qemuSetupCpusetCgroup(virDomainObjPtr vm,
579 580
                      virBitmapPtr nodemask,
                      virCapsPtr caps)
581 582
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
583 584
    char *mem_mask = NULL;
    char *cpu_mask = NULL;
585 586 587 588 589 590 591 592 593 594 595 596
    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)
597
            mem_mask = virBitmapFormat(nodemask);
598
        else
599
            mem_mask = virBitmapFormat(vm->def->numatune.memory.nodemask);
600

601
        if (!mem_mask)
602 603
            goto cleanup;

604
        if (virCgroupSetCpusetMems(priv->cgroup, mem_mask) < 0)
605 606 607
            goto cleanup;
    }

608 609 610 611 612 613 614 615 616 617 618 619 620
    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);
        }

621
        if (!cpu_mask)
622 623
            goto cleanup;

624
        if (virCgroupSetCpusetCpus(priv->cgroup, cpu_mask) < 0)
625 626 627
            goto cleanup;
    }

628
    ret = 0;
629
 cleanup:
630 631
    VIR_FREE(mem_mask);
    VIR_FREE(cpu_mask);
632 633 634 635
    return ret;
}


636 637 638 639 640 641
static int
qemuSetupCpuCgroup(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (!virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
642
       if (vm->def->cputune.sharesSpecified) {
643 644 645 646 647 648 649 650
           virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                          _("CPU tuning is not available on this host"));
           return -1;
       } else {
           return 0;
       }
    }

651 652 653 654 655 656 657 658 659
    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;
    }
660 661 662 663 664

    return 0;
}


665
static int
666
qemuInitCgroup(virQEMUDriverPtr driver,
667
               virDomainObjPtr vm)
668
{
669
    int ret = -1;
670 671 672
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);

673 674 675
    if (!cfg->privileged)
        goto done;

676 677 678
    if (!virCgroupAvailable())
        goto done;

679 680
    virCgroupFree(&priv->cgroup);

681
    if (!vm->def->resource) {
682 683
        virDomainResourceDefPtr res;

684
        if (VIR_ALLOC(res) < 0)
685
            goto cleanup;
686

687
        if (VIR_STRDUP(res->partition, "/machine") < 0) {
688 689 690 691 692
            VIR_FREE(res);
            goto cleanup;
        }

        vm->def->resource = res;
693 694
    }

695 696 697 698 699 700
    if (vm->def->resource->partition[0] != '/') {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("Resource partition '%s' must start with '/'"),
                       vm->def->resource->partition);
        goto cleanup;
    }
701 702 703 704 705 706 707 708 709 710 711

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

715 716
        goto cleanup;
    }
717

718
 done:
719
    ret = 0;
720
 cleanup:
721 722 723
    virObjectUnref(cfg);
    return ret;
}
724

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741

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

742 743 744
    if (virCgroupNewDetectMachine(vm->def->name,
                                  "qemu",
                                  vm->pid,
745 746 747
                                  vm->def->resource ?
                                  vm->def->resource->partition :
                                  NULL,
748
                                  cfg->cgroupControllers,
749
                                  &priv->cgroup) < 0)
750
        goto cleanup;
751

752
 done:
753
    ret = 0;
754
 cleanup:
755
    virObjectUnref(cfg);
756
    return ret;
757 758
}

759 760 761 762
int
qemuSetupCgroup(virQEMUDriverPtr driver,
                virDomainObjPtr vm,
                virBitmapPtr nodemask)
763
{
764
    qemuDomainObjPrivatePtr priv = vm->privateData;
765
    virCapsPtr caps = NULL;
766
    int ret = -1;
767

768 769 770 771 772 773
    if (!vm->pid) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot setup cgroups until process is started"));
        return -1;
    }

774
    if (qemuInitCgroup(driver, vm) < 0)
775
        return -1;
776

777
    if (!priv->cgroup)
778
        return 0;
779

780 781 782
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

783 784
    if (qemuSetupDevicesCgroup(driver, vm) < 0)
        goto cleanup;
785

786 787
    if (qemuSetupBlkioCgroup(vm) < 0)
        goto cleanup;
788

789 790
    if (qemuSetupMemoryCgroup(vm) < 0)
        goto cleanup;
791

792 793
    if (qemuSetupCpuCgroup(vm) < 0)
        goto cleanup;
794

795
    if (qemuSetupCpusetCgroup(vm, nodemask, caps) < 0)
796
        goto cleanup;
797

798
    ret = 0;
799
 cleanup:
800
    virObjectUnref(caps);
801
    return ret;
802 803
}

804 805 806 807
int
qemuSetupCgroupVcpuBW(virCgroupPtr cgroup,
                      unsigned long long period,
                      long long quota)
808 809 810 811 812 813 814 815
{
    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 */
816
        if (virCgroupGetCpuCfsPeriod(cgroup, &old_period) < 0)
817 818
            return -1;

819
        if (virCgroupSetCpuCfsPeriod(cgroup, period) < 0)
820 821 822
            return -1;
    }

823 824 825
    if (quota &&
        virCgroupSetCpuCfsQuota(cgroup, quota) < 0)
        goto error;
826 827 828

    return 0;

829
 error:
830
    if (period) {
831 832 833 834 835 836
        virErrorPtr saved = virSaveLastError();
        ignore_value(virCgroupSetCpuCfsPeriod(cgroup, old_period));
        if (saved) {
            virSetError(saved);
            virFreeError(saved);
        }
837 838 839 840 841
    }

    return -1;
}

842 843 844 845 846
int
qemuSetupCgroupVcpuPin(virCgroupPtr cgroup,
                       virDomainVcpuPinDefPtr *vcpupin,
                       int nvcpupin,
                       int vcpuid)
847
{
848
    size_t i;
849 850 851

    for (i = 0; i < nvcpupin; i++) {
        if (vcpuid == vcpupin[i]->vcpuid) {
852
            return qemuSetupCgroupEmulatorPin(cgroup, vcpupin[i]->cpumask);
853 854 855
        }
    }

856 857 858
    return -1;
}

859 860 861
int
qemuSetupCgroupEmulatorPin(virCgroupPtr cgroup,
                           virBitmapPtr cpumask)
862
{
863
    int ret = -1;
864 865
    char *new_cpus = NULL;

866
    if (!(new_cpus = virBitmapFormat(cpumask)))
867 868
        goto cleanup;

869
    if (virCgroupSetCpusetCpus(cgroup, new_cpus) < 0)
870 871
        goto cleanup;

872
    ret = 0;
873
 cleanup:
874
    VIR_FREE(new_cpus);
875
    return ret;
876 877
}

878 879
int
qemuSetupCgroupForVcpu(virDomainObjPtr vm)
880 881 882
{
    virCgroupPtr cgroup_vcpu = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
883
    virDomainDefPtr def = vm->def;
884
    size_t i, j;
885 886 887
    unsigned long long period = vm->def->cputune.period;
    long long quota = vm->def->cputune.quota;

888
    if ((period || quota) &&
889
        !virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU)) {
890 891
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("cgroup cpu is required for scheduler tuning"));
H
Hu Tao 已提交
892 893 894
        return -1;
    }

895
    /* We are trying to setup cgroups for CPU pinning, which can also be done
896
     * with virProcessSetAffinity, thus the lack of cgroups is not fatal here.
897
     */
898
    if (priv->cgroup == NULL)
899 900
        return 0;

901
    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
902
        /* If we don't know VCPU<->PID mapping or all vcpu runs in the same
W
Wen Congyang 已提交
903
         * thread, we cannot control each vcpu.
904
         */
905 906
        VIR_WARN("Unable to get vcpus' pids.");
        return 0;
907 908 909
    }

    for (i = 0; i < priv->nvcpupids; i++) {
910
        if (virCgroupNewVcpu(priv->cgroup, i, true, &cgroup_vcpu) < 0)
911 912 913
            goto cleanup;

        /* move the thread for vcpu to sub dir */
914
        if (virCgroupAddTask(cgroup_vcpu, priv->vcpupids[i]) < 0)
915 916 917
            goto cleanup;

        if (period || quota) {
H
Hu Tao 已提交
918 919
            if (qemuSetupCgroupVcpuBW(cgroup_vcpu, period, quota) < 0)
                goto cleanup;
920 921
        }

922
        /* Set vcpupin in cgroup if vcpupin xml is provided */
923
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET)) {
M
Martin Kletzander 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
            /* 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;
            }
        }
939

940 941 942 943 944
        virCgroupFree(&cgroup_vcpu);
    }

    return 0;

945
 cleanup:
946 947 948 949 950
    if (cgroup_vcpu) {
        virCgroupRemove(cgroup_vcpu);
        virCgroupFree(&cgroup_vcpu);
    }

951 952 953
    return -1;
}

954 955 956 957
int
qemuSetupCgroupForEmulator(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           virBitmapPtr nodemask)
958
{
959
    virBitmapPtr cpumask = NULL;
960
    virBitmapPtr cpumap = NULL;
961
    virCgroupPtr cgroup_emulator = NULL;
962
    virDomainDefPtr def = vm->def;
963
    qemuDomainObjPrivatePtr priv = vm->privateData;
964 965
    unsigned long long period = vm->def->cputune.emulator_period;
    long long quota = vm->def->cputune.emulator_quota;
966

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

974
    if (priv->cgroup == NULL)
975 976
        return 0; /* Not supported, so claim success */

977
    if (virCgroupNewEmulator(priv->cgroup, true, &cgroup_emulator) < 0)
978 979
        goto cleanup;

980
    if (virCgroupMoveTask(priv->cgroup, cgroup_emulator) < 0)
981
        goto cleanup;
982

983 984 985 986 987
    if (def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
        if (!(cpumap = qemuPrepareCpumap(driver, nodemask)))
            goto cleanup;
        cpumask = cpumap;
    } else if (def->cputune.emulatorpin) {
988
        cpumask = def->cputune.emulatorpin->cpumask;
989
    } else if (def->cpumask) {
990
        cpumask = def->cpumask;
991
    }
992 993

    if (cpumask) {
994 995 996
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPUSET) &&
            qemuSetupCgroupEmulatorPin(cgroup_emulator, cpumask) < 0)
            goto cleanup;
H
Hu Tao 已提交
997
    }
998

999
    if (period || quota) {
1000 1001 1002 1003
        if (virCgroupHasController(priv->cgroup, VIR_CGROUP_CONTROLLER_CPU) &&
            qemuSetupCgroupVcpuBW(cgroup_emulator, period,
                                  quota) < 0)
            goto cleanup;
1004 1005
    }

1006
    virCgroupFree(&cgroup_emulator);
1007
    virBitmapFree(cpumap);
1008 1009
    return 0;

1010
 cleanup:
1011 1012
    virBitmapFree(cpumap);

1013 1014 1015 1016 1017
    if (cgroup_emulator) {
        virCgroupRemove(cgroup_emulator);
        virCgroupFree(&cgroup_emulator);
    }

1018
    return -1;
1019
}
1020

1021 1022
int
qemuRemoveCgroup(virDomainObjPtr vm)
1023
{
1024
    qemuDomainObjPrivatePtr priv = vm->privateData;
1025

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

1029
    return virCgroupRemove(priv->cgroup);
1030 1031
}

1032 1033
int
qemuAddToCgroup(virDomainObjPtr vm)
1034
{
1035
    qemuDomainObjPrivatePtr priv = vm->privateData;
1036

1037
    if (priv->cgroup == NULL)
1038 1039
        return 0; /* Not supported, so claim success */

1040
    return 0;
1041
}