qemu_cgroup.c 26.4 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 "virutil.h"
34
#include "domain_audit.h"
35 36 37 38 39 40 41

#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",
42
    "/dev/rtc", "/dev/hpet",
43 44 45 46 47
    NULL,
};
#define DEVICE_PTY_MAJOR 136
#define DEVICE_SND_MAJOR 116

48
bool qemuCgroupControllerActive(virQEMUDriverPtr driver,
49
                                int controller)
50
{
51
    return virCgroupHasController(driver->cgroup, controller);
52 53
}

54
static int
55
qemuSetupDiskPathAllow(virDomainDiskDefPtr disk,
56 57 58
                       const char *path,
                       size_t depth ATTRIBUTE_UNUSED,
                       void *opaque)
59
{
60
    qemuCgroupData *data = opaque;
61 62 63
    int rc;

    VIR_DEBUG("Process path %s for disk", path);
64 65 66
    rc = virCgroupAllowDevicePath(data->cgroup, path,
                                  (disk->readonly ? VIR_CGROUP_DEVICE_READ
                                   : VIR_CGROUP_DEVICE_RW));
67 68
    virDomainAuditCgroupPath(data->vm, data->cgroup, "allow", path,
                             disk->readonly ? "r" : "rw", rc);
69 70
    if (rc < 0) {
        if (rc == -EACCES) { /* Get this for root squash NFS */
71 72 73 74 75 76 77 78 79 80 81 82
            VIR_DEBUG("Ignoring EACCES for %s", path);
        } else {
            virReportSystemError(-rc,
                                 _("Unable to allow access for disk path %s"),
                                 path);
            return -1;
        }
    }
    return 0;
}


83
int qemuSetupDiskCgroup(virDomainObjPtr vm,
84 85 86
                        virCgroupPtr cgroup,
                        virDomainDiskDefPtr disk)
{
87
    qemuCgroupData data = { vm, cgroup };
88 89 90
    return virDomainDiskDefForeachPath(disk,
                                       true,
                                       qemuSetupDiskPathAllow,
91
                                       &data);
92 93 94
}


95 96 97 98 99
static int
qemuTeardownDiskPathDeny(virDomainDiskDefPtr disk ATTRIBUTE_UNUSED,
                         const char *path,
                         size_t depth ATTRIBUTE_UNUSED,
                         void *opaque)
100
{
101
    qemuCgroupData *data = opaque;
102 103 104
    int rc;

    VIR_DEBUG("Process path %s for disk", path);
105 106
    rc = virCgroupDenyDevicePath(data->cgroup, path,
                                 VIR_CGROUP_DEVICE_RWM);
107
    virDomainAuditCgroupPath(data->vm, data->cgroup, "deny", path, "rwm", rc);
108 109
    if (rc < 0) {
        if (rc == -EACCES) { /* Get this for root squash NFS */
110 111 112 113 114 115 116 117 118 119 120 121
            VIR_DEBUG("Ignoring EACCES for %s", path);
        } else {
            virReportSystemError(-rc,
                                 _("Unable to deny access for disk path %s"),
                                 path);
            return -1;
        }
    }
    return 0;
}


122
int qemuTeardownDiskCgroup(virDomainObjPtr vm,
123 124 125
                           virCgroupPtr cgroup,
                           virDomainDiskDefPtr disk)
{
126
    qemuCgroupData data = { vm, cgroup };
127 128 129
    return virDomainDiskDefForeachPath(disk,
                                       true,
                                       qemuTeardownDiskPathDeny,
130
                                       &data);
131 132
}

133
static int
134 135 136
qemuSetupChrSourceCgroup(virDomainDefPtr def,
                         virDomainChrSourceDefPtr dev,
                         qemuCgroupData *data)
