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

#include <config.h>

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

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

#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

60 61
#define LIBXL_CONFIG_FORMAT_XM "xen-xm"

62 63 64
/* Number of Xen scheduler parameters */
#define XEN_SCHED_CREDIT_NPARAM   2

J
Jim Fehlig 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
/* Append an event registration to the list of registrations */
#define LIBXL_EV_REG_APPEND(head, add)                 \
    do {                                               \
        libxlEventHookInfoPtr temp;                    \
        if (head) {                                    \
            temp = head;                               \
            while (temp->next)                         \
                temp = temp->next;                     \
            temp->next = add;                          \
        } else {                                       \
            head = add;                                \
        }                                              \
    } while (0)

/* Remove an event registration from the list of registrations */
#define LIBXL_EV_REG_REMOVE(head, del)                 \
    do {                                               \
        libxlEventHookInfoPtr temp;                    \
        if (head == del) {                             \
            head = head->next;                         \
        } else {                                       \
            temp = head;                               \
            while (temp->next && temp->next != del)    \
                temp = temp->next;                     \
            if (temp->next) {                          \
                temp->next = del->next;                \
            }                                          \
        }                                              \
    } while (0)

95 96
/* Object used to store info related to libxl event registrations */
struct _libxlEventHookInfo {
J
Jim Fehlig 已提交
97
    libxlEventHookInfoPtr next;
J
Jim Fehlig 已提交
98 99 100 101 102
    libxlDomainObjPrivatePtr priv;
    void *xl_priv;
    int id;
};

103
static virClassPtr libxlDomainObjPrivateClass;
104

J
Jim Fehlig 已提交
105 106 107
static libxlDriverPrivatePtr libxl_driver = NULL;

/* Function declarations */
108 109
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
110 111
                           void *opaque);

J
Jim Fehlig 已提交
112
static int
113 114
libxlVmStart(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
             bool start_paused, int restore_fd);
J
Jim Fehlig 已提交
115

116 117 118
static void
libxlDomainObjPrivateDispose(void *obj);

J
Jim Fehlig 已提交
119
/* Function definitions */
120 121 122 123 124 125
static int
libxlDomainObjPrivateOnceInit(void)
{
    if (!(libxlDomainObjPrivateClass = virClassNew(virClassForObjectLockable(),
                                                   "libxlDomainObjPrivate",
                                                   sizeof(libxlDomainObjPrivate),
126
                                                   libxlDomainObjPrivateDispose)))
127 128 129 130 131 132 133
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(libxlDomainObjPrivate)

J
Jim Fehlig 已提交
134 135 136 137 138 139 140 141 142 143 144 145
static void
libxlDriverLock(libxlDriverPrivatePtr driver)
{
    virMutexLock(&driver->lock);
}

static void
libxlDriverUnlock(libxlDriverPrivatePtr driver)
{
    virMutexUnlock(&driver->lock);
}

146 147 148
static void
libxlEventHookInfoFree(void *obj)
{
149 150 151 152 153
    libxlEventHookInfoPtr info = obj;

    /* Drop reference on libxlDomainObjPrivate */
    virObjectUnref(info->priv);
    VIR_FREE(info);
154 155
}

156 157 158 159
static void
libxlFDEventCallback(int watch ATTRIBUTE_UNUSED,
                     int fd,
                     int vir_events,
160
                     void *fd_info)
J
Jim Fehlig 已提交
161
{
162
    libxlEventHookInfoPtr info = fd_info;
J
Jim Fehlig 已提交
163 164
    int events = 0;

165
    virObjectLock(info->priv);
J
Jim Fehlig 已提交
166 167 168 169 170 171 172 173 174
    if (vir_events & VIR_EVENT_HANDLE_READABLE)
        events |= POLLIN;
    if (vir_events & VIR_EVENT_HANDLE_WRITABLE)
        events |= POLLOUT;
    if (vir_events & VIR_EVENT_HANDLE_ERROR)
        events |= POLLERR;
    if (vir_events & VIR_EVENT_HANDLE_HANGUP)
        events |= POLLHUP;

175
    virObjectUnlock(info->priv);
J
Jim Fehlig 已提交
176 177 178
    libxl_osevent_occurred_fd(info->priv->ctx, info->xl_priv, fd, 0, events);
}

179 180 181
static int
libxlFDRegisterEventHook(void *priv, int fd, void **hndp,
                         short events, void *xl_priv)
J
Jim Fehlig 已提交
182 183
{
    int vir_events = VIR_EVENT_HANDLE_ERROR;
184
    libxlEventHookInfoPtr info;
J
Jim Fehlig 已提交
185

186
    if (VIR_ALLOC(info) < 0)
J
Jim Fehlig 已提交
187 188
        return -1;

189 190 191 192 193 194 195 196 197
    info->priv = priv;
    /*
     * Take a reference on the domain object.  Reference is dropped in
     * libxlEventHookInfoFree, ensuring the domain object outlives the fd
     * event objects.
     */
    virObjectRef(info->priv);
    info->xl_priv = xl_priv;

J
Jim Fehlig 已提交
198 199 200 201
    if (events & POLLIN)
        vir_events |= VIR_EVENT_HANDLE_READABLE;
    if (events & POLLOUT)
        vir_events |= VIR_EVENT_HANDLE_WRITABLE;
202

203 204 205
    info->id = virEventAddHandle(fd, vir_events, libxlFDEventCallback,
                                 info, libxlEventHookInfoFree);
    if (info->id < 0) {
206
        virObjectUnref(info->priv);
207 208
        VIR_FREE(info);
        return -1;
J
Jim Fehlig 已提交
209 210
    }

211 212
    *hndp = info;

J
Jim Fehlig 已提交
213 214 215
    return 0;
}

216 217 218 219 220
static int
libxlFDModifyEventHook(void *priv ATTRIBUTE_UNUSED,
                       int fd ATTRIBUTE_UNUSED,
                       void **hndp,
                       short events)
J
Jim Fehlig 已提交
221
{
222
    libxlEventHookInfoPtr info = *hndp;
J
Jim Fehlig 已提交
223 224
    int vir_events = VIR_EVENT_HANDLE_ERROR;

225
    virObjectLock(info->priv);
J
Jim Fehlig 已提交
226 227 228 229 230
    if (events & POLLIN)
        vir_events |= VIR_EVENT_HANDLE_READABLE;
    if (events & POLLOUT)
        vir_events |= VIR_EVENT_HANDLE_WRITABLE;

231 232 233
    virEventUpdateHandle(info->id, vir_events);
    virObjectUnlock(info->priv);

J
Jim Fehlig 已提交
234 235 236
    return 0;
}

237 238 239 240
static void
libxlFDDeregisterEventHook(void *priv ATTRIBUTE_UNUSED,
                           int fd ATTRIBUTE_UNUSED,
                           void *hnd)
J
Jim Fehlig 已提交
241
{
242 243
    libxlEventHookInfoPtr info = hnd;
    libxlDomainObjPrivatePtr p = info->priv;
J
Jim Fehlig 已提交
244

245 246 247
    virObjectLock(p);
    virEventRemoveHandle(info->id);
    virObjectUnlock(p);
J
Jim Fehlig 已提交
248 249
}

250
static void
251
libxlTimerCallback(int timer ATTRIBUTE_UNUSED, void *timer_info)
J
Jim Fehlig 已提交
252
{
253 254
    libxlEventHookInfoPtr info = timer_info;
    libxlDomainObjPrivatePtr p = info->priv;
J
Jim Fehlig 已提交
255

256
    virObjectLock(p);
J
Jim Fehlig 已提交
257 258 259 260 261 262 263
    /*
     * libxl expects the event to be deregistered when calling
     * libxl_osevent_occurred_timeout, but we dont want the event info
     * destroyed.  Disable the timeout and only remove it after returning
     * from libxl.
     */
    virEventUpdateTimeout(info->id, -1);
264 265 266
    virObjectUnlock(p);
    libxl_osevent_occurred_timeout(p->ctx, info->xl_priv);
    virObjectLock(p);
J
Jim Fehlig 已提交
267 268 269 270 271 272
    /*
     * Timeout could have been freed while the lock was dropped.
     * Only remove it from the list if it still exists.
     */
    if (virEventRemoveTimeout(info->id) == 0)
        LIBXL_EV_REG_REMOVE(p->timerRegistrations, info);
273
    virObjectUnlock(p);
J
Jim Fehlig 已提交
274 275
}

276 277 278 279
static int
libxlTimeoutRegisterEventHook(void *priv,
                              void **hndp,
                              struct timeval abs_t,
280
                              void *xl_priv)
J
Jim Fehlig 已提交
281
{
282
    libxlEventHookInfoPtr info;
J
Jim Fehlig 已提交
283
    struct timeval now;
J
Jim Fehlig 已提交
284 285
    struct timeval res;
    static struct timeval zero;
286
    int timeout;
J
Jim Fehlig 已提交
287

288
    if (VIR_ALLOC(info) < 0)
J
Jim Fehlig 已提交
289 290
        return -1;

291 292 293 294 295 296 297 298 299
    info->priv = priv;
    /*
     * Also take a reference on the domain object.  Reference is dropped in
     * libxlEventHookInfoFree, ensuring the domain object outlives the timeout
     * event objects.
     */
    virObjectRef(info->priv);
    info->xl_priv = xl_priv;

J
Jim Fehlig 已提交
300
    gettimeofday(&now, NULL);
J
Jim Fehlig 已提交
301 302 303 304 305 306 307 308 309
    timersub(&abs_t, &now, &res);
    /* Ensure timeout is not overflowed */
    if (timercmp(&res, &zero, <)) {
        timeout = 0;
    } else if (res.tv_sec > INT_MAX / 1000) {
        timeout = INT_MAX;
    } else {
        timeout = res.tv_sec * 1000 + (res.tv_usec + 999) / 1000;
    }
310 311 312
    info->id = virEventAddTimeout(timeout, libxlTimerCallback,
                                  info, libxlEventHookInfoFree);
    if (info->id < 0) {
313
        virObjectUnref(info->priv);
314 315
        VIR_FREE(info);
        return -1;
J
Jim Fehlig 已提交
316 317
    }

J
Jim Fehlig 已提交
318 319 320
    virObjectLock(info->priv);
    LIBXL_EV_REG_APPEND(info->priv->timerRegistrations, info);
    virObjectUnlock(info->priv);
321 322
    *hndp = info;

J
Jim Fehlig 已提交
323 324 325
    return 0;
}

J
Jim Fehlig 已提交
326 327 328 329 330 331 332 333 334 335
/*
 * Note:  There are two changes wrt timeouts starting with xen-unstable
 * changeset 26469:
 *
 * 1. Timeout modify callbacks will only be invoked with an abs_t of {0,0},
 * i.e. make the timeout fire immediately.  Prior to this commit, timeout
 * modify callbacks were never invoked.
 *
 * 2. Timeout deregister hooks will no longer be called.
 */
336 337 338
static int
libxlTimeoutModifyEventHook(void *priv ATTRIBUTE_UNUSED,
                            void **hndp,
J
Jim Fehlig 已提交
339
                            struct timeval abs_t ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
340
{
341
    libxlEventHookInfoPtr info = *hndp;
J
Jim Fehlig 已提交
342

343
    virObjectLock(info->priv);
J
Jim Fehlig 已提交
344
    /* Make the timeout fire */
345 346 347
    virEventUpdateTimeout(info->id, 0);
    virObjectUnlock(info->priv);

J
Jim Fehlig 已提交
348 349 350
    return 0;
}

351 352 353
static void
libxlTimeoutDeregisterEventHook(void *priv ATTRIBUTE_UNUSED,
                                void *hnd)
J
Jim Fehlig 已提交
354
{
355 356
    libxlEventHookInfoPtr info = hnd;
    libxlDomainObjPrivatePtr p = info->priv;
J
Jim Fehlig 已提交
357

358
    virObjectLock(p);
J
Jim Fehlig 已提交
359 360 361 362 363 364
    /*
     * Only remove the timeout from the list if removal from the
     * event loop is successful.
     */
    if (virEventRemoveTimeout(info->id) == 0)
        LIBXL_EV_REG_REMOVE(p->timerRegistrations, info);
365
    virObjectUnlock(p);
J
Jim Fehlig 已提交
366 367
}

J
Jim Fehlig 已提交
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
static void
libxlRegisteredTimeoutsCleanup(libxlDomainObjPrivatePtr priv)
{
    libxlEventHookInfoPtr info;

    virObjectLock(priv);
    info = priv->timerRegistrations;
    while (info) {
        /*
         * libxl expects the event to be deregistered when calling
         * libxl_osevent_occurred_timeout, but we dont want the event info
         * destroyed.  Disable the timeout and only remove it after returning
         * from libxl.
         */
        virEventUpdateTimeout(info->id, -1);
        libxl_osevent_occurred_timeout(priv->ctx, info->xl_priv);
        virEventRemoveTimeout(info->id);
        info = info->next;
    }
    priv->timerRegistrations = NULL;
    virObjectUnlock(priv);
}

J
Jim Fehlig 已提交
391 392 393 394 395 396 397 398 399
static const libxl_osevent_hooks libxl_event_callbacks = {
    .fd_register = libxlFDRegisterEventHook,
    .fd_modify = libxlFDModifyEventHook,
    .fd_deregister = libxlFDDeregisterEventHook,
    .timeout_register = libxlTimeoutRegisterEventHook,
    .timeout_modify = libxlTimeoutModifyEventHook,
    .timeout_deregister = libxlTimeoutDeregisterEventHook,
};

J
Jim Fehlig 已提交
400 401 402 403 404
static void *
libxlDomainObjPrivateAlloc(void)
{
    libxlDomainObjPrivatePtr priv;

405 406 407 408
    if (libxlDomainObjPrivateInitialize() < 0)
        return NULL;

    if (!(priv = virObjectLockableNew(libxlDomainObjPrivateClass)))
J
Jim Fehlig 已提交
409 410
        return NULL;

411 412
    if (libxl_ctx_alloc(&priv->ctx, LIBXL_VERSION, 0, libxl_driver->logger)) {
        VIR_ERROR(_("Failed libxl context initialization"));
413
        virObjectUnref(priv);
414 415 416
        return NULL;
    }

J
Jim Fehlig 已提交
417
    libxl_osevent_register_hooks(priv->ctx, &libxl_event_callbacks, priv);
J
Jim Fehlig 已提交
418 419 420 421 422

    return priv;
}

static void
423
libxlDomainObjPrivateDispose(void *obj)
J
Jim Fehlig 已提交
424
{
425
    libxlDomainObjPrivatePtr priv = obj;
J
Jim Fehlig 已提交
426

427
    if (priv->deathW)
J
Jim Fehlig 已提交
428
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
J
Jim Fehlig 已提交
429

J
Jim Fehlig 已提交
430
    libxl_ctx_free(priv->ctx);
431 432 433 434 435 436 437 438 439 440 441 442
}

static void
libxlDomainObjPrivateFree(void *data)
{
    libxlDomainObjPrivatePtr priv = data;

    if (priv->deathW) {
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
        priv->deathW = NULL;
    }

443
    virObjectUnref(priv);
J
Jim Fehlig 已提交
444 445
}

446 447 448 449 450
virDomainXMLPrivateDataCallbacks libxlDomainXMLPrivateDataCallbacks = {
    .alloc = libxlDomainObjPrivateAlloc,
    .free = libxlDomainObjPrivateFree,
};

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467

static int
libxlDomainDeviceDefPostParse(virDomainDeviceDefPtr dev,
                              virDomainDefPtr def,
                              virCapsPtr caps ATTRIBUTE_UNUSED,
                              void *opaque ATTRIBUTE_UNUSED)
{
    if (dev->type == VIR_DOMAIN_DEVICE_CHR &&
        dev->data.chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        dev->data.chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE &&
        STRNEQ(def->os.type, "hvm"))
        dev->data.chr->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_XEN;

    return 0;
}


468 469
virDomainDefParserConfig libxlDomainDefParserConfig = {
    .macPrefix = { 0x00, 0x16, 0x3e },
470
    .devicesPostParseCallback = libxlDomainDeviceDefPostParse,
471 472
};

473

474 475 476 477
/* driver must be locked before calling */
static void
libxlDomainEventQueue(libxlDriverPrivatePtr driver, virDomainEventPtr event)
{
478
    virDomainEventStateQueue(driver->domainEventState, event);
479 480
}

481 482
static int
libxlAutostartDomain(virDomainObjPtr vm,
483 484 485 486
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    virErrorPtr err;
487
    int ret = -1;
488

489
    virObjectLock(vm);
490 491 492
    virResetLastError();

    if (vm->autostart && !virDomainObjIsActive(vm) &&
493
        libxlVmStart(driver, vm, false, -1) < 0) {
494 495 496 497
        err = virGetLastError();
        VIR_ERROR(_("Failed to autostart VM '%s': %s"),
                  vm->def->name,
                  err ? err->message : _("unknown error"));
498
        goto cleanup;
499 500
    }

501 502
    ret = 0;
cleanup:
503
    virObjectUnlock(vm);
504
    return ret;
505 506
}

507 508 509 510 511
static int
libxlDoNodeGetInfo(libxlDriverPrivatePtr driver, virNodeInfoPtr info)
{
    libxl_physinfo phy_info;
    const libxl_version_info* ver_info;
512
    virArch hostarch = virArchFromHost();
513

J
Jim Fehlig 已提交
514
    if (libxl_get_physinfo(driver->ctx, &phy_info)) {
515 516
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
517 518 519
        return -1;
    }

J
Jim Fehlig 已提交
520
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
521 522
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_version_info failed"));
523 524 525
        return -1;
    }

526
    if (virStrcpyStatic(info->model, virArchToString(hostarch)) == NULL) {
527 528
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("machine type %s too big for destination"),
529
                       virArchToString(hostarch));
530 531 532 533 534 535 536 537 538 539 540 541 542
        return -1;
    }

    info->memory = phy_info.total_pages * (ver_info->pagesize / 1024);
    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;
    return 0;
}

