libxl_driver.c 128.6 KB
Newer Older
1 2 3
/*
 * libxl_driver.c: core driver methods for managing libxenlight domains
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
5
 * Copyright (C) 2011-2014 SUSE LINUX Products GmbH, Nuernberg, Germany.
6
 * Copyright (C) 2011 Univention GmbH.
J
Jim Fehlig 已提交
7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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
19
 * License along with this library.  If not, see
O
Osier Yang 已提交
20
 * <http://www.gnu.org/licenses/>.
M
Markus Groß 已提交
21 22 23 24 25
 *
 * Authors:
 *     Jim Fehlig <jfehlig@novell.com>
 *     Markus Groß <gross@univention.de>
 *     Daniel P. Berrange <berrange@redhat.com>
J
Jim Fehlig 已提交
26 27 28 29
 */

#include <config.h>

30
#include <math.h>
J
Jim Fehlig 已提交
31
#include <libxl.h>
32
#include <libxl_utils.h>
33
#include <fcntl.h>
34
#include <regex.h>
J
Jim Fehlig 已提交
35 36

#include "internal.h"
37
#include "virlog.h"
38
#include "virerror.h"
39
#include "virconf.h"
J
Jim Fehlig 已提交
40
#include "datatypes.h"
E
Eric Blake 已提交
41
#include "virfile.h"
42
#include "viralloc.h"
43
#include "viruuid.h"
44
#include "vircommand.h"
J
Jim Fehlig 已提交
45
#include "libxl_domain.h"
J
Jim Fehlig 已提交
46 47
#include "libxl_driver.h"
#include "libxl_conf.h"
48
#include "xen_xm.h"
49
#include "virtypedparam.h"
M
Martin Kletzander 已提交
50
#include "viruri.h"
51
#include "virstring.h"
52
#include "virsysinfo.h"
53
#include "viraccessapicheck.h"
54
#include "viratomic.h"
J
Jim Fehlig 已提交
55 56 57 58 59 60 61 62 63

#define VIR_FROM_THIS VIR_FROM_LIBXL

#define LIBXL_DOM_REQ_POWEROFF 0
#define LIBXL_DOM_REQ_REBOOT   1
#define LIBXL_DOM_REQ_SUSPEND  2
#define LIBXL_DOM_REQ_CRASH    3
#define LIBXL_DOM_REQ_HALT     4

64 65
#define LIBXL_CONFIG_FORMAT_XM "xen-xm"

66 67 68
/* Number of Xen scheduler parameters */
#define XEN_SCHED_CREDIT_NPARAM   2

69

J
Jim Fehlig 已提交
70 71 72
static libxlDriverPrivatePtr libxl_driver = NULL;

/* Function declarations */
73 74
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
75 76
                           void *opaque);

J
Jim Fehlig 已提交
77
static int
78 79
libxlVmStart(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
             bool start_paused, int restore_fd);
J
Jim Fehlig 已提交
80

J
Jim Fehlig 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

/* Function definitions */
static virDomainObjPtr
libxlDomObjFromDomain(virDomainPtr dom)
{
    virDomainObjPtr vm;
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
    if (!vm) {
        virUUIDFormat(dom->uuid, uuidstr);
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s' (%s)"),
                       uuidstr, dom->name);
        return NULL;
    }

    return vm;
}

102
static void
103
libxlDomainEventQueue(libxlDriverPrivatePtr driver, virObjectEventPtr event)
104
{
105
    virObjectEventStateQueue(driver->domainEventState, event);
106 107
}

108 109
static int
libxlAutostartDomain(virDomainObjPtr vm,
110 111 112 113
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    virErrorPtr err;
114
    int ret = -1;
115

116
    virObjectLock(vm);
117 118 119
    virResetLastError();

    if (vm->autostart && !virDomainObjIsActive(vm) &&
120
        libxlVmStart(driver, vm, false, -1) < 0) {
121 122 123 124
        err = virGetLastError();
        VIR_ERROR(_("Failed to autostart VM '%s': %s"),
                  vm->def->name,
                  err ? err->message : _("unknown error"));
125
        goto cleanup;
126 127
    }

128 129
    ret = 0;
cleanup:
130
    virObjectUnlock(vm);
131
    return ret;
132 133
}

134 135 136 137
static int
libxlDoNodeGetInfo(libxlDriverPrivatePtr driver, virNodeInfoPtr info)
{
    libxl_physinfo phy_info;
138
    virArch hostarch = virArchFromHost();
139 140
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    int ret = -1;
141

142
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
143 144
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
145
        goto cleanup;
146 147
    }

148
    if (virStrcpyStatic(info->model, virArchToString(hostarch)) == NULL) {
149 150
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("machine type %s too big for destination"),
151
                       virArchToString(hostarch));
152
        goto cleanup;
153 154
    }

155
    info->memory = phy_info.total_pages * (cfg->verInfo->pagesize / 1024);
156 157 158 159 160 161
    info->cpus = phy_info.nr_cpus;
    info->nodes = phy_info.nr_nodes;
    info->cores = phy_info.cores_per_socket;
    info->threads = phy_info.threads_per_core;
    info->sockets = 1;
    info->mhz = phy_info.cpu_khz / 1000;
162 163 164 165 166 167

    ret = 0;

cleanup:
    virObjectUnref(cfg);
    return ret;
168 169
}

170 171 172
static char *
libxlDomainManagedSavePath(libxlDriverPrivatePtr driver, virDomainObjPtr vm) {
    char *ret;
173
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
174

175 176
    ignore_value(virAsprintf(&ret, "%s/%s.save", cfg->saveDir, vm->def->name));
    virObjectUnref(cfg);
177 178 179
    return ret;
}

180 181 182 183 184 185 186 187 188 189
/*
 * This internal function expects the driver lock to already be held on
 * entry.
 */
static int ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5)
libxlSaveImageOpen(libxlDriverPrivatePtr driver,
                   libxlDriverConfigPtr cfg,
                   const char *from,
                   virDomainDefPtr *ret_def,
                   libxlSavefileHeaderPtr ret_hdr)
190 191 192 193 194 195
{
    int fd;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    char *xml = NULL;

L
Laine Stump 已提交
196
    if ((fd = virFileOpenAs(from, O_RDONLY, 0, -1, -1, 0)) < 0) {
197 198
        virReportSystemError(-fd,
                             _("Failed to open domain image file '%s'"), from);
199 200 201 202
        goto error;
    }

    if (saferead(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
203 204
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to read libxl header"));
205 206 207 208
        goto error;
    }

    if (memcmp(hdr.magic, LIBXL_SAVE_MAGIC, sizeof(hdr.magic))) {
209
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("image magic is incorrect"));
210 211 212 213
        goto error;
    }

    if (hdr.version > LIBXL_SAVE_VERSION) {
214 215 216
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("image version is not supported (%d > %d)"),
                       hdr.version, LIBXL_SAVE_VERSION);
217 218 219 220
        goto error;
    }

    if (hdr.xmlLen <= 0) {
221 222
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("invalid XML length: %d"), hdr.xmlLen);
223 224 225
        goto error;
    }

226
    if (VIR_ALLOC_N(xml, hdr.xmlLen) < 0)
227 228 229
        goto error;

    if (saferead(fd, xml, hdr.xmlLen) != hdr.xmlLen) {
230
        virReportError(VIR_ERR_OPERATION_FAILED, "%s", _("failed to read XML"));
231 232 233
        goto error;
    }

234
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
235
                                        1 << VIR_DOMAIN_VIRT_XEN,
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto error;

    VIR_FREE(xml);

    *ret_def = def;
    *ret_hdr = hdr;

    return fd;

error:
    VIR_FREE(xml);
    virDomainDefFree(def);
    VIR_FORCE_CLOSE(fd);
    return -1;
}

J
Jim Fehlig 已提交
253 254 255 256 257 258
/*
 * Cleanup function for domain that has reached shutoff state.
 *
 * virDomainObjPtr should be locked on invocation
 */
static void
J
Jiri Denemark 已提交
259 260 261
libxlVmCleanup(libxlDriverPrivatePtr driver,
               virDomainObjPtr vm,
               virDomainShutoffReason reason)
J
Jim Fehlig 已提交
262 263
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
264
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
265 266
    int vnc_port;
    char *file;
267
    size_t i;
J
Jim Fehlig 已提交
268

269 270
    vm->def->id = -1;

J
Jim Fehlig 已提交
271 272 273
    if (priv->deathW) {
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
        priv->deathW = NULL;
J
Jim Fehlig 已提交
274 275
    }

276
    if (vm->persistent)
J
Jiri Denemark 已提交
277
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, reason);
J
Jim Fehlig 已提交
278

279
    if (virAtomicIntDecAndTest(&driver->nactive) && driver->inhibitCallback)
280 281
        driver->inhibitCallback(false, driver->inhibitOpaque);

J
Jim Fehlig 已提交
282 283 284 285 286
    if ((vm->def->ngraphics == 1) &&
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics[0]->data.vnc.autoport) {
        vnc_port = vm->def->graphics[0]->data.vnc.port;
        if (vnc_port >= LIBXL_VNC_PORT_MIN) {
287 288
            if (virPortAllocatorRelease(driver->reservedVNCPorts,
                                        vnc_port) < 0)
J
Jim Fehlig 已提交
289 290 291 292
                VIR_DEBUG("Could not mark port %d as unused", vnc_port);
        }
    }

293 294 295
    /* Remove any cputune settings */
    if (vm->def->cputune.nvcpupin) {
        for (i = 0; i < vm->def->cputune.nvcpupin; ++i) {
296
            virBitmapFree(vm->def->cputune.vcpupin[i]->cpumask);
297 298 299 300 301 302
            VIR_FREE(vm->def->cputune.vcpupin[i]);
        }
        VIR_FREE(vm->def->cputune.vcpupin);
        vm->def->cputune.nvcpupin = 0;
    }

303
    if (virAsprintf(&file, "%s/%s.xml", cfg->stateDir, vm->def->name) > 0) {
J
Jim Fehlig 已提交
304 305 306 307
        if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR)
            VIR_DEBUG("Failed to remove domain XML for %s", vm->def->name);
        VIR_FREE(file);
    }
308 309 310 311 312 313 314

    if (vm->newDef) {
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->def->id = -1;
        vm->newDef = NULL;
    }
J
Jim Fehlig 已提交
315

316
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
317 318 319
}

/*
J
Jim Fehlig 已提交
320 321 322 323 324
 * Handle previously registered event notification from libxenlight.
 *
 * Note: Xen 4.3 removed the const from the event handler signature.
 * Detect which signature to use based on
 * LIBXL_HAVE_NONCONST_EVENT_OCCURS_EVENT_ARG.
J
Jim Fehlig 已提交
325
 */
J
Jim Fehlig 已提交
326 327 328 329 330 331 332

#ifdef LIBXL_HAVE_NONCONST_EVENT_OCCURS_EVENT_ARG
# define VIR_LIBXL_EVENT_CONST /* empty */
#else
# define VIR_LIBXL_EVENT_CONST const
#endif

333 334 335 336 337 338 339
struct libxlShutdownThreadInfo
{
    virDomainObjPtr vm;
    libxl_event *event;
};


340
static void
341
libxlDomainShutdownThread(void *opaque)
J
Jim Fehlig 已提交
342 343
{
    libxlDriverPrivatePtr driver = libxl_driver;
344 345 346 347 348
    struct libxlShutdownThreadInfo *shutdown_info = opaque;
    virDomainObjPtr vm = shutdown_info->vm;
    libxlDomainObjPrivatePtr priv = vm->privateData;
    libxl_event *ev = shutdown_info->event;
    libxl_ctx *ctx = priv->ctx;
349
    virObjectEventPtr dom_event = NULL;
350 351
    libxl_shutdown_reason xl_reason = ev->u.domain_shutdown.shutdown_reason;
    virDomainShutoffReason reason;
J
Jim Fehlig 已提交
352

353
    virObjectLock(vm);
J
Jiri Denemark 已提交
354

355 356 357 358 359 360 361 362 363 364 365
    switch (xl_reason) {
        case LIBXL_SHUTDOWN_REASON_POWEROFF:
        case LIBXL_SHUTDOWN_REASON_CRASH:
            if (xl_reason == LIBXL_SHUTDOWN_REASON_CRASH) {
                dom_event = virDomainEventLifecycleNewFromObj(vm,
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_CRASHED);
                reason = VIR_DOMAIN_SHUTOFF_CRASHED;
            } else {
                reason = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
            }
J
Jim Fehlig 已提交
366 367
            libxl_domain_destroy(ctx, vm->def->id, NULL);
            libxlVmCleanup(driver, vm, reason);
368 369 370 371 372 373
            if (!vm->persistent) {
                virDomainObjListRemove(driver->domains, vm);
                vm = NULL;
            }
            break;
        case LIBXL_SHUTDOWN_REASON_REBOOT:
J
Jim Fehlig 已提交
374 375
            libxl_domain_destroy(ctx, vm->def->id, NULL);
            libxlVmCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
376 377 378 379 380
            libxlVmStart(driver, vm, 0, -1);
            break;
        default:
            VIR_INFO("Unhandled shutdown_reason %d", xl_reason);
            break;
J
Jim Fehlig 已提交
381 382 383
    }

    if (vm)
384
        virObjectUnlock(vm);
385
    if (dom_event)
386
        libxlDomainEventQueue(driver, dom_event);
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    libxl_event_free(ctx, ev);
    VIR_FREE(shutdown_info);
}

