libxl_driver.c 123.6 KB
Newer Older
1 2 3 4 5 6
/*
 * libxl_driver.c: core driver methods for managing libxenlight domains
 *
 * Copyright (C) 2006-2013 Red Hat, Inc.
 * Copyright (C) 2011-2013 SUSE LINUX Products GmbH, Nuernberg, Germany.
 * 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 103 104
static void
libxlDomainEventQueue(libxlDriverPrivatePtr driver, virDomainEventPtr event)
{
105
    virDomainEventStateQueue(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

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

    if (vm->persistent) {
        vm->def->id = -1;
J
Jiri Denemark 已提交
276
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, reason);
J
Jim Fehlig 已提交
277 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

J
Jim Fehlig 已提交
316
    libxlDomainObjRegisteredTimeoutsCleanup(priv);
317
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
318 319 320 321 322 323 324 325
}

/*
 * Reap a domain from libxenlight.
 *
 * virDomainObjPtr should be locked on invocation
 */
static int
J
Jiri Denemark 已提交
326 327 328
libxlVmReap(libxlDriverPrivatePtr driver,
            virDomainObjPtr vm,
            virDomainShutoffReason reason)
J
Jim Fehlig 已提交
329 330 331
{
    libxlDomainObjPrivatePtr priv = vm->privateData;

J
Jim Fehlig 已提交
332
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
333 334
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to cleanup domain %d"), vm->def->id);
J
Jim Fehlig 已提交
335 336 337
        return -1;
    }

J
Jiri Denemark 已提交
338
    libxlVmCleanup(driver, vm, reason);
J
Jim Fehlig 已提交
339 340 341 342
    return 0;
}

/*
J
Jim Fehlig 已提交
343 344 345 346 347
 * 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 已提交
348
 */
J
Jim Fehlig 已提交
349 350 351 352 353 354 355

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

356
static void
J
Jim Fehlig 已提交
357
libxlEventHandler(void *data, VIR_LIBXL_EVENT_CONST libxl_event *event)
J
Jim Fehlig 已提交
358 359
{
    libxlDriverPrivatePtr driver = libxl_driver;
J
Jim Fehlig 已提交
360
    libxlDomainObjPrivatePtr priv = ((virDomainObjPtr)data)->privateData;
361
    virDomainObjPtr vm = NULL;
362
    virDomainEventPtr dom_event = NULL;
363
    libxl_shutdown_reason xl_reason = event->u.domain_shutdown.shutdown_reason;
J
Jim Fehlig 已提交
364

J
Jim Fehlig 已提交
365
    if (event->type == LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN) {
J
Jiri Denemark 已提交
366 367
        virDomainShutoffReason reason;

368 369 370 371 372 373 374
        /*
         * 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 cleanup;

375
        vm = virDomainObjListFindByID(driver->domains, event->domid);
376
        if (!vm)
J
Jim Fehlig 已提交
377 378
            goto cleanup;

379
        switch (xl_reason) {
J
Jim Fehlig 已提交
380 381
            case LIBXL_SHUTDOWN_REASON_POWEROFF:
            case LIBXL_SHUTDOWN_REASON_CRASH:
382
                if (xl_reason == LIBXL_SHUTDOWN_REASON_CRASH) {
383 384 385
                    dom_event = virDomainEventNewFromObj(vm,
                                              VIR_DOMAIN_EVENT_STOPPED,
                                              VIR_DOMAIN_EVENT_STOPPED_CRASHED);
J
Jiri Denemark 已提交
386 387 388 389
                    reason = VIR_DOMAIN_SHUTOFF_CRASHED;
                } else {
                    reason = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
                }
J
Jim Fehlig 已提交
390
                libxlVmReap(driver, vm, reason);
J
Jim Fehlig 已提交
391
                if (!vm->persistent) {
392
                    virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
393 394 395
                    vm = NULL;
                }
                break;
J
Jim Fehlig 已提交
396 397
            case LIBXL_SHUTDOWN_REASON_REBOOT:
                libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
398
                libxlVmStart(driver, vm, 0, -1);
J
Jim Fehlig 已提交
399 400
                break;
            default:
401
                VIR_INFO("Unhandled shutdown_reason %d", xl_reason);
J
Jim Fehlig 已提交
402 403 404 405 406 407
                break;
        }
    }

cleanup:
    if (vm)
408
        virObjectUnlock(vm);
409
    if (dom_event)
410
        libxlDomainEventQueue(driver, dom_event);
J
Jim Fehlig 已提交
411 412
    /* Cast away any const */
    libxl_event_free(priv->ctx, (libxl_event *)event);
J
Jim Fehlig 已提交
413 414
}

J
Jim Fehlig 已提交
415 416 417 418 419 420
static const struct libxl_event_hooks ev_hooks = {
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlEventHandler,
    .disaster = NULL,
};

J
Jim Fehlig 已提交
421 422 423 424 425 426 427 428 429
/*
 * Register domain events with libxenlight and insert event handles
 * in libvirt's event loop.
 */
static int
libxlCreateDomEvents(virDomainObjPtr vm)
{
    libxlDomainObjPrivatePtr priv = vm->privateData;

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

J
Jim Fehlig 已提交
432
    if (libxl_evenable_domain_death(priv->ctx, vm->def->id, 0, &priv->deathW))
J
Jim Fehlig 已提交
433 434 435 436 437
        goto error;

    return 0;

error:
438
    if (priv->deathW) {
J
Jim Fehlig 已提交
439
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
440 441
        priv->deathW = NULL;
    }
J
Jim Fehlig 已提交
442 443 444
    return -1;
}

445
static int
446
libxlDomainSetVcpuAffinities(libxlDriverPrivatePtr driver, virDomainObjPtr vm)
447 448 449
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
    virDomainDefPtr def = vm->def;
J
Jim Fehlig 已提交
450
    libxl_bitmap map;
451
    virBitmapPtr cpumask = NULL;
452 453 454
    uint8_t *cpumap = NULL;
    virNodeInfo nodeinfo;
    size_t cpumaplen;
455 456
    int vcpu;
    size_t i;
457 458 459 460 461 462 463 464 465 466 467
    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;

468
        if (VIR_ALLOC_N(cpumap, cpumaplen) < 0)
469 470
            goto cleanup;

471
        cpumask = def->cputune.vcpupin[vcpu]->cpumask;
472

473 474 475 476
        for (i = 0; i < virBitmapSize(cpumask); ++i) {
            bool bit;
            ignore_value(virBitmapGetBit(cpumask, i, &bit));
            if (bit)
477
                VIR_USE_CPU(cpumap, i);
478 479 480 481 482
        }

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

J
Jim Fehlig 已提交
483
        if (libxl_set_vcpuaffinity(priv->ctx, def->id, vcpu, &map) != 0) {
484 485
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
486 487 488 489 490 491 492 493 494 495 496 497 498
            goto cleanup;
        }

        VIR_FREE(cpumap);
    }

    ret = 0;

cleanup:
    VIR_FREE(cpumap);
    return ret;
}

M
Markus Groß 已提交
499 500 501 502 503
static int
libxlFreeMem(libxlDomainObjPrivatePtr priv, libxl_domain_config *d_config)
{
    uint32_t needed_mem;
    uint32_t free_mem;
504
    size_t i;
M
Markus Groß 已提交
505 506 507 508
    int ret = -1;
    int tries = 3;
    int wait_secs = 10;

J
Jim Fehlig 已提交
509
    if ((ret = libxl_domain_need_memory(priv->ctx, &d_config->b_info,
M
Markus Groß 已提交
510 511
                                        &needed_mem)) >= 0) {
        for (i = 0; i < tries; ++i) {
J
Jim Fehlig 已提交
512
            if ((ret = libxl_get_free_memory(priv->ctx, &free_mem)) < 0)
M
Markus Groß 已提交
513 514 515 516 517 518 519
                break;

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

J
Jim Fehlig 已提交
520
            if ((ret = libxl_set_memory_target(priv->ctx, 0,
M
Markus Groß 已提交
521 522 523 524
                                               free_mem - needed_mem,
                                               /* relative */ 1, 0)) < 0)
                break;

J
Jim Fehlig 已提交
525
            ret = libxl_wait_for_free_memory(priv->ctx, 0, needed_mem,
M
Markus Groß 已提交
526 527 528 529
                                             wait_secs);
            if (ret == 0 || ret != ERROR_NOMEM)
                break;

J
Jim Fehlig 已提交
530
            if ((ret = libxl_wait_for_memory_target(priv->ctx, 0, 1)) < 0)
M
Markus Groß 已提交
531 532 533 534 535 536 537
                break;
        }
    }

    return ret;
}

J
Jim Fehlig 已提交
538 539 540 541 542 543
/*
 * Start a domain through libxenlight.
 *
 * virDomainObjPtr should be locked on invocation
 */