543 544 545 546
static char *
libxlDomainManagedSavePath(libxlDriverPrivatePtr driver, virDomainObjPtr vm) {
    char *ret;

547
    ignore_value(virAsprintf(&ret, "%s/%s.save", driver->saveDir, vm->def->name));
548 549 550 551 552 553 554 555 556 557 558 559 560 561
    return ret;
}

/* This internal function expects the driver lock to already be held on
 * entry. */
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4)
libxlSaveImageOpen(libxlDriverPrivatePtr driver, const char *from,
                     virDomainDefPtr *ret_def, libxlSavefileHeaderPtr ret_hdr)
{
    int fd;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    char *xml = NULL;

L
Laine Stump 已提交
562
    if ((fd = virFileOpenAs(from, O_RDONLY, 0, -1, -1, 0)) < 0) {
563 564
        virReportSystemError(-fd,
                             _("Failed to open domain image file '%s'"), from);
565 566 567 568
        goto error;
    }

    if (saferead(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
569 570
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to read libxl header"));
571 572 573 574
        goto error;
    }

    if (memcmp(hdr.magic, LIBXL_SAVE_MAGIC, sizeof(hdr.magic))) {
575
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("image magic is incorrect"));
576 577 578 579
        goto error;
    }

    if (hdr.version > LIBXL_SAVE_VERSION) {
580 581 582
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("image version is not supported (%d > %d)"),
                       hdr.version, LIBXL_SAVE_VERSION);
583 584 585 586
        goto error;
    }

    if (hdr.xmlLen <= 0) {
587 588
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("invalid XML length: %d"), hdr.xmlLen);
589 590 591
        goto error;
    }

592
    if (VIR_ALLOC_N(xml, hdr.xmlLen) < 0)
593 594 595
        goto error;

    if (saferead(fd, xml, hdr.xmlLen) != hdr.xmlLen) {
596
        virReportError(VIR_ERR_OPERATION_FAILED, "%s", _("failed to read XML"));
597 598 599
        goto error;
    }

600 601
    if (!(def = virDomainDefParseString(xml, driver->caps, driver->xmlopt,
                                        1 << VIR_DOMAIN_VIRT_XEN,
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
                                        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 已提交
619 620 621 622 623 624
/*
 * Cleanup function for domain that has reached shutoff state.
 *
 * virDomainObjPtr should be locked on invocation
 */
static void
J
Jiri Denemark 已提交
625 626 627
libxlVmCleanup(libxlDriverPrivatePtr driver,
               virDomainObjPtr vm,
               virDomainShutoffReason reason)
J
Jim Fehlig 已提交
628 629 630 631
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
    int vnc_port;
    char *file;
632
    size_t i;
J
Jim Fehlig 已提交
633

J
Jim Fehlig 已提交
634 635 636
    if (priv->deathW) {
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
        priv->deathW = NULL;
J
Jim Fehlig 已提交
637 638 639 640
    }

    if (vm->persistent) {
        vm->def->id = -1;
J
Jiri Denemark 已提交
641
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, reason);
J
Jim Fehlig 已提交
642 643
    }

644 645 646 647
    driver->nactive--;
    if (!driver->nactive && driver->inhibitCallback)
        driver->inhibitCallback(false, driver->inhibitOpaque);

J
Jim Fehlig 已提交
648 649 650 651 652
    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) {
653 654
            if (virPortAllocatorRelease(driver->reservedVNCPorts,
                                        vnc_port) < 0)
J
Jim Fehlig 已提交
655 656 657 658
                VIR_DEBUG("Could not mark port %d as unused", vnc_port);
        }
    }

659 660 661
    /* Remove any cputune settings */
    if (vm->def->cputune.nvcpupin) {
        for (i = 0; i < vm->def->cputune.nvcpupin; ++i) {
662
            virBitmapFree(vm->def->cputune.vcpupin[i]->cpumask);
663 664 665 666 667 668
            VIR_FREE(vm->def->cputune.vcpupin[i]);
        }
        VIR_FREE(vm->def->cputune.vcpupin);
        vm->def->cputune.nvcpupin = 0;
    }

J
Jim Fehlig 已提交
669 670 671 672 673
    if (virAsprintf(&file, "%s/%s.xml", driver->stateDir, vm->def->name) > 0) {
        if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR)
            VIR_DEBUG("Failed to remove domain XML for %s", vm->def->name);
        VIR_FREE(file);
    }
674 675 676 677 678 679 680

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

    libxlRegisteredTimeoutsCleanup(priv);
J
Jim Fehlig 已提交
683 684 685 686 687 688 689 690
}

/*
 * Reap a domain from libxenlight.
 *
 * virDomainObjPtr should be locked on invocation
 */
static int
J
Jiri Denemark 已提交
691 692 693
libxlVmReap(libxlDriverPrivatePtr driver,
            virDomainObjPtr vm,
            virDomainShutoffReason reason)
J
Jim Fehlig 已提交
694 695 696
{
    libxlDomainObjPrivatePtr priv = vm->privateData;

J
Jim Fehlig 已提交
697
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
698 699
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to cleanup domain %d"), vm->def->id);
J
Jim Fehlig 已提交
700 701 702
        return -1;
    }

J
Jiri Denemark 已提交
703
    libxlVmCleanup(driver, vm, reason);
J
Jim Fehlig 已提交
704 705 706 707
    return 0;
}

/*
J
Jim Fehlig 已提交
708 709 710 711 712
 * 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 已提交
713
 */
J
Jim Fehlig 已提交
714 715 716 717 718 719 720

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