static void
libxlEventHandler(void *data, VIR_LIBXL_EVENT_CONST libxl_event *event)
{
    virDomainObjPtr vm = data;
    libxlDomainObjPrivatePtr priv = vm->privateData;
    libxl_shutdown_reason xl_reason = event->u.domain_shutdown.shutdown_reason;
    struct libxlShutdownThreadInfo *shutdown_info;
    virThread thread;

    if (event->type != LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN) {
        VIR_INFO("Unhandled event type %d", event->type);
        goto error;
    }

    /*
     * Similar to the xl implementation, ignore SUSPEND.  Any actions needed
     * after calling libxl_domain_suspend() are handled by it's callers.
     */
    if (xl_reason == LIBXL_SHUTDOWN_REASON_SUSPEND)
        goto error;

    /*
     * Start a thread to handle shutdown.  We don't want to be tying up
     * libxl's event machinery by doing a potentially lengthy shutdown.
     */
    if (VIR_ALLOC(shutdown_info) < 0)
        goto error;

    shutdown_info->vm = data;
    shutdown_info->event = (libxl_event *)event;
    if (virThreadCreate(&thread, false, libxlDomainShutdownThread,
                        shutdown_info) < 0) {
        /*
         * Not much we can do on error here except log it.
         */
        VIR_ERROR(_("Failed to create thread to handle domain shutdown"));
        goto error;
    }

    /*
     * libxl_event freed in shutdown thread
     */
    return;

error:
J
Jim Fehlig 已提交
436 437
    /* Cast away any const */
    libxl_event_free(priv->ctx, (libxl_event *)event);
J
Jim Fehlig 已提交
438 439
}

J
Jim Fehlig 已提交
440 441 442 443 444 445
static const struct libxl_event_hooks ev_hooks = {
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlEventHandler,
    .disaster = NULL,
};

J
Jim Fehlig 已提交
446
/*
447
 * Register for domain events emitted by libxl.
J
Jim Fehlig 已提交
448 449
 */
static int
450
libxlDomEventsRegister(virDomainObjPtr vm)
J
Jim Fehlig 已提交
451 452 453
{
    libxlDomainObjPrivatePtr priv = vm->privateData;

J
Jim Fehlig 已提交
454
    libxl_event_register_callbacks(priv->ctx, &ev_hooks, vm);
J
Jim Fehlig 已提交
455

456
    /* Always enable domain death events */
J
Jim Fehlig 已提交
457
    if (libxl_evenable_domain_death(priv->ctx, vm->def->id, 0, &priv->deathW))
J
Jim Fehlig 已提交
458 459 460 461 462
        goto error;

    return 0;

error:
463
    if (priv->deathW) {
J
Jim Fehlig 已提交
464
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
465 466
        priv->deathW = NULL;
    }
J
Jim Fehlig 已提交
467 468 469
    return -1;
}

470
static int
471
libxlDomainSetVcpuAffinities(libxlDriverPrivatePtr driver, virDomainObjPtr vm)
472 473 474
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
    virDomainDefPtr def = vm->def;
J
Jim Fehlig 已提交
475
    libxl_bitmap map;
476
    virBitmapPtr cpumask = NULL;
477 478 479
    uint8_t *cpumap = NULL;
    virNodeInfo nodeinfo;
    size_t cpumaplen;
480 481
    int vcpu;
    size_t i;
482 483 484 485 486 487 488 489 490 491 492
    int ret = -1;

    if (libxlDoNodeGetInfo(driver, &nodeinfo) < 0)
        goto cleanup;

    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));

    for (vcpu = 0; vcpu < def->cputune.nvcpupin; ++vcpu) {
        if (vcpu != def->cputune.vcpupin[vcpu]->vcpuid)
            continue;

493
        if (VIR_ALLOC_N(cpumap, cpumaplen) < 0)
494 495
            goto cleanup;

496
        cpumask = def->cputune.vcpupin[vcpu]->cpumask;
497

498 499 500 501
        for (i = 0; i < virBitmapSize(cpumask); ++i) {
            bool bit;
            ignore_value(virBitmapGetBit(cpumask, i, &bit));
            if (bit)
502
                VIR_USE_CPU(cpumap, i);
503 504 505 506 507
        }

        map.size = cpumaplen;
        map.map = cpumap;

J
Jim Fehlig 已提交
508
        if (libxl_set_vcpuaffinity(priv->ctx, def->id, vcpu, &map) != 0) {
509 510
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
511 512 513 514 515 516 517 518 519 520 521 522 523
            goto cleanup;
        }

        VIR_FREE(cpumap);
    }

    ret = 0;

cleanup:
    VIR_FREE(cpumap);
    return ret;
}

M
Markus Groß 已提交
524 525 526 527 528
static int
libxlFreeMem(libxlDomainObjPrivatePtr priv, libxl_domain_config *d_config)
{
    uint32_t needed_mem;
    uint32_t free_mem;
529
    size_t i;
M
Markus Groß 已提交
530 531 532 533
    int ret = -1;
    int tries = 3;
    int wait_secs = 10;

J
Jim Fehlig 已提交
534
    if ((ret = libxl_domain_need_memory(priv->ctx, &d_config->b_info,
M
Markus Groß 已提交
535 536
                                        &needed_mem)) >= 0) {
        for (i = 0; i < tries; ++i) {
J
Jim Fehlig 已提交
537
            if ((ret = libxl_get_free_memory(priv->ctx, &free_mem)) < 0)
M
Markus Groß 已提交
538 539 540 541 542 543 544
                break;

            if (free_mem >= needed_mem) {
                ret = 0;
                break;
            }

J
Jim Fehlig 已提交
545
            if ((ret = libxl_set_memory_target(priv->ctx, 0,
M
Markus Groß 已提交
546 547 548 549
                                               free_mem - needed_mem,
                                               /* relative */ 1, 0)) < 0)
                break;

J
Jim Fehlig 已提交
550
            ret = libxl_wait_for_free_memory(priv->ctx, 0, needed_mem,
M
Markus Groß 已提交
551 552 553 554
                                             wait_secs);
            if (ret == 0 || ret != ERROR_NOMEM)
                break;

J
Jim Fehlig 已提交
555
            if ((ret = libxl_wait_for_memory_target(priv->ctx, 0, 1)) < 0)
M
Markus Groß 已提交
556 557 558 559 560 561 562
                break;
        }
    }

    return ret;
}

J
Jim Fehlig 已提交
563 564 565 566 567 568
/*
 * Start a domain through libxenlight.
 *
 * virDomainObjPtr should be locked on invocation
 */
static int
569 570
libxlVmStart(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
             bool start_paused, int restore_fd)
J
Jim Fehlig 已提交
571 572
{
    libxl_domain_config d_config;
573
    virDomainDefPtr def = NULL;
574
    virObjectEventPtr event = NULL;
575
    libxlSavefileHeader hdr;
J
Jim Fehlig 已提交
576 577 578
    int ret;
    uint32_t domid = 0;
    char *dom_xml = NULL;
579 580
    char *managed_save_path = NULL;
    int managed_save_fd = -1;
J
Jim Fehlig 已提交
581
    libxlDomainObjPrivatePtr priv = vm->privateData;
582
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
B
Bamvor Jian Zhang 已提交
583 584 585
#ifdef LIBXL_HAVE_DOMAIN_CREATE_RESTORE_PARAMS
    libxl_domain_restore_params params;
#endif
J
Jim Fehlig 已提交
586

J
Jim Fehlig 已提交
587 588 589
    if (libxlDomainObjPrivateInitCtx(vm) < 0)
        goto error;

590 591 592
    /* If there is a managed saved state restore it instead of starting
     * from scratch. The old state is removed once the restoring succeeded. */
    if (restore_fd < 0) {
593 594
        managed_save_path = libxlDomainManagedSavePath(driver, vm);
        if (managed_save_path == NULL)
595 596
            goto error;

597
        if (virFileExists(managed_save_path)) {
598

599 600
            managed_save_fd = libxlSaveImageOpen(driver, cfg,
                                                 managed_save_path,
601 602
                                                 &def, &hdr);
            if (managed_save_fd < 0)
603 604
                goto error;

605 606
            restore_fd = managed_save_fd;

607 608 609 610 611 612
            if (STRNEQ(vm->def->name, def->name) ||
                memcmp(vm->def->uuid, def->uuid, VIR_UUID_BUFLEN)) {
                char vm_uuidstr[VIR_UUID_STRING_BUFLEN];
                char def_uuidstr[VIR_UUID_STRING_BUFLEN];
                virUUIDFormat(vm->def->uuid, vm_uuidstr);
                virUUIDFormat(def->uuid, def_uuidstr);
613 614 615 616
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("cannot restore domain '%s' uuid %s from a file"
                                 " which belongs to domain '%s' uuid %s"),
                               vm->def->name, vm_uuidstr, def->name, def_uuidstr);
617 618 619
                goto error;
            }

620
            virDomainObjAssignDef(vm, def, true, NULL);
621 622
            def = NULL;

623
            if (unlink(managed_save_path) < 0)
624 625
                VIR_WARN("Failed to remove the managed state %s",
                         managed_save_path);
626

627
            vm->hasManagedSave = false;
628
        }
629
        VIR_FREE(managed_save_path);
630 631
    }

J
Jim Fehlig 已提交
632
    libxl_domain_config_init(&d_config);
J
Jim Fehlig 已提交
633

634
    if (libxlBuildDomainConfig(driver, vm, &d_config) < 0)
635
        goto error;
J
Jim Fehlig 已提交
636

637
    if (cfg->autoballoon && libxlFreeMem(priv, &d_config) < 0) {
638 639 640
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to get free memory for domain '%s'"),
                       d_config.c_info.name);
M
Markus Groß 已提交
641 642
        goto error;
    }
J
Jim Fehlig 已提交
643

J
Jim Fehlig 已提交
644 645
    /* use as synchronous operations => ao_how = NULL and no intermediate reports => ao_progress = NULL */

646
    if (restore_fd < 0) {
J
Jim Fehlig 已提交
647 648
        ret = libxl_domain_create_new(priv->ctx, &d_config,
                                      &domid, NULL, NULL);
649
    } else {
B
Bamvor Jian Zhang 已提交
650 651 652 653 654
#ifdef LIBXL_HAVE_DOMAIN_CREATE_RESTORE_PARAMS
        params.checkpointed_stream = 0;
        ret = libxl_domain_create_restore(priv->ctx, &d_config, &domid,
                                          restore_fd, &params, NULL, NULL);
#else
J
Jim Fehlig 已提交
655 656
        ret = libxl_domain_create_restore(priv->ctx, &d_config, &domid,
                                          restore_fd, NULL, NULL);
B
Bamvor Jian Zhang 已提交
657
#endif
658
    }
659

J
Jim Fehlig 已提交
660
    if (ret) {
661
        if (restore_fd < 0)
662 663 664
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to create new domain '%s'"),
                           d_config.c_info.name);
665
        else
666 667 668
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to restore domain '%s'"),
                           d_config.c_info.name);
J
Jim Fehlig 已提交
669 670 671
        goto error;
    }

672
    vm->def->id = domid;
673 674 675
    if (libxlDomEventsRegister(vm) < 0)
        goto error;

676
    if ((dom_xml = virDomainDefFormat(vm->def, 0)) == NULL)
J
Jim Fehlig 已提交
677 678
        goto error;

J
Jim Fehlig 已提交
679
    if (libxl_userdata_store(priv->ctx, domid, "libvirt-xml",
J
Jim Fehlig 已提交
680
                             (uint8_t *)dom_xml, strlen(dom_xml) + 1)) {
681 682
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to store userdata"));
J
Jim Fehlig 已提交
683 684 685
        goto error;
    }

686
    if (libxlDomainSetVcpuAffinities(driver, vm) < 0)
687 688
        goto error;

J
Jim Fehlig 已提交
689
    if (!start_paused) {
J
Jim Fehlig 已提交
690
        libxl_domain_unpause(priv->ctx, domid);
J
Jiri Denemark 已提交
691
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
J
Jim Fehlig 已提交
692
    } else {
J
Jiri Denemark 已提交
693
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
J
Jim Fehlig 已提交
694 695
    }

696

697
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
J
Jim Fehlig 已提交
698 699
        goto error;

700
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
701 702
        driver->inhibitCallback(true, driver->inhibitOpaque);

703
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STARTED,
704 705 706
                                     restore_fd < 0 ?
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED :
                                         VIR_DOMAIN_EVENT_STARTED_RESTORED);