137 138 139
{
    int rc;

140
    if (dev->type != VIR_DOMAIN_CHR_TYPE_DEV)
141 142
        return 0;

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

145
    rc = virCgroupAllowDevicePath(data->cgroup, dev->data.file.path,
146
                                  VIR_CGROUP_DEVICE_RW);
147
    virDomainAuditCgroupPath(data->vm, data->cgroup, "allow",
148
                             dev->data.file.path, "rw", rc);
149
    if (rc < 0) {
150 151
        virReportSystemError(-rc,
                             _("Unable to allow device %s for %s"),
152
                             dev->data.file.path, def->name);
153 154 155 156 157 158
        return -1;
    }

    return 0;
}

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
static int
qemuSetupChardevCgroup(virDomainDefPtr def,
                       virDomainChrDefPtr dev,
                       void *opaque)
{
    qemuCgroupData *data = opaque;

    return qemuSetupChrSourceCgroup(def, &dev->source, data);
}


static int
qemuSetupTPMCgroup(virDomainDefPtr def,
                   virDomainTPMDefPtr dev,
                   qemuCgroupData *data)
{
    int rc = 0;

    switch (dev->type) {
    case VIR_DOMAIN_TPM_TYPE_PASSTHROUGH:
        rc = qemuSetupChrSourceCgroup(def, &dev->data.passthrough.source,
                                      data);
        break;
    case VIR_DOMAIN_TPM_TYPE_LAST:
        break;
    }

    return rc;
}

189

190
int qemuSetupHostUsbDeviceCgroup(virUSBDevicePtr dev ATTRIBUTE_UNUSED,
191 192 193
                                 const char *path,
                                 void *opaque)
{
194
    qemuCgroupData *data = opaque;
195 196 197
    int rc;

    VIR_DEBUG("Process path '%s' for USB device", path);
198 199
    rc = virCgroupAllowDevicePath(data->cgroup, path,
                                  VIR_CGROUP_DEVICE_RW);
200
    virDomainAuditCgroupPath(data->vm, data->cgroup, "allow", path, "rw", rc);
201
    if (rc < 0) {
202 203 204 205 206 207 208 209 210
        virReportSystemError(-rc,
                             _("Unable to allow device %s"),
                             path);
        return -1;
    }

    return 0;
}

211
int qemuSetupCgroup(virQEMUDriverPtr driver,
212
                    virDomainObjPtr vm,
213
                    virBitmapPtr nodemask)
214 215 216 217
{
    virCgroupPtr cgroup = NULL;
    int rc;
    unsigned int i;
218
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
219
    const char *const *deviceACL =
220 221
        cfg->cgroupDeviceACL ?
        (const char *const *)cfg->cgroupDeviceACL :
222 223 224
        defaultDeviceACL;

    if (driver->cgroup == NULL)
225
        goto done; /* Not supported, so claim success */
226 227 228 229 230 231 232 233 234 235

    rc = virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 1);
    if (rc != 0) {
        virReportSystemError(-rc,
                             _("Unable to create cgroup for %s"),
                             vm->def->name);
        goto cleanup;
    }

    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
236
        qemuCgroupData data = { vm, cgroup };
237
        rc = virCgroupDenyAllDevices(cgroup);
238
        virDomainAuditCgroup(vm, cgroup, "deny", "all", rc == 0);
239 240
        if (rc != 0) {
            if (rc == -EPERM) {
241
                VIR_WARN("Group devices ACL is not accessible, disabling whitelisting");
242 243 244 245 246 247 248 249 250
                goto done;
            }

            virReportSystemError(-rc,
                                 _("Unable to deny all devices for %s"), vm->def->name);
            goto cleanup;
        }

        for (i = 0; i < vm->def->ndisks ; i++) {
251
            if (qemuSetupDiskCgroup(vm, cgroup, vm->def->disks[i]) < 0)
252 253 254
                goto cleanup;
        }

255 256
        rc = virCgroupAllowDeviceMajor(cgroup, 'c', DEVICE_PTY_MAJOR,
                                       VIR_CGROUP_DEVICE_RW);