721
static void
J
Jim Fehlig 已提交
722
libxlEventHandler(void *data, VIR_LIBXL_EVENT_CONST libxl_event *event)
J
Jim Fehlig 已提交
723 724
{
    libxlDriverPrivatePtr driver = libxl_driver;
J
Jim Fehlig 已提交
725
    libxlDomainObjPrivatePtr priv = ((virDomainObjPtr)data)->privateData;
726
    virDomainObjPtr vm = NULL;
727
    virDomainEventPtr dom_event = NULL;
728
    libxl_shutdown_reason xl_reason = event->u.domain_shutdown.shutdown_reason;
J
Jim Fehlig 已提交
729

J
Jim Fehlig 已提交
730
    if (event->type == LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN) {
J
Jiri Denemark 已提交
731 732
        virDomainShutoffReason reason;

733 734 735 736 737 738 739 740
        /*
         * 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;

        libxlDriverLock(driver);
741
        vm = virDomainObjListFindByID(driver->domains, event->domid);
742 743 744
        libxlDriverUnlock(driver);

        if (!vm)
J
Jim Fehlig 已提交
745 746
            goto cleanup;

747
        switch (xl_reason) {
J
Jim Fehlig 已提交
748 749
            case LIBXL_SHUTDOWN_REASON_POWEROFF:
            case LIBXL_SHUTDOWN_REASON_CRASH:
750
                if (xl_reason == LIBXL_SHUTDOWN_REASON_CRASH) {
751 752 753
                    dom_event = virDomainEventNewFromObj(vm,
                                              VIR_DOMAIN_EVENT_STOPPED,
                                              VIR_DOMAIN_EVENT_STOPPED_CRASHED);
J
Jiri Denemark 已提交
754 755 756 757
                    reason = VIR_DOMAIN_SHUTOFF_CRASHED;
                } else {
                    reason = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
                }
J
Jim Fehlig 已提交
758
                libxlVmReap(driver, vm, reason);
J
Jim Fehlig 已提交
759
                if (!vm->persistent) {
760
                    virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
761 762 763
                    vm = NULL;
                }
                break;
J
Jim Fehlig 已提交
764 765
            case LIBXL_SHUTDOWN_REASON_REBOOT:
                libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
766
                libxlVmStart(driver, vm, 0, -1);
J
Jim Fehlig 已提交
767 768
                break;
            default:
769
                VIR_INFO("Unhandled shutdown_reason %d", xl_reason);
J
Jim Fehlig 已提交
770 771 772 773 774 775
                break;
        }
    }

cleanup:
    if (vm)
776
        virObjectUnlock(vm);
777 778 779 780 781
    if (dom_event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, dom_event);
        libxlDriverUnlock(driver);
    }
J
Jim Fehlig 已提交
782 783
    /* Cast away any const */
    libxl_event_free(priv->ctx, (libxl_event *)event);
J
Jim Fehlig 已提交
784 785
}

J
Jim Fehlig 已提交
786 787 788 789 790 791
static const struct libxl_event_hooks ev_hooks = {
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlEventHandler,
    .disaster = NULL,
};

J
Jim Fehlig 已提交
792 793 794 795 796 797 798 799 800
/*
 * 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 已提交
801
    libxl_event_register_callbacks(priv->ctx, &ev_hooks, vm);
J
Jim Fehlig 已提交
802

J
Jim Fehlig 已提交
803
    if (libxl_evenable_domain_death(priv->ctx, vm->def->id, 0, &priv->deathW))
J
Jim Fehlig 已提交
804 805 806 807 808
        goto error;

    return 0;

error:
809
    if (priv->deathW) {
J
Jim Fehlig 已提交
810
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
811 812
        priv->deathW = NULL;
    }
J
Jim Fehlig 已提交
813 814 815
    return -1;
}

816
static int
817
libxlDomainSetVcpuAffinities(libxlDriverPrivatePtr driver, virDomainObjPtr vm)
818 819 820
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
    virDomainDefPtr def = vm->def;
J
Jim Fehlig 已提交
821
    libxl_bitmap map;
822 823 824 825
    uint8_t *cpumask = NULL;
    uint8_t *cpumap = NULL;
    virNodeInfo nodeinfo;
    size_t cpumaplen;
826 827
    int vcpu;
    size_t i;
828 829 830 831 832 833 834 835 836 837 838
    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;

839
        if (VIR_ALLOC_N(cpumap, cpumaplen) < 0)
840 841 842 843 844
            goto cleanup;

        cpumask = (uint8_t*) def->cputune.vcpupin[vcpu]->cpumask;

        for (i = 0; i < VIR_DOMAIN_CPUMASK_LEN; ++i) {
845 846
            if (cpumask[i])
                VIR_USE_CPU(cpumap, i);
847 848 849 850 851
        }

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

J
Jim Fehlig 已提交
852
        if (libxl_set_vcpuaffinity(priv->ctx, def->id, vcpu, &map) != 0) {
853 854
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
855 856 857 858 859 860 861 862 863 864 865 866 867
            goto cleanup;
        }

        VIR_FREE(cpumap);
    }

    ret = 0;

cleanup:
    VIR_FREE(cpumap);
    return ret;
}

M
Markus Groß 已提交
868 869 870 871 872
static int
libxlFreeMem(libxlDomainObjPrivatePtr priv, libxl_domain_config *d_config)
{
    uint32_t needed_mem;
    uint32_t free_mem;
873
    size_t i;
M
Markus Groß 已提交
874 875 876 877
    int ret = -1;
    int tries = 3;
    int wait_secs = 10;

J
Jim Fehlig 已提交
878
    if ((ret = libxl_domain_need_memory(priv->ctx, &d_config->b_info,
M
Markus Groß 已提交
879 880
                                        &needed_mem)) >= 0) {
        for (i = 0; i < tries; ++i) {
J
Jim Fehlig 已提交
881
            if ((ret = libxl_get_free_memory(priv->ctx, &free_mem)) < 0)
M
Markus Groß 已提交
882 883 884 885 886 887 888
                break;

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

J
Jim Fehlig 已提交
889
            if ((ret = libxl_set_memory_target(priv->ctx, 0,
M
Markus Groß 已提交
890 891 892 893
                                               free_mem - needed_mem,
                                               /* relative */ 1, 0)) < 0)
                break;

J
Jim Fehlig 已提交
894
            ret = libxl_wait_for_free_memory(priv->ctx, 0, needed_mem,
M
Markus Groß 已提交
895 896 897 898
                                             wait_secs);
            if (ret == 0 || ret != ERROR_NOMEM)
                break;

J
Jim Fehlig 已提交
899
            if ((ret = libxl_wait_for_memory_target(priv->ctx, 0, 1)) < 0)
M
Markus Groß 已提交
900 901 902 903 904 905 906
                break;
        }
    }

    return ret;
}

J
Jim Fehlig 已提交
907 908 909 910 911 912
/*
 * Start a domain through libxenlight.
 *
 * virDomainObjPtr should be locked on invocation
 */
static int
913 914
libxlVmStart(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
             bool start_paused, int restore_fd)
