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

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

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

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

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

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

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

671

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
}

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

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

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

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

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

    if (!libxlDriverShouldLoad(privileged))
        return 0;

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

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

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

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

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

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

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

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

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

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

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

    libxlReconnectDomains(libxl_driver);

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

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

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

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

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

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

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

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

957 958
    cfg = libxlDriverConfigGet(libxl_driver);

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

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

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


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

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

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

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

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

    return VIR_DRV_OPEN_SUCCESS;
};

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

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

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

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

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

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

1056

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

1062 1063 1064
    return virGetHostname();
}

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

    virCheckFlags(0, NULL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return n;
}

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

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

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

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

    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

    ret = 0;

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


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

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

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

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

    priv = vm->privateData;

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

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

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

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

    ret = 0;

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

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

1404 1405
    virCheckFlags(0, -1);

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

1489 1490
    virCheckFlags(0, -1);

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

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

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

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

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

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

    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1680 1681
    ret = 0;

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

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

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

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

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

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

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

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

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

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

    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

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

    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

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

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

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

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

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

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

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

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

    ret = 0;
1879

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

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

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

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

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

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

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

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

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

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

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

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

1959
static int
1960
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
{
    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 已提交
1971
    if (!(vm = libxlDomObjFromDomain(dom)))
1972 1973
        goto cleanup;

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

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

    priv = vm->privateData;

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

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

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

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

    ret = 0;

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

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

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

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

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

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

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

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

    ret = 0;
2081 2082 2083

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

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

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

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

    vm->hasManagedSave = virFileExists(name);

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

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

    virCheckFlags(0, -1);

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

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

2125
    ret = vm->hasManagedSave;
2126 2127 2128

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

2408 2409 2410 2411
    ret = 0;

cleanup:
    if (vm)
2412
        virObjectUnlock(vm);
2413
    virObjectUnref(cfg);
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
    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;
2427
    size_t i;
2428 2429
    unsigned char *cpumap;

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

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

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

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

    ret = maxinfo;

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

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

2487 2488
    /* Flags checked by virDomainDefFormat */

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

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

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

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

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

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

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

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

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

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

    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2732 2733
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

J
Jim Fehlig 已提交
2830
    if ((ret = libxl_cdrom_insert(priv->ctx, vm->def->id, &x_disk, NULL)) < 0) {
2831 2832 2833
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
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 2864
        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) {
2865
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
2866 2867
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
2868 2869 2870 2871
                    goto cleanup;
                }

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

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

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

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

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

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

cleanup:
    return ret;
}

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

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

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

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

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

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

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

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

    return ret;
}

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

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

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

    return ret;
}

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

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

    return ret;
}

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

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

    ret = 0;

cleanup:
    return ret;
}


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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3510 3511 3512 3513
    ret = numCells;

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

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

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

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

    return ret;
}


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

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

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

    return ret;
}

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

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

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

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

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

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

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

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

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

    autostart = (autostart != 0);

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

        if (autostart) {
3605
            if (virFileMakePath(cfg->autostartDir) < 0) {
3606
                virReportSystemError(errno,
3607
                                     _("cannot create autostart directory %s"),
3608
                                     cfg->autostartDir);
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 3634
                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)
3635
        virObjectUnlock(vm);
3636
    virObjectUnref(cfg);
3637 3638 3639
    return ret;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

    ret = 0;

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

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

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 已提交
3864
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
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 3920
        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;
}

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

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 3957
/* 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;

J
Jim Fehlig 已提交
3958
    if (!(vm = libxlDomObjFromDomain(dom)))
3959 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 4056
        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;

    libxl_bitmap_init(&nodemap);

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

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

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

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

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

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

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

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

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

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

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

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

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

4109 4110 4111 4112
    ret = vm->updated;

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

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

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

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

    return ret;
}


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

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

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

    return ret;
}

J
Jim Fehlig 已提交
4154

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

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

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

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

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

    return ret;
}

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

4195

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

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


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

    return 0;
}