libxl_driver.c 129.9 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>
J
Jim Fehlig 已提交
32 33

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

#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

57 58
#define LIBXL_CONFIG_FORMAT_XM "xen-xm"

59 60 61
/* Number of Xen scheduler parameters */
#define XEN_SCHED_CREDIT_NPARAM   2

J
Jim Fehlig 已提交
62 63 64 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
/* 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)

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

100
static virClassPtr libxlDomainObjPrivateClass;
101

J
Jim Fehlig 已提交
102 103 104
static libxlDriverPrivatePtr libxl_driver = NULL;

/* Function declarations */
105 106
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
107 108
                           void *opaque);

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

/* Function definitions */
114 115 116 117 118 119 120 121 122 123 124 125 126 127
static int
libxlDomainObjPrivateOnceInit(void)
{
    if (!(libxlDomainObjPrivateClass = virClassNew(virClassForObjectLockable(),
                                                   "libxlDomainObjPrivate",
                                                   sizeof(libxlDomainObjPrivate),
                                                   NULL)))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(libxlDomainObjPrivate)

J
Jim Fehlig 已提交
128 129 130 131 132 133 134 135 136 137 138 139
static void
libxlDriverLock(libxlDriverPrivatePtr driver)
{
    virMutexLock(&driver->lock);
}

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

140 141 142
static void
libxlEventHookInfoFree(void *obj)
{
143 144 145 146 147
    libxlEventHookInfoPtr info = obj;

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

150 151 152 153
static void
libxlFDEventCallback(int watch ATTRIBUTE_UNUSED,
                     int fd,
                     int vir_events,
154
                     void *fd_info)
J
Jim Fehlig 已提交
155
{
156
    libxlEventHookInfoPtr info = fd_info;
J
Jim Fehlig 已提交
157 158
    int events = 0;

159
    virObjectLock(info->priv);
J
Jim Fehlig 已提交
160 161 162 163 164 165 166 167 168
    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;

169
    virObjectUnlock(info->priv);
J
Jim Fehlig 已提交
170 171 172
    libxl_osevent_occurred_fd(info->priv->ctx, info->xl_priv, fd, 0, events);
}

173 174 175
static int
libxlFDRegisterEventHook(void *priv, int fd, void **hndp,
                         short events, void *xl_priv)
J
Jim Fehlig 已提交
176 177
{
    int vir_events = VIR_EVENT_HANDLE_ERROR;
178
    libxlEventHookInfoPtr info;
J
Jim Fehlig 已提交
179

180
    if (VIR_ALLOC(info) < 0) {
J
Jim Fehlig 已提交
181 182 183 184
        virReportOOMError();
        return -1;
    }

185 186 187 188 189 190 191 192 193
    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 已提交
194 195 196 197
    if (events & POLLIN)
        vir_events |= VIR_EVENT_HANDLE_READABLE;
    if (events & POLLOUT)
        vir_events |= VIR_EVENT_HANDLE_WRITABLE;
198

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

207 208
    *hndp = info;

J
Jim Fehlig 已提交
209 210 211
    return 0;
}

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

221
    virObjectLock(info->priv);
J
Jim Fehlig 已提交
222 223 224 225 226
    if (events & POLLIN)
        vir_events |= VIR_EVENT_HANDLE_READABLE;
    if (events & POLLOUT)
        vir_events |= VIR_EVENT_HANDLE_WRITABLE;

227 228 229
    virEventUpdateHandle(info->id, vir_events);
    virObjectUnlock(info->priv);

J
Jim Fehlig 已提交
230 231 232
    return 0;
}

233 234 235 236
static void
libxlFDDeregisterEventHook(void *priv ATTRIBUTE_UNUSED,
                           int fd ATTRIBUTE_UNUSED,
                           void *hnd)
J
Jim Fehlig 已提交
237
{
238 239
    libxlEventHookInfoPtr info = hnd;
    libxlDomainObjPrivatePtr p = info->priv;
J
Jim Fehlig 已提交
240

241 242 243
    virObjectLock(p);
    virEventRemoveHandle(info->id);
    virObjectUnlock(p);
J
Jim Fehlig 已提交
244 245
}

246
static void
247
libxlTimerCallback(int timer ATTRIBUTE_UNUSED, void *timer_info)
J
Jim Fehlig 已提交
248
{
249 250
    libxlEventHookInfoPtr info = timer_info;
    libxlDomainObjPrivatePtr p = info->priv;
J
Jim Fehlig 已提交
251

252
    virObjectLock(p);
J
Jim Fehlig 已提交
253 254 255 256 257 258 259
    /*
     * 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);
260 261 262
    virObjectUnlock(p);
    libxl_osevent_occurred_timeout(p->ctx, info->xl_priv);
    virObjectLock(p);
J
Jim Fehlig 已提交
263 264 265 266 267 268
    /*
     * 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);
269
    virObjectUnlock(p);
J
Jim Fehlig 已提交
270 271
}

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

284
    if (VIR_ALLOC(info) < 0) {
J
Jim Fehlig 已提交
285 286 287 288
        virReportOOMError();
        return -1;
    }

289 290 291 292 293 294 295 296 297
    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 已提交
298
    gettimeofday(&now, NULL);
J
Jim Fehlig 已提交
299 300 301 302 303 304 305 306 307
    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;
    }
308 309 310
    info->id = virEventAddTimeout(timeout, libxlTimerCallback,
                                  info, libxlEventHookInfoFree);
    if (info->id < 0) {
311
        virObjectUnref(info->priv);
312 313
        VIR_FREE(info);
        return -1;
J
Jim Fehlig 已提交
314 315
    }

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

J
Jim Fehlig 已提交
321 322 323
    return 0;
}

J
Jim Fehlig 已提交
324 325 326 327 328 329 330 331 332 333
/*
 * 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.
 */
334 335 336
static int
libxlTimeoutModifyEventHook(void *priv ATTRIBUTE_UNUSED,
                            void **hndp,
J
Jim Fehlig 已提交
337
                            struct timeval abs_t ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
338
{
339
    libxlEventHookInfoPtr info = *hndp;
J
Jim Fehlig 已提交
340

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

J
Jim Fehlig 已提交
346 347 348
    return 0;
}

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

356
    virObjectLock(p);
J
Jim Fehlig 已提交
357 358 359 360 361 362
    /*
     * 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);
363
    virObjectUnlock(p);
J
Jim Fehlig 已提交
364 365
}

J
Jim Fehlig 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
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 已提交
389 390 391 392 393 394 395 396 397
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 已提交
398 399 400 401 402
static void *
libxlDomainObjPrivateAlloc(void)
{
    libxlDomainObjPrivatePtr priv;

403 404 405 406
    if (libxlDomainObjPrivateInitialize() < 0)
        return NULL;

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

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

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

    return priv;
}

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

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

J
Jim Fehlig 已提交
428
    libxl_ctx_free(priv->ctx);
429
    virObjectUnref(priv);
J
Jim Fehlig 已提交
430 431
}

432 433 434 435 436
virDomainXMLPrivateDataCallbacks libxlDomainXMLPrivateDataCallbacks = {
    .alloc = libxlDomainObjPrivateAlloc,
    .free = libxlDomainObjPrivateFree,
};

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453

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


454 455
virDomainDefParserConfig libxlDomainDefParserConfig = {
    .macPrefix = { 0x00, 0x16, 0x3e },
456
    .devicesPostParseCallback = libxlDomainDeviceDefPostParse,
457 458
};

459

460 461 462 463
/* driver must be locked before calling */
static void
libxlDomainEventQueue(libxlDriverPrivatePtr driver, virDomainEventPtr event)
{
464
    virDomainEventStateQueue(driver->domainEventState, event);
465 466
}

467 468
static int
libxlAutostartDomain(virDomainObjPtr vm,
469 470 471 472
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    virErrorPtr err;
473
    int ret = -1;
474

475
    virObjectLock(vm);
476 477 478
    virResetLastError();

    if (vm->autostart && !virDomainObjIsActive(vm) &&
479
        libxlVmStart(driver, vm, false, -1) < 0) {
480 481 482 483
        err = virGetLastError();
        VIR_ERROR(_("Failed to autostart VM '%s': %s"),
                  vm->def->name,
                  err ? err->message : _("unknown error"));
484
        goto cleanup;
485 486
    }

487 488
    ret = 0;
cleanup:
489
    virObjectUnlock(vm);
490
    return ret;
491 492
}

493 494 495 496 497
static int
libxlDoNodeGetInfo(libxlDriverPrivatePtr driver, virNodeInfoPtr info)
{
    libxl_physinfo phy_info;
    const libxl_version_info* ver_info;
498
    virArch hostarch = virArchFromHost();
499

J
Jim Fehlig 已提交
500
    if (libxl_get_physinfo(driver->ctx, &phy_info)) {
501 502
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
503 504 505
        return -1;
    }

J
Jim Fehlig 已提交
506
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
507 508
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_version_info failed"));
509 510 511
        return -1;
    }

512
    if (virStrcpyStatic(info->model, virArchToString(hostarch)) == NULL) {
513 514
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("machine type %s too big for destination"),
515
                       virArchToString(hostarch));
516 517 518 519 520 521 522 523 524 525 526 527 528
        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;
}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
static char *
libxlDomainManagedSavePath(libxlDriverPrivatePtr driver, virDomainObjPtr vm) {
    char *ret;

    if (virAsprintf(&ret, "%s/%s.save", driver->saveDir, vm->def->name) < 0) {
        virReportOOMError();
        return NULL;
    }

    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 已提交
552
    if ((fd = virFileOpenAs(from, O_RDONLY, 0, -1, -1, 0)) < 0) {
553 554
        virReportSystemError(-fd,
                             _("Failed to open domain image file '%s'"), from);
555 556 557 558
        goto error;
    }

    if (saferead(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
559 560
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to read libxl header"));
561 562 563 564
        goto error;
    }

    if (memcmp(hdr.magic, LIBXL_SAVE_MAGIC, sizeof(hdr.magic))) {
565
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("image magic is incorrect"));
566 567 568 569
        goto error;
    }

    if (hdr.version > LIBXL_SAVE_VERSION) {
570 571 572
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("image version is not supported (%d > %d)"),
                       hdr.version, LIBXL_SAVE_VERSION);
573 574 575 576
        goto error;
    }

    if (hdr.xmlLen <= 0) {
577 578
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("invalid XML length: %d"), hdr.xmlLen);
579 580 581 582 583 584 585 586 587
        goto error;
    }

    if (VIR_ALLOC_N(xml, hdr.xmlLen) < 0) {
        virReportOOMError();
        goto error;
    }

    if (saferead(fd, xml, hdr.xmlLen) != hdr.xmlLen) {
588
        virReportError(VIR_ERR_OPERATION_FAILED, "%s", _("failed to read XML"));
589 590 591
        goto error;
    }

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

J
Jim Fehlig 已提交
626 627 628
    if (priv->deathW) {
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
        priv->deathW = NULL;
J
Jim Fehlig 已提交
629 630 631 632
    }

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

636 637 638 639
    driver->nactive--;
    if (!driver->nactive && driver->inhibitCallback)
        driver->inhibitCallback(false, driver->inhibitOpaque);

J
Jim Fehlig 已提交
640 641 642 643 644
    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) {
645 646
            if (virPortAllocatorRelease(driver->reservedVNCPorts,
                                        vnc_port) < 0)
J
Jim Fehlig 已提交
647 648 649 650
                VIR_DEBUG("Could not mark port %d as unused", vnc_port);
        }
    }