J
Jim Fehlig 已提交
915 916
{
    libxl_domain_config d_config;
917
    virDomainDefPtr def = NULL;
918
    virDomainEventPtr event = NULL;
919
    libxlSavefileHeader hdr;
J
Jim Fehlig 已提交
920 921 922
    int ret;
    uint32_t domid = 0;
    char *dom_xml = NULL;
923 924
    char *managed_save_path = NULL;
    int managed_save_fd = -1;
J
Jim Fehlig 已提交
925 926
    libxlDomainObjPrivatePtr priv = vm->privateData;

927 928 929
    /* 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) {
930 931
        managed_save_path = libxlDomainManagedSavePath(driver, vm);
        if (managed_save_path == NULL)
932 933
            goto error;

934
        if (virFileExists(managed_save_path)) {
935

936 937 938
            managed_save_fd = libxlSaveImageOpen(driver, managed_save_path,
                                                 &def, &hdr);
            if (managed_save_fd < 0)
939 940
                goto error;

941 942
            restore_fd = managed_save_fd;

943 944 945 946 947 948
            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);
949 950 951 952
                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);
953 954 955
                goto error;
            }

956
            virDomainObjAssignDef(vm, def, true, NULL);
957 958
            def = NULL;

959 960 961 962
            if (unlink(managed_save_path) < 0) {
                VIR_WARN("Failed to remove the managed state %s",
                         managed_save_path);
            }
963
            vm->hasManagedSave = false;
964
        }
965
        VIR_FREE(managed_save_path);
966 967
    }

J
Jim Fehlig 已提交
968
    libxl_domain_config_init(&d_config);
J
Jim Fehlig 已提交
969

970
    if (libxlBuildDomainConfig(driver, vm->def, &d_config) < 0)
971
        goto error;
J
Jim Fehlig 已提交
972

973
    if (driver->autoballoon && libxlFreeMem(priv, &d_config) < 0) {
974 975 976
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to get free memory for domain '%s'"),
                       d_config.c_info.name);
M
Markus Groß 已提交
977 978
        goto error;
    }
J
Jim Fehlig 已提交
979

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

982
    if (restore_fd < 0)
J
Jim Fehlig 已提交
983 984
        ret = libxl_domain_create_new(priv->ctx, &d_config,
                                      &domid, NULL, NULL);
985
    else
J
Jim Fehlig 已提交
986 987
        ret = libxl_domain_create_restore(priv->ctx, &d_config, &domid,
                                          restore_fd, NULL, NULL);
988

J
Jim Fehlig 已提交
989
    if (ret) {
990
        if (restore_fd < 0)
991 992 993
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to create new domain '%s'"),
                           d_config.c_info.name);
994
        else
995 996 997
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to restore domain '%s'"),
                           d_config.c_info.name);
J
Jim Fehlig 已提交
998 999 1000
        goto error;
    }

1001 1002
    vm->def->id = domid;
    if ((dom_xml = virDomainDefFormat(vm->def, 0)) == NULL)
J
Jim Fehlig 已提交
1003 1004
        goto error;

J
Jim Fehlig 已提交
1005
    if (libxl_userdata_store(priv->ctx, domid, "libvirt-xml",
J
Jim Fehlig 已提交
1006
                             (uint8_t *)dom_xml, strlen(dom_xml) + 1)) {
1007 1008
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to store userdata"));
J
Jim Fehlig 已提交
1009 1010 1011 1012 1013 1014
        goto error;
    }

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

1015
    if (libxlDomainSetVcpuAffinities(driver, vm) < 0)
1016 1017
        goto error;

J
Jim Fehlig 已提交
1018
    if (!start_paused) {
J
Jim Fehlig 已提交
1019
        libxl_domain_unpause(priv->ctx, domid);
J
Jiri Denemark 已提交
1020
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
J
Jim Fehlig 已提交
1021
    } else {
J
Jiri Denemark 已提交
1022
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
J
Jim Fehlig 已提交
1023 1024
    }

1025

1026
    if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
J
Jim Fehlig 已提交
1027 1028
        goto error;

1029 1030 1031 1032
    if (!driver->nactive && driver->inhibitCallback)
        driver->inhibitCallback(true, driver->inhibitOpaque);
    driver->nactive++;

1033
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STARTED,
1034 1035 1036
                                     restore_fd < 0 ?
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED :
                                         VIR_DOMAIN_EVENT_STARTED_RESTORED);
1037 1038
    if (event)
        libxlDomainEventQueue(driver, event);
1039

J
Jim Fehlig 已提交
1040
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
1041
    VIR_FREE(dom_xml);
1042
    VIR_FORCE_CLOSE(managed_save_fd);
J
Jim Fehlig 已提交
1043 1044 1045 1046
    return 0;

error:
    if (domid > 0) {
J
Jim Fehlig 已提交
1047
        libxl_domain_destroy(priv->ctx, domid, NULL);
1048
        vm->def->id = -1;
J
Jiri Denemark 已提交
1049
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);
J
Jim Fehlig 已提交
1050
    }
J
Jim Fehlig 已提交
1051
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
1052
    VIR_FREE(dom_xml);
1053
    VIR_FREE(managed_save_path);
1054
    virDomainDefFree(def);
1055
    VIR_FORCE_CLOSE(managed_save_fd);
J
Jim Fehlig 已提交
1056 1057 1058 1059 1060 1061 1062 1063
    return -1;
}


/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
1064 1065
static int
libxlReconnectDomain(virDomainObjPtr vm,
J
Jim Fehlig 已提交
1066 1067 1068 1069 1070 1071 1072 1073
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;

1074
    virObjectLock(vm);
J
Jim Fehlig 已提交
1075 1076

    /* Does domain still exist? */
J
Jim Fehlig 已提交
1077
    rc = libxl_domain_info(driver->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086
    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? */
J
Jim Fehlig 已提交
1087
    if (libxl_userdata_retrieve(driver->ctx, vm->def->id,
J
Jim Fehlig 已提交
1088 1089 1090 1091 1092 1093 1094
                                "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 已提交
1095
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_UNKNOWN);
J
Jim Fehlig 已提交
1096

1097 1098 1099 1100
    if (!driver->nactive && driver->inhibitCallback)
        driver->inhibitCallback(true, driver->inhibitOpaque);
    driver->nactive++;

J
Jim Fehlig 已提交
1101 1102
    /* Recreate domain death et. al. events */
    libxlCreateDomEvents(vm);
1103
    virObjectUnlock(vm);
1104
    return 0;
J
Jim Fehlig 已提交
1105 1106

out:
J
Jiri Denemark 已提交
1107
    libxlVmCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_UNKNOWN);
J
Jim Fehlig 已提交
1108
    if (!vm->persistent)
1109
        virDomainObjListRemoveLocked(driver->domains, vm);
J
Jim Fehlig 已提交
1110
    else
1111
        virObjectUnlock(vm);
1112 1113

    return -1;
J
Jim Fehlig 已提交
1114 1115 1116 1117 1118
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
1119
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
1120 1121 1122
}

static int
1123
libxlStateCleanup(void)
J
Jim Fehlig 已提交
1124 1125 1126 1127 1128
{
    if (!libxl_driver)
        return -1;

    libxlDriverLock(libxl_driver);
1129
    virObjectUnref(libxl_driver->caps);
1130
    virObjectUnref(libxl_driver->xmlopt);
1131
    virObjectUnref(libxl_driver->domains);
J
Jim Fehlig 已提交
1132
    libxl_ctx_free(libxl_driver->ctx);
J
Jim Fehlig 已提交
1133 1134 1135 1136
    xtl_logger_destroy(libxl_driver->logger);
    if (libxl_driver->logger_file)
        VIR_FORCE_FCLOSE(libxl_driver->logger_file);

1137
    virObjectUnref(libxl_driver->reservedVNCPorts);
J
Jim Fehlig 已提交
1138 1139 1140 1141 1142 1143 1144 1145

    VIR_FREE(libxl_driver->configDir);
    VIR_FREE(libxl_driver->autostartDir);
    VIR_FREE(libxl_driver->logDir);
    VIR_FREE(libxl_driver->stateDir);
    VIR_FREE(libxl_driver->libDir);
    VIR_FREE(libxl_driver->saveDir);

E
Eric Blake 已提交
1146
    virDomainEventStateFree(libxl_driver->domainEventState);
1147
    virSysinfoDefFree(libxl_driver->hostsysinfo);
1148

J
Jim Fehlig 已提交
1149 1150 1151 1152 1153 1154 1155
    libxlDriverUnlock(libxl_driver);
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
static bool
libxlGetAutoballoon(libxlDriverPrivatePtr driver)
{
    const libxl_version_info *info;
    regex_t regex;
    int ret;

    info = libxl_get_version_info(driver->ctx);
    if (!info)
        return true; /* default to on */

    ret = regcomp(&regex,
            "(^| )dom0_mem=((|min:|max:)[0-9]+[bBkKmMgG]?,?)+($| )",
            REG_NOSUB | REG_EXTENDED);
    if (ret)
        return true;

    ret = regexec(&regex, info->commandline, 0, NULL, 0);
    regfree(&regex);
    return ret == REG_NOMATCH;
}


J
Jim Fehlig 已提交
1179
static int
1180 1181 1182
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
1183
{
J
Jim Fehlig 已提交
1184 1185 1186
    const libxl_version_info *ver_info;
    char *log_file = NULL;
    virCommandPtr cmd;
D
Daniel Veillard 已提交
1187
    int status, ret = 0;
1188
    unsigned int free_mem;
1189
    char ebuf[1024];
J
Jim Fehlig 已提交
1190 1191 1192

    /* Disable libxl driver if non-root */
    if (!privileged) {
1193
        VIR_INFO("Not running privileged, disabling libxenlight driver");
J
Jim Fehlig 已提交
1194 1195 1196 1197 1198 1199
        return 0;
    }

    /* Disable driver if legacy xen toolstack (xend) is in use */
    cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL);
    if (virCommandRun(cmd, &status) == 0 && status == 0) {
1200
        VIR_INFO("Legacy xen tool stack seems to be in use, disabling "
J
Jim Fehlig 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
                  "libxenlight driver.");
        virCommandFree(cmd);
        return 0;
    }
    virCommandFree(cmd);

    if (VIR_ALLOC(libxl_driver) < 0)
        return -1;

    if (virMutexInit(&libxl_driver->lock) < 0) {
1211
        VIR_ERROR(_("cannot initialize mutex"));
J
Jim Fehlig 已提交
1212 1213 1214 1215 1216 1217
        VIR_FREE(libxl_driver);
        return -1;
    }
    libxlDriverLock(libxl_driver);

    /* Allocate bitmap for vnc port reservation */
1218 1219 1220 1221
    if (!(libxl_driver->reservedVNCPorts =
          virPortAllocatorNew(LIBXL_VNC_PORT_MIN,
                              LIBXL_VNC_PORT_MAX)))
        goto error;
J
Jim Fehlig 已提交
1222

1223 1224
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
1225

1226 1227
    if (VIR_STRDUP(libxl_driver->configDir, LIBXL_CONFIG_DIR) < 0)
        goto error;
J
Jim Fehlig 已提交
1228

1229 1230
    if (VIR_STRDUP(libxl_driver->autostartDir, LIBXL_AUTOSTART_DIR) < 0)
        goto error;
J
Jim Fehlig 已提交
1231

1232 1233
    if (VIR_STRDUP(libxl_driver->logDir, LIBXL_LOG_DIR) < 0)
        goto error;
J
Jim Fehlig 已提交
1234

1235 1236
    if (VIR_STRDUP(libxl_driver->stateDir, LIBXL_STATE_DIR) < 0)
        goto error;
J
Jim Fehlig 已提交
1237

1238 1239
    if (VIR_STRDUP(libxl_driver->libDir, LIBXL_LIB_DIR) < 0)
        goto error;
J
Jim Fehlig 已提交
1240

1241 1242
    if (VIR_STRDUP(libxl_driver->saveDir, LIBXL_SAVE_DIR) < 0)
        goto error;
J
Jim Fehlig 已提交
1243

1244
    if (virFileMakePath(libxl_driver->logDir) < 0) {
J
Jim Fehlig 已提交
1245
        VIR_ERROR(_("Failed to create log dir '%s': %s"),
1246
                  libxl_driver->logDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1247 1248
        goto error;
    }
1249
    if (virFileMakePath(libxl_driver->stateDir) < 0) {
J
Jim Fehlig 已提交
1250
        VIR_ERROR(_("Failed to create state dir '%s': %s"),
1251
                  libxl_driver->stateDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1252 1253
        goto error;
    }
1254
    if (virFileMakePath(libxl_driver->libDir) < 0) {
J
Jim Fehlig 已提交
1255
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
1256
                  libxl_driver->libDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1257 1258
        goto error;
    }
1259
    if (virFileMakePath(libxl_driver->saveDir) < 0) {
J
Jim Fehlig 已提交
1260
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
1261
                  libxl_driver->saveDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1262 1263 1264
        goto error;
    }

1265 1266
    if (virAsprintf(&log_file, "%s/libxl.log", libxl_driver->logDir) < 0)
        goto error;
J
Jim Fehlig 已提交
1267 1268 1269 1270 1271 1272 1273 1274 1275

    if ((libxl_driver->logger_file = fopen(log_file, "a")) == NULL)  {
        virReportSystemError(errno,
                             _("failed to create logfile %s"),
                             log_file);
        goto error;
    }
    VIR_FREE(log_file);

1276 1277 1278 1279
    /* read the host sysinfo */
    if (privileged)
        libxl_driver->hostsysinfo = virSysinfoRead();

1280
    libxl_driver->domainEventState = virDomainEventStateNew();
E
Eric Blake 已提交
1281
    if (!libxl_driver->domainEventState)
1282 1283
        goto error;

J
Jim Fehlig 已提交
1284 1285 1286
    libxl_driver->logger =
            (xentoollog_logger *)xtl_createlogger_stdiostream(libxl_driver->logger_file, XTL_DEBUG,  0);
    if (!libxl_driver->logger) {
1287
        VIR_INFO("cannot create logger for libxenlight, disabling driver");
D
Daniel Veillard 已提交
1288
        goto fail;
J
Jim Fehlig 已提交
1289 1290
    }

J
Jim Fehlig 已提交
1291 1292
    if (libxl_ctx_alloc(&libxl_driver->ctx,
                       LIBXL_VERSION, 0,
J
Jim Fehlig 已提交
1293
                       libxl_driver->logger)) {
1294
        VIR_INFO("cannot initialize libxenlight context, probably not running in a Xen Dom0, disabling driver");
D
Daniel Veillard 已提交
1295
        goto fail;
J
Jim Fehlig 已提交
1296 1297
    }

J
Jim Fehlig 已提交
1298
    if ((ver_info = libxl_get_version_info(libxl_driver->ctx)) == NULL) {
1299
        VIR_INFO("cannot version information from libxenlight, disabling driver");
D
Daniel Veillard 已提交
1300
        goto fail;
J
Jim Fehlig 已提交
1301 1302 1303 1304 1305
    }
    libxl_driver->version = (ver_info->xen_version_major * 1000000) +
            (ver_info->xen_version_minor * 1000);

    if ((libxl_driver->caps =
J
Jim Fehlig 已提交
1306
         libxlMakeCapabilities(libxl_driver->ctx)) == NULL) {
1307
        VIR_ERROR(_("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
1308 1309 1310
        goto error;
    }

1311
    if (!(libxl_driver->xmlopt = virDomainXMLOptionNew(&libxlDomainDefParserConfig,
1312 1313
                                                       &libxlDomainXMLPrivateDataCallbacks,
                                                       NULL)))
1314
        goto error;
J
Jim Fehlig 已提交
1315

1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    /* This will fill xenstore info about free and dom0 memory if missing,
     * should be called before starting first domain */
    if (libxl_get_free_memory(libxl_driver->ctx, &free_mem)) {
        VIR_ERROR(_("Unable to configure libxl's memory management parameters"));
        goto error;
    }

    /* setup autoballoon */
    libxl_driver->autoballoon = libxlGetAutoballoon(libxl_driver);

J
Jim Fehlig 已提交
1326
    /* Load running domains first. */
1327 1328 1329
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
                                       libxl_driver->stateDir,
                                       libxl_driver->autostartDir,
1330 1331 1332 1333
                                       1,
                                       libxl_driver->caps,
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
1334
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
1335 1336 1337 1338 1339
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
1340 1341 1342
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
                                       libxl_driver->configDir,
                                       libxl_driver->autostartDir,
1343 1344 1345 1346
                                       0,
                                       libxl_driver->caps,
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
1347
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
1348 1349
        goto error;

1350 1351
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
J
Jim Fehlig 已提交
1352

1353 1354
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
1355

1356
    libxlDriverUnlock(libxl_driver);
J
Jim Fehlig 已提交
1357 1358 1359 1360

    return 0;

error:
D
Daniel Veillard 已提交
1361 1362
    ret = -1;
fail:
J
Jim Fehlig 已提交
1363 1364 1365
    VIR_FREE(log_file);
    if (libxl_driver)
        libxlDriverUnlock(libxl_driver);
1366
    libxlStateCleanup();
D
Daniel Veillard 已提交
1367
    return ret;
J
Jim Fehlig 已提交
1368 1369 1370
}

static int
1371
libxlStateReload(void)
J
Jim Fehlig 已提交
1372 1373 1374 1375 1376
{
    if (!libxl_driver)
        return 0;

    libxlDriverLock(libxl_driver);
1377 1378 1379
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
                                   libxl_driver->configDir,
                                   libxl_driver->autostartDir,
1380 1381 1382 1383
                                   1,
                                   libxl_driver->caps,
                                   libxl_driver->xmlopt,
                                   1 << VIR_DOMAIN_VIRT_XEN,
1384 1385
                                   NULL, libxl_driver);

1386 1387
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
1388 1389

    libxlDriverUnlock(libxl_driver);
J
Jim Fehlig 已提交
1390 1391 1392 1393 1394 1395

    return 0;
}


static virDrvOpenStatus
1396 1397 1398
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 unsigned int flags)
J
Jim Fehlig 已提交
1399
{
E
Eric Blake 已提交
1400 1401
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
1402 1403 1404 1405
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

1406
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
            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) {
1419 1420
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
1421 1422 1423 1424 1425 1426 1427 1428
            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")) {
1429 1430 1431
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
1432 1433 1434 1435
            return VIR_DRV_OPEN_ERROR;
        }
    }

1436 1437 1438
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
1439 1440 1441 1442 1443 1444
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
1445
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1446 1447 1448 1449 1450 1451
{
    conn->privateData = NULL;
    return 0;
}

static const char *
1452
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
1453
{
1454 1455 1456
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
1457
    return "Xen";
J
Jim Fehlig 已提交
1458 1459 1460
}

static int
1461
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
1462 1463 1464
{
    libxlDriverPrivatePtr driver = conn->privateData;

1465 1466 1467
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

J
Jim Fehlig 已提交
1468 1469 1470 1471 1472 1473
    libxlDriverLock(driver);
    *version = driver->version;
    libxlDriverUnlock(driver);
    return 0;
}

1474

1475
static char *libxlConnectGetHostname(virConnectPtr conn)
1476
{
1477 1478 1479
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

1480 1481 1482
    return virGetHostname();
}

1483 1484 1485 1486 1487 1488 1489 1490
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

1491 1492 1493
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
    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);
}
1508