static int
544 545
libxlVmStart(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
             bool start_paused, int restore_fd)
J
Jim Fehlig 已提交
546 547
{
    libxl_domain_config d_config;
548
    virDomainDefPtr def = NULL;
549
    virDomainEventPtr event = NULL;
550
    libxlSavefileHeader hdr;
J
Jim Fehlig 已提交
551 552 553
    int ret;
    uint32_t domid = 0;
    char *dom_xml = NULL;
554 555
    char *managed_save_path = NULL;
    int managed_save_fd = -1;
J
Jim Fehlig 已提交
556
    libxlDomainObjPrivatePtr priv = vm->privateData;
557
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
B
Bamvor Jian Zhang 已提交
558 559 560
#ifdef LIBXL_HAVE_DOMAIN_CREATE_RESTORE_PARAMS
    libxl_domain_restore_params params;
#endif
J
Jim Fehlig 已提交
561

J
Jim Fehlig 已提交
562 563 564
    if (libxlDomainObjPrivateInitCtx(vm) < 0)
        goto error;

565 566 567
    /* 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) {
568 569
        managed_save_path = libxlDomainManagedSavePath(driver, vm);
        if (managed_save_path == NULL)
570 571
            goto error;

572
        if (virFileExists(managed_save_path)) {
573

574 575
            managed_save_fd = libxlSaveImageOpen(driver, cfg,
                                                 managed_save_path,
576 577
                                                 &def, &hdr);
            if (managed_save_fd < 0)
578 579
                goto error;

580 581
            restore_fd = managed_save_fd;

582 583 584 585 586 587
            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);
588 589 590 591
                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);
592 593 594
                goto error;
            }

595
            virDomainObjAssignDef(vm, def, true, NULL);
596 597
            def = NULL;

598
            if (unlink(managed_save_path) < 0)
599 600
                VIR_WARN("Failed to remove the managed state %s",
                         managed_save_path);
601

602
            vm->hasManagedSave = false;
603
        }
604
        VIR_FREE(managed_save_path);
605 606
    }

J
Jim Fehlig 已提交
607
    libxl_domain_config_init(&d_config);
J
Jim Fehlig 已提交
608

609
    if (libxlBuildDomainConfig(driver, vm, &d_config) < 0)
610
        goto error;
J
Jim Fehlig 已提交
611

612
    if (cfg->autoballoon && libxlFreeMem(priv, &d_config) < 0) {
613 614 615
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to get free memory for domain '%s'"),
                       d_config.c_info.name);
M
Markus Groß 已提交
616 617
        goto error;
    }
J
Jim Fehlig 已提交
618

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

621
    if (restore_fd < 0)
J
Jim Fehlig 已提交
622 623
        ret = libxl_domain_create_new(priv->ctx, &d_config,
                                      &domid, NULL, NULL);
624
    else
B
Bamvor Jian Zhang 已提交
625 626 627 628 629
#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 已提交
630 631
        ret = libxl_domain_create_restore(priv->ctx, &d_config, &domid,
                                          restore_fd, NULL, NULL);
B
Bamvor Jian Zhang 已提交
632
#endif
633

J
Jim Fehlig 已提交
634
    if (ret) {
635
        if (restore_fd < 0)
636 637 638
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to create new domain '%s'"),
                           d_config.c_info.name);
639
        else
640 641 642
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to restore domain '%s'"),
                           d_config.c_info.name);
J
Jim Fehlig 已提交
643 644 645
        goto error;
    }

646 647
    vm->def->id = domid;
    if ((dom_xml = virDomainDefFormat(vm->def, 0)) == NULL)
J
Jim Fehlig 已提交
648 649
        goto error;

J
Jim Fehlig 已提交
650
    if (libxl_userdata_store(priv->ctx, domid, "libvirt-xml",
J
Jim Fehlig 已提交
651
                             (uint8_t *)dom_xml, strlen(dom_xml) + 1)) {
652 653
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to store userdata"));
J
Jim Fehlig 已提交
654 655 656 657 658 659
        goto error;
    }

    if (libxlCreateDomEvents(vm) < 0)
        goto error;

660
    if (libxlDomainSetVcpuAffinities(driver, vm) < 0)
661 662
        goto error;

J
Jim Fehlig 已提交
663
    if (!start_paused) {
J
Jim Fehlig 已提交
664
        libxl_domain_unpause(priv->ctx, domid);
J
Jiri Denemark 已提交
665
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
J
Jim Fehlig 已提交
666
    } else {
J
Jiri Denemark 已提交
667
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
J
Jim Fehlig 已提交
668 669
    }

670

671
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
J
Jim Fehlig 已提交
672 673
        goto error;

674
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
675 676
        driver->inhibitCallback(true, driver->inhibitOpaque);

677
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STARTED,
678 679 680
                                     restore_fd < 0 ?
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED :
                                         VIR_DOMAIN_EVENT_STARTED_RESTORED);
681 682
    if (event)
        libxlDomainEventQueue(driver, event);
683

J
Jim Fehlig 已提交
684
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
685
    VIR_FREE(dom_xml);
686
    VIR_FORCE_CLOSE(managed_save_fd);
687
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
688 689 690 691
    return 0;

error:
    if (domid > 0) {
J
Jim Fehlig 已提交
692
        libxl_domain_destroy(priv->ctx, domid, NULL);
693
        vm->def->id = -1;
J
Jiri Denemark 已提交
694
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);
J
Jim Fehlig 已提交
695
    }
J
Jim Fehlig 已提交
696
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
697
    VIR_FREE(dom_xml);
698
    VIR_FREE(managed_save_path);
699
    virDomainDefFree(def);
700
    VIR_FORCE_CLOSE(managed_save_fd);
701
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
702 703 704 705 706 707 708 709
    return -1;
}


/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
710 711
static int
libxlReconnectDomain(virDomainObjPtr vm,
J
Jim Fehlig 已提交
712 713 714
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
715
    libxlDomainObjPrivatePtr priv = vm->privateData;
J
Jim Fehlig 已提交
716 717 718 719 720
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;

721
    virObjectLock(vm);
J
Jim Fehlig 已提交
722

723
    libxlDomainObjPrivateInitCtx(vm);
J
Jim Fehlig 已提交
724
    /* Does domain still exist? */
725
    rc = libxl_domain_info(priv->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
726 727 728 729 730 731 732 733 734
    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? */
735
    if (libxl_userdata_retrieve(priv->ctx, vm->def->id,
J
Jim Fehlig 已提交
736 737 738 739 740 741 742
                                "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 已提交
743
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_UNKNOWN);
J
Jim Fehlig 已提交
744

745
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
746 747
        driver->inhibitCallback(true, driver->inhibitOpaque);

J
Jim Fehlig 已提交
748 749
    /* Recreate domain death et. al. events */
    libxlCreateDomEvents(vm);
750
    virObjectUnlock(vm);
751
    return 0;
J
Jim Fehlig 已提交
752 753

out:
J
Jiri Denemark 已提交
754
    libxlVmCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_UNKNOWN);
J
Jim Fehlig 已提交
755
    if (!vm->persistent)
756
        virDomainObjListRemoveLocked(driver->domains, vm);
J
Jim Fehlig 已提交
757
    else
758
        virObjectUnlock(vm);
759 760

    return -1;
J
Jim Fehlig 已提交
761 762 763 764 765
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
766
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
767 768 769
}

static int
770
libxlStateCleanup(void)
J
Jim Fehlig 已提交
771 772 773 774
{
    if (!libxl_driver)
        return -1;

775
    virObjectUnref(libxl_driver->config);
776
    virObjectUnref(libxl_driver->xmlopt);
777
    virObjectUnref(libxl_driver->domains);
778
    virObjectUnref(libxl_driver->reservedVNCPorts);
J
Jim Fehlig 已提交
779

E
Eric Blake 已提交
780
    virDomainEventStateFree(libxl_driver->domainEventState);
781
    virSysinfoDefFree(libxl_driver->hostsysinfo);
782

J
Jim Fehlig 已提交
783 784 785 786 787 788
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

789 790
static bool
libxlDriverShouldLoad(bool privileged)
791
{
792
    bool ret = false;
J
Jim Fehlig 已提交
793
    virCommandPtr cmd;
794
    int status;
J
Jim Fehlig 已提交
795

796
    /* Don't load if non-root */
J
Jim Fehlig 已提交
797
    if (!privileged) {
798
        VIR_INFO("Not running privileged, disabling libxenlight driver");
799
        return ret;
J
Jim Fehlig 已提交
800 801
    }

802 803 804 805 806 807 808 809 810
    /* 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 已提交
811 812
    cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL);
    if (virCommandRun(cmd, &status) == 0 && status == 0) {
813
        VIR_INFO("Legacy xen tool stack seems to be in use, disabling "
J
Jim Fehlig 已提交
814
                  "libxenlight driver.");
815 816
    } else {
        ret = true;
J
Jim Fehlig 已提交
817 818 819
    }
    virCommandFree(cmd);

820 821 822 823 824 825 826 827
    return ret;
}

static int
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
828
    libxlDriverConfigPtr cfg;
829 830 831 832 833
    char ebuf[1024];

    if (!libxlDriverShouldLoad(privileged))
        return 0;

J
Jim Fehlig 已提交
834 835 836 837
    if (VIR_ALLOC(libxl_driver) < 0)
        return -1;

    if (virMutexInit(&libxl_driver->lock) < 0) {
838 839
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
J
Jim Fehlig 已提交
840 841 842 843 844
        VIR_FREE(libxl_driver);
        return -1;
    }

    /* Allocate bitmap for vnc port reservation */
845 846 847 848
    if (!(libxl_driver->reservedVNCPorts =
          virPortAllocatorNew(LIBXL_VNC_PORT_MIN,
                              LIBXL_VNC_PORT_MAX)))
        goto error;
J
Jim Fehlig 已提交
849

850 851
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
852

853
    if (!(cfg = libxlDriverConfigNew()))
854
        goto error;
J
Jim Fehlig 已提交
855

856 857
    libxl_driver->config = cfg;
    if (virFileMakePath(cfg->logDir) < 0) {
858 859
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create log dir '%s': %s"),
860
                       cfg->logDir,
861
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
862 863
        goto error;
    }
864
    if (virFileMakePath(cfg->stateDir) < 0) {
865 866
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create state dir '%s': %s"),
867
                       cfg->stateDir,
868
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
869 870
        goto error;
    }
871
    if (virFileMakePath(cfg->libDir) < 0) {
872 873
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create lib dir '%s': %s"),
874
                       cfg->libDir,
875
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
876 877
        goto error;
    }
878
    if (virFileMakePath(cfg->saveDir) < 0) {
879 880
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create save dir '%s': %s"),
881
                       cfg->saveDir,
882
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
883 884 885
        goto error;
    }

886
    /* read the host sysinfo */
887
    libxl_driver->hostsysinfo = virSysinfoRead();
888

889
    libxl_driver->domainEventState = virDomainEventStateNew();
E
Eric Blake 已提交
890
    if (!libxl_driver->domainEventState)
891 892
        goto error;

893
    if ((cfg->caps = libxlMakeCapabilities(cfg->ctx)) == NULL) {
894 895
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
896 897 898
        goto error;
    }

899
    if (!(libxl_driver->xmlopt = virDomainXMLOptionNew(&libxlDomainDefParserConfig,
900 901
                                                       &libxlDomainXMLPrivateDataCallbacks,
                                                       NULL)))
902
        goto error;
J
Jim Fehlig 已提交
903 904

    /* Load running domains first. */
905
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
906 907
                                       cfg->stateDir,
                                       cfg->autostartDir,
908
                                       1,
909
                                       cfg->caps,
910 911
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
912
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
913 914 915 916 917
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
918
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
919 920
                                       cfg->configDir,
                                       cfg->autostartDir,
921
                                       0,
922
                                       cfg->caps,
923 924
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
925
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
926 927
        goto error;

928 929
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
930

J
Jim Fehlig 已提交
931 932 933
    return 0;

error:
934
    libxlStateCleanup();
935
    return -1;
J
Jim Fehlig 已提交
936 937
}

938 939 940 941 942 943 944 945 946 947
static void
libxlStateAutoStart(void)
{
    if (!libxl_driver)
        return;

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

J
Jim Fehlig 已提交
948
static int
949
libxlStateReload(void)
J
Jim Fehlig 已提交
950
{
951 952
    libxlDriverConfigPtr cfg;

J
Jim Fehlig 已提交
953 954 955
    if (!libxl_driver)
        return 0;

956 957
    cfg = libxlDriverConfigGet(libxl_driver);

958
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
959 960
                                   cfg->configDir,
                                   cfg->autostartDir,
961
                                   1,
962
                                   cfg->caps,
963 964
                                   libxl_driver->xmlopt,
                                   1 << VIR_DOMAIN_VIRT_XEN,
965 966
                                   NULL, libxl_driver);

967 968
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
969

970
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
971 972 973 974 975
    return 0;
}


static virDrvOpenStatus
976 977 978
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 unsigned int flags)
J
Jim Fehlig 已提交
979
{
E
Eric Blake 已提交
980 981
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
982 983 984 985
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

986
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
987 988 989 990 991 992 993 994 995 996 997 998
            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) {
999 1000
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
1001 1002 1003 1004 1005 1006 1007 1008
            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")) {
1009 1010 1011
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
1012 1013 1014 1015
            return VIR_DRV_OPEN_ERROR;
        }
    }