651 652 653 654 655 656 657 658 659 660
    /* Remove any cputune settings */
    if (vm->def->cputune.nvcpupin) {
        for (i = 0; i < vm->def->cputune.nvcpupin; ++i) {
            VIR_FREE(vm->def->cputune.vcpupin[i]->cpumask);
            VIR_FREE(vm->def->cputune.vcpupin[i]);
        }
        VIR_FREE(vm->def->cputune.vcpupin);
        vm->def->cputune.nvcpupin = 0;
    }

J
Jim Fehlig 已提交
661 662 663 664 665
    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);
    }
666 667 668 669 670 671 672

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

    libxlRegisteredTimeoutsCleanup(priv);
J
Jim Fehlig 已提交
675 676 677 678 679 680 681 682
}

/*
 * Reap a domain from libxenlight.
 *
 * virDomainObjPtr should be locked on invocation
 */
static int
J
Jiri Denemark 已提交
683 684 685
libxlVmReap(libxlDriverPrivatePtr driver,
            virDomainObjPtr vm,
            virDomainShutoffReason reason)
J
Jim Fehlig 已提交
686 687 688
{
    libxlDomainObjPrivatePtr priv = vm->privateData;

J
Jim Fehlig 已提交
689
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
690 691
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to cleanup domain %d"), vm->def->id);
J
Jim Fehlig 已提交
692 693 694
        return -1;
    }

J
Jiri Denemark 已提交
695
    libxlVmCleanup(driver, vm, reason);
J
Jim Fehlig 已提交
696 697 698 699
    return 0;
}

/*
J
Jim Fehlig 已提交
700 701 702 703 704
 * 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 已提交
705
 */
J
Jim Fehlig 已提交
706 707 708 709 710 711 712

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

713
static void
J
Jim Fehlig 已提交
714
libxlEventHandler(void *data, VIR_LIBXL_EVENT_CONST libxl_event *event)
J
Jim Fehlig 已提交
715 716
{
    libxlDriverPrivatePtr driver = libxl_driver;
J
Jim Fehlig 已提交
717
    libxlDomainObjPrivatePtr priv = ((virDomainObjPtr)data)->privateData;
718
    virDomainObjPtr vm = NULL;
719
    virDomainEventPtr dom_event = NULL;
720
    libxl_shutdown_reason xl_reason = event->u.domain_shutdown.shutdown_reason;
J
Jim Fehlig 已提交
721

J
Jim Fehlig 已提交
722
    if (event->type == LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN) {
J
Jiri Denemark 已提交
723 724
        virDomainShutoffReason reason;

725 726 727 728 729 730 731 732
        /*
         * 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);
733
        vm = virDomainObjListFindByID(driver->domains, event->domid);
734 735 736
        libxlDriverUnlock(driver);

        if (!vm)
J
Jim Fehlig 已提交
737 738
            goto cleanup;

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

cleanup:
    if (vm)
768
        virObjectUnlock(vm);
769 770 771 772 773
    if (dom_event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, dom_event);
        libxlDriverUnlock(driver);
    }
J
Jim Fehlig 已提交
774 775
    /* Cast away any const */
    libxl_event_free(priv->ctx, (libxl_event *)event);
J
Jim Fehlig 已提交
776 777
}

J
Jim Fehlig 已提交
778 779 780 781 782 783
static const struct libxl_event_hooks ev_hooks = {
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlEventHandler,
    .disaster = NULL,
};

J
Jim Fehlig 已提交
784 785 786 787 788 789 790 791 792
/*
 * 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 已提交
793
    libxl_event_register_callbacks(priv->ctx, &ev_hooks, vm);
J
Jim Fehlig 已提交
794

J
Jim Fehlig 已提交
795
    if (libxl_evenable_domain_death(priv->ctx, vm->def->id, 0, &priv->deathW))
J
Jim Fehlig 已提交
796 797 798 799 800
        goto error;

    return 0;

error:
801
    if (priv->deathW) {
J
Jim Fehlig 已提交
802
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
803 804
        priv->deathW = NULL;
    }
J
Jim Fehlig 已提交
805 806 807
    return -1;
}

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

        if (VIR_ALLOC_N(cpumap, cpumaplen) < 0) {
            virReportOOMError();
            goto cleanup;
        }

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

        for (i = 0; i < VIR_DOMAIN_CPUMASK_LEN; ++i) {
838 839
            if (cpumask[i])
                VIR_USE_CPU(cpumap, i);
840 841 842 843 844
        }

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

J
Jim Fehlig 已提交
845
        if (libxl_set_vcpuaffinity(priv->ctx, def->id, vcpu, &map) != 0) {
846 847
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
848 849 850 851 852 853 854 855 856 857 858 859 860
            goto cleanup;
        }

        VIR_FREE(cpumap);
    }

    ret = 0;

cleanup:
    VIR_FREE(cpumap);
    return ret;
}

M
Markus Groß 已提交
861 862 863 864 865 866 867 868 869 870
static int
libxlFreeMem(libxlDomainObjPrivatePtr priv, libxl_domain_config *d_config)
{
    uint32_t needed_mem;
    uint32_t free_mem;
    int i;
    int ret = -1;
    int tries = 3;
    int wait_secs = 10;

J
Jim Fehlig 已提交
871
    if ((ret = libxl_domain_need_memory(priv->ctx, &d_config->b_info,
M
Markus Groß 已提交
872 873
                                        &needed_mem)) >= 0) {
        for (i = 0; i < tries; ++i) {
J
Jim Fehlig 已提交
874
            if ((ret = libxl_get_free_memory(priv->ctx, &free_mem)) < 0)
M
Markus Groß 已提交
875 876 877 878 879 880 881
                break;

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

J
Jim Fehlig 已提交
882
            if ((ret = libxl_set_memory_target(priv->ctx, 0,
M
Markus Groß 已提交
883 884 885 886
                                               free_mem - needed_mem,
                                               /* relative */ 1, 0)) < 0)
                break;

J
Jim Fehlig 已提交
887
            ret = libxl_wait_for_free_memory(priv->ctx, 0, needed_mem,
M
Markus Groß 已提交
888 889 890 891
                                             wait_secs);
            if (ret == 0 || ret != ERROR_NOMEM)
                break;

J
Jim Fehlig 已提交
892
            if ((ret = libxl_wait_for_memory_target(priv->ctx, 0, 1)) < 0)
M
Markus Groß 已提交
893 894 895 896 897 898 899
                break;
        }
    }

    return ret;
}

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