J
Jim Fehlig 已提交
1509
static int
1510
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1511 1512 1513 1514
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;

1515 1516 1517
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

J
Jim Fehlig 已提交
1518
    ret = libxl_get_max_cpus(driver->ctx);
J
Jim Fehlig 已提交
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    /* libxl_get_max_cpus() will return 0 if there were any failures,
       e.g. xc_physinfo() failing */
    if (ret == 0)
        return -1;

    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
1530 1531 1532
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

1533
    return libxlDoNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
1534 1535 1536
}

static char *
1537
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
1538 1539 1540 1541
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;

1542 1543 1544
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553
    libxlDriverLock(driver);
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
        virReportOOMError();
    libxlDriverUnlock(driver);

    return xml;
}

static int
1554
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
1555 1556 1557 1558
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1559 1560 1561
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

J
Jim Fehlig 已提交
1562
    libxlDriverLock(driver);
1563 1564
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1565 1566 1567 1568 1569 1570
    libxlDriverUnlock(driver);

    return n;
}

static int
1571
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
1572 1573 1574 1575
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1576 1577 1578
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

J
Jim Fehlig 已提交
1579
    libxlDriverLock(driver);
1580 1581
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    libxlDriverUnlock(driver);

    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;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);

    libxlDriverLock(driver);
1599 1600
    if (!(def = virDomainDefParseString(xml, driver->caps, driver->xmlopt,
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
1601 1602 1603
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

1604 1605 1606
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

1607
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1608
                                   driver->xmlopt,
1609 1610
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
1611 1612 1613
        goto cleanup;
    def = NULL;

1614 1615
    if (libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0,
                     -1) < 0) {
1616
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
        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)
1628
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
    libxlDriverUnlock(driver);
    return dom;
}

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

    libxlDriverLock(driver);
1641
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
1642 1643 1644
    libxlDriverUnlock(driver);

    if (!vm) {
1645
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1646 1647 1648
        goto cleanup;
    }

1649 1650 1651
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1652 1653 1654 1655 1656 1657
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1658
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
    return dom;
}

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

    libxlDriverLock(driver);
1670
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
1671 1672 1673
    libxlDriverUnlock(driver);

    if (!vm) {
1674
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1675 1676 1677
        goto cleanup;
    }

1678 1679 1680
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1681 1682 1683 1684 1685 1686
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1687
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
    return dom;
}

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

    libxlDriverLock(driver);
1699
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
1700 1701 1702
    libxlDriverUnlock(driver);

    if (!vm) {
1703
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1704 1705 1706
        goto cleanup;
    }

1707 1708 1709
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1710 1711 1712 1713 1714 1715
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1716
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1717 1718 1719
    return dom;
}

1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
    virDomainEventPtr event = NULL;
    int ret = -1;

    libxlDriverLock(driver);
1730
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
1731 1732 1733 1734 1735
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1736 1737
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
1738 1739
        goto cleanup;
    }
1740 1741 1742 1743

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

1744
    if (!virDomainObjIsActive(vm)) {
1745
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1746 1747 1748 1749 1750
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1751
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1752
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
1753 1754 1755
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to suspend domain '%d' with libxenlight"),
                           dom->id);
1756 1757 1758
            goto cleanup;
        }

J
Jiri Denemark 已提交
1759
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1760 1761 1762 1763 1764

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

1765
    if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
1766 1767 1768 1769 1770 1771
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
1772
        virObjectUnlock(vm);
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
    if (event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, event);
        libxlDriverUnlock(driver);
    }
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
    virDomainEventPtr event = NULL;
    int ret = -1;

    libxlDriverLock(driver);
1792
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
1793 1794 1795 1796 1797
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1798 1799
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
1800 1801 1802
        goto cleanup;
    }

1803 1804 1805
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1806
    if (!virDomainObjIsActive(vm)) {
1807
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1808 1809 1810 1811 1812
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1813
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1814
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
1815 1816 1817
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
                           dom->id);
1818 1819 1820
            goto cleanup;
        }

J
Jiri Denemark 已提交
1821 1822
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1823 1824 1825 1826 1827

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

1828
    if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
1829 1830 1831 1832 1833 1834
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
1835
        virObjectUnlock(vm);
1836 1837 1838 1839 1840 1841 1842 1843
    if (event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, event);
        libxlDriverUnlock(driver);
    }
    return ret;
}

J
Jim Fehlig 已提交
1844
static int
1845
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1846 1847 1848 1849 1850 1851
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

1852 1853
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1854
    libxlDriverLock(driver);
1855
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
1856 1857 1858
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1859 1860
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
1861 1862 1863
        goto cleanup;
    }

1864 1865 1866
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1867
    if (!virDomainObjIsActive(vm)) {
1868 1869
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1870 1871 1872 1873
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1874
    if (libxl_domain_shutdown(priv->ctx, dom->id) != 0) {
1875 1876 1877
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
        goto cleanup;
    }

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

cleanup:
    if (vm)
1888
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1889 1890 1891 1892
    libxlDriverUnlock(driver);
    return ret;
}

1893 1894 1895 1896 1897 1898 1899
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
1900
static int
E
Eric Blake 已提交
1901
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1902 1903 1904 1905 1906 1907
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

E
Eric Blake 已提交
1908 1909
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1910
    libxlDriverLock(driver);
1911
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
1912 1913 1914
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1915 1916
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
1917 1918 1919
        goto cleanup;
    }

1920 1921 1922
    if (virDomainRebootEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1923
    if (!virDomainObjIsActive(vm)) {
1924 1925
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1926 1927 1928 1929
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1930
    if (libxl_domain_reboot(priv->ctx, dom->id) != 0) {
1931 1932 1933
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1934 1935 1936 1937 1938 1939
        goto cleanup;
    }
    ret = 0;

cleanup:
    if (vm)
1940
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1941 1942 1943 1944 1945
    libxlDriverUnlock(driver);
    return ret;
}

static int
1946 1947
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1948 1949 1950 1951
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1952
    virDomainEventPtr event = NULL;
J
Jim Fehlig 已提交
1953

1954 1955
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1956
    libxlDriverLock(driver);
1957
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
1958 1959 1960
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1961 1962
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
1963 1964 1965
        goto cleanup;
    }

1966 1967 1968
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1969
    if (!virDomainObjIsActive(vm)) {
1970 1971
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1972 1973 1974
        goto cleanup;
    }

1975 1976 1977
    event = virDomainEventNewFromObj(vm,VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

J
Jim Fehlig 已提交
1978
    if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED) != 0) {
1979 1980
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), dom->id);
J
Jim Fehlig 已提交
1981 1982 1983 1984
        goto cleanup;
    }

    if (!vm->persistent) {
1985
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1986 1987 1988 1989 1990 1991 1992
        vm = NULL;
    }

    ret = 0;

cleanup:
    if (vm)
1993
        virObjectUnlock(vm);
1994 1995
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1996 1997 1998 1999
    libxlDriverUnlock(driver);
    return ret;
}

2000 2001 2002 2003 2004 2005
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

2006 2007 2008 2009 2010 2011 2012 2013
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;

    libxlDriverLock(driver);
2014
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2015 2016 2017 2018
    libxlDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2019 2020
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2021 2022 2023
        goto cleanup;
    }

2024 2025 2026 2027 2028
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

    if (VIR_STRDUP(type, vm->def->os.type) < 0)
        goto cleanup;
2029 2030 2031

cleanup:
    if (vm)
2032
        virObjectUnlock(vm);
2033 2034 2035
    return type;
}

2036
static unsigned long long
2037 2038 2039 2040
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
2041
    unsigned long long ret = 0;
2042 2043

    libxlDriverLock(driver);
2044
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2045 2046 2047
    libxlDriverUnlock(driver);

    if (!vm) {
2048
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
2049 2050
        goto cleanup;
    }
2051 2052 2053 2054

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

2055 2056 2057 2058
    ret = vm->def->mem.max_balloon;

cleanup:
    if (vm)
2059
        virObjectUnlock(vm);
2060 2061 2062 2063
    return ret;
}

static int
2064
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
2065 2066 2067 2068 2069
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
2070 2071
    virDomainDefPtr persistentDef = NULL;
    bool isActive;
2072 2073 2074
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
2075 2076
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
2077 2078

    libxlDriverLock(driver);
2079
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2080 2081 2082
    libxlDriverUnlock(driver);

    if (!vm) {
2083
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
2084 2085 2086
        goto cleanup;
    }

2087 2088 2089
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
    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;
2103 2104
    }

2105
    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
2106 2107
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set memory on an inactive domain"));
2108 2109 2110 2111 2112
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
2113 2114
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a transient domain"));
2115 2116
            goto cleanup;
        }
2117
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps,
2118
                                                           driver->xmlopt,
2119
                                                           vm)))
2120 2121 2122
            goto cleanup;
    }

2123 2124
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
2125

2126 2127
        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
2128
            if (libxl_domain_setmaxmem(priv->ctx, dom->id, newmem) < 0) {
2129 2130 2131
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
                                 " with libxenlight"), dom->id);
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
                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;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
2143 2144 2145
            goto cleanup;
        }

2146 2147
    } else {
        /* resize the current memory */
2148

2149
        if (newmem > vm->def->mem.max_balloon) {
2150 2151
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
2152 2153 2154 2155 2156
            goto cleanup;
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
2157
            if (libxl_set_memory_target(priv->ctx, dom->id, newmem, 0,
2158
                                        /* force */ 1) < 0) {
2159 2160 2161
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
                                 " with libxenlight"), dom->id);
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
                goto cleanup;
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
            ret = virDomainSaveConfig(driver->configDir, persistentDef);
            goto cleanup;
        }
2172 2173
    }

2174 2175
    ret = 0;

2176 2177
cleanup:
    if (vm)
2178
        virObjectUnlock(vm);
2179 2180 2181 2182 2183 2184 2185 2186 2187
    return ret;
}

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

2188 2189 2190 2191 2192 2193
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
2194 2195 2196 2197 2198
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
2199
    libxl_dominfo d_info;
J
Jim Fehlig 已提交
2200 2201 2202
    int ret = -1;

    libxlDriverLock(driver);
2203
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
2204 2205 2206
    libxlDriverUnlock(driver);

    if (!vm) {
2207 2208
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
J
Jim Fehlig 已提交
2209 2210 2211
        goto cleanup;
    }

2212 2213 2214
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2215 2216 2217
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
2218
        info->maxMem = vm->def->mem.max_balloon;
2219
    } else {
J
Jim Fehlig 已提交
2220
        if (libxl_domain_info(driver->ctx, &d_info, dom->id) != 0) {
2221 2222
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxl_domain_info failed for domain '%d'"), dom->id);
2223 2224 2225 2226
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
2227
        info->maxMem = d_info.max_memkb;
2228 2229
    }

J
Jiri Denemark 已提交
2230
    info->state = virDomainObjGetState(vm, NULL);
J
Jim Fehlig 已提交
2231 2232 2233 2234 2235
    info->nrVirtCpu = vm->def->vcpus;
    ret = 0;

  cleanup:
    if (vm)
2236
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2237 2238 2239
    return ret;
}

2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

    libxlDriverLock(driver);
2253
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2254 2255 2256
    libxlDriverUnlock(driver);

    if (!vm) {
2257 2258
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
2259 2260 2261
        goto cleanup;
    }

2262 2263 2264
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
2265
    *state = virDomainObjGetState(vm, reason);
2266 2267 2268 2269
    ret = 0;

  cleanup:
    if (vm)
2270
        virObjectUnlock(vm);
2271 2272 2273
    return ret;
}

2274 2275
/* This internal function expects the driver lock to already be held on
 * entry and the vm must be active. */