257 258
        virDomainAuditCgroupMajor(vm, cgroup, "allow", DEVICE_PTY_MAJOR,
                                  "pty", "rw", rc == 0);
259 260 261 262 263 264
        if (rc != 0) {
            virReportSystemError(-rc, "%s",
                                 _("unable to allow /dev/pts/ devices"));
            goto cleanup;
        }

265 266 267
        if (vm->def->nsounds &&
            (!vm->def->ngraphics ||
             ((vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
268
               cfg->vncAllowHostAudio) ||
269
              (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL)))) {
270 271
            rc = virCgroupAllowDeviceMajor(cgroup, 'c', DEVICE_SND_MAJOR,
                                           VIR_CGROUP_DEVICE_RW);
272 273
            virDomainAuditCgroupMajor(vm, cgroup, "allow", DEVICE_SND_MAJOR,
                                      "sound", "rw", rc == 0);
274 275 276 277 278 279 280 281
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to allow /dev/snd/ devices"));
                goto cleanup;
            }
        }

        for (i = 0; deviceACL[i] != NULL ; i++) {
282 283 284 285 286 287
            if (access(deviceACL[i], F_OK) < 0) {
                VIR_DEBUG("Ignoring non-existant device %s",
                          deviceACL[i]);
                continue;
            }

288 289
            rc = virCgroupAllowDevicePath(cgroup, deviceACL[i],
                                          VIR_CGROUP_DEVICE_RW);
290
            virDomainAuditCgroupPath(vm, cgroup, "allow", deviceACL[i], "rw", rc);
291 292 293 294 295 296 297 298 299 300 301 302
            if (rc < 0 &&
                rc != -ENOENT) {
                virReportSystemError(-rc,
                                     _("unable to allow device %s"),
                                     deviceACL[i]);
                goto cleanup;
            }
        }

        if (virDomainChrDefForeach(vm->def,
                                   true,
                                   qemuSetupChardevCgroup,
303
                                   &data) < 0)
304 305
            goto cleanup;

306 307 308 309 310
        if (vm->def->tpm)
            qemuSetupTPMCgroup(vm->def,
                               vm->def->tpm,
                               &data);

311 312
        for (i = 0; i < vm->def->nhostdevs; i++) {
            virDomainHostdevDefPtr hostdev = vm->def->hostdevs[i];
313
            virUSBDevicePtr usb;
314 315 316 317 318

            if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
                continue;
            if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
                continue;
319 320
            if (hostdev->missing)
                continue;
321

322 323 324
            if ((usb = virUSBDeviceNew(hostdev->source.subsys.u.usb.bus,
                                       hostdev->source.subsys.u.usb.device,
                                       NULL)) == NULL)
325 326
                goto cleanup;

327 328 329
            if (virUSBDeviceFileIterate(usb, qemuSetupHostUsbDeviceCgroup,
                                        &data) < 0) {
                virUSBDeviceFree(usb);
330
                goto cleanup;
331
            }
332
            virUSBDeviceFree(usb);
333 334 335
        }
    }

336 337
    if (vm->def->blkio.weight != 0) {
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
338
            rc = virCgroupSetBlkioWeight(cgroup, vm->def->blkio.weight);
339
            if (rc != 0) {
340 341 342 343 344
                virReportSystemError(-rc,
                                     _("Unable to set io weight for domain %s"),
                                     vm->def->name);
                goto cleanup;
            }
345
        } else {
346 347
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("Block I/O tuning is not available on this host"));
348 349 350 351 352 353 354 355
            goto cleanup;
        }
    }

    if (vm->def->blkio.ndevices) {
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_BLKIO)) {
            for (i = 0; i < vm->def->blkio.ndevices; i++) {
                virBlkioDeviceWeightPtr dw = &vm->def->blkio.devices[i];
356 357
                if (!dw->weight)
                    continue;
358 359 360 361 362 363 364 365 366 367 368
                rc = virCgroupSetBlkioDeviceWeight(cgroup, dw->path,
                                                   dw->weight);
                if (rc != 0) {
                    virReportSystemError(-rc,
                                         _("Unable to set io device weight "
                                           "for domain %s"),
                                         vm->def->name);
                    goto cleanup;
                }
            }
        } else {
369
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
370
                           _("Block I/O tuning is not available on this host"));