707 708
    if (event)
        libxlDomainEventQueue(driver, event);
709

J
Jim Fehlig 已提交
710
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
711
    VIR_FREE(dom_xml);
712
    VIR_FORCE_CLOSE(managed_save_fd);
713
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
714 715 716 717
    return 0;

error:
    if (domid > 0) {
J
Jim Fehlig 已提交
718
        libxl_domain_destroy(priv->ctx, domid, NULL);
719
        vm->def->id = -1;
J
Jiri Denemark 已提交
720
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);
J
Jim Fehlig 已提交
721
    }
J
Jim Fehlig 已提交
722
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
723
    VIR_FREE(dom_xml);
724
    VIR_FREE(managed_save_path);
725
    virDomainDefFree(def);
726
    VIR_FORCE_CLOSE(managed_save_fd);
727
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
728 729 730 731 732 733 734 735
    return -1;
}


/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
736 737
static int
libxlReconnectDomain(virDomainObjPtr vm,
J
Jim Fehlig 已提交
738 739 740
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
741
    libxlDomainObjPrivatePtr priv = vm->privateData;
J
Jim Fehlig 已提交
742 743 744 745 746
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;

747
    virObjectLock(vm);
J
Jim Fehlig 已提交
748

749
    libxlDomainObjPrivateInitCtx(vm);
J
Jim Fehlig 已提交
750
    /* Does domain still exist? */
751
    rc = libxl_domain_info(priv->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
752 753 754 755 756 757 758 759 760
    if (rc == ERROR_INVAL) {
        goto out;
    } else if (rc != 0) {
        VIR_DEBUG("libxl_domain_info failed (code %d), ignoring domain %d",
                  rc, vm->def->id);
        goto out;
    }

    /* Is this a domain that was under libvirt control? */
761
    if (libxl_userdata_retrieve(priv->ctx, vm->def->id,
J
Jim Fehlig 已提交
762 763 764 765 766 767 768
                                "libvirt-xml", &data, &len)) {
        VIR_DEBUG("libxl_userdata_retrieve failed, ignoring domain %d", vm->def->id);
        goto out;
    }

    /* Update domid in case it changed (e.g. reboot) while we were gone? */
    vm->def->id = d_info.domid;
J
Jiri Denemark 已提交
769
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_UNKNOWN);
J
Jim Fehlig 已提交
770

771
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
772 773
        driver->inhibitCallback(true, driver->inhibitOpaque);

774 775
    /* Re-register domain death et. al. events */
    libxlDomEventsRegister(vm);
776
    virObjectUnlock(vm);
777
    return 0;
J
Jim Fehlig 已提交
778 779

out:
J
Jiri Denemark 已提交
780
    libxlVmCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_UNKNOWN);
J
Jim Fehlig 已提交
781
    if (!vm->persistent)
782
        virDomainObjListRemoveLocked(driver->domains, vm);
J
Jim Fehlig 已提交
783
    else
784
        virObjectUnlock(vm);
785 786

    return -1;
J
Jim Fehlig 已提交
787 788 789 790 791
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
792
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
793 794 795
}

static int
796
libxlStateCleanup(void)
J
Jim Fehlig 已提交
797 798 799 800
{
    if (!libxl_driver)
        return -1;

801
    virObjectUnref(libxl_driver->config);
802
    virObjectUnref(libxl_driver->xmlopt);
803
    virObjectUnref(libxl_driver->domains);
804
    virObjectUnref(libxl_driver->reservedVNCPorts);
J
Jim Fehlig 已提交
805

806
    virObjectEventStateFree(libxl_driver->domainEventState);
807
    virSysinfoDefFree(libxl_driver->hostsysinfo);
808

J
Jim Fehlig 已提交
809 810 811 812 813 814
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

815 816
static bool
libxlDriverShouldLoad(bool privileged)
817
{
818
    bool ret = false;
J
Jim Fehlig 已提交
819
    virCommandPtr cmd;
820
    int status;
J
Jim Fehlig 已提交
821

822
    /* Don't load if non-root */
J
Jim Fehlig 已提交
823
    if (!privileged) {
824
        VIR_INFO("Not running privileged, disabling libxenlight driver");
825
        return ret;
J
Jim Fehlig 已提交
826 827
    }

828 829 830 831 832 833 834 835 836
    /* Don't load if not running on a Xen control domain (dom0) */
    if (!virFileExists("/proc/xen/capabilities")) {
        VIR_INFO("No Xen capabilities detected, probably not running "
                 "in a Xen Dom0.  Disabling libxenlight driver");

        return ret;
    }

    /* Don't load if legacy xen toolstack (xend) is in use */
J
Jim Fehlig 已提交
837 838
    cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL);
    if (virCommandRun(cmd, &status) == 0 && status == 0) {
839
        VIR_INFO("Legacy xen tool stack seems to be in use, disabling "
J
Jim Fehlig 已提交
840
                  "libxenlight driver.");
841 842
    } else {
        ret = true;
J
Jim Fehlig 已提交
843 844 845
    }
    virCommandFree(cmd);

846 847 848 849 850 851 852 853
    return ret;
}

static int
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
854
    libxlDriverConfigPtr cfg;
855 856 857 858 859
    char ebuf[1024];

    if (!libxlDriverShouldLoad(privileged))
        return 0;

J
Jim Fehlig 已提交
860 861 862 863
    if (VIR_ALLOC(libxl_driver) < 0)
        return -1;

    if (virMutexInit(&libxl_driver->lock) < 0) {
864 865
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
J
Jim Fehlig 已提交
866 867 868 869 870
        VIR_FREE(libxl_driver);
        return -1;
    }

    /* Allocate bitmap for vnc port reservation */
871
    if (!(libxl_driver->reservedVNCPorts =
J
Ján Tomko 已提交
872 873
          virPortAllocatorNew(_("VNC"),
                              LIBXL_VNC_PORT_MIN,
874 875
                              LIBXL_VNC_PORT_MAX)))
        goto error;
J
Jim Fehlig 已提交
876

877 878
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
879

880
    if (!(cfg = libxlDriverConfigNew()))
881
        goto error;
J
Jim Fehlig 已提交
882

883 884
    libxl_driver->config = cfg;
    if (virFileMakePath(cfg->logDir) < 0) {
885 886
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create log dir '%s': %s"),
887
                       cfg->logDir,
888
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
889 890
        goto error;
    }
891
    if (virFileMakePath(cfg->stateDir) < 0) {
892 893
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create state dir '%s': %s"),
894
                       cfg->stateDir,
895
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
896 897
        goto error;
    }
898
    if (virFileMakePath(cfg->libDir) < 0) {
899 900
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create lib dir '%s': %s"),
901
                       cfg->libDir,
902
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
903 904
        goto error;
    }
905
    if (virFileMakePath(cfg->saveDir) < 0) {
906 907
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create save dir '%s': %s"),
908
                       cfg->saveDir,
909
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
910 911 912
        goto error;
    }

913
    /* read the host sysinfo */
914
    libxl_driver->hostsysinfo = virSysinfoRead();
915

916
    libxl_driver->domainEventState = virObjectEventStateNew();
E
Eric Blake 已提交
917
    if (!libxl_driver->domainEventState)
918 919
        goto error;

920
    if ((cfg->caps = libxlMakeCapabilities(cfg->ctx)) == NULL) {
921 922
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
923 924 925
        goto error;
    }

926
    if (!(libxl_driver->xmlopt = virDomainXMLOptionNew(&libxlDomainDefParserConfig,
927 928
                                                       &libxlDomainXMLPrivateDataCallbacks,
                                                       NULL)))
929
        goto error;
J
Jim Fehlig 已提交
930 931

    /* Load running domains first. */
932
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
933 934
                                       cfg->stateDir,
                                       cfg->autostartDir,
935
                                       1,
936
                                       cfg->caps,
937 938
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
939
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
940 941 942 943 944
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
945
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
946 947
                                       cfg->configDir,
                                       cfg->autostartDir,
948
                                       0,
949
                                       cfg->caps,
950 951
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
952
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
953 954
        goto error;

955 956
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
957

J
Jim Fehlig 已提交
958 959 960
    return 0;

error:
961
    libxlStateCleanup();
962
    return -1;
J
Jim Fehlig 已提交
963 964
}

965 966 967 968 969 970 971 972 973 974
static void
libxlStateAutoStart(void)
{
    if (!libxl_driver)
        return;

    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
}

J
Jim Fehlig 已提交
975
static int
976
libxlStateReload(void)
J
Jim Fehlig 已提交
977
{
978 979
    libxlDriverConfigPtr cfg;

J
Jim Fehlig 已提交
980 981 982
    if (!libxl_driver)
        return 0;

983 984
    cfg = libxlDriverConfigGet(libxl_driver);

985
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
986 987
                                   cfg->configDir,
                                   cfg->autostartDir,
988
                                   1,
989
                                   cfg->caps,
990 991
                                   libxl_driver->xmlopt,
                                   1 << VIR_DOMAIN_VIRT_XEN,
992 993
                                   NULL, libxl_driver);

994 995
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
996

997
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
998 999 1000 1001 1002
    return 0;
}


static virDrvOpenStatus
1003 1004 1005
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 unsigned int flags)
J
Jim Fehlig 已提交
1006
{
E
Eric Blake 已提交
1007 1008
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
1009 1010 1011 1012
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

1013
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
            return VIR_DRV_OPEN_ERROR;
    } else {
        /* Only xen scheme */
        if (conn->uri->scheme == NULL || STRNEQ(conn->uri->scheme, "xen"))
            return VIR_DRV_OPEN_DECLINED;

        /* If server name is given, its for remote driver */
        if (conn->uri->server != NULL)
            return VIR_DRV_OPEN_DECLINED;

        /* Error if xen or libxl scheme specified but driver not started. */
        if (libxl_driver == NULL) {
1026 1027
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
1028 1029 1030 1031 1032 1033 1034 1035
            return VIR_DRV_OPEN_ERROR;
        }

        /* /session isn't supported in libxenlight */
        if (conn->uri->path &&
            STRNEQ(conn->uri->path, "") &&
            STRNEQ(conn->uri->path, "/") &&
            STRNEQ(conn->uri->path, "/system")) {
1036 1037 1038
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
1039 1040 1041 1042
            return VIR_DRV_OPEN_ERROR;
        }
    }

1043 1044 1045
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
1046 1047 1048 1049 1050 1051
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
1052
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1053 1054 1055 1056 1057 1058
{
    conn->privateData = NULL;
    return 0;
}

static const char *
1059
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
1060
{
1061 1062 1063
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
1064
    return "Xen";
J
Jim Fehlig 已提交
1065 1066 1067
}

static int
1068
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
1069 1070
{
    libxlDriverPrivatePtr driver = conn->privateData;
1071
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
1072

1073 1074 1075
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

1076 1077 1078
    cfg = libxlDriverConfigGet(driver);
    *version = cfg->version;
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1079 1080 1081
    return 0;
}

1082

1083
static char *libxlConnectGetHostname(virConnectPtr conn)
1084
{
1085 1086 1087
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

1088 1089 1090
    return virGetHostname();
}

1091 1092 1093 1094 1095 1096 1097 1098
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

1099 1100 1101
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
    if (!driver->hostsysinfo) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Host SMBIOS information is not available"));
        return NULL;
    }

    if (virSysinfoFormat(&buf, driver->hostsysinfo) < 0)
        return NULL;
    if (virBufferError(&buf)) {
        virReportOOMError();
        return NULL;
    }
    return virBufferContentAndReset(&buf);
}
1116

J
Jim Fehlig 已提交
1117
static int
1118
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1119 1120 1121
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;
1122
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
1123

1124 1125 1126
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

1127 1128
    cfg = libxlDriverConfigGet(driver);
    ret = libxl_get_max_cpus(cfg->ctx);
1129 1130 1131 1132 1133
    /* On failure, libxl_get_max_cpus() will return ERROR_FAIL from Xen 4.4
     * onward, but it ever returning 0 is obviously wrong too (and it is
     * what happens, on failure, on Xen 4.3 and earlier). Therefore, a 'less
     * or equal' is the catchall we want. */
    if (ret <= 0)
1134
        ret = -1;
J
Jim Fehlig 已提交
1135

1136
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1137 1138 1139 1140 1141 1142
    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
1143 1144 1145
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

1146
    return libxlDoNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
1147 1148 1149
}

static char *
1150
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
1151 1152 1153
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;
1154
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
1155

1156 1157 1158
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

1159 1160
    cfg = libxlDriverConfigGet(driver);
    if ((xml = virCapabilitiesFormatXML(cfg->caps)) == NULL)
J
Jim Fehlig 已提交
1161 1162
        virReportOOMError();

1163
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1164 1165 1166 1167
    return xml;
}

static int
1168
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
1169 1170 1171 1172
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1173 1174 1175
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

1176 1177
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1178 1179 1180 1181 1182

    return n;
}

static int
1183
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
1184 1185 1186 1187
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1188 1189 1190
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