1016 1017 1018
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
1019 1020 1021 1022 1023 1024
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
1025
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1026 1027 1028 1029 1030 1031
{
    conn->privateData = NULL;
    return 0;
}

static const char *
1032
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
1033
{
1034 1035 1036
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
1037
    return "Xen";
J
Jim Fehlig 已提交
1038 1039 1040
}

static int
1041
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
1042 1043
{
    libxlDriverPrivatePtr driver = conn->privateData;
1044
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
1045

1046 1047 1048
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

1049 1050 1051
    cfg = libxlDriverConfigGet(driver);
    *version = cfg->version;
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1052 1053 1054
    return 0;
}

1055

1056
static char *libxlConnectGetHostname(virConnectPtr conn)
1057
{
1058 1059 1060
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

1061 1062 1063
    return virGetHostname();
}

1064 1065 1066 1067 1068 1069 1070 1071
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

1072 1073 1074
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    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);
}
1089

J
Jim Fehlig 已提交
1090
static int
1091
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1092 1093 1094
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;
1095
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
1096

1097 1098 1099
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

1100 1101
    cfg = libxlDriverConfigGet(driver);
    ret = libxl_get_max_cpus(cfg->ctx);
J
Jim Fehlig 已提交
1102 1103 1104
    /* libxl_get_max_cpus() will return 0 if there were any failures,
       e.g. xc_physinfo() failing */
    if (ret == 0)
1105
        ret = -1;
J
Jim Fehlig 已提交
1106

1107
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1108 1109 1110 1111 1112 1113
    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
1114 1115 1116
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

1117
    return libxlDoNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
1118 1119 1120
}

static char *
1121
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
1122 1123 1124
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;
1125
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
1126

1127 1128 1129
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

1130 1131
    cfg = libxlDriverConfigGet(driver);
    if ((xml = virCapabilitiesFormatXML(cfg->caps)) == NULL)
J
Jim Fehlig 已提交
1132 1133
        virReportOOMError();

1134
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1135 1136 1137 1138
    return xml;
}

static int
1139
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
1140 1141 1142 1143
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1144 1145 1146
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

1147 1148
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1149 1150 1151 1152 1153

    return n;
}

static int
1154
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
1155 1156 1157 1158
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1159 1160 1161
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

1162 1163
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

    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;
1176
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1177 1178 1179

    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);

1180
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
1181
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
1182 1183 1184
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

1185 1186 1187
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

1188
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1189
                                   driver->xmlopt,
1190 1191
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
1192 1193 1194
        goto cleanup;
    def = NULL;

1195 1196
    if (libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0,
                     -1) < 0) {
1197
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
        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)
1209
        virObjectUnlock(vm);
1210
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    return dom;
}

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

1221
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
1222
    if (!vm) {
1223
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1224 1225 1226
        goto cleanup;
    }

1227 1228 1229
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1230 1231 1232 1233 1234 1235
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1236
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    return dom;
}

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

1247
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
1248
    if (!vm) {
1249
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1250 1251 1252
        goto cleanup;
    }

1253 1254 1255
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

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

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

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

1273
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
1274
    if (!vm) {
1275
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1276 1277 1278
        goto cleanup;
    }

1279 1280 1281
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

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

  cleanup:
    if (vm)
1288
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1289 1290 1291
    return dom;
}

1292 1293 1294 1295
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1296
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1297 1298 1299 1300 1301
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
    virDomainEventPtr event = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
1302
    if (!(vm = libxlDomObjFromDomain(dom)))
1303
        goto cleanup;
1304 1305 1306 1307

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

1308
    if (!virDomainObjIsActive(vm)) {
1309
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1310 1311 1312 1313 1314
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1315
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1316
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
1317 1318 1319
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to suspend domain '%d' with libxenlight"),
                           dom->id);
1320 1321 1322
            goto cleanup;
        }

J
Jiri Denemark 已提交
1323
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1324 1325 1326 1327 1328

        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

1329
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1330 1331 1332 1333 1334 1335
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
1336
        virObjectUnlock(vm);