920 921 922
    /* 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) {
923 924
        managed_save_path = libxlDomainManagedSavePath(driver, vm);
        if (managed_save_path == NULL)
925 926
            goto error;

927
        if (virFileExists(managed_save_path)) {
928

929 930 931
            managed_save_fd = libxlSaveImageOpen(driver, managed_save_path,
                                                 &def, &hdr);
            if (managed_save_fd < 0)
932 933
                goto error;

934 935
            restore_fd = managed_save_fd;

936 937 938 939 940 941
            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);
942 943 944 945
                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);
946 947 948
                goto error;
            }

949
            virDomainObjAssignDef(vm, def, true, NULL);
950 951
            def = NULL;

952 953 954 955
            if (unlink(managed_save_path) < 0) {
                VIR_WARN("Failed to remove the managed state %s",
                         managed_save_path);
            }
956
            vm->hasManagedSave = false;
957
        }
958
        VIR_FREE(managed_save_path);
959 960
    }

J
Jim Fehlig 已提交
961
    libxl_domain_config_init(&d_config);
J
Jim Fehlig 已提交
962

963
    if (libxlBuildDomainConfig(driver, vm->def, &d_config) < 0)
964
        goto error;
J
Jim Fehlig 已提交
965

M
Markus Groß 已提交
966
    if (libxlFreeMem(priv, &d_config) < 0) {
967 968 969
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to get free memory for domain '%s'"),
                       d_config.c_info.name);
M
Markus Groß 已提交
970 971
        goto error;
    }
J
Jim Fehlig 已提交
972

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

975
    if (restore_fd < 0)
J
Jim Fehlig 已提交
976 977
        ret = libxl_domain_create_new(priv->ctx, &d_config,
                                      &domid, NULL, NULL);
978
    else
J
Jim Fehlig 已提交
979 980
        ret = libxl_domain_create_restore(priv->ctx, &d_config, &domid,
                                          restore_fd, NULL, NULL);
981

J
Jim Fehlig 已提交
982
    if (ret) {
983
        if (restore_fd < 0)
984 985 986
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to create new domain '%s'"),
                           d_config.c_info.name);
987
        else
988 989 990
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to restore domain '%s'"),
                           d_config.c_info.name);
J
Jim Fehlig 已提交
991 992 993
        goto error;
    }

994 995
    vm->def->id = domid;
    if ((dom_xml = virDomainDefFormat(vm->def, 0)) == NULL)
J
Jim Fehlig 已提交
996 997
        goto error;

J
Jim Fehlig 已提交
998
    if (libxl_userdata_store(priv->ctx, domid, "libvirt-xml",
J
Jim Fehlig 已提交
999
                             (uint8_t *)dom_xml, strlen(dom_xml) + 1)) {
1000 1001
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to store userdata"));
J
Jim Fehlig 已提交
1002 1003 1004 1005 1006 1007
        goto error;
    }

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

1008
    if (libxlDomainSetVcpuAffinities(driver, vm) < 0)
1009 1010
        goto error;

J
Jim Fehlig 已提交
1011
    if (!start_paused) {
J
Jim Fehlig 已提交
1012
        libxl_domain_unpause(priv->ctx, domid);
J
Jiri Denemark 已提交
1013
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
J
Jim Fehlig 已提交
1014
    } else {
J
Jiri Denemark 已提交
1015
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
J
Jim Fehlig 已提交
1016 1017
    }

1018

1019
    if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
J
Jim Fehlig 已提交
1020 1021
        goto error;

1022 1023 1024 1025
    if (!driver->nactive && driver->inhibitCallback)
        driver->inhibitCallback(true, driver->inhibitOpaque);
    driver->nactive++;

1026
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STARTED,
1027 1028 1029
                                     restore_fd < 0 ?
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED :
                                         VIR_DOMAIN_EVENT_STARTED_RESTORED);
1030 1031
    if (event)
        libxlDomainEventQueue(driver, event);
1032

J
Jim Fehlig 已提交
1033
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
1034
    VIR_FREE(dom_xml);
1035
    VIR_FORCE_CLOSE(managed_save_fd);
J
Jim Fehlig 已提交
1036 1037 1038 1039
    return 0;

error:
    if (domid > 0) {
J
Jim Fehlig 已提交
1040
        libxl_domain_destroy(priv->ctx, domid, NULL);
1041
        vm->def->id = -1;
J
Jiri Denemark 已提交
1042
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);
J
Jim Fehlig 已提交
1043
    }
J
Jim Fehlig 已提交
1044
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
1045
    VIR_FREE(dom_xml);
1046
    VIR_FREE(managed_save_path);
1047
    virDomainDefFree(def);
1048
    VIR_FORCE_CLOSE(managed_save_fd);
J
Jim Fehlig 已提交
1049 1050 1051 1052 1053 1054 1055 1056
    return -1;
}


/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
1057 1058
static int
libxlReconnectDomain(virDomainObjPtr vm,
J
Jim Fehlig 已提交
1059 1060 1061 1062 1063 1064 1065 1066
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;

1067
    virObjectLock(vm);
J
Jim Fehlig 已提交
1068 1069

    /* Does domain still exist? */
J
Jim Fehlig 已提交
1070
    rc = libxl_domain_info(driver->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079
    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 已提交
1080
    if (libxl_userdata_retrieve(driver->ctx, vm->def->id,
J
Jim Fehlig 已提交
1081 1082 1083 1084 1085 1086 1087
                                "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 已提交
1088
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_UNKNOWN);
J
Jim Fehlig 已提交
1089

1090 1091 1092 1093
    if (!driver->nactive && driver->inhibitCallback)
        driver->inhibitCallback(true, driver->inhibitOpaque);
    driver->nactive++;

J
Jim Fehlig 已提交
1094 1095
    /* Recreate domain death et. al. events */
    libxlCreateDomEvents(vm);
1096
    virObjectUnlock(vm);
1097
    return 0;
J
Jim Fehlig 已提交
1098 1099

out:
J
Jiri Denemark 已提交
1100
    libxlVmCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_UNKNOWN);
J
Jim Fehlig 已提交
1101
    if (!vm->persistent)
1102
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1103
    else
1104
        virObjectUnlock(vm);
1105 1106

    return -1;
J
Jim Fehlig 已提交
1107 1108 1109 1110 1111
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
1112
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
1113 1114 1115
}