1191 1192
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204

    return n;
}

static virDomainPtr
libxlDomainCreateXML(virConnectPtr conn, const char *xml,
                     unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virDomainDefPtr def;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
1205
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1206 1207 1208

    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);

1209
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
1210
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
1211 1212 1213
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

1214 1215 1216
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

1217
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1218
                                   driver->xmlopt,
1219 1220
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
1221 1222 1223
        goto cleanup;
    def = NULL;

1224 1225
    if (libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0,
                     -1) < 0) {
1226
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
        vm = NULL;
        goto cleanup;
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

cleanup:
    virDomainDefFree(def);
    if (vm)
1238
        virObjectUnlock(vm);
1239
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
    return dom;
}

static virDomainPtr
libxlDomainLookupByID(virConnectPtr conn, int id)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1250
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
1251
    if (!vm) {
1252
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1253 1254 1255
        goto cleanup;
    }

1256 1257 1258
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1259 1260 1261 1262 1263 1264
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1265
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    return dom;
}

static virDomainPtr
libxlDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1276
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
1277
    if (!vm) {
1278
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1279 1280 1281
        goto cleanup;
    }

1282 1283 1284
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1285 1286 1287 1288 1289 1290
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1291
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    return dom;
}

static virDomainPtr
libxlDomainLookupByName(virConnectPtr conn, const char *name)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1302
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
1303
    if (!vm) {
1304
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1305 1306 1307
        goto cleanup;
    }

1308 1309 1310
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1311 1312 1313 1314 1315 1316
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1317
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1318 1319 1320
    return dom;
}

1321 1322 1323 1324
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1325
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1326 1327
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
1328
    virObjectEventPtr event = NULL;
1329 1330
    int ret = -1;

J
Jim Fehlig 已提交
1331
    if (!(vm = libxlDomObjFromDomain(dom)))
1332
        goto cleanup;
1333 1334 1335 1336

    if (virDomainSuspendEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1337
    if (!virDomainObjIsActive(vm)) {
1338
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1339 1340 1341 1342 1343
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1344
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1345
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
1346 1347 1348
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to suspend domain '%d' with libxenlight"),
                           dom->id);
1349 1350 1351
            goto cleanup;
        }

J
Jiri Denemark 已提交
1352
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1353

1354
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
1355 1356 1357
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

1358
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1359 1360 1361 1362 1363 1364
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
1365
        virObjectUnlock(vm);
1366
    if (event)
1367
        libxlDomainEventQueue(driver, event);
1368
    virObjectUnref(cfg);
1369 1370 1371 1372 1373 1374 1375 1376
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1377
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1378 1379
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
1380
    virObjectEventPtr event = NULL;
1381 1382
    int ret = -1;

J
Jim Fehlig 已提交
1383
    if (!(vm = libxlDomObjFromDomain(dom)))
1384 1385
        goto cleanup;

1386 1387 1388
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1389
    if (!virDomainObjIsActive(vm)) {
1390
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1391 1392 1393 1394 1395
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1396
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1397
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
1398 1399 1400
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
                           dom->id);
1401 1402 1403
            goto cleanup;
        }

J
Jiri Denemark 已提交
1404 1405
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1406

1407
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_RESUMED,
1408 1409 1410
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

1411
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1412 1413 1414 1415 1416 1417
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
1418
        virObjectUnlock(vm);
1419
    if (event)
1420
        libxlDomainEventQueue(driver, event);
1421
    virObjectUnref(cfg);
1422 1423 1424
    return ret;
}

J
Jim Fehlig 已提交
1425
static int
1426
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1427 1428 1429 1430 1431
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

1432 1433
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1434
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1435 1436
        goto cleanup;

1437
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1438 1439
        goto cleanup;

J
Jim Fehlig 已提交
1440
    if (!virDomainObjIsActive(vm)) {
1441 1442
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1443 1444 1445 1446
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1447
    if (libxl_domain_shutdown(priv->ctx, dom->id) != 0) {
1448 1449 1450
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
        goto cleanup;
    }

    /* vm is marked shutoff (or removed from domains list if not persistent)
     * in shutdown event handler.
     */
    ret = 0;

cleanup:
    if (vm)
1461
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1462 1463 1464
    return ret;
}

1465 1466 1467 1468 1469 1470 1471
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
1472
static int
E
Eric Blake 已提交
1473
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1474 1475 1476 1477 1478
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

E
Eric Blake 已提交
1479 1480
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1481
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1482 1483
        goto cleanup;

1484
    if (virDomainRebootEnsureACL(dom->conn, vm->def, flags) < 0)
1485 1486
        goto cleanup;

J
Jim Fehlig 已提交
1487
    if (!virDomainObjIsActive(vm)) {
1488 1489
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1490 1491 1492 1493
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1494
    if (libxl_domain_reboot(priv->ctx, dom->id) != 0) {
1495 1496 1497
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1498 1499 1500 1501 1502 1503
        goto cleanup;
    }
    ret = 0;

cleanup:
    if (vm)
1504
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1505 1506 1507 1508
    return ret;
}

static int
1509 1510
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1511 1512 1513 1514
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1515
    virObjectEventPtr event = NULL;
J
Jim Fehlig 已提交
1516
    libxlDomainObjPrivatePtr priv;
J
Jim Fehlig 已提交
1517

1518 1519
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1520
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1521 1522
        goto cleanup;

1523 1524 1525
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1526
    if (!virDomainObjIsActive(vm)) {
1527 1528
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1529 1530 1531
        goto cleanup;
    }

1532
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1533 1534
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

J
Jim Fehlig 已提交
1535 1536
    priv = vm->privateData;
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
1537 1538
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), dom->id);
J
Jim Fehlig 已提交
1539 1540 1541
        goto cleanup;
    }

J
Jim Fehlig 已提交
1542
    libxlVmCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED);
J
Jim Fehlig 已提交
1543
    if (!vm->persistent) {
1544
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1545 1546 1547 1548 1549 1550 1551
        vm = NULL;
    }

    ret = 0;

cleanup:
    if (vm)
1552
        virObjectUnlock(vm);
1553 1554
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1555 1556 1557
    return ret;
}

1558 1559 1560 1561 1562 1563
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1564 1565 1566 1567 1568 1569
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *type = NULL;

J
Jim Fehlig 已提交
1570
    if (!(vm = libxlDomObjFromDomain(dom)))
1571 1572
        goto cleanup;

1573 1574 1575 1576 1577
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

    if (VIR_STRDUP(type, vm->def->os.type) < 0)
        goto cleanup;
1578 1579 1580

cleanup:
    if (vm)
1581
        virObjectUnlock(vm);
1582 1583 1584
    return type;
}

1585
static unsigned long long
1586 1587 1588
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    virDomainObjPtr vm;
1589
    unsigned long long ret = 0;
1590

J
Jim Fehlig 已提交
1591
    if (!(vm = libxlDomObjFromDomain(dom)))
1592
        goto cleanup;
1593 1594 1595 1596

    if (virDomainGetMaxMemoryEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1597 1598 1599 1600
    ret = vm->def->mem.max_balloon;

cleanup:
    if (vm)
1601
        virObjectUnlock(vm);
1602 1603 1604 1605
    return ret;
}

static int
1606
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1607 1608 1609
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1610
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1611 1612
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1613 1614
    virDomainDefPtr persistentDef = NULL;
    bool isActive;
1615 1616 1617
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1618 1619
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1620

J
Jim Fehlig 已提交
1621
    if (!(vm = libxlDomObjFromDomain(dom)))
1622 1623
        goto cleanup;

1624 1625 1626
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
    isActive = virDomainObjIsActive(vm);

    if (flags == VIR_DOMAIN_MEM_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE;
        else
            flags = VIR_DOMAIN_MEM_CONFIG;
    }
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
        else
            flags = VIR_DOMAIN_MEM_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1640 1641
    }

1642
    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
1643 1644
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set memory on an inactive domain"));
1645 1646 1647 1648 1649
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
1650 1651
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a transient domain"));
1652 1653
            goto cleanup;
        }
1654
        if (!(persistentDef = virDomainObjGetPersistentDef(cfg->caps,
1655
                                                           driver->xmlopt,
1656
                                                           vm)))
1657 1658 1659
            goto cleanup;
    }

1660 1661
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1662

1663 1664
        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
1665
            if (libxl_domain_setmaxmem(priv->ctx, dom->id, newmem) < 0) {
1666 1667 1668
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
                                 " with libxenlight"), dom->id);
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
                goto cleanup;
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
1679
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
1680 1681 1682
            goto cleanup;
        }

1683 1684
    } else {
        /* resize the current memory */
1685

1686
        if (newmem > vm->def->mem.max_balloon) {
1687 1688
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1689 1690 1691 1692 1693
            goto cleanup;
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
1694
            if (libxl_set_memory_target(priv->ctx, dom->id, newmem, 0,
1695
                                        /* force */ 1) < 0) {
1696 1697 1698
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
                                 " with libxenlight"), dom->id);
1699 1700 1701 1702 1703 1704 1705
                goto cleanup;
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1706
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
1707 1708
            goto cleanup;
        }
1709 1710
    }

1711 1712
    ret = 0;

1713 1714
cleanup:
    if (vm)
1715
        virObjectUnlock(vm);
1716
    virObjectUnref(cfg);
1717 1718 1719 1720 1721 1722 1723 1724 1725
    return ret;
}

static int
libxlDomainSetMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_LIVE);
}

1726 1727 1728 1729 1730 1731
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1732 1733 1734 1735
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
    virDomainObjPtr vm;
1736
    libxl_dominfo d_info;
1737
    libxlDomainObjPrivatePtr priv;
J
Jim Fehlig 已提交
1738 1739
    int ret = -1;

J
Jim Fehlig 已提交
1740
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1741 1742
        goto cleanup;

1743 1744 1745
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1746
    priv = vm->privateData;
1747 1748 1749
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1750
        info->maxMem = vm->def->mem.max_balloon;
1751
    } else {
1752
        if (libxl_domain_info(priv->ctx, &d_info, dom->id) != 0) {
1753 1754
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxl_domain_info failed for domain '%d'"), dom->id);
1755 1756 1757 1758
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1759
        info->maxMem = d_info.max_memkb;
1760 1761
    }

J
Jiri Denemark 已提交
1762
    info->state = virDomainObjGetState(vm, NULL);
J
Jim Fehlig 已提交
1763 1764 1765 1766 1767
    info->nrVirtCpu = vm->def->vcpus;
    ret = 0;

  cleanup:
    if (vm)
1768
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1769 1770 1771
    return ret;
}

1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1783
    if (!(vm = libxlDomObjFromDomain(dom)))
1784 1785
        goto cleanup;

1786 1787 1788
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1789
    *state = virDomainObjGetState(vm, reason);
1790 1791 1792 1793
    ret = 0;

  cleanup:
    if (vm)
1794
        virObjectUnlock(vm);
1795 1796 1797
    return ret;
}

1798 1799 1800
/*
 * virDomainObjPtr must be locked on invocation
 */
1801
static int
1802 1803
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1804
{
1805
    libxlDomainObjPrivatePtr priv = vm->privateData;
1806
    libxlSavefileHeader hdr;
1807
    virObjectEventPtr event = NULL;
1808 1809
    char *xml = NULL;
    uint32_t xml_len;
1810
    int fd = -1;
1811 1812 1813
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1814 1815 1816
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1817 1818 1819 1820
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1821
                            -1, -1, 0)) < 0) {
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
        virReportSystemError(-fd,
                             _("Failed to create domain save file '%s'"), to);
        goto cleanup;
    }

    if ((xml = virDomainDefFormat(vm->def, 0)) == NULL)
        goto cleanup;
    xml_len = strlen(xml) + 1;

    memset(&hdr, 0, sizeof(hdr));
    memcpy(hdr.magic, LIBXL_SAVE_MAGIC, sizeof(hdr.magic));
    hdr.version = LIBXL_SAVE_VERSION;
    hdr.xmlLen = xml_len;

    if (safewrite(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
1837 1838
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1839 1840 1841 1842
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1843 1844
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1845 1846 1847
        goto cleanup;
    }

J
Jim Fehlig 已提交
1848
    if (libxl_domain_suspend(priv->ctx, vm->def->id, fd, 0, NULL) != 0) {
1849 1850 1851
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1852 1853 1854
        goto cleanup;
    }

1855
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1856 1857
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

J
Jim Fehlig 已提交
1858
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
1859 1860
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1861 1862 1863
        goto cleanup;
    }

J
Jim Fehlig 已提交
1864
    libxlVmCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED);
1865
    vm->hasManagedSave = true;
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
    ret = 0;

cleanup:
    VIR_FREE(xml);
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
    if (event)
        libxlDomainEventQueue(driver, event);
    return ret;
}