2276
static int
2277 2278
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
2279
{
2280
    libxlDomainObjPrivatePtr priv = vm->privateData;
2281 2282 2283 2284
    libxlSavefileHeader hdr;
    virDomainEventPtr event = NULL;
    char *xml = NULL;
    uint32_t xml_len;
2285
    int fd = -1;
2286 2287 2288
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
2289 2290 2291
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
2292 2293 2294 2295
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
2296
                            -1, -1, 0)) < 0) {
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
        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)) {
2312 2313
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
2314 2315 2316 2317
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
2318 2319
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
2320 2321 2322
        goto cleanup;
    }

J
Jim Fehlig 已提交
2323
    if (libxl_domain_suspend(priv->ctx, vm->def->id, fd, 0, NULL) != 0) {
2324 2325 2326
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
2327 2328 2329 2330 2331 2332
        goto cleanup;
    }

    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

J
Jim Fehlig 已提交
2333
    if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED) != 0) {
2334 2335
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
2336 2337 2338
        goto cleanup;
    }

2339
    vm->hasManagedSave = true;
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
    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
2352 2353
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
2354
{
2355 2356
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
2357 2358
    int ret = -1;

2359 2360
    virCheckFlags(0, -1);
    if (dxml) {
2361 2362
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
2363 2364 2365
        return -1;
    }

2366
    libxlDriverLock(driver);
2367
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2368

2369 2370 2371
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2372 2373
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2374 2375 2376
        goto cleanup;
    }

2377 2378 2379
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

2385 2386 2387 2388
    if (libxlDoDomainSave(driver, vm, to) < 0)
        goto cleanup;

    if (!vm->persistent) {
2389
        virDomainObjListRemove(driver->domains, vm);
2390 2391 2392 2393
        vm = NULL;
    }

    ret = 0;
2394

2395 2396
cleanup:
    if (vm)
2397
        virObjectUnlock(vm);
2398 2399 2400
    libxlDriverUnlock(driver);
    return ret;
}
2401

2402
static int
2403 2404 2405 2406 2407 2408 2409 2410
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)
2411 2412 2413 2414 2415 2416 2417
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
2418

2419
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
2420
    if (dxml) {
2421 2422
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
2423 2424 2425
        return -1;
    }

2426
    libxlDriverLock(driver);
2427

2428 2429
    fd = libxlSaveImageOpen(driver, from, &def, &hdr);
    if (fd < 0)
2430 2431
        goto cleanup;

2432 2433 2434
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
        goto cleanup;

2435
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2436
                                   driver->xmlopt,
2437 2438 2439
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
2440 2441 2442 2443
        goto cleanup;

    def = NULL;

2444 2445
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_SAVE_PAUSED) != 0, fd);
    if (ret < 0 && !vm->persistent) {
2446
        virDomainObjListRemove(driver->domains, vm);
2447 2448 2449 2450
        vm = NULL;
    }

cleanup:
2451 2452
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
2453 2454
    virDomainDefFree(def);
    if (vm)
2455
        virObjectUnlock(vm);
2456 2457 2458 2459
    libxlDriverUnlock(driver);
    return ret;
}

2460 2461 2462 2463 2464 2465
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

2466
static int
2467
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
{
    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);

    libxlDriverLock(driver);
2479
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2480 2481 2482 2483 2484
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2485 2486
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2487 2488 2489
        goto cleanup;
    }

2490 2491 2492
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2493
    if (!virDomainObjIsActive(vm)) {
2494
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2495 2496 2497 2498 2499 2500 2501
        goto cleanup;
    }

    priv = vm->privateData;

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
2502
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
2503 2504 2505 2506
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
                           dom->id);
2507 2508 2509 2510 2511 2512
            goto cleanup;
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

J
Jim Fehlig 已提交
2513
    if (libxl_domain_core_dump(priv->ctx, dom->id, to, NULL) != 0) {
2514 2515 2516
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
                       dom->id);
2517 2518 2519 2520 2521
        goto cleanup_unpause;
    }

    libxlDriverLock(driver);
    if (flags & VIR_DUMP_CRASH) {
J
Jim Fehlig 已提交
2522
        if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED) != 0) {
2523 2524
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to destroy domain '%d'"), dom->id);
2525 2526 2527 2528 2529 2530 2531 2532
            goto cleanup_unlock;
        }

        event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

    if ((flags & VIR_DUMP_CRASH) && !vm->persistent) {
2533
        virDomainObjListRemove(driver->domains, vm);
2534 2535 2536 2537 2538 2539 2540 2541 2542
        vm = NULL;
    }

    ret = 0;

cleanup_unlock:
    libxlDriverUnlock(driver);
cleanup_unpause:
    if (virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
2543
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
2544 2545 2546
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
                             " libxenlight"), dom->id);
2547 2548 2549 2550 2551 2552 2553
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
cleanup:
    if (vm)
2554
        virObjectUnlock(vm);
2555 2556 2557 2558 2559 2560 2561 2562
    if (event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, event);
        libxlDriverUnlock(driver);
    }
    return ret;
}

2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
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);

    libxlDriverLock(driver);
2574
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2575 2576 2577
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2578 2579
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2580 2581 2582
        goto cleanup;
    }

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

2586
    if (!virDomainObjIsActive(vm)) {
2587
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2588 2589
        goto cleanup;
    }
2590
    if (!vm->persistent) {
2591 2592
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
2593 2594
        goto cleanup;
    }
2595 2596 2597 2598 2599 2600 2601

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

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

2602 2603 2604 2605
    if (libxlDoDomainSave(driver, vm, name) < 0)
        goto cleanup;

    if (!vm->persistent) {
2606
        virDomainObjListRemove(driver->domains, vm);
2607 2608 2609 2610
        vm = NULL;
    }

    ret = 0;
2611 2612 2613

cleanup:
    if (vm)
2614
        virObjectUnlock(vm);
2615 2616 2617 2618 2619
    libxlDriverUnlock(driver);
    VIR_FREE(name);
    return ret;
}

2620 2621
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
2622 2623 2624 2625
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
2626
    int ret = -1;
2627

2628
    virObjectLock(vm);
2629 2630 2631 2632 2633 2634

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

    vm->hasManagedSave = virFileExists(name);

2635
    ret = 0;
2636
cleanup:
2637
    virObjectUnlock(vm);
2638
    VIR_FREE(name);
2639
    return ret;
2640 2641
}

2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

    libxlDriverLock(driver);
2652
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2653 2654 2655
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2656 2657
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2658 2659 2660
        goto cleanup;
    }

2661 2662 2663
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2664
    ret = vm->hasManagedSave;
2665 2666 2667

cleanup:
    if (vm)
2668
        virObjectUnlock(vm);
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
    libxlDriverUnlock(driver);
    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);

    libxlDriverLock(driver);
2684
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2685 2686 2687
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2688 2689
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2690 2691 2692
        goto cleanup;
    }

2693 2694 2695
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2696 2697 2698 2699 2700
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
2701
    vm->hasManagedSave = false;
2702 2703 2704 2705

cleanup:
    VIR_FREE(name);
    if (vm)
2706
        virObjectUnlock(vm);
2707 2708 2709 2710
    libxlDriverUnlock(driver);
    return ret;
}

2711 2712 2713 2714 2715 2716 2717 2718
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
2719
    libxl_bitmap map;
2720 2721
    uint8_t *bitmask = NULL;
    unsigned int maplen;
2722 2723
    size_t i;
    unsigned int pos;
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
    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)) {
2736 2737
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2738 2739 2740 2741
        return -1;
    }

    if (!nvcpus) {
2742
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2743 2744 2745 2746
        return -1;
    }

    libxlDriverLock(driver);
2747
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2748 2749 2750
    libxlDriverUnlock(driver);

    if (!vm) {
2751
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
2752 2753 2754
        goto cleanup;
    }

2755 2756 2757
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2758
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2759 2760
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2761 2762 2763 2764
        goto cleanup;
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2765 2766
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2767 2768 2769
        goto cleanup;
    }

2770
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2771 2772
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2773 2774 2775 2776 2777 2778 2779 2780
        goto cleanup;
    }

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

    if (nvcpus > max) {
2781 2782 2783
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2784 2785 2786 2787 2788
        goto cleanup;
    }

    priv = vm->privateData;

2789
    if (!(def = virDomainObjGetPersistentDef(driver->caps, driver->xmlopt, vm)))
2790 2791
        goto cleanup;

E
Eric Blake 已提交
2792
    maplen = VIR_CPU_MAPLEN(nvcpus);
2793
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
2794 2795 2796
        goto cleanup;

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2797
        pos = i / 8;
2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
        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 已提交
2816
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2817 2818 2819
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2820 2821 2822 2823 2824
            goto cleanup;
        }
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2825
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2826 2827 2828
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842
            goto cleanup;
        }
        def->vcpus = nvcpus;
        break;
    }

    ret = 0;

    if (flags & VIR_DOMAIN_VCPU_CONFIG)
        ret = virDomainSaveConfig(driver->configDir, def);

cleanup:
    VIR_FREE(bitmask);
     if (vm)
2843
        virObjectUnlock(vm);
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
    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)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDefPtr def;
    int ret = -1;
2860
    bool active;
2861 2862 2863 2864 2865 2866

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

    libxlDriverLock(driver);
2867
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2868 2869 2870
    libxlDriverUnlock(driver);

    if (!vm) {
2871
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
2872 2873 2874
        goto cleanup;
    }

2875 2876 2877
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2878 2879 2880 2881 2882 2883 2884 2885 2886
    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)) {
2887 2888
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2889 2890 2891
        return -1;
    }

2892
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2893
        if (!active) {
2894 2895
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2896 2897 2898 2899
            goto cleanup;
        }
        def = vm->def;
    } else {
2900
        if (!vm->persistent) {
2901 2902
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2903 2904
            goto cleanup;
        }
2905 2906 2907 2908 2909 2910 2911
        def = vm->newDef ? vm->newDef : vm->def;
    }

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

cleanup:
    if (vm)
2912
        virObjectUnlock(vm);
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
    return ret;
}

static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    int ret = -1;
J
Jim Fehlig 已提交
2924
    libxl_bitmap map;
2925 2926

    libxlDriverLock(driver);
2927
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2928 2929 2930
    libxlDriverUnlock(driver);

    if (!vm) {
2931
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
2932 2933 2934
        goto cleanup;
    }

2935 2936 2937
    if (virDomainPinVcpuEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2938
    if (!virDomainObjIsActive(vm)) {
2939 2940
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot pin vcpus on an inactive domain"));
2941 2942 2943 2944 2945 2946 2947
        goto cleanup;
    }

    priv = vm->privateData;

    map.size = maplen;
    map.map = cpumap;
J
Jim Fehlig 已提交
2948
    if (libxl_set_vcpuaffinity(priv->ctx, dom->id, vcpu, &map) != 0) {
2949 2950
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
2951 2952
        goto cleanup;
    }
2953

H
Hu Tao 已提交
2954
    if (!vm->def->cputune.vcpupin) {
2955
        if (VIR_ALLOC(vm->def->cputune.vcpupin) < 0)
H
Hu Tao 已提交
2956 2957 2958
            goto cleanup;
        vm->def->cputune.nvcpupin = 0;
    }
2959
    if (virDomainVcpuPinAdd(&vm->def->cputune.vcpupin,
H
Hu Tao 已提交
2960 2961 2962 2963
                            &vm->def->cputune.nvcpupin,
                            cpumap,
                            maplen,
                            vcpu) < 0) {
2964 2965
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to update or add vcpupin xml"));
2966 2967 2968
        goto cleanup;
    }

2969
    if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
2970 2971
        goto cleanup;

2972 2973 2974 2975
    ret = 0;

cleanup:
    if (vm)
2976
        virObjectUnlock(vm);
2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
    return ret;
}


static int
libxlDomainGetVcpus(virDomainPtr dom, virVcpuInfoPtr info, int maxinfo,
                    unsigned char *cpumaps, int maplen)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    int ret = -1;
    libxl_vcpuinfo *vcpuinfo;
    int maxcpu, hostcpus;
2991
    size_t i;
2992 2993 2994
    unsigned char *cpumap;

    libxlDriverLock(driver);
2995
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2996 2997 2998
    libxlDriverUnlock(driver);

    if (!vm) {
2999
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
3000 3001 3002
        goto cleanup;
    }