1337
    if (event)
1338
        libxlDomainEventQueue(driver, event);
1339
    virObjectUnref(cfg);
1340 1341 1342 1343 1344 1345 1346 1347
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1348
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1349 1350 1351 1352 1353
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
    virDomainEventPtr event = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
1354
    if (!(vm = libxlDomObjFromDomain(dom)))
1355 1356
        goto cleanup;

1357 1358 1359
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1360
    if (!virDomainObjIsActive(vm)) {
1361
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1362 1363 1364 1365 1366
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1367
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1368
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
1369 1370 1371
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
                           dom->id);
1372 1373 1374
            goto cleanup;
        }

J
Jiri Denemark 已提交
1375 1376
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1377 1378 1379 1380 1381

        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

1382
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1383 1384 1385 1386 1387 1388
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
1389
        virObjectUnlock(vm);
1390
    if (event)
1391
        libxlDomainEventQueue(driver, event);
1392
    virObjectUnref(cfg);
1393 1394 1395
    return ret;
}

J
Jim Fehlig 已提交
1396
static int
1397
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1398 1399 1400 1401 1402
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

1403 1404
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1405
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1406 1407
        goto cleanup;

1408 1409 1410
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1411
    if (!virDomainObjIsActive(vm)) {
1412 1413
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1414 1415 1416 1417
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1418
    if (libxl_domain_shutdown(priv->ctx, dom->id) != 0) {
1419 1420 1421
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        goto cleanup;
    }

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

cleanup:
    if (vm)
1432
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1433 1434 1435
    return ret;
}

1436 1437 1438 1439 1440 1441 1442
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
1443
static int
E
Eric Blake 已提交
1444
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1445 1446 1447 1448 1449
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

E
Eric Blake 已提交
1450 1451
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1452
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1453 1454
        goto cleanup;

1455 1456 1457
    if (virDomainRebootEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1458
    if (!virDomainObjIsActive(vm)) {
1459 1460
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1461 1462 1463 1464
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1465
    if (libxl_domain_reboot(priv->ctx, dom->id) != 0) {
1466 1467 1468
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1469 1470 1471 1472 1473 1474
        goto cleanup;
    }
    ret = 0;

cleanup:
    if (vm)
1475
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1476 1477 1478 1479
    return ret;
}

static int
1480 1481
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1482 1483 1484 1485
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1486
    virDomainEventPtr event = NULL;
J
Jim Fehlig 已提交
1487

1488 1489
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1490
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1491 1492
        goto cleanup;

1493 1494 1495
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1496
    if (!virDomainObjIsActive(vm)) {
1497 1498
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1499 1500 1501
        goto cleanup;
    }

1502 1503 1504
    event = virDomainEventNewFromObj(vm,VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

J
Jim Fehlig 已提交
1505
    if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED) != 0) {
1506 1507
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), dom->id);
J
Jim Fehlig 已提交
1508 1509 1510 1511
        goto cleanup;
    }

    if (!vm->persistent) {
1512
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1513 1514 1515 1516 1517 1518 1519
        vm = NULL;
    }

    ret = 0;

cleanup:
    if (vm)
1520
        virObjectUnlock(vm);
1521 1522
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1523 1524 1525
    return ret;
}

1526 1527 1528 1529 1530 1531
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1532 1533 1534 1535 1536 1537
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *type = NULL;

J
Jim Fehlig 已提交
1538
    if (!(vm = libxlDomObjFromDomain(dom)))
1539 1540
        goto cleanup;

1541 1542 1543 1544 1545
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

    if (VIR_STRDUP(type, vm->def->os.type) < 0)
        goto cleanup;
1546 1547 1548

cleanup:
    if (vm)
1549
        virObjectUnlock(vm);
1550 1551 1552
    return type;
}

1553
static unsigned long long
1554 1555 1556
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    virDomainObjPtr vm;
1557
    unsigned long long ret = 0;
1558

J
Jim Fehlig 已提交
1559
    if (!(vm = libxlDomObjFromDomain(dom)))
1560
        goto cleanup;
1561 1562 1563 1564

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

1565 1566 1567 1568
    ret = vm->def->mem.max_balloon;

cleanup:
    if (vm)
1569
        virObjectUnlock(vm);
1570 1571 1572 1573
    return ret;
}

static int
1574
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1575 1576 1577
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1578
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1579 1580
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1581 1582
    virDomainDefPtr persistentDef = NULL;
    bool isActive;
1583 1584 1585
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1586 1587
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1588

J
Jim Fehlig 已提交
1589
    if (!(vm = libxlDomObjFromDomain(dom)))
1590 1591
        goto cleanup;

1592 1593 1594
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
    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;
1608 1609
    }

1610
    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
1611 1612
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set memory on an inactive domain"));
1613 1614 1615 1616 1617
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
1618 1619
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a transient domain"));
1620 1621
            goto cleanup;
        }
1622
        if (!(persistentDef = virDomainObjGetPersistentDef(cfg->caps,
1623
                                                           driver->xmlopt,
1624
                                                           vm)))
1625 1626 1627
            goto cleanup;
    }

1628 1629
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1630

1631 1632
        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
1633
            if (libxl_domain_setmaxmem(priv->ctx, dom->id, newmem) < 0) {
1634 1635 1636
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
                                 " with libxenlight"), dom->id);
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
                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;
1647
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
1648 1649 1650
            goto cleanup;
        }

1651 1652
    } else {
        /* resize the current memory */
1653

1654
        if (newmem > vm->def->mem.max_balloon) {
1655 1656
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1657 1658 1659 1660 1661
            goto cleanup;
        }

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

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1674
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
1675 1676
            goto cleanup;
        }
1677 1678
    }

1679 1680
    ret = 0;

1681 1682
cleanup:
    if (vm)
1683
        virObjectUnlock(vm);
1684
    virObjectUnref(cfg);
1685 1686 1687 1688 1689 1690 1691 1692 1693
    return ret;
}

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

1694 1695 1696 1697 1698 1699
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1700 1701 1702 1703
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
    virDomainObjPtr vm;
1704
    libxl_dominfo d_info;
1705
    libxlDomainObjPrivatePtr priv;
J
Jim Fehlig 已提交
1706 1707
    int ret = -1;

J
Jim Fehlig 已提交
1708
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1709 1710
        goto cleanup;

1711 1712 1713
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1714
    priv = vm->privateData;
1715 1716 1717
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1718
        info->maxMem = vm->def->mem.max_balloon;
1719
    } else {
1720
        if (libxl_domain_info(priv->ctx, &d_info, dom->id) != 0) {
1721 1722
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxl_domain_info failed for domain '%d'"), dom->id);
1723 1724 1725 1726
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1727
        info->maxMem = d_info.max_memkb;
1728 1729
    }

J
Jiri Denemark 已提交
1730
    info->state = virDomainObjGetState(vm, NULL);
J
Jim Fehlig 已提交
1731 1732 1733 1734 1735
    info->nrVirtCpu = vm->def->vcpus;
    ret = 0;

  cleanup:
    if (vm)
1736
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1737 1738 1739
    return ret;
}

1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1751
    if (!(vm = libxlDomObjFromDomain(dom)))
1752 1753
        goto cleanup;

1754 1755 1756
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1757
    *state = virDomainObjGetState(vm, reason);
1758 1759 1760 1761
    ret = 0;

  cleanup:
    if (vm)
1762
        virObjectUnlock(vm);
1763 1764 1765
    return ret;
}

1766 1767
/* This internal function expects the driver lock to already be held on
 * entry and the vm must be active. */
1768
static int
1769 1770
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1771
{
1772
    libxlDomainObjPrivatePtr priv = vm->privateData;
1773 1774 1775 1776
    libxlSavefileHeader hdr;
    virDomainEventPtr event = NULL;
    char *xml = NULL;
    uint32_t xml_len;
1777
    int fd = -1;
1778 1779 1780
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1781 1782 1783
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1784 1785 1786 1787
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1788
                            -1, -1, 0)) < 0) {
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
        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)) {
1804 1805
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1806 1807 1808 1809
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1810 1811
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1812 1813 1814
        goto cleanup;
    }

J
Jim Fehlig 已提交
1815
    if (libxl_domain_suspend(priv->ctx, vm->def->id, fd, 0, NULL) != 0) {
1816 1817 1818
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1819 1820 1821 1822 1823 1824
        goto cleanup;
    }

    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

J
Jim Fehlig 已提交
1825
    if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED) != 0) {
1826 1827
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1828 1829 1830
        goto cleanup;
    }

1831
    vm->hasManagedSave = true;
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
    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