static int
1878 1879
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1880
{
1881 1882
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1883 1884
    int ret = -1;

1885 1886
    virCheckFlags(0, -1);
    if (dxml) {
1887 1888
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1889 1890 1891
        return -1;
    }

J
Jim Fehlig 已提交
1892
    if (!(vm = libxlDomObjFromDomain(dom)))
1893 1894
        goto cleanup;

1895 1896 1897
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1898
    if (!virDomainObjIsActive(vm)) {
1899
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1900 1901 1902
        goto cleanup;
    }

1903 1904 1905 1906
    if (libxlDoDomainSave(driver, vm, to) < 0)
        goto cleanup;

    if (!vm->persistent) {
1907
        virDomainObjListRemove(driver->domains, vm);
1908 1909 1910 1911
        vm = NULL;
    }

    ret = 0;
1912

1913 1914
cleanup:
    if (vm)
1915
        virObjectUnlock(vm);
1916 1917
    return ret;
}
1918

1919
static int
1920 1921 1922 1923 1924 1925 1926 1927
libxlDomainSave(virDomainPtr dom, const char *to)
{
    return libxlDomainSaveFlags(dom, to, NULL, 0);
}

static int
libxlDomainRestoreFlags(virConnectPtr conn, const char *from,
                        const char *dxml, unsigned int flags)
1928 1929
{
    libxlDriverPrivatePtr driver = conn->privateData;
1930
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1931 1932 1933 1934 1935
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1936

1937
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1938
    if (dxml) {
1939 1940
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1941 1942 1943
        return -1;
    }

1944
    fd = libxlSaveImageOpen(driver, cfg, from, &def, &hdr);
1945
    if (fd < 0)
1946
        goto cleanup_unlock;
1947

1948
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1949
        goto cleanup_unlock;
1950

1951
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1952
                                   driver->xmlopt,
1953 1954 1955
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1956
        goto cleanup_unlock;
1957 1958 1959

    def = NULL;

1960 1961
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_SAVE_PAUSED) != 0, fd);
    if (ret < 0 && !vm->persistent) {
1962
        virDomainObjListRemove(driver->domains, vm);
1963 1964 1965 1966
        vm = NULL;
    }

cleanup:
1967 1968
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1969 1970
    virDomainDefFree(def);
    if (vm)
1971
        virObjectUnlock(vm);
1972
    virObjectUnref(cfg);
1973
    return ret;
1974 1975 1976 1977

cleanup_unlock:
    libxlDriverUnlock(driver);
    goto cleanup;
1978 1979
}

1980 1981 1982 1983 1984 1985
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

1986
static int
1987
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1988 1989 1990 1991
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1992
    virObjectEventPtr event = NULL;
1993 1994 1995 1996 1997
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

J
Jim Fehlig 已提交
1998
    if (!(vm = libxlDomObjFromDomain(dom)))
1999 2000
        goto cleanup;

2001 2002 2003
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2004
    if (!virDomainObjIsActive(vm)) {
2005
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2006 2007 2008 2009 2010 2011 2012
        goto cleanup;
    }

    priv = vm->privateData;

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
2013
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
2014 2015 2016 2017
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
                           dom->id);
2018 2019 2020 2021 2022 2023
            goto cleanup;
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

J
Jim Fehlig 已提交
2024
    if (libxl_domain_core_dump(priv->ctx, dom->id, to, NULL) != 0) {
2025 2026 2027
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
                       dom->id);
2028 2029 2030 2031
        goto cleanup_unpause;
    }

    if (flags & VIR_DUMP_CRASH) {
J
Jim Fehlig 已提交
2032
        if (libxl_domain_destroy(priv->ctx, dom->id, NULL) < 0) {
2033 2034
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to destroy domain '%d'"), dom->id);
2035
            goto cleanup_unpause;
2036 2037
        }

J
Jim Fehlig 已提交
2038
        libxlVmCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED);
2039
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
2040
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
J
Jim Fehlig 已提交
2041 2042 2043 2044
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
2045 2046 2047 2048 2049
    }

    ret = 0;

cleanup_unpause:
J
Jim Fehlig 已提交
2050
    if (vm && virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
2051
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
2052 2053 2054
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
                             " libxenlight"), dom->id);
2055 2056 2057 2058 2059 2060 2061
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
cleanup:
    if (vm)
2062
        virObjectUnlock(vm);
2063
    if (event)
2064 2065 2066 2067
        libxlDomainEventQueue(driver, event);
    return ret;
}

2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
static int
libxlDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2078
    if (!(vm = libxlDomObjFromDomain(dom)))
2079 2080
        goto cleanup;

2081 2082 2083
    if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2084
    if (!virDomainObjIsActive(vm)) {
2085
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2086 2087
        goto cleanup;
    }
2088
    if (!vm->persistent) {
2089 2090
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
2091 2092
        goto cleanup;
    }
2093 2094 2095 2096 2097 2098 2099

    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    VIR_INFO("Saving state to %s", name);

2100 2101 2102 2103
    if (libxlDoDomainSave(driver, vm, name) < 0)
        goto cleanup;

    if (!vm->persistent) {
2104
        virDomainObjListRemove(driver->domains, vm);
2105 2106 2107 2108
        vm = NULL;
    }

    ret = 0;
2109 2110 2111

cleanup:
    if (vm)
2112
        virObjectUnlock(vm);
2113 2114 2115 2116
    VIR_FREE(name);
    return ret;
}

2117 2118
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
2119 2120 2121 2122
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
2123
    int ret = -1;
2124

2125
    virObjectLock(vm);
2126 2127 2128 2129 2130 2131

    if (!(name = libxlDomainManagedSavePath(driver, vm)))
        goto cleanup;

    vm->hasManagedSave = virFileExists(name);

2132
    ret = 0;
2133
cleanup:
2134
    virObjectUnlock(vm);
2135
    VIR_FREE(name);
2136
    return ret;
2137 2138
}

2139 2140 2141 2142 2143 2144 2145 2146
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2147
    if (!(vm = libxlDomObjFromDomain(dom)))
2148 2149
        goto cleanup;

2150 2151 2152
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2153
    ret = vm->hasManagedSave;
2154 2155 2156

cleanup:
    if (vm)
2157
        virObjectUnlock(vm);
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
    return ret;
}

static int
libxlDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    char *name = NULL;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2171
    if (!(vm = libxlDomObjFromDomain(dom)))
2172 2173
        goto cleanup;

2174 2175 2176
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2177 2178 2179 2180 2181
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
2182
    vm->hasManagedSave = false;
2183 2184 2185 2186

cleanup:
    VIR_FREE(name);
    if (vm)
2187
        virObjectUnlock(vm);
2188 2189 2190
    return ret;
}

2191 2192 2193 2194 2195
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2196
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2197 2198 2199
    libxlDomainObjPrivatePtr priv;
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
2200
    libxl_bitmap map;
2201 2202
    uint8_t *bitmask = NULL;
    unsigned int maplen;
2203 2204
    size_t i;
    unsigned int pos;
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
    int max;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    /* At least one of LIVE or CONFIG must be set.  MAXIMUM cannot be
     * mixed with LIVE.  */
    if ((flags & (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) == 0 ||
        (flags & (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_LIVE)) ==
         (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_LIVE)) {
2217 2218
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2219 2220 2221 2222
        return -1;
    }

    if (!nvcpus) {
2223
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2224 2225 2226
        return -1;
    }

J
Jim Fehlig 已提交
2227
    if (!(vm = libxlDomObjFromDomain(dom)))
2228 2229
        goto cleanup;

2230 2231 2232
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2233
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2234 2235
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2236 2237 2238 2239
        goto cleanup;
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2240 2241
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2242 2243 2244
        goto cleanup;
    }

2245
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2246 2247
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2248 2249 2250 2251 2252 2253 2254 2255
        goto cleanup;
    }

    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && vm->def->maxvcpus < max) {
        max = vm->def->maxvcpus;
    }

    if (nvcpus > max) {
2256 2257 2258
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2259 2260 2261 2262 2263
        goto cleanup;
    }

    priv = vm->privateData;

2264
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm)))
2265 2266
        goto cleanup;

E
Eric Blake 已提交
2267
    maplen = VIR_CPU_MAPLEN(nvcpus);
2268
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
2269 2270 2271
        goto cleanup;

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2272
        pos = i / 8;
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
        bitmask[pos] |= 1 << (i % 8);
    }

    map.size = maplen;
    map.map = bitmask;

    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
        def->maxvcpus = nvcpus;
        if (nvcpus < def->vcpus)
            def->vcpus = nvcpus;
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
        def->vcpus = nvcpus;
        break;

    case VIR_DOMAIN_VCPU_LIVE:
J
Jim Fehlig 已提交
2291
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2292 2293 2294
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2295 2296 2297 2298 2299
            goto cleanup;
        }
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2300
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2301 2302 2303
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2304 2305 2306 2307 2308 2309 2310 2311 2312
            goto cleanup;
        }
        def->vcpus = nvcpus;
        break;
    }

    ret = 0;

    if (flags & VIR_DOMAIN_VCPU_CONFIG)
2313
        ret = virDomainSaveConfig(cfg->configDir, def);
2314 2315 2316 2317

cleanup:
    VIR_FREE(bitmask);
     if (vm)
2318
        virObjectUnlock(vm);
2319
     virObjectUnref(cfg);
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
    return ret;
}

static int
libxlDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
    return libxlDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_VCPU_LIVE);
}

static int
libxlDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm;
    virDomainDefPtr def;
    int ret = -1;
2335
    bool active;
2336 2337 2338 2339 2340

    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

J
Jim Fehlig 已提交
2341
    if (!(vm = libxlDomObjFromDomain(dom)))
2342 2343
        goto cleanup;

2344
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2345 2346
        goto cleanup;

2347 2348 2349 2350 2351 2352 2353 2354 2355
    active = virDomainObjIsActive(vm);

    if ((flags & (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) == 0) {
        if (active)
            flags |= VIR_DOMAIN_VCPU_LIVE;
        else
            flags |= VIR_DOMAIN_VCPU_CONFIG;
    }
    if ((flags & VIR_DOMAIN_VCPU_LIVE) && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2356 2357
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2358 2359 2360
        return -1;
    }

2361
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2362
        if (!active) {
2363 2364
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2365 2366 2367 2368
            goto cleanup;
        }
        def = vm->def;
    } else {
2369
        if (!vm->persistent) {
2370 2371
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2372 2373
            goto cleanup;
        }
2374 2375 2376 2377 2378 2379 2380
        def = vm->newDef ? vm->newDef : vm->def;
    }

    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;

cleanup:
    if (vm)
2381
        virObjectUnlock(vm);
2382 2383 2384 2385
    return ret;
}

static int
2386 2387 2388
libxlDomainPinVcpuFlags(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen,
                        unsigned int flags)
2389 2390
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2391
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2392
    virDomainDefPtr targetDef = NULL;
2393
    virBitmapPtr pcpumap = NULL;
2394 2395
    virDomainObjPtr vm;
    int ret = -1;
2396 2397 2398

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
2399

J
Jim Fehlig 已提交
2400
    if (!(vm = libxlDomObjFromDomain(dom)))
2401 2402
        goto cleanup;

2403
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2404 2405
        goto cleanup;

2406
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) && !virDomainObjIsActive(vm)) {
2407
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2408
                       _("domain is inactive"));
2409 2410 2411
        goto cleanup;
    }

2412 2413
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
2414
        goto cleanup;
2415 2416 2417 2418 2419 2420 2421 2422

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        targetDef = vm->def;
    }

    /* Make sure coverity knows targetDef is valid at this point. */
    sa_assert(targetDef);

2423 2424 2425 2426
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
        goto cleanup;

2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        libxl_bitmap map = { .size = maplen, .map = cpumap };
        libxlDomainObjPrivatePtr priv;

        priv = vm->privateData;
        if (libxl_set_vcpuaffinity(priv->ctx, dom->id, vcpu, &map) != 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"),
                           vcpu);
            goto cleanup;
        }
2438
    }
2439

2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
    /* full bitmap means reset the settings (if any). */
    if (virBitmapIsAllSet(pcpumap)) {
        if (virDomainVcpuPinDel(targetDef, vcpu) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to delete vcpupin xml for vcpu '%d'"),
                           vcpu);
            goto cleanup;
        }
        goto out;
    }

2451 2452
    if (!targetDef->cputune.vcpupin) {
        if (VIR_ALLOC(targetDef->cputune.vcpupin) < 0)
H
Hu Tao 已提交
2453
            goto cleanup;
2454
        targetDef->cputune.nvcpupin = 0;
H
Hu Tao 已提交
2455
    }
2456 2457
    if (virDomainVcpuPinAdd(&targetDef->cputune.vcpupin,
                            &targetDef->cputune.nvcpupin,
H
Hu Tao 已提交
2458 2459 2460
                            cpumap,
                            maplen,
                            vcpu) < 0) {
2461 2462
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to update or add vcpupin xml"));
2463 2464 2465
        goto cleanup;
    }

2466
out:
2467 2468
    ret = 0;

2469 2470 2471 2472 2473 2474
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        ret = virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm);
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        ret = virDomainSaveConfig(cfg->configDir, targetDef);
    }