3003 3004 3005
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3006
    if (!virDomainObjIsActive(vm)) {
3007
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3008 3009 3010 3011
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
3012
    if ((vcpuinfo = libxl_list_vcpu(priv->ctx, dom->id, &maxcpu,
3013
                                    &hostcpus)) == NULL) {
3014 3015 3016
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
                       dom->id);
3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038
        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 已提交
3039
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
3040 3041 3042 3043 3044 3045 3046
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

cleanup:
    if (vm)
3047
        virObjectUnlock(vm);
3048 3049 3050
    return ret;
}

J
Jim Fehlig 已提交
3051
static char *
3052
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
3053 3054 3055 3056 3057
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

3058 3059
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
3060
    libxlDriverLock(driver);
3061
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
3062 3063 3064
    libxlDriverUnlock(driver);

    if (!vm) {
3065 3066
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
J
Jim Fehlig 已提交
3067 3068 3069
        goto cleanup;
    }

3070 3071 3072
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
3073 3074 3075 3076
    ret = virDomainDefFormat(vm->def, flags);

  cleanup:
    if (vm)
3077
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
3078 3079 3080
    return ret;
}

3081
static char *
3082 3083 3084
libxlConnectDomainXMLFromNative(virConnectPtr conn, const char * nativeFormat,
                                const char * nativeConfig,
                                unsigned int flags)
3085 3086 3087 3088 3089 3090 3091
{
    libxlDriverPrivatePtr driver = conn->privateData;
    const libxl_version_info *ver_info;
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
3092 3093
    virCheckFlags(0, NULL);

3094 3095 3096
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

3097
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
3098 3099
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
3100 3101 3102
        goto cleanup;
    }

J
Jim Fehlig 已提交
3103
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
3104
        VIR_ERROR(_("cannot get version information from libxenlight"));
3105 3106 3107 3108 3109 3110 3111
        goto cleanup;
    }

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

    if (!(def = xenParseXM(conf, ver_info->xen_version_major, driver->caps))) {
3112
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("parsing xm config failed"));
3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
        goto cleanup;
    }

    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);

cleanup:
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
    return xml;
}

#define MAX_CONFIG_SIZE (1024 * 65)
static char *
3127 3128 3129
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
3130 3131 3132 3133 3134 3135 3136 3137
{
    libxlDriverPrivatePtr driver = conn->privateData;
    const libxl_version_info *ver_info;
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    int len = MAX_CONFIG_SIZE;
    char *ret = NULL;

E
Eric Blake 已提交
3138 3139
    virCheckFlags(0, NULL);

3140 3141 3142
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

3143
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
3144 3145
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
3146 3147 3148
        goto cleanup;
    }

J
Jim Fehlig 已提交
3149
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
3150
        VIR_ERROR(_("cannot get version information from libxenlight"));
3151 3152 3153
        goto cleanup;
    }

3154 3155
    if (!(def = virDomainDefParseString(domainXml,
                                        driver->caps, driver->xmlopt,
M
Matthias Bolte 已提交
3156
                                        1 << VIR_DOMAIN_VIRT_XEN, 0)))
3157 3158 3159 3160 3161
        goto cleanup;

    if (!(conf = xenFormatXM(conn, def, ver_info->xen_version_major)))
        goto cleanup;

3162
    if (VIR_ALLOC_N(ret, len) < 0)
3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
        goto cleanup;

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

cleanup:
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
    return ret;
}

J
Jim Fehlig 已提交
3177
static int
3178 3179
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
3180 3181 3182 3183
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

3184 3185 3186
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

J
Jim Fehlig 已提交
3187
    libxlDriverLock(driver);
3188 3189
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
3190 3191 3192 3193 3194
    libxlDriverUnlock(driver);
    return n;
}

static int
3195
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
3196 3197 3198 3199
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

3200 3201 3202
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

J
Jim Fehlig 已提交
3203
    libxlDriverLock(driver);
3204
    n = virDomainObjListNumOfDomains(driver->domains, false,
3205 3206
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
3207 3208 3209 3210 3211 3212 3213
    libxlDriverUnlock(driver);

    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
3214
                           unsigned int flags)
J
Jim Fehlig 已提交
3215 3216 3217 3218 3219 3220 3221 3222
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

    libxlDriverLock(driver);
3223
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
3224 3225 3226
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3227 3228
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
3229 3230 3231
        goto cleanup;
    }

3232 3233 3234
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
3235
    if (virDomainObjIsActive(vm)) {
3236 3237
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
J
Jim Fehlig 已提交
3238 3239 3240
        goto cleanup;
    }

3241
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0, -1);
J
Jim Fehlig 已提交
3242 3243 3244

cleanup:
    if (vm)
3245
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
    libxlDriverUnlock(driver);
    return ret;
}

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

static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
3263
    virDomainEventPtr event = NULL;
3264
    virDomainDefPtr oldDef = NULL;
J
Jim Fehlig 已提交
3265 3266

    libxlDriverLock(driver);
3267
    if (!(def = virDomainDefParseString(xml, driver->caps, driver->xmlopt,
M
Matthias Bolte 已提交
3268
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
3269 3270 3271
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

3272 3273 3274
    if (virDomainDefineXMLEnsureACL(conn, def) < 0)
        goto cleanup;

3275
    if (!(vm = virDomainObjListAdd(driver->domains, def,
3276
                                   driver->xmlopt,
3277 3278
                                   0,
                                   &oldDef)))
J
Jim Fehlig 已提交
3279 3280 3281 3282 3283 3284
        goto cleanup;
    def = NULL;
    vm->persistent = 1;

    if (virDomainSaveConfig(driver->configDir,
                            vm->newDef ? vm->newDef : vm->def) < 0) {
3285
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
3286 3287 3288 3289 3290 3291 3292 3293
        vm = NULL;
        goto cleanup;
    }

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

3294
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
3295
                                     !oldDef ?
3296 3297 3298
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

J
Jim Fehlig 已提交
3299 3300
cleanup:
    virDomainDefFree(def);
3301
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
3302
    if (vm)
3303
        virObjectUnlock(vm);
3304 3305
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
3306 3307 3308 3309 3310
    libxlDriverUnlock(driver);
    return dom;
}

static int
3311 3312
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
3313 3314 3315
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
3316
    virDomainEventPtr event = NULL;
3317
    char *name = NULL;
J
Jim Fehlig 已提交
3318 3319
    int ret = -1;

3320 3321
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
3322
    libxlDriverLock(driver);
3323
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
3324 3325 3326 3327 3328

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
3329 3330
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
3331 3332 3333
        goto cleanup;
    }

3334 3335 3336
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
3337
    if (!vm->persistent) {
3338 3339
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
3340 3341 3342
        goto cleanup;
    }

3343 3344 3345 3346 3347 3348 3349
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
3350 3351
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
3352 3353 3354
                goto cleanup;
            }
        } else {
3355 3356 3357
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
3358 3359 3360 3361
            goto cleanup;
        }
    }

J
Jim Fehlig 已提交
3362 3363 3364 3365 3366
    if (virDomainDeleteConfig(driver->configDir,
                              driver->autostartDir,
                              vm) < 0)
        goto cleanup;

3367 3368 3369
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

3370 3371 3372
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
3373
        virDomainObjListRemove(driver->domains, vm);
3374 3375 3376
        vm = NULL;
    }

J
Jim Fehlig 已提交
3377 3378 3379
    ret = 0;

  cleanup:
3380
    VIR_FREE(name);
J
Jim Fehlig 已提交
3381
    if (vm)
3382
        virObjectUnlock(vm);
3383 3384
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
3385 3386 3387 3388
    libxlDriverUnlock(driver);
    return ret;
}

3389 3390 3391 3392 3393 3394
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

3395 3396 3397 3398 3399 3400
static int
libxlDomainChangeEjectableMedia(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDiskDefPtr disk)
{
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
3401
    size_t i;
3402 3403
    int ret = -1;

3404
    for (i = 0; i < vm->def->ndisks; i++) {
3405 3406 3407 3408 3409 3410 3411 3412
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
3413 3414 3415
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
3416 3417 3418 3419
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
3420 3421 3422
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
3423 3424 3425
        return -1;
    }

J
Jim Fehlig 已提交
3426
    if (libxlMakeDisk(disk, &x_disk) < 0)
3427 3428
        goto cleanup;

J
Jim Fehlig 已提交
3429
    if ((ret = libxl_cdrom_insert(priv->ctx, vm->def->id, &x_disk, NULL)) < 0) {
3430 3431 3432
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463
        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) {
3464
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
3465 3466
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
3467 3468 3469 3470
                    goto cleanup;
                }

                if (!l_disk->src) {
3471 3472
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
3473 3474 3475
                    goto cleanup;
                }

3476
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
3477 3478
                    goto cleanup;

J
Jim Fehlig 已提交
3479
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3480 3481
                    goto cleanup;

J
Jim Fehlig 已提交
3482 3483
                if ((ret = libxl_device_disk_add(priv->ctx, vm->def->id,
                                                &x_disk, NULL)) < 0) {
3484 3485 3486
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
3487 3488 3489 3490 3491 3492
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
3493 3494 3495
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
3496 3497 3498
            }
            break;
        default:
3499 3500 3501
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514
            break;
    }

cleanup:
    return ret;
}

static int
libxlDomainDetachDeviceDiskLive(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
3515
    int idx;
3516 3517 3518 3519 3520 3521
    int ret = -1;

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

3522 3523 3524
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
3525 3526
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3527 3528 3529
                    goto cleanup;
                }

3530
                l_disk = vm->def->disks[idx];
3531

J
Jim Fehlig 已提交
3532
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3533 3534
                    goto cleanup;

J
Jim Fehlig 已提交
3535 3536
                if ((ret = libxl_device_disk_remove(priv->ctx, vm->def->id,
                                                    &x_disk, NULL)) < 0) {
3537 3538 3539
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3540 3541 3542
                    goto cleanup;
                }

3543
                virDomainDiskRemove(vm->def, idx);
3544 3545 3546
                virDomainDiskDefFree(l_disk);

            } else {
3547 3548 3549
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3550 3551 3552
            }
            break;
        default:
3553 3554 3555
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576
            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:
3577 3578 3579
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
            break;
    }

    return ret;
}

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

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3594
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3595 3596
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3597 3598
                return -1;
            }
3599
            if (virDomainDiskInsert(vmdef, disk))
3600 3601 3602 3603 3604 3605
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;

        default:
3606 3607
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624
            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:
3625 3626 3627
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3628 3629 3630 3631 3632 3633 3634 3635 3636
            break;
    }

    return ret;
}

static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3637
    virDomainDiskDefPtr disk, detach;
3638 3639 3640 3641 3642
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3643
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3644 3645
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3646 3647
                break;
            }
3648
            virDomainDiskDefFree(detach);
3649 3650 3651
            ret = 0;
            break;
        default:
3652 3653
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676
            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:
3677 3678 3679
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3680 3681 3682 3683
                    break;
            }
            break;
        default:
3684 3685 3686
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr orig;
    virDomainDiskDefPtr disk;
3698
    int idx;
3699 3700 3701 3702 3703
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3704
            if ((idx = virDomainDiskIndexByName(vmdef, disk->dst, false)) < 0) {
3705 3706
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3707 3708
                goto cleanup;
            }
3709
            orig = vmdef->disks[idx];
3710
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3711 3712
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723
                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;
            }
3724
            orig->format = disk->format;
3725 3726 3727
            disk->src = NULL;
            break;
        default:
3728 3729
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740
            goto cleanup;
    }

    ret = 0;

cleanup:
    return ret;
}


static int
3741 3742
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    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);

    libxlDriverLock(driver);
3755
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
3756 3757

    if (!vm) {
3758
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
3759 3760 3761
        goto cleanup;
    }

3762 3763 3764
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3765 3766 3767 3768 3769 3770 3771 3772
    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) {
3773 3774
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3775 3776 3777 3778 3779
            goto cleanup;
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
3780 3781
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3782 3783 3784 3785 3786 3787
         goto cleanup;
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3788 3789
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
                                            driver->caps, driver->xmlopt,
3790 3791 3792 3793
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3794 3795
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, driver->caps,
                                                    driver->xmlopt)))
3796 3797
            goto cleanup;

3798 3799 3800
        if ((ret = libxlDomainAttachDeviceConfig(vmdef, dev)) < 0)
            goto cleanup;
    } else {
3801
        ret = 0;
3802
    }