1844 1845
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1846
{
1847 1848
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1849 1850
    int ret = -1;

1851 1852
    virCheckFlags(0, -1);
    if (dxml) {
1853 1854
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1855 1856 1857
        return -1;
    }

J
Jim Fehlig 已提交
1858
    if (!(vm = libxlDomObjFromDomain(dom)))
1859 1860
        goto cleanup;

1861 1862 1863
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1869 1870 1871 1872
    if (libxlDoDomainSave(driver, vm, to) < 0)
        goto cleanup;

    if (!vm->persistent) {
1873
        virDomainObjListRemove(driver->domains, vm);
1874 1875 1876 1877
        vm = NULL;
    }

    ret = 0;
1878

1879 1880
cleanup:
    if (vm)
1881
        virObjectUnlock(vm);
1882 1883
    return ret;
}
1884

1885
static int
1886 1887 1888 1889 1890 1891 1892 1893
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)
1894 1895
{
    libxlDriverPrivatePtr driver = conn->privateData;
1896
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1897 1898 1899 1900 1901
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1902

1903
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1904
    if (dxml) {
1905 1906
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1907 1908 1909
        return -1;
    }

1910 1911 1912
    /* Lock the driver until domain def is read from the saved
       image and a virDomainObj is created and locked.
    */
1913
    libxlDriverLock(driver);
1914

1915
    fd = libxlSaveImageOpen(driver, cfg, from, &def, &hdr);
1916
    if (fd < 0)
1917
        goto cleanup_unlock;
1918

1919
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1920
        goto cleanup_unlock;
1921

1922
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1923
                                   driver->xmlopt,
1924 1925 1926
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1927
        goto cleanup_unlock;
1928

1929
    libxlDriverUnlock(driver);
1930 1931
    def = NULL;

1932 1933
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_SAVE_PAUSED) != 0, fd);
    if (ret < 0 && !vm->persistent) {
1934
        virDomainObjListRemove(driver->domains, vm);
1935 1936 1937 1938
        vm = NULL;
    }

cleanup:
1939 1940
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1941 1942
    virDomainDefFree(def);
    if (vm)
1943
        virObjectUnlock(vm);
1944
    virObjectUnref(cfg);
1945
    return ret;
1946 1947 1948 1949

cleanup_unlock:
    libxlDriverUnlock(driver);
    goto cleanup;
1950 1951
}

1952 1953 1954 1955 1956 1957
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

1958
static int
1959
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    virDomainEventPtr event = NULL;
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

J
Jim Fehlig 已提交
1970
    if (!(vm = libxlDomObjFromDomain(dom)))
1971 1972
        goto cleanup;

1973 1974 1975
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1976
    if (!virDomainObjIsActive(vm)) {
1977
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1978 1979 1980 1981 1982 1983 1984
        goto cleanup;
    }

    priv = vm->privateData;

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
1985
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
1986 1987 1988 1989
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
                           dom->id);
1990 1991 1992 1993 1994 1995
            goto cleanup;
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

J
Jim Fehlig 已提交
1996
    if (libxl_domain_core_dump(priv->ctx, dom->id, to, NULL) != 0) {
1997 1998 1999
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
                       dom->id);
2000 2001 2002 2003
        goto cleanup_unpause;
    }

    if (flags & VIR_DUMP_CRASH) {
J
Jim Fehlig 已提交
2004
        if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED) != 0) {
2005 2006
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to destroy domain '%d'"), dom->id);
2007
            goto cleanup_unpause;
2008 2009 2010 2011
        }

        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
J
Jim Fehlig 已提交
2012 2013 2014 2015
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
2016 2017 2018 2019 2020
    }

    ret = 0;

cleanup_unpause:
J
Jim Fehlig 已提交
2021
    if (vm && virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
2022
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
2023 2024 2025
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
                             " libxenlight"), dom->id);
2026 2027 2028 2029 2030 2031 2032
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
cleanup:
    if (vm)
2033
        virObjectUnlock(vm);
2034
    if (event)
2035 2036 2037 2038
        libxlDomainEventQueue(driver, event);
    return ret;
}

2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
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 已提交
2049
    if (!(vm = libxlDomObjFromDomain(dom)))
2050 2051
        goto cleanup;

2052 2053 2054
    if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2055
    if (!virDomainObjIsActive(vm)) {
2056
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2057 2058
        goto cleanup;
    }
2059
    if (!vm->persistent) {
2060 2061
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
2062 2063
        goto cleanup;
    }
2064 2065 2066 2067 2068 2069 2070

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

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

2071 2072 2073 2074
    if (libxlDoDomainSave(driver, vm, name) < 0)
        goto cleanup;

    if (!vm->persistent) {
2075
        virDomainObjListRemove(driver->domains, vm);
2076 2077 2078 2079
        vm = NULL;
    }

    ret = 0;
2080 2081 2082

cleanup:
    if (vm)
2083
        virObjectUnlock(vm);
2084 2085 2086 2087
    VIR_FREE(name);
    return ret;
}

2088 2089
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
2090 2091 2092 2093
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
2094
    int ret = -1;
2095

2096
    virObjectLock(vm);
2097 2098 2099 2100 2101 2102

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

    vm->hasManagedSave = virFileExists(name);

2103
    ret = 0;
2104
cleanup:
2105
    virObjectUnlock(vm);
2106
    VIR_FREE(name);
2107
    return ret;
2108 2109
}

2110 2111 2112 2113 2114 2115 2116 2117
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2118
    if (!(vm = libxlDomObjFromDomain(dom)))
2119 2120
        goto cleanup;

2121 2122 2123
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2124
    ret = vm->hasManagedSave;
2125 2126 2127

cleanup:
    if (vm)
2128
        virObjectUnlock(vm);
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
    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 已提交
2142
    if (!(vm = libxlDomObjFromDomain(dom)))
2143 2144
        goto cleanup;

2145 2146 2147
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2148 2149 2150 2151 2152
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
2153
    vm->hasManagedSave = false;
2154 2155 2156 2157

cleanup:
    VIR_FREE(name);
    if (vm)
2158
        virObjectUnlock(vm);
2159 2160 2161
    return ret;
}

2162 2163 2164 2165 2166
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2167
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2168 2169 2170
    libxlDomainObjPrivatePtr priv;
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
2171
    libxl_bitmap map;
2172 2173
    uint8_t *bitmask = NULL;
    unsigned int maplen;
2174 2175
    size_t i;
    unsigned int pos;
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
    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)) {
2188 2189
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2190 2191 2192 2193
        return -1;
    }

    if (!nvcpus) {
2194
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2195 2196 2197
        return -1;
    }

J
Jim Fehlig 已提交
2198
    if (!(vm = libxlDomObjFromDomain(dom)))
2199 2200
        goto cleanup;

2201 2202 2203
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2204
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2205 2206
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2207 2208 2209 2210
        goto cleanup;
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2211 2212
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2213 2214 2215
        goto cleanup;
    }

2216
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2217 2218
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2219 2220 2221 2222 2223 2224 2225 2226
        goto cleanup;
    }

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

    if (nvcpus > max) {
2227 2228 2229
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2230 2231 2232 2233 2234
        goto cleanup;
    }

    priv = vm->privateData;

2235
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm)))
2236 2237
        goto cleanup;

E
Eric Blake 已提交
2238
    maplen = VIR_CPU_MAPLEN(nvcpus);
2239
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
2240 2241 2242
        goto cleanup;

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2243
        pos = i / 8;
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
        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 已提交
2262
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2263 2264 2265
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2266 2267 2268 2269 2270
            goto cleanup;
        }
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2271
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2272 2273 2274
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2275 2276 2277 2278 2279 2280 2281 2282 2283
            goto cleanup;
        }
        def->vcpus = nvcpus;
        break;
    }

    ret = 0;

    if (flags & VIR_DOMAIN_VCPU_CONFIG)
2284
        ret = virDomainSaveConfig(cfg->configDir, def);
2285 2286 2287 2288

cleanup:
    VIR_FREE(bitmask);
     if (vm)
2289
        virObjectUnlock(vm);
2290
     virObjectUnref(cfg);
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
    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;
2306
    bool active;
2307 2308 2309 2310 2311

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

J
Jim Fehlig 已提交
2312
    if (!(vm = libxlDomObjFromDomain(dom)))
2313 2314
        goto cleanup;

2315 2316 2317
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2318 2319 2320 2321 2322 2323 2324 2325 2326
    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)) {
2327 2328
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2329 2330 2331
        return -1;
    }

2332
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2333
        if (!active) {
2334 2335
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2336 2337 2338 2339
            goto cleanup;
        }
        def = vm->def;
    } else {
2340
        if (!vm->persistent) {
2341 2342
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2343 2344
            goto cleanup;
        }
2345 2346 2347 2348 2349 2350 2351
        def = vm->newDef ? vm->newDef : vm->def;
    }

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

cleanup:
    if (vm)
2352
        virObjectUnlock(vm);