static int
1116
libxlStateCleanup(void)
J
Jim Fehlig 已提交
1117 1118 1119 1120 1121
{
    if (!libxl_driver)
        return -1;

    libxlDriverLock(libxl_driver);
1122
    virObjectUnref(libxl_driver->caps);
1123
    virObjectUnref(libxl_driver->xmlopt);
1124
    virObjectUnref(libxl_driver->domains);
J
Jim Fehlig 已提交
1125
    libxl_ctx_free(libxl_driver->ctx);
J
Jim Fehlig 已提交
1126 1127 1128 1129
    xtl_logger_destroy(libxl_driver->logger);
    if (libxl_driver->logger_file)
        VIR_FORCE_FCLOSE(libxl_driver->logger_file);

1130
    virObjectUnref(libxl_driver->reservedVNCPorts);
J
Jim Fehlig 已提交
1131 1132 1133 1134 1135 1136 1137 1138

    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 已提交
1139
    virDomainEventStateFree(libxl_driver->domainEventState);
1140

J
Jim Fehlig 已提交
1141 1142 1143 1144 1145 1146 1147 1148
    libxlDriverUnlock(libxl_driver);
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

static int
1149 1150 1151
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
1152
{
J
Jim Fehlig 已提交
1153 1154 1155
    const libxl_version_info *ver_info;
    char *log_file = NULL;
    virCommandPtr cmd;
D
Daniel Veillard 已提交
1156
    int status, ret = 0;
1157
    char ebuf[1024];
J
Jim Fehlig 已提交
1158 1159 1160

    /* Disable libxl driver if non-root */
    if (!privileged) {
1161
        VIR_INFO("Not running privileged, disabling libxenlight driver");
J
Jim Fehlig 已提交
1162 1163 1164 1165 1166 1167
        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) {
1168
        VIR_INFO("Legacy xen tool stack seems to be in use, disabling "
J
Jim Fehlig 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
                  "libxenlight driver.");
        virCommandFree(cmd);
        return 0;
    }
    virCommandFree(cmd);

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

    if (virMutexInit(&libxl_driver->lock) < 0) {
1179
        VIR_ERROR(_("cannot initialize mutex"));
J
Jim Fehlig 已提交
1180 1181 1182 1183 1184 1185
        VIR_FREE(libxl_driver);
        return -1;
    }
    libxlDriverLock(libxl_driver);

    /* Allocate bitmap for vnc port reservation */
1186 1187 1188 1189
    if (!(libxl_driver->reservedVNCPorts =
          virPortAllocatorNew(LIBXL_VNC_PORT_MIN,
                              LIBXL_VNC_PORT_MAX)))
        goto error;
J
Jim Fehlig 已提交
1190

1191 1192
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

    if (virAsprintf(&libxl_driver->configDir,
                    "%s", LIBXL_CONFIG_DIR) == -1)
        goto out_of_memory;

    if (virAsprintf(&libxl_driver->autostartDir,
                    "%s", LIBXL_AUTOSTART_DIR) == -1)
        goto out_of_memory;

    if (virAsprintf(&libxl_driver->logDir,
                    "%s", LIBXL_LOG_DIR) == -1)
        goto out_of_memory;

    if (virAsprintf(&libxl_driver->stateDir,
                    "%s", LIBXL_STATE_DIR) == -1)
        goto out_of_memory;

    if (virAsprintf(&libxl_driver->libDir,
                    "%s", LIBXL_LIB_DIR) == -1)
        goto out_of_memory;

    if (virAsprintf(&libxl_driver->saveDir,
                    "%s", LIBXL_SAVE_DIR) == -1)
        goto out_of_memory;

1218
    if (virFileMakePath(libxl_driver->logDir) < 0) {
J
Jim Fehlig 已提交
1219
        VIR_ERROR(_("Failed to create log dir '%s': %s"),
1220
                  libxl_driver->logDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1221 1222
        goto error;
    }
1223
    if (virFileMakePath(libxl_driver->stateDir) < 0) {
J
Jim Fehlig 已提交
1224
        VIR_ERROR(_("Failed to create state dir '%s': %s"),
1225
                  libxl_driver->stateDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1226 1227
        goto error;
    }
1228
    if (virFileMakePath(libxl_driver->libDir) < 0) {
J
Jim Fehlig 已提交
1229
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
1230
                  libxl_driver->libDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1231 1232
        goto error;
    }
1233
    if (virFileMakePath(libxl_driver->saveDir) < 0) {
J
Jim Fehlig 已提交
1234
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
1235
                  libxl_driver->saveDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
        goto error;
    }

    if (virAsprintf(&log_file, "%s/libxl.log", libxl_driver->logDir) < 0) {
        goto out_of_memory;
    }

    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);

1251
    libxl_driver->domainEventState = virDomainEventStateNew();
E
Eric Blake 已提交
1252
    if (!libxl_driver->domainEventState)
1253 1254
        goto error;

J
Jim Fehlig 已提交
1255 1256 1257
    libxl_driver->logger =
            (xentoollog_logger *)xtl_createlogger_stdiostream(libxl_driver->logger_file, XTL_DEBUG,  0);
    if (!libxl_driver->logger) {
1258
        VIR_INFO("cannot create logger for libxenlight, disabling driver");
D
Daniel Veillard 已提交
1259
        goto fail;
J
Jim Fehlig 已提交
1260 1261
    }

J
Jim Fehlig 已提交
1262 1263
    if (libxl_ctx_alloc(&libxl_driver->ctx,
                       LIBXL_VERSION, 0,
J
Jim Fehlig 已提交
1264
                       libxl_driver->logger)) {
1265
        VIR_INFO("cannot initialize libxenlight context, probably not running in a Xen Dom0, disabling driver");
D
Daniel Veillard 已提交
1266
        goto fail;
J
Jim Fehlig 已提交
1267 1268
    }

J
Jim Fehlig 已提交
1269
    if ((ver_info = libxl_get_version_info(libxl_driver->ctx)) == NULL) {
1270
        VIR_INFO("cannot version information from libxenlight, disabling driver");
D
Daniel Veillard 已提交
1271
        goto fail;
J
Jim Fehlig 已提交
1272 1273 1274 1275 1276
    }
    libxl_driver->version = (ver_info->xen_version_major * 1000000) +
            (ver_info->xen_version_minor * 1000);

    if ((libxl_driver->caps =
J
Jim Fehlig 已提交
1277
         libxlMakeCapabilities(libxl_driver->ctx)) == NULL) {
1278
        VIR_ERROR(_("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
1279 1280 1281
        goto error;
    }

1282
    if (!(libxl_driver->xmlopt = virDomainXMLOptionNew(&libxlDomainDefParserConfig,
1283 1284
                                                       &libxlDomainXMLPrivateDataCallbacks,
                                                       NULL)))
1285
        goto error;
J
Jim Fehlig 已提交
1286 1287

    /* Load running domains first. */
1288 1289 1290
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
                                       libxl_driver->stateDir,
                                       libxl_driver->autostartDir,
1291 1292 1293 1294
                                       1,
                                       libxl_driver->caps,
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
1295
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
1296 1297 1298 1299 1300
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
1301 1302 1303
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
                                       libxl_driver->configDir,
                                       libxl_driver->autostartDir,
1304 1305 1306 1307
                                       0,
                                       libxl_driver->caps,
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
1308
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
1309 1310
        goto error;

1311 1312
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
J
Jim Fehlig 已提交
1313

1314 1315
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
1316

1317
    libxlDriverUnlock(libxl_driver);
J
Jim Fehlig 已提交
1318 1319 1320 1321 1322 1323

    return 0;

out_of_memory:
    virReportOOMError();
error:
D
Daniel Veillard 已提交
1324 1325
    ret = -1;
fail:
J
Jim Fehlig 已提交
1326 1327 1328
    VIR_FREE(log_file);
    if (libxl_driver)
        libxlDriverUnlock(libxl_driver);
1329
    libxlStateCleanup();
D
Daniel Veillard 已提交
1330
    return ret;
J
Jim Fehlig 已提交
1331 1332 1333
}

static int
1334
libxlStateReload(void)
J
Jim Fehlig 已提交
1335 1336 1337 1338 1339
{
    if (!libxl_driver)
        return 0;

    libxlDriverLock(libxl_driver);
1340 1341 1342
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
                                   libxl_driver->configDir,
                                   libxl_driver->autostartDir,
1343 1344 1345 1346
                                   1,
                                   libxl_driver->caps,
                                   libxl_driver->xmlopt,
                                   1 << VIR_DOMAIN_VIRT_XEN,
1347 1348
                                   NULL, libxl_driver);

1349 1350
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
1351 1352

    libxlDriverUnlock(libxl_driver);
J
Jim Fehlig 已提交
1353 1354 1355 1356 1357 1358

    return 0;
}


static virDrvOpenStatus
1359 1360 1361
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 unsigned int flags)
J
Jim Fehlig 已提交
1362
{
E
Eric Blake 已提交
1363 1364
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
1365 1366 1367 1368
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

1369
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
            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) {
1382 1383
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
1384 1385 1386 1387 1388 1389 1390 1391
            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")) {
1392 1393 1394
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
1405
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1406 1407 1408 1409 1410 1411
{
    conn->privateData = NULL;
    return 0;
}

static const char *
1412
libxlConnectGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1413 1414 1415 1416 1417
{
    return "xenlight";
}

static int
1418
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427
{
    libxlDriverPrivatePtr driver = conn->privateData;

    libxlDriverLock(driver);
    *version = driver->version;
    libxlDriverUnlock(driver);
    return 0;
}

1428 1429 1430 1431 1432 1433 1434

static char *libxlConnectGetHostname(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return virGetHostname();
}


J
Jim Fehlig 已提交
1435
static int
1436
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1437 1438 1439 1440
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;

J
Jim Fehlig 已提交
1441
    ret = libxl_get_max_cpus(driver->ctx);
J
Jim Fehlig 已提交
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
    /* 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)
{
1453
    return libxlDoNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
1454 1455 1456
}

static char *
1457
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;

    libxlDriverLock(driver);
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
        virReportOOMError();
    libxlDriverUnlock(driver);

    return xml;
}

static int
1471
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
1472 1473 1474 1475 1476
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

    libxlDriverLock(driver);
1477
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids);
J
Jim Fehlig 已提交
1478 1479 1480 1481 1482 1483
    libxlDriverUnlock(driver);

    return n;
}

static int
1484
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
1485 1486 1487 1488 1489
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

    libxlDriverLock(driver);
1490
    n = virDomainObjListNumOfDomains(driver->domains, 1);
J
Jim Fehlig 已提交
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
    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);
1508 1509
    if (!(def = virDomainDefParseString(xml, driver->caps, driver->xmlopt,
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
1510 1511 1512
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

1513
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1514
                                   driver->xmlopt,
1515 1516
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
1517 1518 1519
        goto cleanup;
    def = NULL;

1520 1521
    if (libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0,
                     -1) < 0) {
1522
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
        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)
1534
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
    libxlDriverUnlock(driver);
    return dom;
}

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

    libxlDriverLock(driver);
1547
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
1548 1549 1550
    libxlDriverUnlock(driver);

    if (!vm) {
1551
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1552 1553 1554 1555 1556 1557 1558 1559 1560
        goto cleanup;
    }

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

  cleanup:
    if (vm)
1561
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
    return dom;
}

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

    libxlDriverLock(driver);
1573
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
1574 1575 1576
    libxlDriverUnlock(driver);

    if (!vm) {
1577
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1578 1579 1580 1581 1582 1583 1584 1585 1586
        goto cleanup;
    }

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

  cleanup:
    if (vm)
1587
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    return dom;
}

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

    libxlDriverLock(driver);
1599
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
1600 1601 1602
    libxlDriverUnlock(driver);

    if (!vm) {
1603
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1604 1605 1606 1607 1608 1609 1610 1611 1612
        goto cleanup;
    }

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

  cleanup:
    if (vm)
1613
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1614 1615 1616
    return dom;
}

1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
    virDomainEventPtr event = NULL;
    int ret = -1;

    libxlDriverLock(driver);
1627
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
1628 1629 1630 1631 1632
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1633 1634
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
1635 1636 1637
        goto cleanup;
    }
    if (!virDomainObjIsActive(vm)) {
1638
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1639 1640 1641 1642 1643
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1644
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1645
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
1646 1647 1648
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to suspend domain '%d' with libxenlight"),
                           dom->id);
1649 1650 1651
            goto cleanup;
        }

J
Jiri Denemark 已提交
1652
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1653 1654 1655 1656 1657

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

1658
    if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
1659 1660 1661 1662 1663 1664
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
1665
        virObjectUnlock(vm);
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
    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);
1685
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
1686 1687 1688 1689 1690
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1691 1692
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
1693 1694 1695 1696
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
1697
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1698 1699 1700 1701 1702
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1703
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1704
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
1705 1706 1707
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
                           dom->id);
1708 1709 1710
            goto cleanup;
        }

J
Jiri Denemark 已提交
1711 1712
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1713 1714 1715 1716 1717

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

1718
    if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
1719 1720 1721 1722 1723 1724
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
1725
        virObjectUnlock(vm);
1726 1727 1728 1729 1730 1731 1732 1733
    if (event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, event);
        libxlDriverUnlock(driver);
    }
    return ret;
}

J
Jim Fehlig 已提交
1734
static int
1735
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1736 1737 1738 1739 1740 1741
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

1742 1743
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1744
    libxlDriverLock(driver);
1745
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
1746 1747 1748
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1749 1750
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
1751 1752 1753 1754
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
1755 1756
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1757 1758 1759 1760
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1761
    if (libxl_domain_shutdown(priv->ctx, dom->id) != 0) {
1762 1763 1764
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
        goto cleanup;
    }

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

cleanup:
    if (vm)
1775
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1776 1777 1778 1779
    libxlDriverUnlock(driver);
    return ret;
}

1780 1781 1782 1783 1784 1785 1786
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
1787
static int
E
Eric Blake 已提交
1788
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1789 1790 1791 1792 1793 1794
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

E
Eric Blake 已提交
1795 1796
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1797
    libxlDriverLock(driver);
1798
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
1799 1800 1801
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1802 1803
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
1804 1805 1806 1807
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
1808 1809
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1810 1811 1812 1813
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1814
    if (libxl_domain_reboot(priv->ctx, dom->id) != 0) {
1815 1816 1817
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1818 1819 1820 1821 1822 1823
        goto cleanup;
    }
    ret = 0;

cleanup:
    if (vm)
1824
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1825 1826 1827 1828 1829
    libxlDriverUnlock(driver);
    return ret;
}

static int
1830 1831
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1832 1833 1834 1835
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1836
    virDomainEventPtr event = NULL;
J
Jim Fehlig 已提交
1837

1838 1839
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1840
    libxlDriverLock(driver);
1841
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
1842 1843 1844
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1845 1846
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
1847 1848 1849 1850
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
1851 1852
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1853 1854 1855
        goto cleanup;
    }

1856 1857 1858
    event = virDomainEventNewFromObj(vm,VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

J
Jim Fehlig 已提交
1859
    if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED) != 0) {
1860 1861
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), dom->id);
J
Jim Fehlig 已提交
1862 1863 1864 1865
        goto cleanup;
    }

    if (!vm->persistent) {
1866
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1867 1868 1869 1870 1871 1872 1873
        vm = NULL;
    }

    ret = 0;

cleanup:
    if (vm)
1874
        virObjectUnlock(vm);
1875 1876
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1877 1878 1879 1880
    libxlDriverUnlock(driver);
    return ret;
}

1881 1882 1883 1884 1885 1886
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1887 1888 1889 1890 1891 1892 1893 1894
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;

    libxlDriverLock(driver);
1895
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
1896 1897 1898 1899
    libxlDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1900 1901
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
1902 1903 1904
        goto cleanup;
    }

1905
    ignore_value(VIR_STRDUP(type, vm->def->os.type));
1906 1907 1908

cleanup:
    if (vm)
1909
        virObjectUnlock(vm);
1910 1911 1912
    return type;
}

1913
static unsigned long long
1914 1915 1916 1917
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1918
    unsigned long long ret = 0;
1919 1920

    libxlDriverLock(driver);
1921
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
1922 1923 1924
    libxlDriverUnlock(driver);

    if (!vm) {
1925
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
1926 1927 1928 1929 1930 1931
        goto cleanup;
    }
    ret = vm->def->mem.max_balloon;

cleanup:
    if (vm)
1932
        virObjectUnlock(vm);
1933 1934 1935 1936
    return ret;
}

static int
1937
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1938 1939 1940 1941 1942
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1943 1944
    virDomainDefPtr persistentDef = NULL;
    bool isActive;
1945 1946 1947
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1948 1949
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1950 1951

    libxlDriverLock(driver);
1952
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
1953 1954 1955
    libxlDriverUnlock(driver);

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

1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
    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;
1973 1974
    }

1975
    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
1976 1977
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set memory on an inactive domain"));
1978 1979 1980 1981 1982
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
1983 1984
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a transient domain"));
1985 1986
            goto cleanup;
        }
1987
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps,
1988
                                                           driver->xmlopt,
1989
                                                           vm)))
1990 1991 1992
            goto cleanup;
    }

1993 1994
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1995

1996 1997
        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
1998
            if (libxl_domain_setmaxmem(priv->ctx, dom->id, newmem) < 0) {
1999 2000 2001
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
                                 " with libxenlight"), dom->id);
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
                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);
2013 2014 2015
            goto cleanup;
        }

2016 2017
    } else {
        /* resize the current memory */
2018

2019
        if (newmem > vm->def->mem.max_balloon) {
2020 2021
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
2022 2023 2024 2025 2026
            goto cleanup;
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
2027
            if (libxl_set_memory_target(priv->ctx, dom->id, newmem, 0,
2028
                                        /* force */ 1) < 0) {
2029 2030 2031
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
                                 " with libxenlight"), dom->id);
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
                goto cleanup;
            }
        }

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

2044 2045
    ret = 0;

2046 2047
cleanup:
    if (vm)
2048
        virObjectUnlock(vm);
2049 2050 2051 2052 2053 2054 2055 2056 2057
    return ret;
}

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