2475 2476
cleanup:
    if (vm)
2477
        virObjectUnlock(vm);
2478
    virBitmapFree(pcpumap);
2479
    virObjectUnref(cfg);
2480 2481 2482
    return ret;
}

2483 2484 2485 2486 2487 2488 2489 2490
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
static int
libxlDomainGetVcpuPinInfo(virDomainPtr dom, int ncpumaps,
                          unsigned char *cpumaps, int maplen,
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    virDomainObjPtr vm = NULL;
    virDomainDefPtr targetDef = NULL;
    virDomainVcpuPinDefPtr *vcpupin_list;
    virBitmapPtr cpumask = NULL;
    int maxcpu, hostcpus, vcpu, pcpu, n, ret = -1;
    unsigned char *cpumap;
    bool pinned;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    if (!(vm = libxlDomObjFromDomain(dom)))
        goto cleanup;

    if (virDomainGetVcpuPinInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
        goto cleanup;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        targetDef = vm->def;
    }

    /* Make sure coverity knows targetDef is valid at this point. */
    sa_assert(targetDef);

    /* Clamp to actual number of vcpus */
    if (ncpumaps > targetDef->vcpus)
        ncpumaps = targetDef->vcpus;

    /* we use cfg->ctx, as vm->privateData->ctx may be NULL if VM is down. */
    if ((hostcpus = libxl_get_max_cpus(cfg->ctx)) < 0)
        goto cleanup;

    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;

    /* initialize cpumaps */
    memset(cpumaps, 0xff, maplen * ncpumaps);
    if (maxcpu % 8) {
        for (vcpu = 0; vcpu < ncpumaps; vcpu++) {
            cpumap = VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
            cpumap[maplen - 1] &= (1 << maxcpu % 8) - 1;
        }
    }

    /* if vcpupin setting exists, there may be unused pcpus */
    for (n = 0; n < targetDef->cputune.nvcpupin; n++) {
        vcpupin_list = targetDef->cputune.vcpupin;
        vcpu = vcpupin_list[n]->vcpuid;
        cpumask = vcpupin_list[n]->cpumask;
        cpumap = VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
        for (pcpu = 0; pcpu < maxcpu; pcpu++) {
            if (virBitmapGetBit(cpumask, pcpu, &pinned) < 0)
                goto cleanup;
            if (!pinned)
                VIR_UNUSE_CPU(cpumap, pcpu);
        }
    }
    ret = ncpumaps;

cleanup:
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(cfg);
    return ret;
}
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577

static int
libxlDomainGetVcpus(virDomainPtr dom, virVcpuInfoPtr info, int maxinfo,
                    unsigned char *cpumaps, int maplen)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    int ret = -1;
    libxl_vcpuinfo *vcpuinfo;
    int maxcpu, hostcpus;
2578
    size_t i;
2579 2580
    unsigned char *cpumap;

J
Jim Fehlig 已提交
2581
    if (!(vm = libxlDomObjFromDomain(dom)))
2582 2583
        goto cleanup;

2584 2585 2586
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2587
    if (!virDomainObjIsActive(vm)) {
2588
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2589 2590 2591 2592
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
2593
    if ((vcpuinfo = libxl_list_vcpu(priv->ctx, dom->id, &maxcpu,
2594
                                    &hostcpus)) == NULL) {
2595 2596 2597
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
                       dom->id);
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
        goto cleanup;
    }

    if (cpumaps && maplen > 0)
        memset(cpumaps, 0, maplen * maxinfo);
    for (i = 0; i < maxcpu && i < maxinfo; ++i) {
        info[i].number = vcpuinfo[i].vcpuid;
        info[i].cpu = vcpuinfo[i].cpu;
        info[i].cpuTime = vcpuinfo[i].vcpu_time;
        if (vcpuinfo[i].running)
            info[i].state = VIR_VCPU_RUNNING;
        else if (vcpuinfo[i].blocked)
            info[i].state = VIR_VCPU_BLOCKED;
        else
            info[i].state = VIR_VCPU_OFFLINE;

        if (cpumaps && maplen > 0) {
            cpumap = VIR_GET_CPUMAP(cpumaps, maplen, i);
            memcpy(cpumap, vcpuinfo[i].cpumap.map,
                   MIN(maplen, vcpuinfo[i].cpumap.size));
        }

J
Jim Fehlig 已提交
2620
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2621 2622 2623 2624 2625 2626 2627
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

cleanup:
    if (vm)
2628
        virObjectUnlock(vm);
2629 2630 2631
    return ret;
}

J
Jim Fehlig 已提交
2632
static char *
2633
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2634 2635 2636 2637
{
    virDomainObjPtr vm;
    char *ret = NULL;

2638 2639
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2640
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2641 2642
        goto cleanup;

2643 2644 2645
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2646 2647 2648 2649
    ret = virDomainDefFormat(vm->def, flags);

  cleanup:
    if (vm)
2650
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2651 2652 2653
    return ret;
}

2654
static char *
2655 2656 2657
libxlConnectDomainXMLFromNative(virConnectPtr conn, const char * nativeFormat,
                                const char * nativeConfig,
                                unsigned int flags)
2658 2659
{
    libxlDriverPrivatePtr driver = conn->privateData;
2660
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2661 2662 2663 2664
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2665 2666
    virCheckFlags(0, NULL);

2667 2668 2669
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

2670
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2671 2672
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2673 2674 2675 2676 2677 2678
        goto cleanup;
    }

    if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
        goto cleanup;

2679
    if (!(def = xenParseXM(conf,
2680 2681
                           cfg->verInfo->xen_version_major,
                           cfg->caps))) {
2682
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("parsing xm config failed"));
2683 2684 2685 2686 2687 2688 2689 2690 2691
        goto cleanup;
    }

    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);

cleanup:
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2692
    virObjectUnref(cfg);
2693 2694 2695 2696 2697
    return xml;
}

#define MAX_CONFIG_SIZE (1024 * 65)
static char *
2698 2699 2700
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
2701 2702
{
    libxlDriverPrivatePtr driver = conn->privateData;
2703
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2704 2705 2706 2707 2708
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    int len = MAX_CONFIG_SIZE;
    char *ret = NULL;

E
Eric Blake 已提交
2709 2710
    virCheckFlags(0, NULL);

2711 2712 2713
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

2714
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2715 2716
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2717 2718 2719
        goto cleanup;
    }

2720
    if (!(def = virDomainDefParseString(domainXml,
2721
                                        cfg->caps, driver->xmlopt,
M
Matthias Bolte 已提交
2722
                                        1 << VIR_DOMAIN_VIRT_XEN, 0)))
2723 2724
        goto cleanup;

2725
    if (!(conf = xenFormatXM(conn, def, cfg->verInfo->xen_version_major)))
2726 2727
        goto cleanup;

2728
    if (VIR_ALLOC_N(ret, len) < 0)
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
        goto cleanup;

    if (virConfWriteMem(ret, &len, conf) < 0) {
        VIR_FREE(ret);
        goto cleanup;
    }

cleanup:
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2740
    virObjectUnref(cfg);
2741 2742 2743
    return ret;
}

J
Jim Fehlig 已提交
2744
static int
2745 2746
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
2747 2748 2749 2750
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2751 2752 2753
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2754 2755
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
2756 2757 2758 2759
    return n;
}

static int
2760
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
2761 2762 2763 2764
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2765 2766 2767
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2768
    n = virDomainObjListNumOfDomains(driver->domains, false,
2769 2770
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
2771 2772 2773 2774 2775
    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
2776
                           unsigned int flags)
J
Jim Fehlig 已提交
2777 2778 2779 2780 2781 2782 2783
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

J
Jim Fehlig 已提交
2784
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2785 2786
        goto cleanup;

2787 2788 2789
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2790
    if (virDomainObjIsActive(vm)) {
2791 2792
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
J
Jim Fehlig 已提交
2793 2794 2795
        goto cleanup;
    }

2796
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0, -1);
J
Jim Fehlig 已提交
2797 2798 2799

cleanup:
    if (vm)
2800
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813
    return ret;
}

static int
libxlDomainCreate(virDomainPtr dom)
{
    return libxlDomainCreateWithFlags(dom, 0);
}

static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    libxlDriverPrivatePtr driver = conn->privateData;
2814
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2815 2816 2817
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
2818
    virObjectEventPtr event = NULL;
2819
    virDomainDefPtr oldDef = NULL;
J
Jim Fehlig 已提交
2820

2821
    /* Lock the driver until the virDomainObj is created and locked */
J
Jim Fehlig 已提交
2822
    libxlDriverLock(driver);
2823
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
M
Matthias Bolte 已提交
2824
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
2825
                                        VIR_DOMAIN_XML_INACTIVE)))
2826
        goto cleanup_unlock;
J
Jim Fehlig 已提交
2827

2828
    if (virDomainDefineXMLEnsureACL(conn, def) < 0)
2829
        goto cleanup_unlock;
2830

2831
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2832
                                   driver->xmlopt,
2833 2834
                                   0,
                                   &oldDef)))
2835 2836
        goto cleanup_unlock;

J
Jim Fehlig 已提交
2837 2838
    def = NULL;
    vm->persistent = 1;
2839
    libxlDriverUnlock(driver);
J
Jim Fehlig 已提交
2840

2841
    if (virDomainSaveConfig(cfg->configDir,
J
Jim Fehlig 已提交
2842
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2843
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
2844 2845 2846 2847 2848 2849 2850 2851
        vm = NULL;
        goto cleanup;
    }

    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

2852
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2853
                                     !oldDef ?
2854 2855 2856
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

J
Jim Fehlig 已提交
2857 2858
cleanup:
    virDomainDefFree(def);
2859
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
2860
    if (vm)
2861
        virObjectUnlock(vm);
2862 2863
    if (event)
        libxlDomainEventQueue(driver, event);
2864
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2865
    return dom;
2866 2867 2868 2869

cleanup_unlock:
    libxlDriverUnlock(driver);
    goto cleanup;
J
Jim Fehlig 已提交
2870 2871 2872
}

static int
2873 2874
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2875 2876
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2877
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2878
    virDomainObjPtr vm;
2879
    virObjectEventPtr event = NULL;
2880
    char *name = NULL;
J
Jim Fehlig 已提交
2881 2882
    int ret = -1;

2883 2884
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2885
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2886 2887
        goto cleanup;

2888 2889 2890
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2891
    if (!vm->persistent) {
2892 2893
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2894 2895 2896
        goto cleanup;
    }

2897 2898 2899 2900 2901 2902 2903
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2904 2905
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2906 2907 2908
                goto cleanup;
            }
        } else {
2909 2910 2911
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2912 2913 2914 2915
            goto cleanup;
        }
    }

2916
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2917 2918
        goto cleanup;

2919
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2920 2921
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2922 2923 2924
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
2925
        virDomainObjListRemove(driver->domains, vm);
2926 2927 2928
        vm = NULL;
    }

J
Jim Fehlig 已提交
2929 2930 2931
    ret = 0;

  cleanup:
2932
    VIR_FREE(name);
J
Jim Fehlig 已提交
2933
    if (vm)
2934
        virObjectUnlock(vm);
2935 2936
    if (event)
        libxlDomainEventQueue(driver, event);
2937
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2938 2939 2940
    return ret;
}

2941 2942 2943 2944 2945 2946
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2947 2948 2949 2950 2951 2952
static int
libxlDomainChangeEjectableMedia(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDiskDefPtr disk)
{
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2953
    size_t i;
2954 2955
    int ret = -1;

2956
    for (i = 0; i < vm->def->ndisks; i++) {
2957 2958 2959 2960 2961 2962 2963 2964
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
2965 2966 2967
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
2968 2969 2970 2971
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2972 2973 2974
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
2975 2976 2977
        return -1;
    }

J
Jim Fehlig 已提交
2978
    if (libxlMakeDisk(disk, &x_disk) < 0)
2979 2980
        goto cleanup;

J
Jim Fehlig 已提交
2981
    if ((ret = libxl_cdrom_insert(priv->ctx, vm->def->id, &x_disk, NULL)) < 0) {
2982 2983 2984
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
        goto cleanup;
    }

    VIR_FREE(origdisk->src);
    origdisk->src = disk->src;
    disk->src = NULL;
    origdisk->type = disk->type;


    virDomainDiskDefFree(disk);

    ret = 0;

cleanup:
    return ret;
}

static int
libxlDomainAttachDeviceDiskLive(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr l_disk = dev->data.disk;
    libxl_device_disk x_disk;
    int ret = -1;

    switch (l_disk->device)  {
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
            ret = libxlDomainChangeEjectableMedia(priv, vm, l_disk);
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (l_disk->bus == VIR_DOMAIN_DISK_BUS_XEN) {
3016
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
3017 3018
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
3019 3020 3021 3022
                    goto cleanup;
                }

                if (!l_disk->src) {
3023 3024
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
3025 3026 3027
                    goto cleanup;
                }

3028
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
3029 3030
                    goto cleanup;

J
Jim Fehlig 已提交
3031
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3032 3033
                    goto cleanup;

J
Jim Fehlig 已提交
3034 3035
                if ((ret = libxl_device_disk_add(priv->ctx, vm->def->id,
                                                &x_disk, NULL)) < 0) {
3036 3037 3038
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
3039 3040 3041 3042 3043 3044
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
3045 3046 3047
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
3048 3049 3050
            }
            break;
        default:
3051 3052 3053
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066
            break;
    }

cleanup:
    return ret;
}