2353 2354 2355 2356 2357 2358 2359 2360
    return ret;
}

static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2361
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2362 2363 2364
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    int ret = -1;
J
Jim Fehlig 已提交
2365
    libxl_bitmap map;
2366

J
Jim Fehlig 已提交
2367
    if (!(vm = libxlDomObjFromDomain(dom)))
2368 2369
        goto cleanup;

2370 2371 2372
    if (virDomainPinVcpuEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2373
    if (!virDomainObjIsActive(vm)) {
2374 2375
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot pin vcpus on an inactive domain"));
2376 2377 2378 2379 2380 2381 2382
        goto cleanup;
    }

    priv = vm->privateData;

    map.size = maplen;
    map.map = cpumap;
J
Jim Fehlig 已提交
2383
    if (libxl_set_vcpuaffinity(priv->ctx, dom->id, vcpu, &map) != 0) {
2384 2385
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
2386 2387
        goto cleanup;
    }
2388

H
Hu Tao 已提交
2389
    if (!vm->def->cputune.vcpupin) {
2390
        if (VIR_ALLOC(vm->def->cputune.vcpupin) < 0)
H
Hu Tao 已提交
2391 2392 2393
            goto cleanup;
        vm->def->cputune.nvcpupin = 0;
    }
2394
    if (virDomainVcpuPinAdd(&vm->def->cputune.vcpupin,
H
Hu Tao 已提交
2395 2396 2397 2398
                            &vm->def->cputune.nvcpupin,
                            cpumap,
                            maplen,
                            vcpu) < 0) {
2399 2400
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to update or add vcpupin xml"));
2401 2402 2403
        goto cleanup;
    }

2404
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
2405 2406
        goto cleanup;

2407 2408 2409 2410
    ret = 0;

cleanup:
    if (vm)
2411
        virObjectUnlock(vm);
2412
    virObjectUnref(cfg);
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
    return ret;
}


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;
2426
    size_t i;
2427 2428
    unsigned char *cpumap;

J
Jim Fehlig 已提交
2429
    if (!(vm = libxlDomObjFromDomain(dom)))
2430 2431
        goto cleanup;

2432 2433 2434
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2435
    if (!virDomainObjIsActive(vm)) {
2436
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2437 2438 2439 2440
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
2441
    if ((vcpuinfo = libxl_list_vcpu(priv->ctx, dom->id, &maxcpu,
2442
                                    &hostcpus)) == NULL) {
2443 2444 2445
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
                       dom->id);
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
        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 已提交
2468
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2469 2470 2471 2472 2473 2474 2475
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

cleanup:
    if (vm)
2476
        virObjectUnlock(vm);
2477 2478 2479
    return ret;
}

J
Jim Fehlig 已提交
2480
static char *
2481
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2482 2483 2484 2485
{
    virDomainObjPtr vm;
    char *ret = NULL;

2486 2487
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2488
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2489 2490
        goto cleanup;

2491 2492 2493
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2494 2495 2496 2497
    ret = virDomainDefFormat(vm->def, flags);

  cleanup:
    if (vm)
2498
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2499 2500 2501
    return ret;
}

2502
static char *
2503 2504 2505
libxlConnectDomainXMLFromNative(virConnectPtr conn, const char * nativeFormat,
                                const char * nativeConfig,
                                unsigned int flags)
2506 2507
{
    libxlDriverPrivatePtr driver = conn->privateData;
2508
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2509 2510 2511 2512
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2513 2514
    virCheckFlags(0, NULL);

2515 2516 2517
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

2518
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2519 2520
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2521 2522 2523 2524 2525 2526
        goto cleanup;
    }

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

2527
    if (!(def = xenParseXM(conf,
2528 2529
                           cfg->verInfo->xen_version_major,
                           cfg->caps))) {
2530
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("parsing xm config failed"));
2531 2532 2533 2534 2535 2536 2537 2538 2539
        goto cleanup;
    }

    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);

cleanup:
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2540
    virObjectUnref(cfg);
2541 2542 2543 2544 2545
    return xml;
}

#define MAX_CONFIG_SIZE (1024 * 65)
static char *
2546 2547 2548
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
2549 2550
{
    libxlDriverPrivatePtr driver = conn->privateData;
2551
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2552 2553 2554 2555 2556
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    int len = MAX_CONFIG_SIZE;
    char *ret = NULL;

E
Eric Blake 已提交
2557 2558
    virCheckFlags(0, NULL);

2559 2560 2561
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

2562
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2563 2564
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2565 2566 2567
        goto cleanup;
    }

2568
    if (!(def = virDomainDefParseString(domainXml,
2569
                                        cfg->caps, driver->xmlopt,
M
Matthias Bolte 已提交
2570
                                        1 << VIR_DOMAIN_VIRT_XEN, 0)))
2571 2572
        goto cleanup;

2573
    if (!(conf = xenFormatXM(conn, def, cfg->verInfo->xen_version_major)))
2574 2575
        goto cleanup;

2576
    if (VIR_ALLOC_N(ret, len) < 0)
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
        goto cleanup;

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

cleanup:
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2588
    virObjectUnref(cfg);
2589 2590 2591
    return ret;
}

J
Jim Fehlig 已提交
2592
static int
2593 2594
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
2595 2596 2597 2598
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2599 2600 2601
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2602 2603
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
2604 2605 2606 2607
    return n;
}

static int
2608
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
2609 2610 2611 2612
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2613 2614 2615
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2616
    n = virDomainObjListNumOfDomains(driver->domains, false,
2617 2618
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
2619 2620 2621 2622 2623
    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
2624
                           unsigned int flags)
J
Jim Fehlig 已提交
2625 2626 2627 2628 2629 2630 2631
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

J
Jim Fehlig 已提交
2632
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2633 2634
        goto cleanup;

2635 2636 2637
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2638
    if (virDomainObjIsActive(vm)) {
2639 2640
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
J
Jim Fehlig 已提交
2641 2642 2643
        goto cleanup;
    }

2644
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0, -1);
J
Jim Fehlig 已提交
2645 2646 2647

cleanup:
    if (vm)
2648
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
    return ret;
}

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

static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    libxlDriverPrivatePtr driver = conn->privateData;
2662
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2663 2664 2665
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
2666
    virDomainEventPtr event = NULL;
2667
    virDomainDefPtr oldDef = NULL;
J
Jim Fehlig 已提交
2668

2669
    /* Lock the driver until the virDomainObj is created and locked */
J
Jim Fehlig 已提交
2670
    libxlDriverLock(driver);
2671
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
M
Matthias Bolte 已提交
2672
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
2673
                                        VIR_DOMAIN_XML_INACTIVE)))
2674
        goto cleanup_unlock;
J
Jim Fehlig 已提交
2675

2676
    if (virDomainDefineXMLEnsureACL(conn, def) < 0)
2677
        goto cleanup_unlock;
2678

2679
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2680
                                   driver->xmlopt,
2681 2682
                                   0,
                                   &oldDef)))
2683 2684
        goto cleanup_unlock;

J
Jim Fehlig 已提交
2685 2686
    def = NULL;
    vm->persistent = 1;
2687
    libxlDriverUnlock(driver);
J
Jim Fehlig 已提交
2688

2689
    if (virDomainSaveConfig(cfg->configDir,
J
Jim Fehlig 已提交
2690
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2691
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
2692 2693 2694 2695 2696 2697 2698 2699
        vm = NULL;
        goto cleanup;
    }

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

2700
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2701
                                     !oldDef ?
2702 2703 2704
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

J
Jim Fehlig 已提交
2705 2706
cleanup:
    virDomainDefFree(def);
2707
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
2708
    if (vm)
2709
        virObjectUnlock(vm);
2710 2711
    if (event)
        libxlDomainEventQueue(driver, event);
2712
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2713
    return dom;
2714 2715 2716 2717

cleanup_unlock:
    libxlDriverUnlock(driver);
    goto cleanup;
J
Jim Fehlig 已提交
2718 2719 2720
}

static int
2721 2722
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2723 2724
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2725
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2726
    virDomainObjPtr vm;
2727
    virDomainEventPtr event = NULL;
2728
    char *name = NULL;
J
Jim Fehlig 已提交
2729 2730
    int ret = -1;

2731 2732
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2733
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2734 2735
        goto cleanup;

2736 2737 2738
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2739
    if (!vm->persistent) {
2740 2741
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2742 2743 2744
        goto cleanup;
    }

2745 2746 2747 2748 2749 2750 2751
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2752 2753
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2754 2755 2756
                goto cleanup;
            }
        } else {
2757 2758 2759
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2760 2761 2762 2763
            goto cleanup;
        }
    }

2764
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2765 2766
        goto cleanup;

2767 2768 2769
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2770 2771 2772
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
2773
        virDomainObjListRemove(driver->domains, vm);