371
            goto cleanup;
372 373 374
        }
    }

375 376 377 378
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
        unsigned long long hard_limit = vm->def->mem.hard_limit;

        if (!hard_limit) {
M
Michal Privoznik 已提交
379
            /* If there is no hard_limit set, set a reasonable one to avoid
E
Eric Blake 已提交
380 381
             * system thrashing caused by exploited qemu.  A 'reasonable
             * limit' has been chosen:
M
Michal Privoznik 已提交
382 383 384 385
             *     (1 + k) * (domain memory + total video memory) + (32MB for
             *     cache per each disk) + F
             * where k = 0.5 and F = 200MB.  The cache for disks is important as
             * kernel cache on the host side counts into the RSS limit. */
386 387 388
            hard_limit = vm->def->mem.max_balloon;
            for (i = 0; i < vm->def->nvideos; i++)
                hard_limit += vm->def->videos[i]->vram;
M
Michal Privoznik 已提交
389 390
            hard_limit = hard_limit * 1.5 + 204800;
            hard_limit += vm->def->ndisks * 32768;
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
        }

        rc = virCgroupSetMemoryHardLimit(cgroup, hard_limit);
        if (rc != 0) {
            virReportSystemError(-rc,
                                 _("Unable to set memory hard limit for domain %s"),
                                 vm->def->name);
            goto cleanup;
        }
        if (vm->def->mem.soft_limit != 0) {
            rc = virCgroupSetMemorySoftLimit(cgroup, vm->def->mem.soft_limit);
            if (rc != 0) {
                virReportSystemError(-rc,
                                     _("Unable to set memory soft limit for domain %s"),
                                     vm->def->name);
                goto cleanup;
407
            }
408
        }
409

410 411 412 413 414 415 416
        if (vm->def->mem.swap_hard_limit != 0) {
            rc = virCgroupSetMemSwapHardLimit(cgroup, vm->def->mem.swap_hard_limit);
            if (rc != 0) {
                virReportSystemError(-rc,
                                     _("Unable to set swap hard limit for domain %s"),
                                     vm->def->name);
                goto cleanup;
417 418
            }
        }
419 420 421 422 423 424 425
    } else 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"));
    } else {
        VIR_WARN("Could not autoset a RSS limit for domain %s", vm->def->name);
426 427
    }

428 429
    if (vm->def->cputune.shares != 0) {
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
430
            rc = virCgroupSetCpuShares(cgroup, vm->def->cputune.shares);
431
            if (rc != 0) {
432 433 434 435 436
                virReportSystemError(-rc,
                                     _("Unable to set io cpu shares for domain %s"),
                                     vm->def->name);
                goto cleanup;
            }
437
        } else {
438 439
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("CPU tuning is not available on this host"));
440 441 442
        }
    }

443 444
    if ((vm->def->numatune.memory.nodemask ||
         (vm->def->numatune.memory.placement_mode ==
G
Gao feng 已提交
445
          VIR_NUMA_TUNE_MEM_PLACEMENT_MODE_AUTO)) &&
H
Hu Tao 已提交
446 447
        vm->def->numatune.memory.mode == VIR_DOMAIN_NUMATUNE_MEM_STRICT &&
        qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPUSET)) {
448 449
        char *mask = NULL;
        if (vm->def->numatune.memory.placement_mode ==
G
Gao feng 已提交
450
            VIR_NUMA_TUNE_MEM_PLACEMENT_MODE_AUTO)
451
            mask = virBitmapFormat(nodemask);
452
        else
453
            mask = virBitmapFormat(vm->def->numatune.memory.nodemask);
H
Hu Tao 已提交
454
        if (!mask) {
455 456
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to convert memory nodemask"));
H
Hu Tao 已提交
457 458 459 460 461 462 463 464 465 466 467 468
            goto cleanup;
        }

        rc = virCgroupSetCpusetMems(cgroup, mask);
        VIR_FREE(mask);
        if (rc != 0) {
            virReportSystemError(-rc,
                                 _("Unable to set cpuset.mems for domain %s"),
                                 vm->def->name);
            goto cleanup;
        }
    }