static int
libxlDomainDetachDeviceDiskLive(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
3067
    int idx;
3068 3069 3070 3071 3072 3073
    int ret = -1;

    switch (dev->data.disk->device)  {
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_XEN) {

3074 3075 3076
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
3077 3078
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3079 3080 3081
                    goto cleanup;
                }

3082
                l_disk = vm->def->disks[idx];
3083

J
Jim Fehlig 已提交
3084
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3085 3086
                    goto cleanup;

J
Jim Fehlig 已提交
3087 3088
                if ((ret = libxl_device_disk_remove(priv->ctx, vm->def->id,
                                                    &x_disk, NULL)) < 0) {
3089 3090 3091
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3092 3093 3094
                    goto cleanup;
                }

3095
                virDomainDiskRemove(vm->def, idx);
3096 3097 3098
                virDomainDiskDefFree(l_disk);

            } else {
3099 3100 3101
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3102 3103 3104
            }
            break;
        default:
3105 3106 3107
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
            break;
    }

cleanup:
    return ret;
}

static int
libxlDomainAttachDeviceLive(libxlDomainObjPrivatePtr priv, virDomainObjPtr vm,
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            ret = libxlDomainAttachDeviceDiskLive(priv, vm, dev);
            if (!ret)
                dev->data.disk = NULL;
            break;

        default:
3129 3130 3131
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145
            break;
    }

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3146
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3147 3148
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3149 3150
                return -1;
            }
3151
            if (virDomainDiskInsert(vmdef, disk))
3152 3153 3154 3155 3156 3157
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;

        default:
3158 3159
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
            return -1;
    }
    return 0;
}

static int
libxlDomainDetachDeviceLive(libxlDomainObjPrivatePtr priv, virDomainObjPtr vm,
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            ret = libxlDomainDetachDeviceDiskLive(priv, vm, dev);
            break;

        default:
3177 3178 3179
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3180 3181 3182 3183 3184 3185 3186 3187 3188
            break;
    }

    return ret;
}

static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3189
    virDomainDiskDefPtr disk, detach;
3190 3191 3192 3193 3194
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3195
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3196 3197
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3198 3199
                break;
            }
3200
            virDomainDiskDefFree(detach);
3201 3202 3203
            ret = 0;
            break;
        default:
3204 3205
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceLive(libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
            switch (disk->device) {
                case VIR_DOMAIN_DISK_DEVICE_CDROM:
                    ret = libxlDomainChangeEjectableMedia(priv, vm, disk);
                    if (ret == 0)
                        dev->data.disk = NULL;
                    break;
                default:
3229 3230 3231
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3232 3233 3234 3235
                    break;
            }
            break;
        default:
3236 3237 3238
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr orig;
    virDomainDiskDefPtr disk;
3250
    int idx;
3251 3252 3253 3254 3255
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3256
            if ((idx = virDomainDiskIndexByName(vmdef, disk->dst, false)) < 0) {
3257 3258
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3259 3260
                goto cleanup;
            }
3261
            orig = vmdef->disks[idx];
3262
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3263 3264
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
                goto cleanup;
            }

            VIR_FREE(orig->src);
            orig->src = disk->src;
            orig->type = disk->type;
            if (disk->driverName) {
                VIR_FREE(orig->driverName);
                orig->driverName = disk->driverName;
                disk->driverName = NULL;
            }
3276
            orig->format = disk->format;
3277 3278 3279
            disk->src = NULL;
            break;
        default:
3280 3281
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292
            goto cleanup;
    }

    ret = 0;

cleanup:
    return ret;
}


static int
3293 3294
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3295 3296
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3297
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3298 3299 3300 3301 3302 3303 3304 3305 3306
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    libxlDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3307
    if (!(vm = libxlDomObjFromDomain(dom)))
3308 3309
        goto cleanup;

3310 3311 3312
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3313 3314 3315 3316 3317 3318 3319 3320
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
3321 3322
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3323 3324 3325 3326 3327
            goto cleanup;
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
3328 3329
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3330 3331 3332 3333 3334 3335
         goto cleanup;
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3336
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3337
                                            cfg->caps, driver->xmlopt,
3338 3339 3340 3341
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3342
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3343
                                                    driver->xmlopt)))
3344 3345
            goto cleanup;

3346 3347 3348
        if ((ret = libxlDomainAttachDeviceConfig(vmdef, dev)) < 0)
            goto cleanup;
    } else {
3349
        ret = 0;
3350
    }
3351 3352 3353 3354

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
3355
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3356
                                            cfg->caps, driver->xmlopt,
3357 3358 3359
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

3360 3361 3362
        if ((ret = libxlDomainAttachDeviceLive(priv, vm, dev)) < 0)
            goto cleanup;

3363 3364 3365 3366
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3367
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3368 3369 3370 3371 3372
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3373
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3374
        if (!ret) {
3375
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3376 3377 3378 3379 3380 3381 3382 3383
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3384
        virObjectUnlock(vm);
3385
    virObjectUnref(cfg);
3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399
    return ret;
}

static int
libxlDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return libxlDomainAttachDeviceFlags(dom, xml,
                                        VIR_DOMAIN_DEVICE_MODIFY_LIVE);
}

static int
libxlDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
{
3400
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3401
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3402 3403 3404 3405 3406 3407 3408 3409 3410
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    libxlDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3411
    if (!(vm = libxlDomObjFromDomain(dom)))
3412 3413
        goto cleanup;

3414 3415 3416
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
            goto cleanup;
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
         goto cleanup;
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3441
                                            cfg->caps, driver->xmlopt,
3442 3443 3444 3445
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3446
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459
                                                    driver->xmlopt)))
            goto cleanup;

        if ((ret = libxlDomainDetachDeviceConfig(vmdef, dev)) < 0)
            goto cleanup;
    } else {
        ret = 0;
    }

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3460
                                            cfg->caps, driver->xmlopt,
3461 3462 3463 3464 3465 3466 3467 3468 3469 3470
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        if ((ret = libxlDomainDetachDeviceLive(priv, vm, dev)) < 0)
            goto cleanup;

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3471
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3472 3473 3474 3475 3476
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3477
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3489
    virObjectUnref(cfg);
3490
    return ret;
3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503
}

static int
libxlDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return libxlDomainDetachDeviceFlags(dom, xml,
                                        VIR_DOMAIN_DEVICE_MODIFY_LIVE);
}

static int
libxlDomainUpdateDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
{
3504
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3505
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3506 3507 3508 3509 3510 3511 3512 3513 3514
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    libxlDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3515
    if (!(vm = libxlDomObjFromDomain(dom)))
3516 3517
        goto cleanup;

3518 3519 3520
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
            goto cleanup;
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
         goto cleanup;
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3545
                                            cfg->caps, driver->xmlopt,
3546 3547 3548 3549
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3550
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
                                                    driver->xmlopt)))
            goto cleanup;

        if ((ret = libxlDomainUpdateDeviceConfig(vmdef, dev)) < 0)
            goto cleanup;
    } else {
        ret = 0;
    }

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3564
                                            cfg->caps, driver->xmlopt,
3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        if ((ret = libxlDomainUpdateDeviceLive(priv, vm, dev)) < 0)
            goto cleanup;

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3575
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3576 3577 3578 3579 3580
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3581
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3593
    virObjectUnref(cfg);
3594
    return ret;
3595 3596
}

3597 3598 3599 3600 3601
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
3602 3603
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
3604

3605
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
3606
        goto cleanup;
3607

3608
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
3609 3610
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3611
        goto cleanup;
3612 3613
    }

3614 3615 3616 3617 3618
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

cleanup:
    virObjectUnref(cfg);
    return ret;
3619 3620
}

3621 3622 3623 3624 3625 3626 3627 3628 3629 3630
static int
libxlNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;
    int ret = -1, nr_nodes = 0;
    libxl_numainfo *numa_info = NULL;
    libxlDriverPrivatePtr driver = conn->privateData;
3631
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3632 3633

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
3634
        goto cleanup;
3635

3636
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
3637
    if (numa_info == NULL || nr_nodes == 0) {
3638 3639 3640
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
3641 3642 3643
    }

    /* Check/sanitize the cell range */
3644
    if (startCell >= nr_nodes) {
3645 3646
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
3647
                       startCell, nr_nodes - 1);
3648 3649 3650
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
3651 3652
    if (lastCell >= nr_nodes)
        lastCell = nr_nodes - 1;
3653 3654 3655 3656 3657 3658 3659

    for (numCells = 0, n = startCell; n <= lastCell; n++) {
        if (numa_info[n].size == LIBXL_NUMAINFO_INVALID_ENTRY)
            freeMems[numCells++] = 0;
        else
            freeMems[numCells++] = numa_info[n].free;
    }
3660

3661 3662 3663 3664
    ret = numCells;

cleanup:
    libxl_numainfo_list_free(numa_info, nr_nodes);
3665
    virObjectUnref(cfg);
3666 3667 3668
    return ret;
}

3669
static int
3670
libxlConnectDomainEventRegister(virConnectPtr conn,
3671 3672
                                virConnectDomainEventCallback callback,
                                void *opaque,
3673
                                virFreeCallback freecb)
3674 3675 3676
{
    libxlDriverPrivatePtr driver = conn->privateData;

3677 3678 3679
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

3680 3681 3682 3683
    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        return -1;
3684

3685
    return 0;
3686 3687 3688 3689
}


static int
3690 3691
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
3692 3693 3694
{
    libxlDriverPrivatePtr driver = conn->privateData;

3695 3696 3697
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

3698 3699 3700 3701
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
3702

3703
    return 0;
3704 3705
}

3706 3707 3708 3709 3710 3711
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
3712
    if (!(vm = libxlDomObjFromDomain(dom)))
3713 3714
        goto cleanup;

3715 3716 3717
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3718 3719 3720 3721 3722
    *autostart = vm->autostart;
    ret = 0;

cleanup:
    if (vm)
3723
        virObjectUnlock(vm);
3724 3725 3726 3727 3728 3729 3730
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3731
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3732 3733 3734 3735
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
3736
    if (!(vm = libxlDomObjFromDomain(dom)))
3737 3738
        goto cleanup;

3739 3740 3741
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3742
    if (!vm->persistent) {
3743 3744
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
3745 3746 3747 3748 3749 3750
        goto cleanup;
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
3751
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
3752
            goto cleanup;
3753
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
3754 3755 3756
            goto cleanup;

        if (autostart) {
3757
            if (virFileMakePath(cfg->autostartDir) < 0) {
3758
                virReportSystemError(errno,
3759
                                     _("cannot create autostart directory %s"),
3760
                                     cfg->autostartDir);
3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786
                goto cleanup;
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
                goto cleanup;
            }
        }

        vm->autostart = autostart;
    }
    ret = 0;

cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    if (vm)
3787
        virObjectUnlock(vm);
3788
    virObjectUnref(cfg);
3789 3790 3791
    return ret;
}

3792 3793 3794 3795 3796 3797
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    char * ret = NULL;
3798
    const char *name = NULL;
J
Jim Fehlig 已提交
3799
    libxl_scheduler sched_id;
3800

J
Jim Fehlig 已提交
3801
    if (!(vm = libxlDomObjFromDomain(dom)))
3802 3803
        goto cleanup;

3804 3805 3806
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3807
    if (!virDomainObjIsActive(vm)) {
3808
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3809 3810 3811 3812
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
3813
    sched_id = libxl_get_scheduler(priv->ctx);
3814

3815 3816
    if (nparams)
        *nparams = 0;
3817
    switch (sched_id) {
J
Jim Fehlig 已提交
3818
    case LIBXL_SCHEDULER_SEDF:
3819
        name = "sedf";
3820
        break;
J
Jim Fehlig 已提交
3821
    case LIBXL_SCHEDULER_CREDIT:
3822
        name = "credit";
3823 3824
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
3825
        break;
J
Jim Fehlig 已提交
3826
    case LIBXL_SCHEDULER_CREDIT2:
3827
        name = "credit2";
3828
        break;
J
Jim Fehlig 已提交
3829
    case LIBXL_SCHEDULER_ARINC653:
3830
        name = "arinc653";
3831 3832
        break;
    default:
J
Jim Fehlig 已提交
3833 3834 3835
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
                     " with libxenlight"), dom->id);
3836 3837 3838
        goto cleanup;
    }

3839
    ignore_value(VIR_STRDUP(ret, name));
3840 3841 3842

cleanup:
    if (vm)