2774 2775 2776
        vm = NULL;
    }

J
Jim Fehlig 已提交
2777 2778 2779
    ret = 0;

  cleanup:
2780
    VIR_FREE(name);
J
Jim Fehlig 已提交
2781
    if (vm)
2782
        virObjectUnlock(vm);
2783 2784
    if (event)
        libxlDomainEventQueue(driver, event);
2785
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2786 2787 2788
    return ret;
}

2789 2790 2791 2792 2793 2794
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2795 2796 2797 2798 2799 2800
static int
libxlDomainChangeEjectableMedia(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDiskDefPtr disk)
{
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2801
    size_t i;
2802 2803
    int ret = -1;

2804
    for (i = 0; i < vm->def->ndisks; i++) {
2805 2806 2807 2808 2809 2810 2811 2812
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
2813 2814 2815
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
2816 2817 2818 2819
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2820 2821 2822
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
2823 2824 2825
        return -1;
    }

J
Jim Fehlig 已提交
2826
    if (libxlMakeDisk(disk, &x_disk) < 0)
2827 2828
        goto cleanup;

J
Jim Fehlig 已提交
2829
    if ((ret = libxl_cdrom_insert(priv->ctx, vm->def->id, &x_disk, NULL)) < 0) {
2830 2831 2832
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863
        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) {
2864
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
2865 2866
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
2867 2868 2869 2870
                    goto cleanup;
                }

                if (!l_disk->src) {
2871 2872
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
2873 2874 2875
                    goto cleanup;
                }

2876
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
2877 2878
                    goto cleanup;

J
Jim Fehlig 已提交
2879
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
2880 2881
                    goto cleanup;

J
Jim Fehlig 已提交
2882 2883
                if ((ret = libxl_device_disk_add(priv->ctx, vm->def->id,
                                                &x_disk, NULL)) < 0) {
2884 2885 2886
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
2887 2888 2889 2890 2891 2892
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
2893 2894 2895
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
2896 2897 2898
            }
            break;
        default:
2899 2900 2901
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914
            break;
    }

cleanup:
    return ret;
}

static int
libxlDomainDetachDeviceDiskLive(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
2915
    int idx;
2916 2917 2918 2919 2920 2921
    int ret = -1;

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

2922 2923 2924
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
2925 2926
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
2927 2928 2929
                    goto cleanup;
                }

2930
                l_disk = vm->def->disks[idx];
2931

J
Jim Fehlig 已提交
2932
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
2933 2934
                    goto cleanup;

J
Jim Fehlig 已提交
2935 2936
                if ((ret = libxl_device_disk_remove(priv->ctx, vm->def->id,
                                                    &x_disk, NULL)) < 0) {
2937 2938 2939
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
2940 2941 2942
                    goto cleanup;
                }

2943
                virDomainDiskRemove(vm->def, idx);
2944 2945 2946
                virDomainDiskDefFree(l_disk);

            } else {
2947 2948 2949
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
2950 2951 2952
            }
            break;
        default:
2953 2954 2955
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
            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:
2977 2978 2979
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
            break;
    }

    return ret;
}

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

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
2994
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
2995 2996
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
2997 2998
                return -1;
            }
2999
            if (virDomainDiskInsert(vmdef, disk))
3000 3001 3002 3003 3004 3005
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;

        default:
3006 3007
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
            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:
3025 3026 3027
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3028 3029 3030 3031 3032 3033 3034 3035 3036
            break;
    }

    return ret;
}

static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3037
    virDomainDiskDefPtr disk, detach;
3038 3039 3040 3041 3042
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3043
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3044 3045
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3046 3047
                break;
            }
3048
            virDomainDiskDefFree(detach);
3049 3050 3051
            ret = 0;
            break;
        default:
3052 3053
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076
            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:
3077 3078 3079
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3080 3081 3082 3083
                    break;
            }
            break;
        default:
3084 3085 3086
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr orig;
    virDomainDiskDefPtr disk;
3098
    int idx;
3099 3100 3101 3102 3103
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3104
            if ((idx = virDomainDiskIndexByName(vmdef, disk->dst, false)) < 0) {
3105 3106
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3107 3108
                goto cleanup;
            }
3109
            orig = vmdef->disks[idx];
3110
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3111 3112
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123
                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;
            }
3124
            orig->format = disk->format;
3125 3126 3127
            disk->src = NULL;
            break;
        default:
3128 3129
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140
            goto cleanup;
    }

    ret = 0;

cleanup:
    return ret;
}


static int
3141 3142
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3143 3144
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3145
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3146 3147 3148 3149 3150 3151 3152 3153 3154
    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 已提交
3155
    if (!(vm = libxlDomObjFromDomain(dom)))
3156 3157
        goto cleanup;

3158 3159 3160
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3161 3162 3163 3164 3165 3166 3167 3168
    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) {
3169 3170
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3171 3172 3173 3174 3175
            goto cleanup;
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
3176 3177
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3178 3179 3180 3181 3182 3183
         goto cleanup;
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3184
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3185
                                            cfg->caps, driver->xmlopt,
3186 3187 3188 3189
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3190
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3191
                                                    driver->xmlopt)))
3192 3193
            goto cleanup;

3194 3195 3196
        if ((ret = libxlDomainAttachDeviceConfig(vmdef, dev)) < 0)
            goto cleanup;
    } else {
3197
        ret = 0;
3198
    }
3199 3200 3201 3202

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

3208 3209 3210
        if ((ret = libxlDomainAttachDeviceLive(priv, vm, dev)) < 0)
            goto cleanup;

3211 3212 3213 3214
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3215
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3216 3217 3218 3219 3220
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3221
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3222
        if (!ret) {
3223
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3224 3225 3226 3227 3228 3229 3230 3231
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3232
        virObjectUnlock(vm);
3233
    virObjectUnref(cfg);
3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247
    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)
{
3248
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3249
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3250 3251 3252 3253 3254 3255 3256 3257 3258
    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 已提交
3259
    if (!(vm = libxlDomObjFromDomain(dom)))
3260 3261
        goto cleanup;

3262 3263 3264
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288
    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,
3289
                                            cfg->caps, driver->xmlopt,
3290 3291 3292 3293
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3294
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307
                                                    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,
3308
                                            cfg->caps, driver->xmlopt,
3309 3310 3311 3312 3313 3314 3315 3316 3317 3318
                                            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.
         */
3319
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3320 3321 3322 3323 3324
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3325
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3337
    virObjectUnref(cfg);
3338
    return ret;
3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
}

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)
{
3352
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3353
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3354 3355 3356 3357 3358 3359 3360 3361 3362
    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 已提交
3363
    if (!(vm = libxlDomObjFromDomain(dom)))
3364 3365
        goto cleanup;

3366 3367 3368
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392
    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,
3393
                                            cfg->caps, driver->xmlopt,
3394 3395 3396 3397
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3398
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411
                                                    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,
3412
                                            cfg->caps, driver->xmlopt,
3413 3414 3415 3416 3417 3418 3419 3420 3421 3422
                                            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.
         */
3423
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3424 3425 3426 3427 3428
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3429
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3441
    virObjectUnref(cfg);
3442
    return ret;
3443 3444
}

3445 3446 3447 3448 3449
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
3450 3451
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
3452

3453
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
3454
        goto cleanup;
3455

3456
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
3457 3458
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3459
        goto cleanup;
3460 3461
    }

3462 3463 3464 3465 3466
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

cleanup:
    virObjectUnref(cfg);
    return ret;
3467 3468
}

3469 3470 3471 3472 3473 3474 3475 3476 3477 3478
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;
3479
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3480 3481

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
3482
        goto cleanup;
3483

3484
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
3485
    if (numa_info == NULL || nr_nodes == 0) {
3486 3487 3488
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
3489 3490 3491
    }

    /* Check/sanitize the cell range */
3492
    if (startCell >= nr_nodes) {
3493 3494
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
3495
                       startCell, nr_nodes - 1);
3496 3497 3498
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
3499 3500
    if (lastCell >= nr_nodes)
        lastCell = nr_nodes - 1;
3501 3502 3503 3504 3505 3506 3507

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

3509 3510 3511 3512
    ret = numCells;

cleanup:
    libxl_numainfo_list_free(numa_info, nr_nodes);
3513
    virObjectUnref(cfg);
3514 3515 3516
    return ret;
}

3517
static int
3518 3519 3520
libxlConnectDomainEventRegister(virConnectPtr conn,
                                virConnectDomainEventCallback callback, void *opaque,
                                virFreeCallback freecb)
3521 3522 3523 3524
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

3525 3526 3527
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

3528 3529 3530
    ret = virDomainEventStateRegister(conn,
                                      driver->domainEventState,
                                      callback, opaque, freecb);
3531 3532 3533 3534 3535 3536

    return ret;
}