2058 2059 2060 2061 2062 2063
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
2064 2065 2066 2067 2068
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
2069
    libxl_dominfo d_info;
J
Jim Fehlig 已提交
2070 2071 2072
    int ret = -1;

    libxlDriverLock(driver);
2073
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
2074 2075 2076
    libxlDriverUnlock(driver);

    if (!vm) {
2077 2078
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
J
Jim Fehlig 已提交
2079 2080 2081
        goto cleanup;
    }

2082 2083 2084
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
2085
        info->maxMem = vm->def->mem.max_balloon;
2086
    } else {
J
Jim Fehlig 已提交
2087
        if (libxl_domain_info(driver->ctx, &d_info, dom->id) != 0) {
2088 2089
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxl_domain_info failed for domain '%d'"), dom->id);
2090 2091 2092 2093
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
2094
        info->maxMem = d_info.max_memkb;
2095 2096
    }

J
Jiri Denemark 已提交
2097
    info->state = virDomainObjGetState(vm, NULL);
J
Jim Fehlig 已提交
2098 2099 2100 2101 2102
    info->nrVirtCpu = vm->def->vcpus;
    ret = 0;

  cleanup:
    if (vm)
2103
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2104 2105 2106
    return ret;
}

2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
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);
2120
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2121 2122 2123
    libxlDriverUnlock(driver);

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

J
Jiri Denemark 已提交
2129
    *state = virDomainObjGetState(vm, reason);
2130 2131 2132 2133
    ret = 0;

  cleanup:
    if (vm)
2134
        virObjectUnlock(vm);
2135 2136 2137
    return ret;
}

2138 2139
/* This internal function expects the driver lock to already be held on
 * entry and the vm must be active. */
2140
static int
2141 2142
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
2143
{
2144
    libxlDomainObjPrivatePtr priv = vm->privateData;
2145 2146 2147 2148
    libxlSavefileHeader hdr;
    virDomainEventPtr event = NULL;
    char *xml = NULL;
    uint32_t xml_len;
2149
    int fd = -1;
2150 2151 2152
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
2153 2154 2155
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
2156 2157 2158 2159
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
2160
                            -1, -1, 0)) < 0) {
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
        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)) {
2176 2177
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
2178 2179 2180 2181
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
2182 2183
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
2184 2185 2186
        goto cleanup;
    }

J
Jim Fehlig 已提交
2187
    if (libxl_domain_suspend(priv->ctx, vm->def->id, fd, 0, NULL) != 0) {
2188 2189 2190
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
2191 2192 2193 2194 2195 2196
        goto cleanup;
    }

    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

J
Jim Fehlig 已提交
2197
    if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED) != 0) {
2198 2199
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
2200 2201 2202
        goto cleanup;
    }

2203
    vm->hasManagedSave = true;
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
    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
2216 2217
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
2218
{
2219 2220
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
2221 2222
    int ret = -1;

2223 2224
    virCheckFlags(0, -1);
    if (dxml) {
2225 2226
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
2227 2228 2229
        return -1;
    }

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

2233 2234 2235
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2236 2237
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2238 2239 2240
        goto cleanup;
    }

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

2246 2247 2248 2249
    if (libxlDoDomainSave(driver, vm, to) < 0)
        goto cleanup;

    if (!vm->persistent) {
2250
        virDomainObjListRemove(driver->domains, vm);
2251 2252 2253 2254
        vm = NULL;
    }

    ret = 0;
2255

2256 2257
cleanup:
    if (vm)
2258
        virObjectUnlock(vm);
2259 2260 2261
    libxlDriverUnlock(driver);
    return ret;
}
2262

2263
static int
2264 2265 2266 2267 2268 2269 2270 2271
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)
2272 2273 2274 2275 2276 2277 2278
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
2279

2280 2281
    virCheckFlags(0, -1);
    if (dxml) {
2282 2283
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
2284 2285 2286
        return -1;
    }

2287
    libxlDriverLock(driver);
2288

2289 2290
    fd = libxlSaveImageOpen(driver, from, &def, &hdr);
    if (fd < 0)
2291 2292
        goto cleanup;

2293
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2294
                                   driver->xmlopt,
2295 2296 2297
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
2298 2299 2300 2301 2302 2303
        goto cleanup;

    def = NULL;

    if ((ret = libxlVmStart(driver, vm, false, fd)) < 0 &&
        !vm->persistent) {
2304
        virDomainObjListRemove(driver->domains, vm);
2305 2306 2307 2308
        vm = NULL;
    }

cleanup:
2309 2310
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
2311 2312
    virDomainDefFree(def);
    if (vm)
2313
        virObjectUnlock(vm);
2314 2315 2316 2317
    libxlDriverUnlock(driver);
    return ret;
}

2318 2319 2320 2321 2322 2323
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

2324
static int
2325
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
{
    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);
2337
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2338 2339 2340 2341 2342
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2343 2344
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2345 2346 2347 2348
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
2349
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2350 2351 2352 2353 2354 2355 2356
        goto cleanup;
    }

    priv = vm->privateData;

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
2357
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
2358 2359 2360 2361
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
                           dom->id);
2362 2363 2364 2365 2366 2367
            goto cleanup;
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

J
Jim Fehlig 已提交
2368
    if (libxl_domain_core_dump(priv->ctx, dom->id, to, NULL) != 0) {
2369 2370 2371
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
                       dom->id);