3843
        virObjectUnlock(vm);
3844 3845 3846
    return ret;
}

3847
static int
3848 3849 3850 3851
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
3852 3853 3854
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3855 3856
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
3857 3858
    int ret = -1;

3859 3860 3861 3862
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We don't return strings, and thus trivially support this flag.  */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;
3863

J
Jim Fehlig 已提交
3864
    if (!(vm = libxlDomObjFromDomain(dom)))
3865 3866
        goto cleanup;

3867 3868 3869
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3870
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
3871 3872
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
3873 3874 3875 3876 3877
        goto cleanup;
    }

    priv = vm->privateData;

J
Jim Fehlig 已提交
3878
    sched_id = libxl_get_scheduler(priv->ctx);
3879

J
Jim Fehlig 已提交
3880
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3881 3882
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3883 3884 3885
        goto cleanup;
    }

J
Jim Fehlig 已提交
3886
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
3887 3888 3889
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3890 3891 3892
        goto cleanup;
    }

3893 3894
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
3895 3896
        goto cleanup;

3897
    if (*nparams > 1) {
3898 3899
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
3900
            goto cleanup;
3901 3902
    }

3903 3904
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
3905 3906 3907 3908
    ret = 0;

cleanup:
    if (vm)
3909
        virObjectUnlock(vm);
3910 3911 3912 3913
    return ret;
}

static int
3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924
libxlDomainGetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int *nparams)
{
    return libxlDomainGetSchedulerParametersFlags(dom, params, nparams, 0);
}

static int
libxlDomainSetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int nparams,
                                       unsigned int flags)
3925 3926 3927
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3928
    libxl_domain_sched_params sc_info;
3929
    int sched_id;
3930
    size_t i;
3931 3932
    int ret = -1;

3933
    virCheckFlags(0, -1);
3934 3935 3936 3937 3938 3939
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
3940
        return -1;
3941

J
Jim Fehlig 已提交
3942
    if (!(vm = libxlDomObjFromDomain(dom)))
3943 3944
        goto cleanup;

3945 3946 3947
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3948
    if (!virDomainObjIsActive(vm)) {
3949
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3950 3951 3952 3953 3954
        goto cleanup;
    }

    priv = vm->privateData;

J
Jim Fehlig 已提交
3955
    sched_id = libxl_get_scheduler(priv->ctx);
3956

J
Jim Fehlig 已提交
3957
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3958 3959
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3960 3961 3962
        goto cleanup;
    }

J
Jim Fehlig 已提交
3963
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
3964 3965 3966
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3967 3968 3969 3970
        goto cleanup;
    }

    for (i = 0; i < nparams; ++i) {
3971
        virTypedParameterPtr param = &params[i];
3972

3973
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
3974
            sc_info.weight = params[i].value.ui;
3975
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
3976 3977 3978
            sc_info.cap = params[i].value.ui;
    }

J
Jim Fehlig 已提交
3979
    if (libxl_domain_sched_params_set(priv->ctx, dom->id, &sc_info) != 0) {
3980 3981 3982
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3983 3984 3985 3986 3987 3988 3989
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
3990
        virObjectUnlock(vm);
3991 3992 3993
    return ret;
}

B
Bamvor Jian Zhang 已提交
3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015

static int
libxlDomainOpenConsole(virDomainPtr dom,
                       const char *dev_name,
                       virStreamPtr st,
                       unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainChrDefPtr chr = NULL;
    libxlDomainObjPrivatePtr priv;
    char *console = NULL;

    virCheckFlags(VIR_DOMAIN_CONSOLE_FORCE, -1);

    if (dev_name) {
        /* XXX support device aliases in future */
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Named device aliases are not supported"));
        goto cleanup;
    }

J
Jim Fehlig 已提交
4016
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072
        goto cleanup;

    if (virDomainOpenConsoleEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto cleanup;
    }

    priv = vm->privateData;

    if (vm->def->nserials)
        chr = vm->def->serials[0];

    if (!chr) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot find character device %s"),
                       NULLSTR(dev_name));
        goto cleanup;
    }

    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("character device %s is not using a PTY"),
                       NULLSTR(dev_name));
        goto cleanup;
    }

    ret = libxl_primary_console_get_tty(priv->ctx, vm->def->id, &console);
    if (ret)
        goto cleanup;

    if (VIR_STRDUP(chr->source.data.file.path, console) < 0)
        goto cleanup;

    /* handle mutually exclusive access to console devices */
    ret = virChrdevOpen(priv->devs,
                        &chr->source,
                        st,
                        (flags & VIR_DOMAIN_CONSOLE_FORCE) != 0);

    if (ret == 1) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Active console session exists for this domain"));
        ret = -1;
    }

cleanup:
    VIR_FREE(console);
    if (vm)
        virObjectUnlock(vm);
    return ret;
}

4073 4074 4075 4076 4077 4078 4079
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109
/* NUMA node affinity information is available through libxl
 * starting from Xen 4.3. */
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY

/* Number of Xen NUMA parameters */
# define LIBXL_NUMA_NPARAM 2

static int
libxlDomainGetNumaParameters(virDomainPtr dom,
                             virTypedParameterPtr params,
                             int *nparams,
                             unsigned int flags)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    libxl_bitmap nodemap;
    virBitmapPtr nodes = NULL;
    char *nodeset = NULL;
    int rc, ret = -1;
    size_t i, j;

    /* In Xen 4.3, it is possible to query the NUMA node affinity of a domain
     * via libxl, but not to change it. We therefore only allow AFFECT_LIVE. */
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We blindly return a string, and let libvirt.c and remote_driver.c do
     * the filtering on behalf of older clients that can't parse it. */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

4110 4111
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
4112
    if (!(vm = libxlDomObjFromDomain(dom)))
4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133
        goto cleanup;

    if (virDomainGetNumaParametersEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
        goto cleanup;
    }

    priv = vm->privateData;

    if ((*nparams) == 0) {
        *nparams = LIBXL_NUMA_NPARAM;
        ret = 0;
        goto cleanup;
    }

    for (i = 0; i < LIBXL_NUMA_NPARAM && i < *nparams; i++) {
        virMemoryParameterPtr param = &params[i];
4134
        int numnodes;
4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152

        switch (i) {
        case 0:
            /* NUMA mode */

            /* Xen implements something that is really close to numactl's
             * 'interleave' policy (see `man 8 numactl' for details). */
            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_MODE,
                                        VIR_TYPED_PARAM_INT,
                                        VIR_DOMAIN_NUMATUNE_MEM_INTERLEAVE) < 0)
                goto cleanup;

            break;

        case 1:
            /* Node affinity */

            /* Let's allocate both libxl and libvirt bitmaps */
4153 4154 4155 4156
            numnodes = libxl_get_max_nodes(priv->ctx);
            if (numnodes <= 0)
                goto cleanup;

4157
            if (libxl_node_bitmap_alloc(priv->ctx, &nodemap, 0) ||
4158
                !(nodes = virBitmapNew(numnodes))) {
4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210
                virReportOOMError();
                goto cleanup;
            }

            rc = libxl_domain_get_nodeaffinity(priv->ctx,
                                               vm->def->id,
                                               &nodemap);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get numa affinity"));
                goto cleanup;
            }

            /* First, we convert libxl_bitmap into virBitmap. After that,
             * we format virBitmap as a string that can be returned. */
            virBitmapClearAll(nodes);
            libxl_for_each_set_bit(j, nodemap) {
                if (virBitmapSetBit(nodes, j)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Node %zu out of range"), j);
                    goto cleanup;
                }
            }

            nodeset = virBitmapFormat(nodes);
            if (!nodeset && VIR_STRDUP(nodeset, "") < 0)
                goto cleanup;

            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_NODESET,
                                        VIR_TYPED_PARAM_STRING, nodeset) < 0)
                goto cleanup;

            nodeset = NULL;

            break;
        }
    }

    if (*nparams > LIBXL_NUMA_NPARAM)
        *nparams = LIBXL_NUMA_NPARAM;
    ret = 0;

cleanup:
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
    if (vm)
        virObjectUnlock(vm);
    return ret;
}
#endif

J
Jim Fehlig 已提交
4211 4212 4213 4214 4215 4216
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4217
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4218
        goto cleanup;
4219 4220 4221 4222

    if (virDomainIsActiveEnsureACL(dom->conn, obj->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
4223 4224 4225 4226
    ret = virDomainObjIsActive(obj);

  cleanup:
    if (obj)
4227
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4228 4229 4230 4231 4232 4233 4234 4235 4236
    return ret;
}

static int
libxlDomainIsPersistent(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4237
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4238
        goto cleanup;
4239 4240 4241 4242

    if (virDomainIsPersistentEnsureACL(dom->conn, obj->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
4243 4244 4245 4246
    ret = obj->persistent;

  cleanup:
    if (obj)
4247
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4248 4249 4250
    return ret;
}

4251 4252 4253 4254 4255 4256
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4257
    if (!(vm = libxlDomObjFromDomain(dom)))
4258
        goto cleanup;
4259 4260 4261 4262

    if (virDomainIsUpdatedEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4263 4264 4265 4266
    ret = vm->updated;

cleanup:
    if (vm)
4267
        virObjectUnlock(vm);
4268 4269 4270
    return ret;
}

4271
static int
4272 4273 4274
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4275 4276 4277 4278
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4279 4280 4281
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4282 4283 4284 4285
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4286
        ret = -1;
4287 4288 4289 4290 4291 4292

    return ret;
}


static int
4293
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4294 4295 4296
{
    libxlDriverPrivatePtr driver = conn->privateData;

4297 4298 4299
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4300 4301 4302 4303
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        return -1;
4304

4305
    return 0;
4306 4307
}

J
Jim Fehlig 已提交
4308

4309
static int
4310
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4311 4312 4313 4314
{
    return 1;
}

4315
static int
4316 4317 4318
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4319 4320 4321 4322
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4323
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4324

4325 4326 4327
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4328 4329
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
4330 4331 4332 4333

    return ret;
}

4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347
/* Which features are supported by this driver? */
static int
libxlConnectSupportsFeature(virConnectPtr conn, int feature)
{
    if (virConnectSupportsFeatureEnsureACL(conn) < 0)
        return -1;

    switch (feature) {
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
        return 1;
    default:
        return 0;
    }
}
4348

4349

J
Jim Fehlig 已提交
4350
static virDriver libxlDriver = {
4351 4352
    .no = VIR_DRV_LIBXL,
    .name = "xenlight",
4353 4354 4355 4356
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
4357
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
4358
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
4359
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
4360
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
4361 4362 4363 4364
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
4365 4366 4367 4368 4369 4370 4371
    .domainCreateXML = libxlDomainCreateXML, /* 0.9.0 */
    .domainLookupByID = libxlDomainLookupByID, /* 0.9.0 */
    .domainLookupByUUID = libxlDomainLookupByUUID, /* 0.9.0 */
    .domainLookupByName = libxlDomainLookupByName, /* 0.9.0 */
    .domainSuspend = libxlDomainSuspend, /* 0.9.0 */
    .domainResume = libxlDomainResume, /* 0.9.0 */
    .domainShutdown = libxlDomainShutdown, /* 0.9.0 */
4372
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
4373 4374
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
4375
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
4376 4377
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
4378
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
4379 4380 4381 4382
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
4383
    .domainSave = libxlDomainSave, /* 0.9.2 */
4384
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
4385
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
4386
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
4387
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
4388 4389 4390 4391
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
4392
    .domainPinVcpuFlags = libxlDomainPinVcpuFlags, /* 1.2.1 */
4393
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
4394
    .domainGetVcpuPinInfo = libxlDomainGetVcpuPinInfo, /* 1.2.1 */
4395
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
4396 4397 4398 4399
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
4400 4401 4402 4403
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
4404
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
4405 4406 4407 4408 4409
    .domainAttachDevice = libxlDomainAttachDevice, /* 0.9.2 */
    .domainAttachDeviceFlags = libxlDomainAttachDeviceFlags, /* 0.9.2 */
    .domainDetachDevice = libxlDomainDetachDevice,    /* 0.9.2 */
    .domainDetachDeviceFlags = libxlDomainDetachDeviceFlags, /* 0.9.2 */
    .domainUpdateDeviceFlags = libxlDomainUpdateDeviceFlags, /* 0.9.2 */
4410 4411 4412 4413
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
4414
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
4415
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
4416
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
4417 4418 4419
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
4420
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
4421
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
4422 4423
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
4424 4425 4426
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
4427
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
4428 4429 4430
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
4431 4432 4433
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
4434
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
J
Jim Fehlig 已提交
4435 4436 4437 4438
};

static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
4439
    .stateInitialize = libxlStateInitialize,
4440
    .stateAutoStart = libxlStateAutoStart,
4441 4442
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455
};


int
libxlRegister(void)
{
    if (virRegisterDriver(&libxlDriver) < 0)
        return -1;
    if (virRegisterStateDriver(&libxlStateDriver) < 0)
        return -1;

    return 0;
}