469
done:
470
    virObjectUnref(cfg);
471 472 473 474
    virCgroupFree(&cgroup);
    return 0;

cleanup:
475
    virObjectUnref(cfg);
476 477 478 479 480 481 482
    if (cgroup) {
        virCgroupRemove(cgroup);
        virCgroupFree(&cgroup);
    }
    return -1;
}

483 484 485 486 487 488 489 490 491 492 493 494 495 496
int qemuSetupCgroupVcpuBW(virCgroupPtr cgroup, unsigned long long period,
                          long long quota)
{
    int rc;
    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 */
        rc = virCgroupGetCpuCfsPeriod(cgroup, &old_period);
        if (rc < 0) {
            virReportSystemError(-rc,
W
Wen Congyang 已提交
497
                                 "%s", _("Unable to get cpu bandwidth period"));
498 499 500 501 502 503
            return -1;
        }

        rc = virCgroupSetCpuCfsPeriod(cgroup, period);
        if (rc < 0) {
            virReportSystemError(-rc,
W
Wen Congyang 已提交
504
                                 "%s", _("Unable to set cpu bandwidth period"));
505 506 507 508 509 510 511 512
            return -1;
        }
    }

    if (quota) {
        rc = virCgroupSetCpuCfsQuota(cgroup, quota);
        if (rc < 0) {
            virReportSystemError(-rc,
W
Wen Congyang 已提交
513
                                 "%s", _("Unable to set cpu bandwidth quota"));
514 515 516 517 518 519 520 521 522 523
            goto cleanup;
        }
    }

    return 0;

cleanup:
    if (period) {
        rc = virCgroupSetCpuCfsPeriod(cgroup, old_period);
        if (rc < 0)
524
            virReportSystemError(-rc, "%s",
525
                                 _("Unable to rollback cpu bandwidth period"));
526 527 528 529 530
    }

    return -1;
}

531 532 533 534 535
int qemuSetupCgroupVcpuPin(virCgroupPtr cgroup,
                           virDomainVcpuPinDefPtr *vcpupin,
                           int nvcpupin,
                           int vcpuid)
{
536
    int i;
537 538 539

    for (i = 0; i < nvcpupin; i++) {
        if (vcpuid == vcpupin[i]->vcpuid) {
540
            return qemuSetupCgroupEmulatorPin(cgroup, vcpupin[i]->cpumask);
541 542 543
        }
    }

544 545 546 547
    return -1;
}

int qemuSetupCgroupEmulatorPin(virCgroupPtr cgroup,
548
                               virBitmapPtr cpumask)
549 550 551 552
{
    int rc = 0;
    char *new_cpus = NULL;

553
    new_cpus = virBitmapFormat(cpumask);
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
    if (!new_cpus) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to convert cpu mask"));
        rc = -1;
        goto cleanup;
    }

    rc = virCgroupSetCpusetCpus(cgroup, new_cpus);
    if (rc < 0) {
        virReportSystemError(-rc,
                             "%s",
                             _("Unable to set cpuset.cpus"));
        goto cleanup;
    }

569 570 571 572 573
cleanup:
    VIR_FREE(new_cpus);
    return rc;
}