2372 2373 2374 2375 2376
        goto cleanup_unpause;
    }

    libxlDriverLock(driver);
    if (flags & VIR_DUMP_CRASH) {
J
Jim Fehlig 已提交
2377
        if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED) != 0) {
2378 2379
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to destroy domain '%d'"), dom->id);
2380 2381 2382 2383 2384 2385 2386 2387
            goto cleanup_unlock;
        }

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

    if ((flags & VIR_DUMP_CRASH) && !vm->persistent) {
2388
        virDomainObjListRemove(driver->domains, vm);
2389 2390 2391 2392 2393 2394 2395 2396 2397
        vm = NULL;
    }

    ret = 0;

cleanup_unlock:
    libxlDriverUnlock(driver);
cleanup_unpause:
    if (virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
2398
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
2399 2400 2401
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
                             " libxenlight"), dom->id);
2402 2403 2404 2405 2406 2407 2408
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
cleanup:
    if (vm)
2409
        virObjectUnlock(vm);
2410 2411 2412 2413 2414 2415 2416 2417
    if (event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, event);
        libxlDriverUnlock(driver);
    }
    return ret;
}

2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
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);
2429
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2430 2431 2432
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2433 2434
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2435 2436 2437 2438
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
2439
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2440 2441
        goto cleanup;
    }
2442
    if (!vm->persistent) {
2443 2444
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
2445 2446
        goto cleanup;
    }
2447 2448 2449 2450 2451 2452 2453

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

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

2454 2455 2456 2457
    if (libxlDoDomainSave(driver, vm, name) < 0)
        goto cleanup;

    if (!vm->persistent) {
2458
        virDomainObjListRemove(driver->domains, vm);
2459 2460 2461 2462
        vm = NULL;
    }

    ret = 0;
2463 2464 2465

cleanup:
    if (vm)
2466
        virObjectUnlock(vm);
2467 2468 2469 2470 2471
    libxlDriverUnlock(driver);
    VIR_FREE(name);
    return ret;
}

2472 2473
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
2474 2475 2476 2477
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
2478
    int ret = -1;
2479

2480
    virObjectLock(vm);
2481 2482 2483 2484 2485 2486

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

    vm->hasManagedSave = virFileExists(name);

2487
    ret = 0;
2488
cleanup:
2489
    virObjectUnlock(vm);
2490
    VIR_FREE(name);
2491
    return ret;
2492 2493
}

2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

    libxlDriverLock(driver);
2504
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2505 2506 2507
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2508 2509
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2510 2511 2512
        goto cleanup;
    }

2513
    ret = vm->hasManagedSave;
2514 2515 2516

cleanup:
    if (vm)
2517
        virObjectUnlock(vm);
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
    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);
2533
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2534 2535 2536
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2537 2538
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2539 2540 2541 2542 2543 2544 2545 2546
        goto cleanup;
    }

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

    ret = unlink(name);
2547
    vm->hasManagedSave = false;
2548 2549 2550 2551

cleanup:
    VIR_FREE(name);
    if (vm)
2552
        virObjectUnlock(vm);
2553 2554 2555 2556
    libxlDriverUnlock(driver);
    return ret;
}

2557 2558 2559 2560 2561 2562 2563 2564
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 已提交
2565
    libxl_bitmap map;
2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
    uint8_t *bitmask = NULL;
    unsigned int maplen;
    unsigned int i, pos;
    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)) {
2581 2582
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2583 2584 2585 2586
        return -1;
    }

    if (!nvcpus) {
2587
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2588 2589 2590 2591
        return -1;
    }

    libxlDriverLock(driver);
2592
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2593 2594 2595
    libxlDriverUnlock(driver);

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

    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2601 2602
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2603 2604 2605 2606
        goto cleanup;
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2607 2608
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2609 2610 2611
        goto cleanup;
    }

2612
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2613 2614
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2615 2616 2617 2618 2619 2620 2621 2622
        goto cleanup;
    }

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

    if (nvcpus > max) {
2623 2624 2625
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2626 2627 2628 2629 2630
        goto cleanup;
    }

    priv = vm->privateData;

2631
    if (!(def = virDomainObjGetPersistentDef(driver->caps, driver->xmlopt, vm)))
2632 2633
        goto cleanup;

E
Eric Blake 已提交
2634
    maplen = VIR_CPU_MAPLEN(nvcpus);
2635 2636 2637 2638 2639 2640
    if (VIR_ALLOC_N(bitmask, maplen) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2641
        pos = i / 8;
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
        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 已提交
2660
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2661 2662 2663
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2664 2665 2666 2667 2668
            goto cleanup;
        }
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2669
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2670 2671 2672
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686
            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)
2687
        virObjectUnlock(vm);
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
    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;
2704
    bool active;
2705 2706 2707 2708 2709 2710

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

    libxlDriverLock(driver);
2711
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2712 2713 2714
    libxlDriverUnlock(driver);

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

2719 2720 2721 2722 2723 2724 2725 2726 2727
    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)) {
2728 2729
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2730 2731 2732
        return -1;
    }

2733
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2734
        if (!active) {
2735 2736
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2737 2738 2739 2740
            goto cleanup;
        }
        def = vm->def;
    } else {
2741
        if (!vm->persistent) {
2742 2743
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2744 2745
            goto cleanup;
        }
2746 2747 2748 2749 2750 2751 2752
        def = vm->newDef ? vm->newDef : vm->def;
    }

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

cleanup:
    if (vm)
2753
        virObjectUnlock(vm);
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
    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 已提交
2765
    libxl_bitmap map;
2766 2767

    libxlDriverLock(driver);
2768
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2769 2770 2771
    libxlDriverUnlock(driver);

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

    if (!virDomainObjIsActive(vm)) {
2777 2778
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot pin vcpus on an inactive domain"));
2779 2780 2781 2782 2783 2784 2785
        goto cleanup;
    }

    priv = vm->privateData;

    map.size = maplen;
    map.map = cpumap;
J
Jim Fehlig 已提交
2786
    if (libxl_set_vcpuaffinity(priv->ctx, dom->id, vcpu, &map) != 0) {
2787 2788
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
2789 2790
        goto cleanup;
    }
2791

H
Hu Tao 已提交
2792 2793 2794 2795 2796 2797 2798
    if (!vm->def->cputune.vcpupin) {
        if (VIR_ALLOC(vm->def->cputune.vcpupin) < 0) {
            virReportOOMError();
            goto cleanup;
        }
        vm->def->cputune.nvcpupin = 0;
    }
2799
    if (virDomainVcpuPinAdd(&vm->def->cputune.vcpupin,
H
Hu Tao 已提交
2800 2801 2802 2803
                            &vm->def->cputune.nvcpupin,
                            cpumap,
                            maplen,
                            vcpu) < 0) {
2804 2805
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to update or add vcpupin xml"));
2806 2807 2808
        goto cleanup;
    }

2809
    if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
2810 2811
        goto cleanup;

2812 2813 2814 2815
    ret = 0;

cleanup:
    if (vm)
2816
        virObjectUnlock(vm);
2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
    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;
    unsigned int i;
    unsigned char *cpumap;

    libxlDriverLock(driver);
2835
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
2836 2837 2838
    libxlDriverUnlock(driver);

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

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

    priv = vm->privateData;
J
Jim Fehlig 已提交
2849
    if ((vcpuinfo = libxl_list_vcpu(priv->ctx, dom->id, &maxcpu,
2850
                                    &hostcpus)) == NULL) {
2851 2852 2853
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
                       dom->id);
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875
        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 已提交
2876
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2877 2878 2879 2880 2881 2882 2883
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

cleanup:
    if (vm)
2884
        virObjectUnlock(vm);
2885 2886 2887
    return ret;
}

J
Jim Fehlig 已提交
2888
static char *
2889
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2890 2891 2892 2893 2894
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

2895 2896
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2897
    libxlDriverLock(driver);
2898
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
2899 2900 2901
    libxlDriverUnlock(driver);

    if (!vm) {
2902 2903
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
J
Jim Fehlig 已提交
2904 2905 2906 2907 2908 2909 2910
        goto cleanup;
    }

    ret = virDomainDefFormat(vm->def, flags);

  cleanup:
    if (vm)
2911
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2912 2913 2914
    return ret;
}

2915
static char *
2916 2917 2918
libxlConnectDomainXMLFromNative(virConnectPtr conn, const char * nativeFormat,
                                const char * nativeConfig,
                                unsigned int flags)
2919 2920 2921 2922 2923 2924 2925
{
    libxlDriverPrivatePtr driver = conn->privateData;
    const libxl_version_info *ver_info;
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2926 2927
    virCheckFlags(0, NULL);

2928
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2929 2930
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2931 2932 2933
        goto cleanup;
    }

J
Jim Fehlig 已提交
2934
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
2935
        VIR_ERROR(_("cannot get version information from libxenlight"));
2936 2937 2938 2939 2940 2941 2942
        goto cleanup;
    }

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

    if (!(def = xenParseXM(conf, ver_info->xen_version_major, driver->caps))) {
2943
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("parsing xm config failed"));
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
        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 *
2958 2959 2960
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
2961 2962 2963 2964 2965 2966 2967 2968
{
    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 已提交
2969 2970
    virCheckFlags(0, NULL);

2971
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2972 2973
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2974 2975 2976
        goto cleanup;
    }

J
Jim Fehlig 已提交
2977
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
2978
        VIR_ERROR(_("cannot get version information from libxenlight"));
2979 2980 2981
        goto cleanup;
    }