static int
3537 3538
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
3539 3540 3541 3542
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

3543 3544 3545
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

3546 3547 3548
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
3549 3550 3551 3552

    return ret;
}

3553 3554 3555 3556 3557 3558
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
3559
    if (!(vm = libxlDomObjFromDomain(dom)))
3560 3561
        goto cleanup;

3562 3563 3564
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3565 3566 3567 3568 3569
    *autostart = vm->autostart;
    ret = 0;

cleanup:
    if (vm)
3570
        virObjectUnlock(vm);
3571 3572 3573 3574 3575 3576 3577
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3578
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3579 3580 3581 3582
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
3583
    if (!(vm = libxlDomObjFromDomain(dom)))
3584 3585
        goto cleanup;

3586 3587 3588
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3589
    if (!vm->persistent) {
3590 3591
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
3592 3593 3594 3595 3596 3597
        goto cleanup;
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
3598
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
3599
            goto cleanup;
3600
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
3601 3602 3603
            goto cleanup;

        if (autostart) {
3604
            if (virFileMakePath(cfg->autostartDir) < 0) {
3605
                virReportSystemError(errno,
3606
                                     _("cannot create autostart directory %s"),
3607
                                     cfg->autostartDir);
3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633
                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)
3634
        virObjectUnlock(vm);
3635
    virObjectUnref(cfg);
3636 3637 3638
    return ret;
}

3639 3640 3641 3642 3643 3644
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    char * ret = NULL;
3645
    const char *name = NULL;
J
Jim Fehlig 已提交
3646
    libxl_scheduler sched_id;
3647

J
Jim Fehlig 已提交
3648
    if (!(vm = libxlDomObjFromDomain(dom)))
3649 3650
        goto cleanup;

3651 3652 3653
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3654
    if (!virDomainObjIsActive(vm)) {
3655
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3656 3657 3658 3659
        goto cleanup;
    }

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

3662 3663
    if (nparams)
        *nparams = 0;
3664
    switch (sched_id) {
J
Jim Fehlig 已提交
3665
    case LIBXL_SCHEDULER_SEDF:
3666
        name = "sedf";
3667
        break;
J
Jim Fehlig 已提交
3668
    case LIBXL_SCHEDULER_CREDIT:
3669
        name = "credit";
3670 3671
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
3672
        break;
J
Jim Fehlig 已提交
3673
    case LIBXL_SCHEDULER_CREDIT2:
3674
        name = "credit2";
3675
        break;
J
Jim Fehlig 已提交
3676
    case LIBXL_SCHEDULER_ARINC653:
3677
        name = "arinc653";
3678 3679
        break;
    default:
J
Jim Fehlig 已提交
3680 3681 3682
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
                     " with libxenlight"), dom->id);
3683 3684 3685
        goto cleanup;
    }

3686
    ignore_value(VIR_STRDUP(ret, name));
3687 3688 3689

cleanup:
    if (vm)
3690
        virObjectUnlock(vm);
3691 3692 3693
    return ret;
}

3694
static int
3695 3696 3697 3698
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
3699 3700 3701
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3702 3703
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
3704 3705
    int ret = -1;

3706 3707 3708 3709
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

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

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

3717
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
3718 3719
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
3720 3721 3722 3723 3724
        goto cleanup;
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
3727
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3728 3729
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3730 3731 3732
        goto cleanup;
    }

J
Jim Fehlig 已提交
3733
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
3734 3735 3736
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3737 3738 3739
        goto cleanup;
    }

3740 3741
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
3742 3743
        goto cleanup;

3744
    if (*nparams > 1) {
3745 3746
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
3747
            goto cleanup;
3748 3749
    }

3750 3751
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
3752 3753 3754 3755
    ret = 0;

cleanup:
    if (vm)
3756
        virObjectUnlock(vm);
3757 3758 3759 3760
    return ret;
}

static int
3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771
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)
3772 3773 3774
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3775
    libxl_domain_sched_params sc_info;
3776
    int sched_id;
3777
    size_t i;
3778 3779
    int ret = -1;

3780
    virCheckFlags(0, -1);
3781 3782 3783 3784 3785 3786
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
3787
        return -1;
3788

J
Jim Fehlig 已提交
3789
    if (!(vm = libxlDomObjFromDomain(dom)))
3790 3791
        goto cleanup;

3792 3793 3794
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3795
    if (!virDomainObjIsActive(vm)) {
3796
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3797 3798 3799 3800 3801
        goto cleanup;
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
3804
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3805 3806
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3807 3808 3809
        goto cleanup;
    }

J
Jim Fehlig 已提交
3810
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
3811 3812 3813
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3814 3815 3816 3817
        goto cleanup;
    }

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

3820
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
3821
            sc_info.weight = params[i].value.ui;
3822
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
3823 3824 3825
            sc_info.cap = params[i].value.ui;
    }

J
Jim Fehlig 已提交
3826
    if (libxl_domain_sched_params_set(priv->ctx, dom->id, &sc_info) != 0) {
3827 3828 3829
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3830 3831 3832 3833 3834 3835 3836
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
3837
        virObjectUnlock(vm);
3838 3839 3840
    return ret;
}

B
Bamvor Jian Zhang 已提交
3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862

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 已提交
3863
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919
        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;
}

3920 3921 3922 3923 3924 3925 3926
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956
/* 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;

3957 3958
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
3959
    if (!(vm = libxlDomObjFromDomain(dom)))
3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 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
        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];

        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 */
            if (libxl_node_bitmap_alloc(priv->ctx, &nodemap, 0) ||
                !(nodes = virBitmapNew(libxl_get_max_nodes(priv->ctx)))) {
                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;

        default:
            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 已提交
4056 4057 4058 4059 4060 4061
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4062
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4063
        goto cleanup;
4064 4065 4066 4067

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

J
Jim Fehlig 已提交
4068 4069 4070 4071
    ret = virDomainObjIsActive(obj);

  cleanup:
    if (obj)
4072
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4073 4074 4075 4076 4077 4078 4079 4080 4081
    return ret;
}

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

J
Jim Fehlig 已提交
4082
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4083
        goto cleanup;
4084 4085 4086 4087

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

J
Jim Fehlig 已提交
4088 4089 4090 4091
    ret = obj->persistent;

  cleanup:
    if (obj)
4092
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4093 4094 4095
    return ret;
}

4096 4097 4098 4099 4100 4101
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4102
    if (!(vm = libxlDomObjFromDomain(dom)))
4103
        goto cleanup;
4104 4105 4106 4107

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

4108 4109 4110 4111
    ret = vm->updated;

cleanup:
    if (vm)
4112
        virObjectUnlock(vm);
4113 4114 4115
    return ret;
}

4116
static int
4117 4118 4119
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4120 4121 4122 4123
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4124 4125 4126
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4127 4128 4129 4130
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4131
        ret = -1;
4132 4133 4134 4135 4136 4137

    return ret;
}


static int
4138
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4139 4140 4141 4142
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4143 4144 4145
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4146 4147 4148
    ret = virDomainEventStateDeregisterID(conn,
                                          driver->domainEventState,
                                          callbackID);
4149 4150 4151 4152

    return ret;
}

J
Jim Fehlig 已提交
4153

4154
static int
4155
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4156 4157 4158 4159
{
    return 1;
}

4160
static int
4161 4162 4163
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4164 4165 4166 4167
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4168
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4169

4170 4171 4172
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4173 4174
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
4175 4176 4177 4178

    return ret;
}

4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192
/* 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;
    }
}
4193

4194

J
Jim Fehlig 已提交
4195
static virDriver libxlDriver = {
4196 4197
    .no = VIR_DRV_LIBXL,
    .name = "xenlight",
4198 4199 4200 4201
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
4202
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
4203
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
4204
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
4205
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
4206 4207 4208 4209
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
4210 4211 4212 4213 4214 4215 4216
    .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 */
4217
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
4218 4219
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
4220
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
4221 4222
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
4223
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
4224 4225 4226 4227
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
4228
    .domainSave = libxlDomainSave, /* 0.9.2 */
4229
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
4230
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
4231
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
4232
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
4233 4234 4235 4236 4237 4238
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
4239 4240 4241 4242
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
4243 4244 4245 4246
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
4247
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
4248 4249 4250 4251 4252
    .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 */
4253 4254 4255 4256
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
4257
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
4258
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
4259
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
4260 4261 4262
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
4263
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
4264
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
4265 4266
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
4267 4268 4269
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
4270
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
4271 4272 4273
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
4274 4275 4276
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
4277
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
J
Jim Fehlig 已提交
4278 4279 4280 4281
};

static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
4282
    .stateInitialize = libxlStateInitialize,
4283
    .stateAutoStart = libxlStateAutoStart,
4284 4285
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298
};


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

    return 0;
}