574
int qemuSetupCgroupForVcpu(virQEMUDriverPtr driver, virDomainObjPtr vm)
575 576 577 578
{
    virCgroupPtr cgroup = NULL;
    virCgroupPtr cgroup_vcpu = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
579
    virDomainDefPtr def = vm->def;
580
    int rc;
M
Martin Kletzander 已提交
581
    unsigned int i, j;
582 583 584
    unsigned long long period = vm->def->cputune.period;
    long long quota = vm->def->cputune.quota;

585
    if ((period || quota) &&
586 587 588 589
        (!driver->cgroup ||
         !qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU))) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("cgroup cpu is required for scheduler tuning"));
H
Hu Tao 已提交
590 591 592
        return -1;
    }

593 594 595 596 597 598 599
    /* 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.
     */
    if (driver->cgroup == NULL)
        return 0;

600 601 602 603 604 605 606 607 608
    rc = virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0);
    if (rc != 0) {
        virReportSystemError(-rc,
                             _("Unable to find cgroup for %s"),
                             vm->def->name);
        goto cleanup;
    }

    if (priv->nvcpupids == 0 || priv->vcpupids[0] == vm->pid) {
609
        /* If we don't know VCPU<->PID mapping or all vcpu runs in the same
W
Wen Congyang 已提交
610
         * thread, we cannot control each vcpu.
611
         */
612 613 614
        VIR_WARN("Unable to get vcpus' pids.");
        virCgroupFree(&cgroup);
        return 0;
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    }

    for (i = 0; i < priv->nvcpupids; i++) {
        rc = virCgroupForVcpu(cgroup, i, &cgroup_vcpu, 1);
        if (rc < 0) {
            virReportSystemError(-rc,
                                 _("Unable to create vcpu cgroup for %s(vcpu:"
                                   " %d)"),
                                 vm->def->name, i);
            goto cleanup;
        }

        /* move the thread for vcpu to sub dir */
        rc = virCgroupAddTask(cgroup_vcpu, priv->vcpupids[i]);
        if (rc < 0) {
            virReportSystemError(-rc,
                                 _("unable to add vcpu %d task %d to cgroup"),
                                 i, priv->vcpupids[i]);
            goto cleanup;
        }

        if (period || quota) {
H
Hu Tao 已提交
637 638
            if (qemuSetupCgroupVcpuBW(cgroup_vcpu, period, quota) < 0)
                goto cleanup;
639 640
        }

641
        /* Set vcpupin in cgroup if vcpupin xml is provided */
M
Martin Kletzander 已提交
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPUSET)) {
            /* 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;
            }
        }
658

659 660 661 662 663 664 665
        virCgroupFree(&cgroup_vcpu);
    }

    virCgroupFree(&cgroup);
    return 0;

cleanup:
666 667 668 669 670
    if (cgroup_vcpu) {
        virCgroupRemove(cgroup_vcpu);
        virCgroupFree(&cgroup_vcpu);
    }

671 672 673 674 675 676 677 678
    if (cgroup) {
        virCgroupRemove(cgroup);
        virCgroupFree(&cgroup);
    }

    return -1;
}

679
int qemuSetupCgroupForEmulator(virQEMUDriverPtr driver,
680 681
                               virDomainObjPtr vm,
                               virBitmapPtr nodemask)
682
{
683
    virBitmapPtr cpumask = NULL;
684
    virBitmapPtr cpumap = NULL;
685 686
    virCgroupPtr cgroup = NULL;
    virCgroupPtr cgroup_emulator = NULL;
687
    virDomainDefPtr def = vm->def;
688 689
    unsigned long long period = vm->def->cputune.emulator_period;
    long long quota = vm->def->cputune.emulator_quota;
690
    int rc;
691

692 693 694 695 696 697 698 699
    if ((period || quota) &&
        (!driver->cgroup ||
         !qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU))) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("cgroup cpu is required for scheduler tuning"));
        return -1;
    }

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    if (driver->cgroup == NULL)
        return 0; /* Not supported, so claim success */

    rc = virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0);
    if (rc != 0) {
        virReportSystemError(-rc,
                             _("Unable to find cgroup for %s"),
                             vm->def->name);
        goto cleanup;
    }

    rc = virCgroupForEmulator(cgroup, &cgroup_emulator, 1);
    if (rc < 0) {
        virReportSystemError(-rc,
                             _("Unable to create emulator cgroup for %s"),
                             vm->def->name);
        goto cleanup;
    }