2982 2983
    if (!(def = virDomainDefParseString(domainXml,
                                        driver->caps, driver->xmlopt,
M
Matthias Bolte 已提交
2984
                                        1 << VIR_DOMAIN_VIRT_XEN, 0)))
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006
        goto cleanup;

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

    if (VIR_ALLOC_N(ret, len) < 0) {
        virReportOOMError();
        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 已提交
3007
static int
3008 3009
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
3010 3011 3012 3013 3014
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

    libxlDriverLock(driver);
3015
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames);
J
Jim Fehlig 已提交
3016 3017 3018 3019 3020
    libxlDriverUnlock(driver);
    return n;
}

static int
3021
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
3022 3023 3024 3025 3026
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

    libxlDriverLock(driver);
3027
    n = virDomainObjListNumOfDomains(driver->domains, 0);
J
Jim Fehlig 已提交
3028 3029 3030 3031 3032 3033 3034
    libxlDriverUnlock(driver);

    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
3035
                           unsigned int flags)
J
Jim Fehlig 已提交
3036 3037 3038 3039 3040 3041 3042 3043
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

    libxlDriverLock(driver);
3044
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
3045 3046 3047
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3048 3049
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
3050 3051 3052 3053
        goto cleanup;
    }

    if (virDomainObjIsActive(vm)) {
3054 3055
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
J
Jim Fehlig 已提交
3056 3057 3058
        goto cleanup;
    }

3059
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0, -1);
J
Jim Fehlig 已提交
3060 3061 3062

cleanup:
    if (vm)
3063
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
    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;
3081
    virDomainEventPtr event = NULL;
3082
    virDomainDefPtr oldDef = NULL;
J
Jim Fehlig 已提交
3083 3084

    libxlDriverLock(driver);
3085
    if (!(def = virDomainDefParseString(xml, driver->caps, driver->xmlopt,
M
Matthias Bolte 已提交
3086
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
3087 3088 3089
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

3090
    if (!(vm = virDomainObjListAdd(driver->domains, def,
3091
                                   driver->xmlopt,
3092 3093
                                   0,
                                   &oldDef)))
J
Jim Fehlig 已提交
3094 3095 3096 3097 3098 3099
        goto cleanup;
    def = NULL;
    vm->persistent = 1;

    if (virDomainSaveConfig(driver->configDir,
                            vm->newDef ? vm->newDef : vm->def) < 0) {
3100
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
3101 3102 3103 3104 3105 3106 3107 3108
        vm = NULL;
        goto cleanup;
    }

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

3109
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
3110
                                     !oldDef ?
3111 3112 3113
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

J
Jim Fehlig 已提交
3114 3115
cleanup:
    virDomainDefFree(def);
3116
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
3117
    if (vm)
3118
        virObjectUnlock(vm);
3119 3120
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
3121 3122 3123 3124 3125
    libxlDriverUnlock(driver);
    return dom;
}

static int
3126 3127
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
3128 3129 3130
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
3131
    virDomainEventPtr event = NULL;
3132
    char *name = NULL;
J
Jim Fehlig 已提交
3133 3134
    int ret = -1;

3135 3136
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
3137
    libxlDriverLock(driver);
3138
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
3139 3140 3141 3142 3143

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

        virUUIDFormat(dom->uuid, uuidstr);
3144 3145
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
3146 3147 3148 3149
        goto cleanup;
    }

    if (!vm->persistent) {
3150 3151
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
3152 3153 3154
        goto cleanup;
    }

3155 3156 3157 3158 3159 3160 3161
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
3162 3163
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
3164 3165 3166
                goto cleanup;
            }
        } else {
3167 3168 3169
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
3170 3171 3172 3173
            goto cleanup;
        }
    }

J
Jim Fehlig 已提交
3174 3175 3176 3177 3178
    if (virDomainDeleteConfig(driver->configDir,
                              driver->autostartDir,
                              vm) < 0)
        goto cleanup;

3179 3180 3181
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

3182 3183 3184
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
3185
        virDomainObjListRemove(driver->domains, vm);
3186 3187 3188
        vm = NULL;
    }

J
Jim Fehlig 已提交
3189 3190 3191
    ret = 0;

  cleanup:
3192
    VIR_FREE(name);
J
Jim Fehlig 已提交
3193
    if (vm)
3194
        virObjectUnlock(vm);
3195 3196
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
3197 3198 3199 3200
    libxlDriverUnlock(driver);
    return ret;
}

3201 3202 3203 3204 3205 3206
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
static int
libxlDomainChangeEjectableMedia(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDiskDefPtr disk)
{
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
    int i;
    int ret = -1;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
3225 3226 3227
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
3228 3229 3230 3231
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
3232 3233 3234
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
3235 3236 3237
        return -1;
    }

J
Jim Fehlig 已提交
3238
    if (libxlMakeDisk(disk, &x_disk) < 0)
3239 3240
        goto cleanup;

J
Jim Fehlig 已提交
3241
    if ((ret = libxl_cdrom_insert(priv->ctx, vm->def->id, &x_disk, NULL)) < 0) {
3242 3243 3244
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
        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) {
3276
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
3277 3278
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
3279 3280 3281 3282
                    goto cleanup;
                }

                if (!l_disk->src) {
3283 3284
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
3285 3286 3287 3288 3289 3290 3291 3292
                    goto cleanup;
                }

                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
                    virReportOOMError();
                    goto cleanup;
                }

J
Jim Fehlig 已提交
3293
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3294 3295
                    goto cleanup;

J
Jim Fehlig 已提交
3296 3297
                if ((ret = libxl_device_disk_add(priv->ctx, vm->def->id,
                                                &x_disk, NULL)) < 0) {
3298 3299 3300
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
3301 3302 3303 3304 3305 3306
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
3307 3308 3309
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
3310 3311 3312
            }
            break;
        default:
3313 3314 3315
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336
            break;
    }

cleanup:
    return ret;
}

static int
libxlDomainDetachDeviceDiskLive(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
    int i;
    int ret = -1;

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

                if ((i = virDomainDiskIndexByName(vm->def,
3337 3338
                                                  dev->data.disk->dst,
                                                  false)) < 0) {
3339 3340
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3341 3342 3343 3344 3345
                    goto cleanup;
                }

                l_disk = vm->def->disks[i];

J
Jim Fehlig 已提交
3346
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3347 3348
                    goto cleanup;

J
Jim Fehlig 已提交
3349 3350
                if ((ret = libxl_device_disk_remove(priv->ctx, vm->def->id,
                                                    &x_disk, NULL)) < 0) {
3351 3352 3353
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3354 3355 3356 3357 3358 3359 3360
                    goto cleanup;
                }

                virDomainDiskRemove(vm->def, i);
                virDomainDiskDefFree(l_disk);

            } else {
3361 3362 3363
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3364 3365 3366
            }
            break;
        default:
3367 3368 3369
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390
            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:
3391 3392 3393
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407
            break;
    }

    return ret;
}

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

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3408
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3409 3410
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
                return -1;
            }
            if (virDomainDiskInsert(vmdef, disk)) {
                virReportOOMError();
                return -1;
            }
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;

        default:
3422 3423
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440
            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:
3441 3442 3443
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3444 3445 3446 3447 3448 3449 3450 3451 3452
            break;
    }

    return ret;
}

static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3453
    virDomainDiskDefPtr disk, detach;
3454 3455 3456 3457 3458
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3459
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3460 3461
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3462 3463
                break;
            }
3464
            virDomainDiskDefFree(detach);
3465 3466 3467
            ret = 0;
            break;
        default:
3468 3469
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
            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:
3493 3494 3495
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3496 3497 3498 3499
                    break;
            }
            break;
        default:
3500 3501 3502
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr orig;
    virDomainDiskDefPtr disk;
    int i;
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3520
            if ((i = virDomainDiskIndexByName(vmdef, disk->dst, false)) < 0) {
3521 3522
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3523 3524 3525 3526
                goto cleanup;
            }
            orig = vmdef->disks[i];
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3527 3528
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539
                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;
            }
3540
            orig->format = disk->format;
3541 3542 3543
            disk->src = NULL;
            break;
        default:
3544 3545
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
            goto cleanup;
    }

    ret = 0;

cleanup:
    return ret;
}


static int
3557 3558
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570
{
    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);
3571
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
3572 3573

    if (!vm) {
3574
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
        goto cleanup;
    }

    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) {
3586 3587
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3588 3589 3590 3591 3592
            goto cleanup;
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
3593 3594
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3595 3596 3597 3598 3599 3600
         goto cleanup;
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3601 3602
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
                                            driver->caps, driver->xmlopt,
3603 3604 3605 3606
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3607 3608
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, driver->caps,
                                                    driver->xmlopt)))
3609 3610
            goto cleanup;

3611 3612 3613
        if ((ret = libxlDomainAttachDeviceConfig(vmdef, dev)) < 0)
            goto cleanup;
    } else {
3614
        ret = 0;
3615
    }
3616 3617 3618 3619

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
3620 3621
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
                                            driver->caps, driver->xmlopt,
3622 3623 3624
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

3625 3626 3627
        if ((ret = libxlDomainAttachDeviceLive(priv, vm, dev)) < 0)
            goto cleanup;

3628 3629 3630 3631
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3632
        if (virDomainSaveStatus(driver->xmlopt, driver->stateDir, vm) < 0)
3633 3634 3635 3636 3637 3638 3639
            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) {
3640
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3641 3642 3643 3644 3645 3646 3647 3648
            vmdef = NULL;
        }
    }

cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3649
        virObjectUnlock(vm);