3803 3804 3805 3806

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
3807 3808
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
                                            driver->caps, driver->xmlopt,
3809 3810 3811
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

3812 3813 3814
        if ((ret = libxlDomainAttachDeviceLive(priv, vm, dev)) < 0)
            goto cleanup;

3815 3816 3817 3818
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3819
        if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
3820 3821 3822 3823 3824 3825 3826
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
3827
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3828 3829 3830 3831 3832 3833 3834 3835
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3836
        virObjectUnlock(vm);
3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851
    libxlDriverUnlock(driver);
    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)
{
3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    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);

    libxlDriverLock(driver);
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);

    if (!vm) {
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
        goto cleanup;
    }

3870 3871 3872
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946
    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,
                                            driver->caps, driver->xmlopt,
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, driver->caps,
                                                    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,
                                            driver->caps, driver->xmlopt,
                                            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.
         */
        if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
    libxlDriverUnlock(driver);
    return ret;
3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959
}

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)
{
3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    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);

    libxlDriverLock(driver);
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);

    if (!vm) {
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
        goto cleanup;
    }

3978 3979 3980
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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
    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,
                                            driver->caps, driver->xmlopt,
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, driver->caps,
                                                    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,
                                            driver->caps, driver->xmlopt,
                                            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.
         */
        if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
        ret = virDomainSaveConfig(driver->configDir, vmdef);
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
    libxlDriverUnlock(driver);
    return ret;
4055 4056
}

4057 4058 4059 4060 4061 4062 4063
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    const libxl_version_info* ver_info;
    libxlDriverPrivatePtr driver = conn->privateData;

4064 4065 4066
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
        return 0;

J
Jim Fehlig 已提交
4067
    if (libxl_get_physinfo(driver->ctx, &phy_info)) {
4068 4069
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
4070 4071 4072
        return 0;
    }

J
Jim Fehlig 已提交
4073
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
4074 4075
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_version_info failed"));
4076 4077 4078 4079 4080 4081
        return 0;
    }

    return phy_info.free_pages * ver_info->pagesize;
}

4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
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;

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
        return -1;

    /* Early failure is probably worth just a warning */
    numa_info = libxl_get_numainfo(driver->ctx, &nr_nodes);
    if (numa_info == NULL || nr_nodes == 0) {
        VIR_WARN("libxl_get_numainfo failed to retrieve NUMA data");
        return 0;
    }

    /* Check/sanitize the cell range */
    if (startCell > nr_nodes) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
                       startCell, nr_nodes);
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
    if (lastCell > nr_nodes)
        lastCell = nr_nodes;

    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;
    }
    ret = numCells;

cleanup:
    libxl_numainfo_list_free(numa_info, nr_nodes);
    return ret;
}

4127
static int
4128 4129 4130
libxlConnectDomainEventRegister(virConnectPtr conn,
                                virConnectDomainEventCallback callback, void *opaque,
                                virFreeCallback freecb)
4131 4132 4133 4134
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4135 4136 4137
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

4138
    libxlDriverLock(driver);
4139 4140 4141
    ret = virDomainEventStateRegister(conn,
                                      driver->domainEventState,
                                      callback, opaque, freecb);
4142 4143 4144 4145 4146 4147 4148
    libxlDriverUnlock(driver);

    return ret;
}


static int
4149 4150
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
4151 4152 4153 4154
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4155 4156 4157
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

4158
    libxlDriverLock(driver);
4159 4160 4161
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
4162 4163 4164 4165 4166
    libxlDriverUnlock(driver);

    return ret;
}

4167 4168 4169 4170 4171 4172 4173 4174
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    libxlDriverLock(driver);
4175
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4176 4177 4178 4179 4180
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4181 4182
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
4183 4184 4185
        goto cleanup;
    }

4186 4187 4188
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4189 4190 4191 4192 4193
    *autostart = vm->autostart;
    ret = 0;

cleanup:
    if (vm)
4194
        virObjectUnlock(vm);
4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

    libxlDriverLock(driver);
4207
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4208 4209 4210 4211

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4212 4213
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
4214 4215 4216
        goto cleanup;
    }

4217 4218 4219
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4220
    if (!vm->persistent) {
4221 4222
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234
        goto cleanup;
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
        if (!(configFile = virDomainConfigFile(driver->configDir, vm->def->name)))
            goto cleanup;
        if (!(autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)))
            goto cleanup;

        if (autostart) {
4235 4236
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
                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)
4265
        virObjectUnlock(vm);
4266 4267 4268 4269
    libxlDriverUnlock(driver);
    return ret;
}

4270 4271 4272 4273 4274 4275 4276
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    char * ret = NULL;
4277
    const char *name = NULL;
J
Jim Fehlig 已提交
4278
    libxl_scheduler sched_id;
4279 4280

    libxlDriverLock(driver);
4281
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4282 4283 4284
    libxlDriverUnlock(driver);

    if (!vm) {
4285
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
4286 4287 4288
        goto cleanup;
    }

4289 4290 4291
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4292
    if (!virDomainObjIsActive(vm)) {
4293
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4294 4295 4296 4297
        goto cleanup;
    }

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

4300 4301
    if (nparams)
        *nparams = 0;
4302
    switch (sched_id) {
J
Jim Fehlig 已提交
4303
    case LIBXL_SCHEDULER_SEDF:
4304
        name = "sedf";
4305
        break;
J
Jim Fehlig 已提交
4306
    case LIBXL_SCHEDULER_CREDIT:
4307
        name = "credit";
4308 4309
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
4310
        break;
J
Jim Fehlig 已提交
4311
    case LIBXL_SCHEDULER_CREDIT2:
4312
        name = "credit2";
4313
        break;
J
Jim Fehlig 已提交
4314
    case LIBXL_SCHEDULER_ARINC653:
4315
        name = "arinc653";
4316 4317
        break;
    default:
J
Jim Fehlig 已提交
4318 4319 4320
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
                     " with libxenlight"), dom->id);
4321 4322 4323
        goto cleanup;
    }

4324
    ignore_value(VIR_STRDUP(ret, name));
4325 4326 4327

cleanup:
    if (vm)
4328
        virObjectUnlock(vm);
4329 4330 4331
    return ret;
}

4332
static int
4333 4334 4335 4336
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
4337 4338 4339 4340
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4341 4342
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
4343 4344
    int ret = -1;

4345 4346
    virCheckFlags(0, -1);

4347
    libxlDriverLock(driver);
4348
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4349 4350 4351
    libxlDriverUnlock(driver);

    if (!vm) {
J
Jim Fehlig 已提交
4352 4353
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
4354 4355 4356
        goto cleanup;
    }

4357 4358 4359
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4360
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
4361 4362
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
4363 4364 4365 4366 4367
        goto cleanup;
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
4370
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4371 4372
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4373 4374 4375
        goto cleanup;
    }

J
Jim Fehlig 已提交
4376
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
4377 4378 4379
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
4380 4381 4382
        goto cleanup;
    }

4383 4384
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
4385 4386
        goto cleanup;

4387
    if (*nparams > 1) {
4388 4389
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
4390
            goto cleanup;
4391 4392
    }

4393 4394
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
4395 4396 4397 4398
    ret = 0;

cleanup:
    if (vm)
4399
        virObjectUnlock(vm);
4400 4401 4402 4403
    return ret;
}

static int
4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414
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)
4415 4416 4417 4418
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4419
    libxl_domain_sched_params sc_info;
4420
    int sched_id;
4421
    size_t i;
4422 4423
    int ret = -1;

4424
    virCheckFlags(0, -1);
4425 4426 4427 4428 4429 4430
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
4431
        return -1;
4432

4433
    libxlDriverLock(driver);
4434
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4435 4436 4437
    libxlDriverUnlock(driver);

    if (!vm) {
4438
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
4439 4440 4441
        goto cleanup;
    }

4442 4443 4444
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4445
    if (!virDomainObjIsActive(vm)) {
4446
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4447 4448 4449 4450 4451
        goto cleanup;
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
4454
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4455 4456
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4457 4458 4459
        goto cleanup;
    }

J
Jim Fehlig 已提交
4460
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
4461 4462 4463
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
4464 4465 4466 4467
        goto cleanup;
    }

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

4470
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT)) {
4471
            sc_info.weight = params[i].value.ui;
4472
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP)) {
4473 4474 4475 4476
            sc_info.cap = params[i].value.ui;
        }
    }

J
Jim Fehlig 已提交
4477
    if (libxl_domain_sched_params_set(priv->ctx, dom->id, &sc_info) != 0) {
4478 4479 4480
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
4481 4482 4483 4484 4485 4486 4487
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
4488
        virObjectUnlock(vm);
4489 4490 4491
    return ret;
}

4492 4493 4494 4495 4496 4497 4498
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

J
Jim Fehlig 已提交
4499 4500 4501 4502 4503 4504 4505 4506
static int
libxlDomainIsActive(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    libxlDriverLock(driver);
4507
    obj = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
4508 4509
    libxlDriverUnlock(driver);
    if (!obj) {
4510
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
4511 4512
        goto cleanup;
    }
4513 4514 4515 4516

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

J
Jim Fehlig 已提交
4517 4518 4519 4520
    ret = virDomainObjIsActive(obj);

  cleanup:
    if (obj)
4521
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532
    return ret;
}

static int
libxlDomainIsPersistent(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    libxlDriverLock(driver);
4533
    obj = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
4534 4535
    libxlDriverUnlock(driver);
    if (!obj) {
4536
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
4537 4538
        goto cleanup;
    }
4539 4540 4541 4542

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

J
Jim Fehlig 已提交
4543 4544 4545 4546
    ret = obj->persistent;

  cleanup:
    if (obj)
4547
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4548 4549 4550
    return ret;
}

4551 4552 4553 4554 4555 4556 4557 4558
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    libxlDriverLock(driver);
4559
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4560 4561
    libxlDriverUnlock(driver);
    if (!vm) {
4562
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
4563 4564
        goto cleanup;
    }
4565 4566 4567 4568

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

4569 4570 4571 4572
    ret = vm->updated;

cleanup:
    if (vm)
4573
        virObjectUnlock(vm);
4574 4575 4576
    return ret;
}

4577
static int
4578 4579 4580
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4581 4582 4583 4584
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4585 4586 4587
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4588
    libxlDriverLock(driver);
4589 4590 4591 4592
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4593
        ret = -1;
4594 4595 4596 4597 4598 4599 4600
    libxlDriverUnlock(driver);

    return ret;
}


static int
4601
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4602 4603 4604 4605
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4606 4607 4608
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4609
    libxlDriverLock(driver);
4610 4611 4612
    ret = virDomainEventStateDeregisterID(conn,
                                          driver->domainEventState,
                                          callbackID);
4613 4614 4615 4616 4617
    libxlDriverUnlock(driver);

    return ret;
}

J
Jim Fehlig 已提交
4618

4619
static int
4620
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4621 4622 4623 4624
{
    return 1;
}

4625
static int
4626 4627 4628
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4629 4630 4631 4632
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4633
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4634

4635 4636 4637
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4638
    libxlDriverLock(driver);
4639 4640
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
4641 4642 4643 4644 4645 4646
    libxlDriverUnlock(driver);

    return ret;
}


4647

J
Jim Fehlig 已提交
4648
static virDriver libxlDriver = {
4649 4650
    .no = VIR_DRV_LIBXL,
    .name = "xenlight",
4651 4652 4653 4654
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
4655
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
4656
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
4657
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
4658
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
4659 4660 4661 4662
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
4663 4664 4665 4666 4667 4668 4669
    .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 */
4670
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
4671 4672
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
4673
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
4674 4675
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
4676
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
4677 4678 4679 4680
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
4681
    .domainSave = libxlDomainSave, /* 0.9.2 */
4682
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
4683
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
4684
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
4685
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
4686 4687 4688 4689 4690 4691
    .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 */
4692 4693 4694 4695
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
4696 4697 4698 4699
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
4700
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
4701 4702 4703 4704 4705
    .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 */
4706 4707 4708 4709
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
4710
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
4711
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
4712
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
4713
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
4714
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
4715 4716
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
4717 4718 4719
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
4720 4721 4722
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
4723 4724 4725
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
J
Jim Fehlig 已提交
4726 4727 4728 4729
};

static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
4730 4731 4732
    .stateInitialize = libxlStateInitialize,
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745
};


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

    return 0;
}