719 720 721 722 723 724 725
    rc = virCgroupMoveTask(cgroup, cgroup_emulator);
    if (rc < 0) {
        virReportSystemError(-rc,
                             _("Unable to move tasks from domain cgroup to "
                               "emulator cgroup for %s"),
                             vm->def->name);
        goto cleanup;
726 727
    }

728 729 730 731 732
    if (def->placement_mode == VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {
        if (!(cpumap = qemuPrepareCpumap(driver, nodemask)))
            goto cleanup;
        cpumask = cpumap;
    } else if (def->cputune.emulatorpin) {
733
        cpumask = def->cputune.emulatorpin->cpumask;
734
    } else if (def->cpumask) {
735
        cpumask = def->cpumask;
736
    }
737 738 739 740 741 742 743 744

    if (cpumask) {
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPUSET)) {
            rc = qemuSetupCgroupEmulatorPin(cgroup_emulator, cpumask);
            if (rc < 0)
                goto cleanup;
        }
        cpumask = NULL; /* sanity */
H
Hu Tao 已提交
745
    }
746

747 748
    if (period || quota) {
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
H
Hu Tao 已提交
749 750
            if ((rc = qemuSetupCgroupVcpuBW(cgroup_emulator, period,
                                            quota)) < 0)
751 752 753 754
                goto cleanup;
        }
    }

755 756
    virCgroupFree(&cgroup_emulator);
    virCgroupFree(&cgroup);
757
    virBitmapFree(cpumap);
758 759 760
    return 0;

cleanup:
761 762
    virBitmapFree(cpumap);

763 764 765 766 767 768 769 770 771 772 773 774
    if (cgroup_emulator) {
        virCgroupRemove(cgroup_emulator);
        virCgroupFree(&cgroup_emulator);
    }

    if (cgroup) {
        virCgroupRemove(cgroup);
        virCgroupFree(&cgroup);
    }

    return rc;
}
775

776
int qemuRemoveCgroup(virQEMUDriverPtr driver,
777 778 779 780 781 782 783 784 785 786 787 788
                     virDomainObjPtr vm,
                     int quiet)
{
    virCgroupPtr cgroup;
    int rc;

    if (driver->cgroup == NULL)
        return 0; /* Not supported, so claim success */

    rc = virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0);
    if (rc != 0) {
        if (!quiet)
789 790 791
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find cgroup for %s"),
                           vm->def->name);
792 793 794 795 796 797 798 799
        return rc;
    }

    rc = virCgroupRemove(cgroup);
    virCgroupFree(&cgroup);
    return rc;
}

800
int qemuAddToCgroup(virQEMUDriverPtr driver,
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
                    virDomainDefPtr def)
{
    virCgroupPtr cgroup = NULL;
    int ret = -1;
    int rc;

    if (driver->cgroup == NULL)
        return 0; /* Not supported, so claim success */

    rc = virCgroupForDomain(driver->cgroup, def->name, &cgroup, 0);
    if (rc != 0) {
        virReportSystemError(-rc,
                             _("unable to find cgroup for domain %s"),
                             def->name);
        goto cleanup;
    }

    rc = virCgroupAddTask(cgroup, getpid());
    if (rc != 0) {
        virReportSystemError(-rc,
                             _("unable to add domain %s task %d to cgroup"),
                             def->name, getpid());
        goto cleanup;
    }

    ret = 0;

cleanup:
    virCgroupFree(&cgroup);
    return ret;
}