3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664
    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)
{
3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756
    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;
    }

    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;
3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769
}

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)
{
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861
    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;
    }

    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;
3862 3863
}

3864 3865 3866 3867 3868 3869 3870
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    const libxl_version_info* ver_info;
    libxlDriverPrivatePtr driver = conn->privateData;

J
Jim Fehlig 已提交
3871
    if (libxl_get_physinfo(driver->ctx, &phy_info)) {
3872 3873
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3874 3875 3876
        return 0;
    }

J
Jim Fehlig 已提交
3877
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
3878 3879
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_version_info failed"));
3880 3881 3882 3883 3884 3885
        return 0;
    }

    return phy_info.free_pages * ver_info->pagesize;
}

3886
static int
3887 3888 3889
libxlConnectDomainEventRegister(virConnectPtr conn,
                                virConnectDomainEventCallback callback, void *opaque,
                                virFreeCallback freecb)
3890 3891 3892 3893 3894
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

    libxlDriverLock(driver);
3895 3896 3897
    ret = virDomainEventStateRegister(conn,
                                      driver->domainEventState,
                                      callback, opaque, freecb);
3898 3899 3900 3901 3902 3903 3904
    libxlDriverUnlock(driver);

    return ret;
}


static int
3905 3906
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
3907 3908 3909 3910 3911
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

    libxlDriverLock(driver);
3912 3913 3914
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
3915 3916 3917 3918 3919
    libxlDriverUnlock(driver);

    return ret;
}

3920 3921 3922 3923 3924 3925 3926 3927
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    libxlDriverLock(driver);
3928
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
3929 3930 3931 3932 3933
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3934 3935
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
3936 3937 3938 3939 3940 3941 3942 3943
        goto cleanup;
    }

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

cleanup:
    if (vm)
3944
        virObjectUnlock(vm);
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956
    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);
3957
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
3958 3959 3960 3961

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3962 3963
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
3964 3965 3966 3967
        goto cleanup;
    }

    if (!vm->persistent) {
3968 3969
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981
        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) {
3982 3983
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
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
                                     _("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)
4012
        virObjectUnlock(vm);
4013 4014 4015 4016
    libxlDriverUnlock(driver);
    return ret;
}

4017 4018 4019 4020 4021 4022 4023
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    char * ret = NULL;
4024
    const char *name = NULL;
J
Jim Fehlig 已提交
4025
    libxl_scheduler sched_id;
4026 4027

    libxlDriverLock(driver);
4028
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4029 4030 4031
    libxlDriverUnlock(driver);

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

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

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

4044 4045
    if (nparams)
        *nparams = 0;
4046
    switch (sched_id) {
J
Jim Fehlig 已提交
4047
    case LIBXL_SCHEDULER_SEDF:
4048
        name = "sedf";
4049
        break;
J
Jim Fehlig 已提交
4050
    case LIBXL_SCHEDULER_CREDIT:
4051
        name = "credit";
4052 4053
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
4054
        break;
J
Jim Fehlig 已提交
4055
    case LIBXL_SCHEDULER_CREDIT2:
4056
        name = "credit2";
4057
        break;
J
Jim Fehlig 已提交
4058
    case LIBXL_SCHEDULER_ARINC653:
4059
        name = "arinc653";
4060 4061
        break;
    default:
J
Jim Fehlig 已提交
4062 4063 4064
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
                     " with libxenlight"), dom->id);
4065 4066 4067
        goto cleanup;
    }

4068
    ignore_value(VIR_STRDUP(ret, name));
4069 4070 4071

cleanup:
    if (vm)
4072
        virObjectUnlock(vm);
4073 4074 4075
    return ret;
}

4076
static int
4077 4078 4079 4080
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
4081 4082 4083 4084
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4085 4086
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
4087 4088
    int ret = -1;

4089 4090
    virCheckFlags(0, -1);

4091
    libxlDriverLock(driver);
4092
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4093 4094 4095
    libxlDriverUnlock(driver);

    if (!vm) {
J
Jim Fehlig 已提交
4096 4097
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
4098 4099 4100 4101
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
4102 4103
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
4104 4105 4106 4107 4108
        goto cleanup;
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
4111
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4112 4113
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4114 4115 4116
        goto cleanup;
    }

J
Jim Fehlig 已提交
4117
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
4118 4119 4120
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
4121 4122 4123
        goto cleanup;
    }

4124 4125
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
4126 4127
        goto cleanup;

4128
    if (*nparams > 1) {
4129 4130
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
4131
            goto cleanup;
4132 4133
    }

4134 4135
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
4136 4137 4138 4139
    ret = 0;

cleanup:
    if (vm)
4140
        virObjectUnlock(vm);
4141 4142 4143 4144
    return ret;
}

static int
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155
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)
4156 4157 4158 4159
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4160
    libxl_domain_sched_params sc_info;
4161 4162 4163 4164
    int sched_id;
    int i;
    int ret = -1;

4165
    virCheckFlags(0, -1);
4166 4167 4168 4169 4170 4171 4172
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_SCHEDULER_WEIGHT,
                                       VIR_TYPED_PARAM_UINT,
                                       VIR_DOMAIN_SCHEDULER_CAP,
                                       VIR_TYPED_PARAM_UINT,
                                       NULL) < 0)
        return -1;
4173

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

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

    if (!virDomainObjIsActive(vm)) {
4184
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4185 4186 4187 4188 4189
        goto cleanup;
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
4192
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4193 4194
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4195 4196 4197
        goto cleanup;
    }

J
Jim Fehlig 已提交
4198
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
4199 4200 4201
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
4202 4203 4204 4205
        goto cleanup;
    }

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

4208
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT)) {
4209
            sc_info.weight = params[i].value.ui;
4210
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP)) {
4211 4212 4213 4214
            sc_info.cap = params[i].value.ui;
        }
    }

J
Jim Fehlig 已提交
4215
    if (libxl_domain_sched_params_set(priv->ctx, dom->id, &sc_info) != 0) {
4216 4217 4218
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
4219 4220 4221 4222 4223 4224 4225
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
4226
        virObjectUnlock(vm);
4227 4228 4229
    return ret;
}

4230 4231 4232 4233 4234 4235 4236
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

J
Jim Fehlig 已提交
4237 4238 4239 4240 4241 4242 4243 4244
static int
libxlDomainIsActive(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    libxlDriverLock(driver);
4245
    obj = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
4246 4247
    libxlDriverUnlock(driver);
    if (!obj) {
4248
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
4249 4250 4251 4252 4253 4254
        goto cleanup;
    }
    ret = virDomainObjIsActive(obj);

  cleanup:
    if (obj)
4255
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266
    return ret;
}

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

    libxlDriverLock(driver);
4267
    obj = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
4268 4269
    libxlDriverUnlock(driver);
    if (!obj) {
4270
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
4271 4272 4273 4274 4275 4276
        goto cleanup;
    }
    ret = obj->persistent;

  cleanup:
    if (obj)
4277
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4278 4279 4280
    return ret;
}

4281 4282 4283 4284 4285 4286 4287 4288
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    libxlDriverLock(driver);
4289
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
4290 4291
    libxlDriverUnlock(driver);
    if (!vm) {
4292
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
4293 4294 4295 4296 4297 4298
        goto cleanup;
    }
    ret = vm->updated;

cleanup:
    if (vm)
4299
        virObjectUnlock(vm);
4300 4301 4302
    return ret;
}

4303
static int
4304 4305 4306
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4307 4308 4309 4310 4311
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

    libxlDriverLock(driver);
4312 4313 4314 4315
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4316
        ret = -1;
4317 4318 4319 4320 4321 4322 4323
    libxlDriverUnlock(driver);

    return ret;
}


static int
4324
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4325 4326 4327 4328 4329
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

    libxlDriverLock(driver);
4330 4331 4332
    ret = virDomainEventStateDeregisterID(conn,
                                          driver->domainEventState,
                                          callbackID);
4333 4334 4335 4336 4337
    libxlDriverUnlock(driver);

    return ret;
}

J
Jim Fehlig 已提交
4338

4339
static int
4340
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4341 4342 4343 4344
{
    return 1;
}

4345
static int
4346 4347 4348
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4349 4350 4351 4352
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4353
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4354 4355

    libxlDriverLock(driver);
4356
    ret = virDomainObjListExport(driver->domains, conn, domains, flags);
4357 4358 4359 4360 4361 4362
    libxlDriverUnlock(driver);

    return ret;
}


4363

J
Jim Fehlig 已提交
4364
static virDriver libxlDriver = {
4365 4366
    .no = VIR_DRV_LIBXL,
    .name = "xenlight",
4367 4368 4369 4370
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
4371
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
4372
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
4373
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
4374 4375 4376 4377
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
4378 4379 4380 4381 4382 4383 4384
    .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 */
4385
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
4386 4387
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
4388
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
4389 4390
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
4391
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
4392 4393 4394 4395
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
4396
    .domainSave = libxlDomainSave, /* 0.9.2 */
4397
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
4398
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
4399
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
4400
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
4401 4402 4403 4404 4405 4406
    .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 */
4407 4408 4409 4410
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
4411 4412 4413 4414
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
4415
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
4416 4417 4418 4419 4420
    .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 */
4421 4422 4423 4424
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
4425
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
4426
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
4427
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
4428
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
4429 4430
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
4431 4432 4433
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
4434 4435 4436
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
4437 4438 4439
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
J
Jim Fehlig 已提交
4440 4441 4442 4443
};

static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
4444 4445 4446
    .stateInitialize = libxlStateInitialize,
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459
};


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

    return 0;
}