libxl_driver.c 116.9 KB
Newer Older
J
Jim Fehlig 已提交
1
/*---------------------------------------------------------------------------*/
2 3
/*  Copyright (C) 2006-2012 Red Hat, Inc.
 *  Copyright (c) 2011 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 29
 */
/*---------------------------------------------------------------------------*/

#include <config.h>

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

#include "internal.h"
#include "logging.h"
#include "virterror_internal.h"
37
#include "conf.h"
J
Jim Fehlig 已提交
38
#include "datatypes.h"
E
Eric Blake 已提交
39
#include "virfile.h"
J
Jim Fehlig 已提交
40 41 42
#include "memory.h"
#include "uuid.h"
#include "command.h"
J
Jim Fehlig 已提交
43
#include "libxl.h"
J
Jim Fehlig 已提交
44 45
#include "libxl_driver.h"
#include "libxl_conf.h"
46
#include "xen_xm.h"
47
#include "virtypedparam.h"
M
Martin Kletzander 已提交
48
#include "viruri.h"
J
Jim Fehlig 已提交
49 50 51 52 53 54 55 56 57

#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

58 59
#define LIBXL_CONFIG_FORMAT_XM "xen-xm"

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

J
Jim Fehlig 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75
struct libxlOSEventHookFDInfo {
    libxlDomainObjPrivatePtr priv;
    void *xl_priv;
    int watch;
};

struct libxlOSEventHookTimerInfo {
    libxlDomainObjPrivatePtr priv;
    void *xl_priv;
    int id;
};


76 77 78 79 80
static void libxlDomainManagedSaveLoad(void *payload,
                                       const void *n ATTRIBUTE_UNUSED,
                                       void *opaque);


J
Jim Fehlig 已提交
81 82 83 84
static libxlDriverPrivatePtr libxl_driver = NULL;

/* Function declarations */
static int
85 86
libxlVmStart(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
             bool start_paused, int restore_fd);
J
Jim Fehlig 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100

/* Function definitions */
static void
libxlDriverLock(libxlDriverPrivatePtr driver)
{
    virMutexLock(&driver->lock);
}

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

J
Jim Fehlig 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

static void libxlFDEventCallback(int watch ATTRIBUTE_UNUSED,
                                 int fd,
                                 int vir_events,
                                 void *fdinfo)
{
    struct libxlOSEventHookFDInfo *info = fdinfo;
    int events = 0;

    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;

    libxl_osevent_occurred_fd(info->priv->ctx, info->xl_priv, fd, 0, events);
}

static void libxlFreeFDInfo(void *obj)
{
    VIR_FREE(obj);
}

static int libxlFDRegisterEventHook(void *priv, int fd, void **hndp,
                                    short events, void *xl_priv)
{
    int vir_events = VIR_EVENT_HANDLE_ERROR;
    struct libxlOSEventHookFDInfo *fdinfo;

    if (VIR_ALLOC(fdinfo) < 0) {
        virReportOOMError();
        return -1;
    }

    fdinfo->priv = priv;
    fdinfo->xl_priv = xl_priv;
    *hndp = fdinfo;

    if (events & POLLIN)
        vir_events |= VIR_EVENT_HANDLE_READABLE;
    if (events & POLLOUT)
        vir_events |= VIR_EVENT_HANDLE_WRITABLE;
    fdinfo->watch = virEventAddHandle(fd, vir_events, libxlFDEventCallback,
                                      fdinfo, libxlFreeFDInfo);
    if (fdinfo->watch < 0) {
        VIR_FREE(fdinfo);
        return fdinfo->watch;
    }

    return 0;
}

static int libxlFDModifyEventHook(void *priv ATTRIBUTE_UNUSED,
                                  int fd ATTRIBUTE_UNUSED,
                                  void **hndp,
                                  short events)
{
    struct libxlOSEventHookFDInfo *fdinfo = *hndp;
    int vir_events = VIR_EVENT_HANDLE_ERROR;

    if (events & POLLIN)
        vir_events |= VIR_EVENT_HANDLE_READABLE;
    if (events & POLLOUT)
        vir_events |= VIR_EVENT_HANDLE_WRITABLE;

    virEventUpdateHandle(fdinfo->watch, vir_events);
    return 0;
}

static void libxlFDDeregisterEventHook(void *priv ATTRIBUTE_UNUSED,
                                       int fd ATTRIBUTE_UNUSED,
                                       void *hnd)
{
    struct libxlOSEventHookFDInfo *fdinfo = hnd;

    virEventRemoveHandle(fdinfo->watch);
}


static void libxlTimerCallback(int timer ATTRIBUTE_UNUSED, void *timer_v)
{
    struct libxlOSEventHookTimerInfo *timer_info = timer_v;

    libxl_osevent_occurred_timeout(timer_info->priv->ctx, timer_info->xl_priv);
}

static void libxlTimerInfoFree(void* obj)
{
    VIR_FREE(obj);
}

static int libxlTimeoutRegisterEventHook(void *priv,
                                         void **hndp,
                                         struct timeval abs_t,
                                         void *for_libxl)
{
    struct timeval now;
    struct libxlOSEventHookTimerInfo *timer_info;
    int timeout, timer_id;

    if (VIR_ALLOC(timer_info) < 0) {
        virReportOOMError();
        return -1;
    }

    gettimeofday(&now, NULL);
    timeout = (abs_t.tv_usec - now.tv_usec) / 1000;
    timeout += (abs_t.tv_sec - now.tv_sec) * 1000;
    timer_id = virEventAddTimeout(timeout, libxlTimerCallback,
                                  timer_info, libxlTimerInfoFree);
    if (timer_id < 0) {
        VIR_FREE(timer_info);
        return timer_id;
    }

    timer_info->priv = priv;
    timer_info->xl_priv = for_libxl;
    timer_info->id = timer_id;
    *hndp = timer_info;
    return 0;
}

static int libxlTimeoutModifyEventHook(void *priv ATTRIBUTE_UNUSED,
                                       void **hndp,
                                       struct timeval abs_t)
{
    struct timeval now;
    int timeout;
    struct libxlOSEventHookTimerInfo *timer_info = *hndp;

    gettimeofday(&now, NULL);
    timeout = (abs_t.tv_usec - now.tv_usec) / 1000;
    timeout += (abs_t.tv_sec - now.tv_sec) * 1000;
    virEventUpdateTimeout(timer_info->id, timeout);
    return 0;
}

static void libxlTimeoutDeregisterEventHook(void *priv ATTRIBUTE_UNUSED,
                                            void *hnd)
{
    struct libxlOSEventHookTimerInfo *timer_info = hnd;

    virEventRemoveTimeout(timer_info->id);
}

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 已提交
258 259 260 261 262 263 264 265
static void *
libxlDomainObjPrivateAlloc(void)
{
    libxlDomainObjPrivatePtr priv;

    if (VIR_ALLOC(priv) < 0)
        return NULL;

J
Jim Fehlig 已提交
266 267 268
    libxl_ctx_alloc(&priv->ctx, LIBXL_VERSION, 0, libxl_driver->logger);
    priv->deathW = NULL;
    libxl_osevent_register_hooks(priv->ctx, &libxl_event_callbacks, priv);
J
Jim Fehlig 已提交
269 270 271 272 273 274 275 276 277

    return priv;
}

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

J
Jim Fehlig 已提交
278 279 280
    if (priv->deathW) {
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
        VIR_FREE(priv->deathW);
J
Jim Fehlig 已提交
281 282
    }

J
Jim Fehlig 已提交
283
    libxl_ctx_free(priv->ctx);
J
Jim Fehlig 已提交
284 285 286
    VIR_FREE(priv);
}

287 288 289 290 291

/* driver must be locked before calling */
static void
libxlDomainEventQueue(libxlDriverPrivatePtr driver, virDomainEventPtr event)
{
292
    virDomainEventStateQueue(driver->domainEventState, event);
293 294
}

295 296 297 298 299 300 301 302 303 304 305 306
static void
libxlAutostartDomain(void *payload, const void *name ATTRIBUTE_UNUSED,
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    virDomainObjPtr vm = payload;
    virErrorPtr err;

    virDomainObjLock(vm);
    virResetLastError();

    if (vm->autostart && !virDomainObjIsActive(vm) &&
307
        libxlVmStart(driver, vm, false, -1) < 0) {
308 309 310 311 312 313 314 315 316 317
        err = virGetLastError();
        VIR_ERROR(_("Failed to autostart VM '%s': %s"),
                  vm->def->name,
                  err ? err->message : _("unknown error"));
    }

    if (vm)
        virDomainObjUnlock(vm);
}

318 319 320 321 322 323 324
static int
libxlDoNodeGetInfo(libxlDriverPrivatePtr driver, virNodeInfoPtr info)
{
    libxl_physinfo phy_info;
    const libxl_version_info* ver_info;
    struct utsname utsname;

J
Jim Fehlig 已提交
325
    if (libxl_get_physinfo(driver->ctx, &phy_info)) {
326 327
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
328 329 330
        return -1;
    }

J
Jim Fehlig 已提交
331
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
332 333
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_version_info failed"));
334 335 336 337 338 339 340 341
        return -1;
    }

    uname(&utsname);
    if (virStrncpy(info->model,
                   utsname.machine,
                   strlen(utsname.machine),
                   sizeof(info->model)) == NULL) {
342 343 344
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("machine type %s too big for destination"),
                       utsname.machine);
345 346 347 348 349 350 351 352 353 354 355 356 357
        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;
}

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
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 已提交
381
    if ((fd = virFileOpenAs(from, O_RDONLY, 0, -1, -1, 0)) < 0) {
382 383
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("cannot read domain image"));
384 385 386 387
        goto error;
    }

    if (saferead(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
388 389
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to read libxl header"));
390 391 392 393
        goto error;
    }

    if (memcmp(hdr.magic, LIBXL_SAVE_MAGIC, sizeof(hdr.magic))) {
394
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("image magic is incorrect"));
395 396 397 398
        goto error;
    }

    if (hdr.version > LIBXL_SAVE_VERSION) {
399 400 401
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("image version is not supported (%d > %d)"),
                       hdr.version, LIBXL_SAVE_VERSION);
402 403 404 405
        goto error;
    }

    if (hdr.xmlLen <= 0) {
406 407
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("invalid XML length: %d"), hdr.xmlLen);
408 409 410 411 412 413 414 415 416
        goto error;
    }

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

    if (saferead(fd, xml, hdr.xmlLen) != hdr.xmlLen) {
417
        virReportError(VIR_ERR_OPERATION_FAILED, "%s", _("failed to read XML"));
418 419 420 421
        goto error;
    }

    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
422
                                        1 << VIR_DOMAIN_VIRT_XEN,
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
                                        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 已提交
440 441 442 443 444 445
/*
 * Cleanup function for domain that has reached shutoff state.
 *
 * virDomainObjPtr should be locked on invocation
 */
static void
J
Jiri Denemark 已提交
446 447 448
libxlVmCleanup(libxlDriverPrivatePtr driver,
               virDomainObjPtr vm,
               virDomainShutoffReason reason)
J
Jim Fehlig 已提交
449 450 451 452
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
    int vnc_port;
    char *file;
453
    int i;
J
Jim Fehlig 已提交
454

J
Jim Fehlig 已提交
455 456 457
    if (priv->deathW) {
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
        priv->deathW = NULL;
J
Jim Fehlig 已提交
458 459 460 461
    }

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

465 466 467 468
    driver->nactive--;
    if (!driver->nactive && driver->inhibitCallback)
        driver->inhibitCallback(false, driver->inhibitOpaque);

J
Jim Fehlig 已提交
469 470 471 472 473 474 475 476 477 478 479
    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) {
            if (virBitmapClearBit(driver->reservedVNCPorts,
                                  vnc_port - LIBXL_VNC_PORT_MIN) < 0)
                VIR_DEBUG("Could not mark port %d as unused", vnc_port);
        }
    }

480 481 482 483 484 485 486 487 488 489
    /* 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 已提交
490 491 492 493 494
    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);
    }
495 496 497 498 499 500 501

    if (vm->newDef) {
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->def->id = -1;
        vm->newDef = NULL;
    }
J
Jim Fehlig 已提交
502 503 504 505 506 507 508 509
}

/*
 * Reap a domain from libxenlight.
 *
 * virDomainObjPtr should be locked on invocation
 */
static int
J
Jiri Denemark 已提交
510 511 512
libxlVmReap(libxlDriverPrivatePtr driver,
            virDomainObjPtr vm,
            virDomainShutoffReason reason)
J
Jim Fehlig 已提交
513 514 515
{
    libxlDomainObjPrivatePtr priv = vm->privateData;

J
Jim Fehlig 已提交
516
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
517 518
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to cleanup domain %d"), vm->def->id);
J
Jim Fehlig 已提交
519 520 521
        return -1;
    }

J
Jiri Denemark 已提交
522
    libxlVmCleanup(driver, vm, reason);
J
Jim Fehlig 已提交
523 524 525 526 527 528
    return 0;
}

/*
 * Handle previously registered event notification from libxenlight
 */
J
Jim Fehlig 已提交
529
static void libxlEventHandler(void *data, const libxl_event *event)
J
Jim Fehlig 已提交
530 531 532
{
    libxlDriverPrivatePtr driver = libxl_driver;
    virDomainObjPtr vm = data;
533
    virDomainEventPtr dom_event = NULL;
J
Jim Fehlig 已提交
534 535 536 537 538

    libxlDriverLock(driver);
    virDomainObjLock(vm);
    libxlDriverUnlock(driver);

J
Jim Fehlig 已提交
539
    if (event->type == LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN) {
J
Jiri Denemark 已提交
540 541
        virDomainShutoffReason reason;

J
Jim Fehlig 已提交
542
        if (event->domid != vm->def->id)
J
Jim Fehlig 已提交
543 544
            goto cleanup;

J
Jim Fehlig 已提交
545 546 547 548
        switch (event->u.domain_shutdown.shutdown_reason) {
            case LIBXL_SHUTDOWN_REASON_POWEROFF:
            case LIBXL_SHUTDOWN_REASON_CRASH:
                if (event->u.domain_shutdown.shutdown_reason == LIBXL_SHUTDOWN_REASON_CRASH) {
549 550 551
                    dom_event = virDomainEventNewFromObj(vm,
                                              VIR_DOMAIN_EVENT_STOPPED,
                                              VIR_DOMAIN_EVENT_STOPPED_CRASHED);
J
Jiri Denemark 已提交
552 553 554 555
                    reason = VIR_DOMAIN_SHUTOFF_CRASHED;
                } else {
                    reason = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
                }
J
Jim Fehlig 已提交
556
                libxlVmReap(driver, vm, reason);
J
Jim Fehlig 已提交
557 558 559 560 561
                if (!vm->persistent) {
                    virDomainRemoveInactive(&driver->domains, vm);
                    vm = NULL;
                }
                break;
J
Jim Fehlig 已提交
562 563
            case LIBXL_SHUTDOWN_REASON_REBOOT:
                libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
564
                libxlVmStart(driver, vm, 0, -1);
J
Jim Fehlig 已提交
565 566
                break;
            default:
J
Jim Fehlig 已提交
567
                VIR_INFO("Unhandled shutdown_reason %d", event->u.domain_shutdown.shutdown_reason);
J
Jim Fehlig 已提交
568 569 570 571 572 573 574
                break;
        }
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
575 576 577 578 579
    if (dom_event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, dom_event);
        libxlDriverUnlock(driver);
    }
J
Jim Fehlig 已提交
580 581
}

J
Jim Fehlig 已提交
582 583 584 585 586 587
static const struct libxl_event_hooks ev_hooks = {
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlEventHandler,
    .disaster = NULL,
};

J
Jim Fehlig 已提交
588 589 590 591 592 593 594 595 596
/*
 * 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 已提交
597
    libxl_event_register_callbacks(priv->ctx, &ev_hooks, vm);
J
Jim Fehlig 已提交
598

J
Jim Fehlig 已提交
599
    if (libxl_evenable_domain_death(priv->ctx, vm->def->id, 0, &priv->deathW))
J
Jim Fehlig 已提交
600 601 602 603 604
        goto error;

    return 0;

error:
J
Jim Fehlig 已提交
605 606 607
    if (priv->deathW)
        libxl_evdisable_domain_death(priv->ctx, priv->deathW);
    VIR_FREE(priv->deathW);
J
Jim Fehlig 已提交
608 609 610
    return -1;
}

611 612 613 614 615
static int
libxlDomainSetVcpuAffinites(libxlDriverPrivatePtr driver, virDomainObjPtr vm)
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
    virDomainDefPtr def = vm->def;
J
Jim Fehlig 已提交
616
    libxl_bitmap map;
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    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) {
641 642
            if (cpumask[i])
                VIR_USE_CPU(cpumap, i);
643 644 645 646 647
        }

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

J
Jim Fehlig 已提交
648
        if (libxl_set_vcpuaffinity(priv->ctx, def->id, vcpu, &map) != 0) {
649 650
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
651 652 653 654 655 656 657 658 659 660 661 662 663
            goto cleanup;
        }

        VIR_FREE(cpumap);
    }

    ret = 0;

cleanup:
    VIR_FREE(cpumap);
    return ret;
}

M
Markus Groß 已提交
664 665 666 667 668 669 670 671 672 673
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 已提交
674
    if ((ret = libxl_domain_need_memory(priv->ctx, &d_config->b_info,
M
Markus Groß 已提交
675 676
                                        &needed_mem)) >= 0) {
        for (i = 0; i < tries; ++i) {
J
Jim Fehlig 已提交
677
            if ((ret = libxl_get_free_memory(priv->ctx, &free_mem)) < 0)
M
Markus Groß 已提交
678 679 680 681 682 683 684
                break;

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

J
Jim Fehlig 已提交
685
            if ((ret = libxl_set_memory_target(priv->ctx, 0,
M
Markus Groß 已提交
686 687 688 689
                                               free_mem - needed_mem,
                                               /* relative */ 1, 0)) < 0)
                break;

J
Jim Fehlig 已提交
690
            ret = libxl_wait_for_free_memory(priv->ctx, 0, needed_mem,
M
Markus Groß 已提交
691 692 693 694
                                             wait_secs);
            if (ret == 0 || ret != ERROR_NOMEM)
                break;

J
Jim Fehlig 已提交
695
            if ((ret = libxl_wait_for_memory_target(priv->ctx, 0, 1)) < 0)
M
Markus Groß 已提交
696 697 698 699 700 701 702
                break;
        }
    }

    return ret;
}

J
Jim Fehlig 已提交
703 704 705 706 707 708
/*
 * Start a domain through libxenlight.
 *
 * virDomainObjPtr should be locked on invocation
 */
static int
709 710
libxlVmStart(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
             bool start_paused, int restore_fd)
J
Jim Fehlig 已提交
711 712
{
    libxl_domain_config d_config;
713
    virDomainDefPtr def = NULL;
714
    virDomainEventPtr event = NULL;
715
    libxlSavefileHeader hdr;
J
Jim Fehlig 已提交
716 717 718
    int ret;
    uint32_t domid = 0;
    char *dom_xml = NULL;
719 720
    char *managed_save_path = NULL;
    int managed_save_fd = -1;
J
Jim Fehlig 已提交
721 722
    libxlDomainObjPrivatePtr priv = vm->privateData;

723 724 725
    /* 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) {
726 727
        managed_save_path = libxlDomainManagedSavePath(driver, vm);
        if (managed_save_path == NULL)
728 729
            goto error;

730
        if (virFileExists(managed_save_path)) {
731

732 733 734
            managed_save_fd = libxlSaveImageOpen(driver, managed_save_path,
                                                 &def, &hdr);
            if (managed_save_fd < 0)
735 736
                goto error;

737 738
            restore_fd = managed_save_fd;

739 740 741 742 743 744
            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);
745 746 747 748
                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);
749 750 751 752 753 754
                goto error;
            }

            virDomainObjAssignDef(vm, def, true);
            def = NULL;

755 756 757 758
            if (unlink(managed_save_path) < 0) {
                VIR_WARN("Failed to remove the managed state %s",
                         managed_save_path);
            }
759
            vm->hasManagedSave = false;
760
        }
761
        VIR_FREE(managed_save_path);
762 763
    }

J
Jim Fehlig 已提交
764
    libxl_domain_config_init(&d_config);
J
Jim Fehlig 已提交
765

766
    if (libxlBuildDomainConfig(driver, vm->def, &d_config) < 0)
J
Jim Fehlig 已提交
767 768
        return -1;

M
Markus Groß 已提交
769
    if (libxlFreeMem(priv, &d_config) < 0) {
770 771 772
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to get free memory for domain '%s'"),
                       d_config.c_info.name);
M
Markus Groß 已提交
773 774
        goto error;
    }
J
Jim Fehlig 已提交
775

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

778
    if (restore_fd < 0)
J
Jim Fehlig 已提交
779 780
        ret = libxl_domain_create_new(priv->ctx, &d_config,
                                      &domid, NULL, NULL);
781
    else
J
Jim Fehlig 已提交
782 783
        ret = libxl_domain_create_restore(priv->ctx, &d_config, &domid,
                                          restore_fd, NULL, NULL);
784

J
Jim Fehlig 已提交
785
    if (ret) {
786
        if (restore_fd < 0)
787 788 789
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to create new domain '%s'"),
                           d_config.c_info.name);
790
        else
791 792 793
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to restore domain '%s'"),
                           d_config.c_info.name);
J
Jim Fehlig 已提交
794 795 796
        goto error;
    }

797 798
    vm->def->id = domid;
    if ((dom_xml = virDomainDefFormat(vm->def, 0)) == NULL)
J
Jim Fehlig 已提交
799 800
        goto error;

J
Jim Fehlig 已提交
801
    if (libxl_userdata_store(priv->ctx, domid, "libvirt-xml",
J
Jim Fehlig 已提交
802
                             (uint8_t *)dom_xml, strlen(dom_xml) + 1)) {
803 804
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to store userdata"));
J
Jim Fehlig 已提交
805 806 807 808 809 810
        goto error;
    }

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

811 812 813
    if (libxlDomainSetVcpuAffinites(driver, vm) < 0)
        goto error;

J
Jim Fehlig 已提交
814
    if (!start_paused) {
J
Jim Fehlig 已提交
815
        libxl_domain_unpause(priv->ctx, domid);
J
Jiri Denemark 已提交
816
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
J
Jim Fehlig 已提交
817
    } else {
J
Jiri Denemark 已提交
818
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
J
Jim Fehlig 已提交
819 820
    }

821

J
Jim Fehlig 已提交
822 823 824
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto error;

825 826 827 828
    if (!driver->nactive && driver->inhibitCallback)
        driver->inhibitCallback(true, driver->inhibitOpaque);
    driver->nactive++;

829
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STARTED,
830 831 832
                                     restore_fd < 0 ?
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED :
                                         VIR_DOMAIN_EVENT_STARTED_RESTORED);
833 834
    libxlDomainEventQueue(driver, event);

J
Jim Fehlig 已提交
835
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
836
    VIR_FREE(dom_xml);
837
    VIR_FORCE_CLOSE(managed_save_fd);
J
Jim Fehlig 已提交
838 839 840 841
    return 0;

error:
    if (domid > 0) {
J
Jim Fehlig 已提交
842
        libxl_domain_destroy(priv->ctx, domid, NULL);
843
        vm->def->id = -1;
J
Jiri Denemark 已提交
844
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);
J
Jim Fehlig 已提交
845
    }
J
Jim Fehlig 已提交
846
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
847
    VIR_FREE(dom_xml);
848
    VIR_FREE(managed_save_path);
849
    virDomainDefFree(def);
850
    VIR_FORCE_CLOSE(managed_save_fd);
J
Jim Fehlig 已提交
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
    return -1;
}


/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
static void
libxlReconnectDomain(void *payload,
                     const void *name ATTRIBUTE_UNUSED,
                     void *opaque)
{
    virDomainObjPtr vm = payload;
    libxlDriverPrivatePtr driver = opaque;
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;

    virDomainObjLock(vm);

    /* Does domain still exist? */
J
Jim Fehlig 已提交
874
    rc = libxl_domain_info(driver->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
875 876 877 878 879 880 881 882 883
    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 已提交
884
    if (libxl_userdata_retrieve(driver->ctx, vm->def->id,
J
Jim Fehlig 已提交
885 886 887 888 889 890 891
                                "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 已提交
892
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_UNKNOWN);
J
Jim Fehlig 已提交
893

894 895 896 897
    if (!driver->nactive && driver->inhibitCallback)
        driver->inhibitCallback(true, driver->inhibitOpaque);
    driver->nactive++;

J
Jim Fehlig 已提交
898 899 900 901 902 903
    /* Recreate domain death et. al. events */
    libxlCreateDomEvents(vm);
    virDomainObjUnlock(vm);
    return;

out:
J
Jiri Denemark 已提交
904
    libxlVmCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_UNKNOWN);
J
Jim Fehlig 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
    if (!vm->persistent)
        virDomainRemoveInactive(&driver->domains, vm);
    else
        virDomainObjUnlock(vm);
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
    virHashForEach(driver->domains.objs, libxlReconnectDomain, driver);
}

static int
libxlShutdown(void)
{
    if (!libxl_driver)
        return -1;

    libxlDriverLock(libxl_driver);
    virCapabilitiesFree(libxl_driver->caps);
    virDomainObjListDeinit(&libxl_driver->domains);
J
Jim Fehlig 已提交
926
    libxl_ctx_free(libxl_driver->ctx);
J
Jim Fehlig 已提交
927 928 929 930 931 932 933 934 935 936 937 938 939
    xtl_logger_destroy(libxl_driver->logger);
    if (libxl_driver->logger_file)
        VIR_FORCE_FCLOSE(libxl_driver->logger_file);

    virBitmapFree(libxl_driver->reservedVNCPorts);

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

J
Jim Fehlig 已提交
942 943 944 945 946 947 948 949
    libxlDriverUnlock(libxl_driver);
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

static int
950 951 952 953
libxlStartup(bool privileged,
             virStateInhibitCallback callback ATTRIBUTE_UNUSED,
             void *opaque ATTRIBUTE_UNUSED)
{
J
Jim Fehlig 已提交
954 955 956
    const libxl_version_info *ver_info;
    char *log_file = NULL;
    virCommandPtr cmd;
D
Daniel Veillard 已提交
957
    int status, ret = 0;
958
    char ebuf[1024];
J
Jim Fehlig 已提交
959 960 961

    /* Disable libxl driver if non-root */
    if (!privileged) {
962
        VIR_INFO("Not running privileged, disabling libxenlight driver");
J
Jim Fehlig 已提交
963 964 965 966 967 968
        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) {
969
        VIR_INFO("Legacy xen tool stack seems to be in use, disabling "
J
Jim Fehlig 已提交
970 971 972 973 974 975 976 977 978 979
                  "libxenlight driver.");
        virCommandFree(cmd);
        return 0;
    }
    virCommandFree(cmd);

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

    if (virMutexInit(&libxl_driver->lock) < 0) {
980
        VIR_ERROR(_("cannot initialize mutex"));
J
Jim Fehlig 已提交
981 982 983 984 985 986 987
        VIR_FREE(libxl_driver);
        return -1;
    }
    libxlDriverLock(libxl_driver);

    /* Allocate bitmap for vnc port reservation */
    if ((libxl_driver->reservedVNCPorts =
988
         virBitmapNew(LIBXL_VNC_PORT_MAX - LIBXL_VNC_PORT_MIN)) == NULL)
J
Jim Fehlig 已提交
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
        goto out_of_memory;

    if (virDomainObjListInit(&libxl_driver->domains) < 0)
        goto out_of_memory;

    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;

1018
    if (virFileMakePath(libxl_driver->logDir) < 0) {
J
Jim Fehlig 已提交
1019
        VIR_ERROR(_("Failed to create log dir '%s': %s"),
1020
                  libxl_driver->logDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1021 1022
        goto error;
    }
1023
    if (virFileMakePath(libxl_driver->stateDir) < 0) {
J
Jim Fehlig 已提交
1024
        VIR_ERROR(_("Failed to create state dir '%s': %s"),
1025
                  libxl_driver->stateDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1026 1027
        goto error;
    }
1028
    if (virFileMakePath(libxl_driver->libDir) < 0) {
J
Jim Fehlig 已提交
1029
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
1030
                  libxl_driver->libDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1031 1032
        goto error;
    }
1033
    if (virFileMakePath(libxl_driver->saveDir) < 0) {
J
Jim Fehlig 已提交
1034
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
1035
                  libxl_driver->saveDir, virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        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);

1051
    libxl_driver->domainEventState = virDomainEventStateNew();
E
Eric Blake 已提交
1052
    if (!libxl_driver->domainEventState)
1053 1054
        goto error;

J
Jim Fehlig 已提交
1055 1056 1057
    libxl_driver->logger =
            (xentoollog_logger *)xtl_createlogger_stdiostream(libxl_driver->logger_file, XTL_DEBUG,  0);
    if (!libxl_driver->logger) {
1058
        VIR_INFO("cannot create logger for libxenlight, disabling driver");
D
Daniel Veillard 已提交
1059
        goto fail;
J
Jim Fehlig 已提交
1060 1061
    }

J
Jim Fehlig 已提交
1062 1063
    if (libxl_ctx_alloc(&libxl_driver->ctx,
                       LIBXL_VERSION, 0,
J
Jim Fehlig 已提交
1064
                       libxl_driver->logger)) {
1065
        VIR_INFO("cannot initialize libxenlight context, probably not running in a Xen Dom0, disabling driver");
D
Daniel Veillard 已提交
1066
        goto fail;
J
Jim Fehlig 已提交
1067 1068
    }

J
Jim Fehlig 已提交
1069
    if ((ver_info = libxl_get_version_info(libxl_driver->ctx)) == NULL) {
1070
        VIR_INFO("cannot version information from libxenlight, disabling driver");
D
Daniel Veillard 已提交
1071
        goto fail;
J
Jim Fehlig 已提交
1072 1073 1074 1075 1076
    }
    libxl_driver->version = (ver_info->xen_version_major * 1000000) +
            (ver_info->xen_version_minor * 1000);

    if ((libxl_driver->caps =
J
Jim Fehlig 已提交
1077
         libxlMakeCapabilities(libxl_driver->ctx)) == NULL) {
1078
        VIR_ERROR(_("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
        goto error;
    }

    libxl_driver->caps->privateDataAllocFunc = libxlDomainObjPrivateAlloc;
    libxl_driver->caps->privateDataFreeFunc = libxlDomainObjPrivateFree;

    /* Load running domains first. */
    if (virDomainLoadAllConfigs(libxl_driver->caps,
                                &libxl_driver->domains,
                                libxl_driver->stateDir,
                                libxl_driver->autostartDir,
M
Matthias Bolte 已提交
1090 1091
                                1, 1 << VIR_DOMAIN_VIRT_XEN,
                                NULL, NULL) < 0)
J
Jim Fehlig 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
    if (virDomainLoadAllConfigs(libxl_driver->caps,
                                &libxl_driver->domains,
                                libxl_driver->configDir,
                                libxl_driver->autostartDir,
M
Matthias Bolte 已提交
1101 1102
                                0, 1 << VIR_DOMAIN_VIRT_XEN,
                                NULL, NULL) < 0)
J
Jim Fehlig 已提交
1103 1104
        goto error;

1105 1106
    virHashForEach(libxl_driver->domains.objs, libxlAutostartDomain,
                   libxl_driver);
J
Jim Fehlig 已提交
1107

1108 1109 1110
    virHashForEach(libxl_driver->domains.objs, libxlDomainManagedSaveLoad,
                   libxl_driver);

1111
    libxlDriverUnlock(libxl_driver);
J
Jim Fehlig 已提交
1112 1113 1114 1115 1116 1117

    return 0;

out_of_memory:
    virReportOOMError();
error:
D
Daniel Veillard 已提交
1118 1119
    ret = -1;
fail:
J
Jim Fehlig 已提交
1120 1121 1122 1123
    VIR_FREE(log_file);
    if (libxl_driver)
        libxlDriverUnlock(libxl_driver);
    libxlShutdown();
D
Daniel Veillard 已提交
1124
    return ret;
J
Jim Fehlig 已提交
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
}

static int
libxlReload(void)
{
    if (!libxl_driver)
        return 0;

    libxlDriverLock(libxl_driver);
    virDomainLoadAllConfigs(libxl_driver->caps,
                            &libxl_driver->domains,
                            libxl_driver->configDir,
                            libxl_driver->autostartDir,
M
Matthias Bolte 已提交
1138 1139
                            1, 1 << VIR_DOMAIN_VIRT_XEN,
                            NULL, libxl_driver);
J
Jim Fehlig 已提交
1140

1141 1142 1143 1144
    virHashForEach(libxl_driver->domains.objs, libxlAutostartDomain,
                   libxl_driver);

    libxlDriverUnlock(libxl_driver);
J
Jim Fehlig 已提交
1145 1146 1147 1148 1149 1150 1151 1152

    return 0;
}


static virDrvOpenStatus
libxlOpen(virConnectPtr conn,
          virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
1153
          unsigned int flags)
J
Jim Fehlig 已提交
1154
{
E
Eric Blake 已提交
1155 1156
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
1157 1158 1159 1160
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

1161
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
            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) {
1174 1175
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
1176 1177 1178 1179 1180 1181 1182 1183
            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")) {
1184 1185 1186
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
1187 1188 1189 1190 1191 1192 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 1218 1219 1220 1221 1222 1223 1224 1225
            return VIR_DRV_OPEN_ERROR;
        }
    }

    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
libxlClose(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    conn->privateData = NULL;
    return 0;
}

static const char *
libxlGetType(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return "xenlight";
}

static int
libxlGetVersion(virConnectPtr conn, unsigned long *version)
{
    libxlDriverPrivatePtr driver = conn->privateData;

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

static int
libxlGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;

J
Jim Fehlig 已提交
1226
    ret = libxl_get_max_cpus(driver->ctx);
J
Jim Fehlig 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
    /* 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)
{
1238
    return libxlDoNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
}

static char *
libxlGetCapabilities(virConnectPtr conn)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;

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

    return xml;
}

static int
libxlListDomains(virConnectPtr conn, int *ids, int nids)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

    libxlDriverLock(driver);
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
    libxlDriverUnlock(driver);

    return n;
}

static int
libxlNumDomains(virConnectPtr conn)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

    libxlDriverLock(driver);
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
    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);
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
1294
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
        goto cleanup;

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains, def, false)))
        goto cleanup;
    def = NULL;

1306 1307
    if (libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0,
                     -1) < 0) {
J
Jim Fehlig 已提交
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
        virDomainRemoveInactive(&driver->domains, vm);
        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)
        virDomainObjUnlock(vm);
    libxlDriverUnlock(driver);
    return dom;
}

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

    libxlDriverLock(driver);
    vm = virDomainFindByID(&driver->domains, id);
    libxlDriverUnlock(driver);

    if (!vm) {
1337
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
        goto cleanup;
    }

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

  cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return dom;
}

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

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, uuid);
    libxlDriverUnlock(driver);

    if (!vm) {
1363
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
        goto cleanup;
    }

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

  cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return dom;
}

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

    libxlDriverLock(driver);
    vm = virDomainFindByName(&driver->domains, name);
    libxlDriverUnlock(driver);

    if (!vm) {
1389
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
        goto cleanup;
    }

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

  cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return dom;
}

1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
    virDomainEventPtr event = NULL;
    int ret = -1;

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1419 1420
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
1421 1422 1423
        goto cleanup;
    }
    if (!virDomainObjIsActive(vm)) {
1424
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1425 1426 1427 1428 1429
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1430
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1431
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
1432 1433 1434
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to suspend domain '%d' with libxenlight"),
                           dom->id);
1435 1436 1437
            goto cleanup;
        }

J
Jiri Denemark 已提交
1438
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476

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

    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    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);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1477 1478
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
1479 1480 1481 1482
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
1483
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1484 1485 1486 1487 1488
        goto cleanup;
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1489
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1490
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
1491 1492 1493
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
                           dom->id);
1494 1495 1496
            goto cleanup;
        }

J
Jiri Denemark 已提交
1497 1498
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519

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

    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto cleanup;

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    if (event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, event);
        libxlDriverUnlock(driver);
    }
    return ret;
}

J
Jim Fehlig 已提交
1520
static int
1521
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1522 1523 1524 1525 1526 1527
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

1528 1529
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1530 1531 1532 1533 1534
    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1535 1536
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
1537 1538 1539 1540
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
1541 1542
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1543 1544 1545 1546
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1547
    if (libxl_domain_shutdown(priv->ctx, dom->id) != 0) {
1548 1549 1550
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
        goto cleanup;
    }

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

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    libxlDriverUnlock(driver);
    return ret;
}

1566 1567 1568 1569 1570 1571 1572
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
1573
static int
E
Eric Blake 已提交
1574
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1575 1576 1577 1578 1579 1580
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

E
Eric Blake 已提交
1581 1582
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1583 1584 1585 1586 1587
    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1588 1589
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
1590 1591 1592 1593
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
1594 1595
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1596 1597 1598 1599
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1600
    if (libxl_domain_reboot(priv->ctx, dom->id) != 0) {
1601 1602 1603
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
        goto cleanup;
    }
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    libxlDriverUnlock(driver);
    return ret;
}

static int
1616 1617
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1618 1619 1620 1621
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1622
    virDomainEventPtr event = NULL;
J
Jim Fehlig 已提交
1623

1624 1625
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1626 1627 1628 1629 1630
    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1631 1632
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
1633 1634 1635 1636
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
1637 1638
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1639 1640 1641
        goto cleanup;
    }

1642 1643 1644
    event = virDomainEventNewFromObj(vm,VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

J
Jim Fehlig 已提交
1645
    if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED) != 0) {
1646 1647
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), dom->id);
J
Jim Fehlig 已提交
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
        goto cleanup;
    }

    if (!vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
1661 1662
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1663 1664 1665 1666
    libxlDriverUnlock(driver);
    return ret;
}

1667 1668 1669 1670 1671 1672
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
1686 1687
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
        goto cleanup;
    }

    if (!(type = strdup(vm->def->os.type)))
        virReportOOMError();

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return type;
}

1700
static unsigned long long
1701 1702 1703 1704
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1705
    unsigned long long ret = 0;
1706 1707 1708 1709 1710 1711

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

    if (!vm) {
1712
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
        goto cleanup;
    }
    ret = vm->def->mem.max_balloon;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

static int
1724
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1725 1726 1727 1728 1729
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1730 1731
    virDomainDefPtr persistentDef = NULL;
    bool isActive;
1732 1733 1734
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1735 1736
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1737 1738 1739 1740 1741 1742

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

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

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
    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;
1760 1761
    }

1762
    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
1763 1764
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set memory on an inactive domain"));
1765 1766 1767 1768 1769
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
1770 1771
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a transient domain"));
1772 1773
            goto cleanup;
        }
1774
        if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
1775 1776 1777
            goto cleanup;
    }

1778 1779
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1780

1781 1782
        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
1783
            if (libxl_domain_setmaxmem(priv->ctx, dom->id, newmem) < 0) {
1784 1785 1786
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
                                 " with libxenlight"), dom->id);
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
                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);
1798 1799 1800
            goto cleanup;
        }

1801 1802
    } else {
        /* resize the current memory */
1803

1804
        if (newmem > vm->def->mem.max_balloon) {
1805 1806
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1807 1808 1809 1810 1811
            goto cleanup;
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
1812
            if (libxl_set_memory_target(priv->ctx, dom->id, newmem, 0,
1813
                                        /* force */ 1) < 0) {
1814 1815 1816
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
                                 " with libxenlight"), dom->id);
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
                goto cleanup;
            }
        }

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

1829 1830
    ret = 0;

1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

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

1843 1844 1845 1846 1847 1848
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1849 1850 1851 1852 1853
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1854
    libxl_dominfo d_info;
J
Jim Fehlig 已提交
1855 1856 1857 1858 1859 1860 1861
    int ret = -1;

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

    if (!vm) {
1862 1863
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
J
Jim Fehlig 已提交
1864 1865 1866
        goto cleanup;
    }

1867 1868 1869
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1870
        info->maxMem = vm->def->mem.max_balloon;
1871
    } else {
J
Jim Fehlig 已提交
1872
        if (libxl_domain_info(driver->ctx, &d_info, dom->id) != 0) {
1873 1874
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxl_domain_info failed for domain '%d'"), dom->id);
1875 1876 1877 1878
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1879
        info->maxMem = d_info.max_memkb;
1880 1881
    }

J
Jiri Denemark 已提交
1882
    info->state = virDomainObjGetState(vm, NULL);
J
Jim Fehlig 已提交
1883 1884 1885 1886 1887 1888 1889 1890 1891
    info->nrVirtCpu = vm->def->vcpus;
    ret = 0;

  cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
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);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

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

J
Jiri Denemark 已提交
1914
    *state = virDomainObjGetState(vm, reason);
1915 1916 1917 1918 1919 1920 1921 1922
    ret = 0;

  cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

1923 1924
/* This internal function expects the driver lock to already be held on
 * entry and the vm must be active. */
1925
static int
1926 1927
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1928
{
1929
    libxlDomainObjPrivatePtr priv = vm->privateData;
1930 1931 1932 1933 1934 1935 1936 1937
    libxlSavefileHeader hdr;
    virDomainEventPtr event = NULL;
    char *xml = NULL;
    uint32_t xml_len;
    int fd;
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1938 1939 1940
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1941 1942 1943 1944
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1945
                            -1, -1, 0)) < 0) {
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
        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)) {
1961 1962
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1963 1964 1965 1966
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1967 1968
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1969 1970 1971
        goto cleanup;
    }

J
Jim Fehlig 已提交
1972
    if (libxl_domain_suspend(priv->ctx, vm->def->id, fd, 0, NULL) != 0) {
1973 1974 1975
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1976 1977 1978 1979 1980 1981
        goto cleanup;
    }

    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

J
Jim Fehlig 已提交
1982
    if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED) != 0) {
1983 1984
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1985 1986 1987
        goto cleanup;
    }

1988 1989
    vm->hasManagedSave = true;

1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
    if (!vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

    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
2007 2008
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
2009
{
2010 2011
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
2012 2013
    int ret = -1;

2014 2015
    virCheckFlags(0, -1);
    if (dxml) {
2016 2017
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
2018 2019 2020
        return -1;
    }

2021
    libxlDriverLock(driver);
2022
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2023

2024 2025 2026
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2027 2028
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2029 2030 2031
        goto cleanup;
    }

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

2037
    ret = libxlDoDomainSave(driver, vm, to);
2038

2039 2040 2041 2042 2043 2044
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    libxlDriverUnlock(driver);
    return ret;
}
2045

2046
static int
2047 2048 2049 2050 2051 2052 2053 2054
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)
2055 2056 2057 2058 2059 2060 2061
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
2062

2063 2064
    virCheckFlags(0, -1);
    if (dxml) {
2065 2066
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
2067 2068 2069
        return -1;
    }

2070
    libxlDriverLock(driver);
2071

2072 2073
    fd = libxlSaveImageOpen(driver, from, &def, &hdr);
    if (fd < 0)
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
        goto cleanup;

    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
        goto cleanup;

    if (!(vm = virDomainAssignDef(driver->caps, &driver->domains, def, true)))
        goto cleanup;

    def = NULL;

    if ((ret = libxlVmStart(driver, vm, false, fd)) < 0 &&
        !vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

cleanup:
2091 2092
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
2093 2094 2095 2096 2097 2098 2099
    virDomainDefFree(def);
    if (vm)
        virDomainObjUnlock(vm);
    libxlDriverUnlock(driver);
    return ret;
}

2100 2101 2102 2103 2104 2105
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

2106
static int
2107
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
{
    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);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2125 2126
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2127 2128 2129 2130
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
2131
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2132 2133 2134 2135 2136 2137 2138
        goto cleanup;
    }

    priv = vm->privateData;

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
2139
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
2140 2141 2142 2143
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
                           dom->id);
2144 2145 2146 2147 2148 2149
            goto cleanup;
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

J
Jim Fehlig 已提交
2150
    if (libxl_domain_core_dump(priv->ctx, dom->id, to, NULL) != 0) {
2151 2152 2153
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
                       dom->id);
2154 2155 2156 2157 2158
        goto cleanup_unpause;
    }

    libxlDriverLock(driver);
    if (flags & VIR_DUMP_CRASH) {
J
Jim Fehlig 已提交
2159
        if (libxlVmReap(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED) != 0) {
2160 2161
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to destroy domain '%d'"), dom->id);
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
            goto cleanup_unlock;
        }

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

    if ((flags & VIR_DUMP_CRASH) && !vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

    ret = 0;

cleanup_unlock:
    libxlDriverUnlock(driver);
cleanup_unpause:
    if (virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
2180
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
2181 2182 2183
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
                             " libxenlight"), dom->id);
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    if (event) {
        libxlDriverLock(driver);
        libxlDomainEventQueue(driver, event);
        libxlDriverUnlock(driver);
    }
    return ret;
}

2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
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);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2215 2216
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2217 2218 2219 2220
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
2221
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2222 2223
        goto cleanup;
    }
2224
    if (!vm->persistent) {
2225 2226
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
2227 2228
        goto cleanup;
    }
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245

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

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

    ret = libxlDoDomainSave(driver, vm, name);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    libxlDriverUnlock(driver);
    VIR_FREE(name);
    return ret;
}

2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
static void
libxlDomainManagedSaveLoad(void *payload,
                           const void *n ATTRIBUTE_UNUSED,
                           void *opaque)
{
    virDomainObjPtr vm = payload;
    libxlDriverPrivatePtr driver = opaque;
    char *name;

    virDomainObjLock(vm);

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

    vm->hasManagedSave = virFileExists(name);

cleanup:
    virDomainObjUnlock(vm);
    VIR_FREE(name);
}

2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2281 2282
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2283 2284 2285
        goto cleanup;
    }

2286
    ret = vm->hasManagedSave;
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    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);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2310 2311
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
2312 2313 2314 2315 2316 2317 2318 2319
        goto cleanup;
    }

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

    ret = unlink(name);
2320
    vm->hasManagedSave = false;
2321 2322 2323 2324 2325 2326 2327 2328 2329

cleanup:
    VIR_FREE(name);
    if (vm)
        virDomainObjUnlock(vm);
    libxlDriverUnlock(driver);
    return ret;
}

2330 2331 2332 2333 2334 2335 2336 2337
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 已提交
2338
    libxl_bitmap map;
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
    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)) {
2354 2355
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2356 2357 2358 2359
        return -1;
    }

    if (!nvcpus) {
2360
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2361 2362 2363 2364 2365 2366 2367 2368
        return -1;
    }

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

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

    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2374 2375
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2376 2377 2378 2379
        goto cleanup;
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2380 2381
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2382 2383 2384 2385
        goto cleanup;
    }

    if ((max = libxlGetMaxVcpus(dom->conn, NULL)) < 0) {
2386 2387
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2388 2389 2390 2391 2392 2393 2394 2395
        goto cleanup;
    }

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

    if (nvcpus > max) {
2396 2397 2398
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2399 2400 2401 2402 2403 2404 2405 2406
        goto cleanup;
    }

    priv = vm->privateData;

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

E
Eric Blake 已提交
2407
    maplen = VIR_CPU_MAPLEN(nvcpus);
2408 2409 2410 2411 2412 2413
    if (VIR_ALLOC_N(bitmask, maplen) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2414
        pos = i / 8;
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
        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 已提交
2433
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2434 2435 2436
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2437 2438 2439 2440 2441
            goto cleanup;
        }
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2442
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2443 2444 2445
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
            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)
        virDomainObjUnlock(vm);
    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;
2477
    bool active;
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487

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

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

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

2492 2493 2494 2495 2496 2497 2498 2499 2500
    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)) {
2501 2502
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2503 2504 2505
        return -1;
    }

2506
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2507
        if (!active) {
2508 2509
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2510 2511 2512 2513
            goto cleanup;
        }
        def = vm->def;
    } else {
2514
        if (!vm->persistent) {
2515 2516
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2517 2518
            goto cleanup;
        }
2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537
        def = vm->newDef ? vm->newDef : vm->def;
    }

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

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    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 已提交
2538
    libxl_bitmap map;
2539 2540 2541 2542 2543 2544

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

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

    if (!virDomainObjIsActive(vm)) {
2550 2551
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot pin vcpus on an inactive domain"));
2552 2553 2554 2555 2556 2557 2558
        goto cleanup;
    }

    priv = vm->privateData;

    map.size = maplen;
    map.map = cpumap;
J
Jim Fehlig 已提交
2559
    if (libxl_set_vcpuaffinity(priv->ctx, dom->id, vcpu, &map) != 0) {
2560 2561
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
2562 2563
        goto cleanup;
    }
2564

H
Hu Tao 已提交
2565 2566 2567 2568 2569 2570 2571
    if (!vm->def->cputune.vcpupin) {
        if (VIR_ALLOC(vm->def->cputune.vcpupin) < 0) {
            virReportOOMError();
            goto cleanup;
        }
        vm->def->cputune.nvcpupin = 0;
    }
2572
    if (virDomainVcpuPinAdd(&vm->def->cputune.vcpupin,
H
Hu Tao 已提交
2573 2574 2575 2576
                            &vm->def->cputune.nvcpupin,
                            cpumap,
                            maplen,
                            vcpu) < 0) {
2577 2578
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to update or add vcpupin xml"));
2579 2580 2581 2582 2583 2584
        goto cleanup;
    }

    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        goto cleanup;

2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    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);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

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

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

    priv = vm->privateData;
J
Jim Fehlig 已提交
2622
    if ((vcpuinfo = libxl_list_vcpu(priv->ctx, dom->id, &maxcpu,
2623
                                    &hostcpus)) == NULL) {
2624 2625 2626
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
                       dom->id);
2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
        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 已提交
2649
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

J
Jim Fehlig 已提交
2661
static char *
2662
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2663 2664 2665 2666 2667
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

2668 2669
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2670 2671 2672 2673 2674
    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

    if (!vm) {
2675 2676
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
J
Jim Fehlig 已提交
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
        goto cleanup;
    }

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

  cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

2688 2689 2690
static char *
libxlDomainXMLFromNative(virConnectPtr conn, const char * nativeFormat,
                         const char * nativeConfig,
E
Eric Blake 已提交
2691
                         unsigned int flags)
2692 2693 2694 2695 2696 2697 2698
{
    libxlDriverPrivatePtr driver = conn->privateData;
    const libxl_version_info *ver_info;
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2699 2700
    virCheckFlags(0, NULL);

2701
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2702 2703
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2704 2705 2706
        goto cleanup;
    }

J
Jim Fehlig 已提交
2707
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
2708
        VIR_ERROR(_("cannot get version information from libxenlight"));
2709 2710 2711 2712 2713 2714 2715
        goto cleanup;
    }

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

    if (!(def = xenParseXM(conf, ver_info->xen_version_major, driver->caps))) {
2716
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("parsing xm config failed"));
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
        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 *
libxlDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                       const char * domainXml,
E
Eric Blake 已提交
2733
                       unsigned int flags)
2734 2735 2736 2737 2738 2739 2740 2741
{
    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 已提交
2742 2743
    virCheckFlags(0, NULL);

2744
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2745 2746
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2747 2748 2749
        goto cleanup;
    }

J
Jim Fehlig 已提交
2750
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
2751
        VIR_ERROR(_("cannot get version information from libxenlight"));
2752 2753 2754
        goto cleanup;
    }

M
Matthias Bolte 已提交
2755 2756
    if (!(def = virDomainDefParseString(driver->caps, domainXml,
                                        1 << VIR_DOMAIN_VIRT_XEN, 0)))
2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
        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 已提交
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806
static int
libxlListDefinedDomains(virConnectPtr conn,
                        char **const names, int nnames)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

    libxlDriverLock(driver);
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
    libxlDriverUnlock(driver);
    return n;
}

static int
libxlNumDefinedDomains(virConnectPtr conn)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

    libxlDriverLock(driver);
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
    libxlDriverUnlock(driver);

    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
2807
                           unsigned int flags)
J
Jim Fehlig 已提交
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2820 2821
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
2822 2823 2824 2825
        goto cleanup;
    }

    if (virDomainObjIsActive(vm)) {
2826 2827
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
J
Jim Fehlig 已提交
2828 2829 2830
        goto cleanup;
    }

2831
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0, -1);
J
Jim Fehlig 已提交
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    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;
2853
    virDomainEventPtr event = NULL;
J
Jim Fehlig 已提交
2854 2855 2856 2857
    int dupVM;

    libxlDriverLock(driver);
    if (!(def = virDomainDefParseString(driver->caps, xml,
M
Matthias Bolte 已提交
2858
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

   if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains, def, false)))
        goto cleanup;
    def = NULL;
    vm->persistent = 1;

    if (virDomainSaveConfig(driver->configDir,
                            vm->newDef ? vm->newDef : vm->def) < 0) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
        goto cleanup;
    }

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

2882 2883 2884 2885 2886
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
                                     !dupVM ?
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

J
Jim Fehlig 已提交
2887 2888 2889 2890
cleanup:
    virDomainDefFree(def);
    if (vm)
        virDomainObjUnlock(vm);
2891 2892
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
2893 2894 2895 2896 2897
    libxlDriverUnlock(driver);
    return dom;
}

static int
2898 2899
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2900 2901 2902
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
2903
    virDomainEventPtr event = NULL;
2904
    char *name = NULL;
J
Jim Fehlig 已提交
2905 2906
    int ret = -1;

2907 2908
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2909 2910 2911 2912 2913 2914 2915
    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

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

        virUUIDFormat(dom->uuid, uuidstr);
2916 2917
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s'"), uuidstr);
J
Jim Fehlig 已提交
2918 2919 2920 2921
        goto cleanup;
    }

    if (!vm->persistent) {
2922 2923
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2924 2925 2926
        goto cleanup;
    }

2927 2928 2929 2930 2931 2932 2933
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2934 2935
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2936 2937 2938
                goto cleanup;
            }
        } else {
2939 2940 2941
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2942 2943 2944 2945
            goto cleanup;
        }
    }

J
Jim Fehlig 已提交
2946 2947 2948 2949 2950
    if (virDomainDeleteConfig(driver->configDir,
                              driver->autostartDir,
                              vm) < 0)
        goto cleanup;

2951 2952 2953
    event = virDomainEventNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2954 2955 2956 2957 2958 2959 2960
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }

J
Jim Fehlig 已提交
2961 2962 2963
    ret = 0;

  cleanup:
2964
    VIR_FREE(name);
J
Jim Fehlig 已提交
2965 2966
    if (vm)
        virDomainObjUnlock(vm);
2967 2968
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
2969 2970 2971 2972
    libxlDriverUnlock(driver);
    return ret;
}

2973 2974 2975 2976 2977 2978
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996
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) {
2997 2998 2999
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
3000 3001 3002 3003
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
3004 3005 3006
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
3007 3008 3009
        return -1;
    }

J
Jim Fehlig 已提交
3010
    if (libxlMakeDisk(disk, &x_disk) < 0)
3011 3012
        goto cleanup;

J
Jim Fehlig 已提交
3013
    if ((ret = libxl_cdrom_insert(priv->ctx, vm->def->id, &x_disk, NULL)) < 0) {
3014 3015 3016
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047
        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) {
3048
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
3049 3050
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
3051 3052 3053 3054
                    goto cleanup;
                }

                if (!l_disk->src) {
3055 3056
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
3057 3058 3059 3060 3061 3062 3063 3064
                    goto cleanup;
                }

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

J
Jim Fehlig 已提交
3065
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3066 3067
                    goto cleanup;

J
Jim Fehlig 已提交
3068 3069
                if ((ret = libxl_device_disk_add(priv->ctx, vm->def->id,
                                                &x_disk, NULL)) < 0) {
3070 3071 3072
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
3073 3074 3075 3076 3077 3078
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
3079 3080 3081
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
3082 3083 3084
            }
            break;
        default:
3085 3086 3087
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108
            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,
3109 3110
                                                  dev->data.disk->dst,
                                                  false)) < 0) {
3111 3112
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3113 3114 3115 3116 3117
                    goto cleanup;
                }

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

J
Jim Fehlig 已提交
3118
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3119 3120
                    goto cleanup;

J
Jim Fehlig 已提交
3121 3122
                if ((ret = libxl_device_disk_remove(priv->ctx, vm->def->id,
                                                    &x_disk, NULL)) < 0) {
3123 3124 3125
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3126 3127 3128 3129 3130 3131 3132
                    goto cleanup;
                }

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

            } else {
3133 3134 3135
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3136 3137 3138
            }
            break;
        default:
3139 3140 3141
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
            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:
3163 3164 3165
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179
            break;
    }

    return ret;
}

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

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3180
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3181 3182
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
                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:
3194 3195
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
            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:
3213 3214 3215
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3216 3217 3218 3219 3220 3221 3222 3223 3224
            break;
    }

    return ret;
}

static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3225
    virDomainDiskDefPtr disk, detach;
3226 3227 3228 3229 3230
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3231
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3232 3233
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3234 3235
                break;
            }
3236
            virDomainDiskDefFree(detach);
3237 3238 3239
            ret = 0;
            break;
        default:
3240 3241
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264
            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:
3265 3266 3267
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3268 3269 3270 3271
                    break;
            }
            break;
        default:
3272 3273 3274
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291
            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;
3292
            if ((i = virDomainDiskIndexByName(vmdef, disk->dst, false)) < 0) {
3293 3294
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3295 3296 3297 3298
                goto cleanup;
            }
            orig = vmdef->disks[i];
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3299 3300
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311
                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;
            }
3312
            orig->format = disk->format;
3313 3314 3315
            disk->src = NULL;
            break;
        default:
3316 3317
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
            goto cleanup;
    }

    ret = 0;

cleanup:
    return ret;
}

/* Actions for libxlDomainModifyDeviceFlags */
enum {
    LIBXL_DEVICE_ATTACH,
    LIBXL_DEVICE_DETACH,
    LIBXL_DEVICE_UPDATE,
};

static int
libxlDomainModifyDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags, int action)
{
    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 = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
3352
        virReportError(VIR_ERR_NO_DOMAIN, "%s", _("no domain with matching uuid"));
3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
        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) {
3364 3365
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3366 3367 3368 3369 3370
            goto cleanup;
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
3371 3372
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396
         goto cleanup;
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

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

        switch (action) {
            case LIBXL_DEVICE_ATTACH:
                ret = libxlDomainAttachDeviceConfig(vmdef, dev);
                break;
            case LIBXL_DEVICE_DETACH:
                ret = libxlDomainDetachDeviceConfig(vmdef, dev);
                break;
            case LIBXL_DEVICE_UPDATE:
                ret = libxlDomainUpdateDeviceConfig(vmdef, dev);
            default:
3397 3398
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown domain modify action %d"), action);
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420
                break;
        }
    } 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(driver->caps, vm->def, xml,
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        switch (action) {
            case LIBXL_DEVICE_ATTACH:
                ret = libxlDomainAttachDeviceLive(priv, vm, dev);
                break;
            case LIBXL_DEVICE_DETACH:
                ret = libxlDomainDetachDeviceLive(priv, vm, dev);
                break;
            case LIBXL_DEVICE_UPDATE:
                ret = libxlDomainUpdateDeviceLive(priv, vm, dev);
            default:
3421 3422
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unknown domain modify action %d"), action);
3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485
                break;
        }
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
        if (virDomainSaveStatus(driver->caps, 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);
            vmdef = NULL;
        }
    }

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

static int
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
{
    return libxlDomainModifyDeviceFlags(dom, xml, flags, LIBXL_DEVICE_ATTACH);
}

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)
{
    return libxlDomainModifyDeviceFlags(dom, xml, flags, LIBXL_DEVICE_DETACH);
}

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)
{
    return libxlDomainModifyDeviceFlags(dom, xml, flags, LIBXL_DEVICE_UPDATE);
}

3486 3487 3488 3489 3490 3491 3492
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    const libxl_version_info* ver_info;
    libxlDriverPrivatePtr driver = conn->privateData;

J
Jim Fehlig 已提交
3493
    if (libxl_get_physinfo(driver->ctx, &phy_info)) {
3494 3495
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3496 3497 3498
        return 0;
    }

J
Jim Fehlig 已提交
3499
    if ((ver_info = libxl_get_version_info(driver->ctx)) == NULL) {
3500 3501
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_version_info failed"));
3502 3503 3504 3505 3506 3507
        return 0;
    }

    return phy_info.free_pages * ver_info->pagesize;
}

3508 3509 3510 3511 3512 3513 3514 3515 3516
static int
libxlDomainEventRegister(virConnectPtr conn,
                         virConnectDomainEventCallback callback, void *opaque,
                         virFreeCallback freecb)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

    libxlDriverLock(driver);
3517 3518 3519
    ret = virDomainEventStateRegister(conn,
                                      driver->domainEventState,
                                      callback, opaque, freecb);
3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
    libxlDriverUnlock(driver);

    return ret;
}


static int
libxlDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

    libxlDriverLock(driver);
3534 3535 3536
    ret = virDomainEventStateDeregister(conn,
                                        driver->domainEventState,
                                        callback);
3537 3538 3539 3540 3541
    libxlDriverUnlock(driver);

    return ret;
}

3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3556 3557
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583
        goto cleanup;
    }

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

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    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);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3584 3585
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("No domain with matching uuid '%s'"), uuidstr);
3586 3587 3588 3589
        goto cleanup;
    }

    if (!vm->persistent) {
3590 3591
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603
        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) {
3604 3605
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638
                                     _("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)
        virDomainObjUnlock(vm);
    libxlDriverUnlock(driver);
    return ret;
}

3639 3640 3641 3642 3643 3644 3645
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    char * ret = NULL;
J
Jim Fehlig 已提交
3646
    libxl_scheduler sched_id;
3647 3648 3649 3650 3651 3652

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

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

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

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

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

    if (!ret)
        virReportOOMError();

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

3698
static int
3699 3700 3701 3702
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
3703 3704 3705 3706
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3707 3708
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
3709 3710
    int ret = -1;

3711 3712
    virCheckFlags(0, -1);

3713 3714 3715 3716 3717
    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

    if (!vm) {
J
Jim Fehlig 已提交
3718 3719
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
3720 3721 3722 3723
        goto cleanup;
    }

    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
3724 3725
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
3726 3727 3728 3729 3730
        goto cleanup;
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
3733
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3734 3735
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3736 3737 3738
        goto cleanup;
    }

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

3746 3747
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
3748 3749
        goto cleanup;

3750
    if (*nparams > 1) {
3751 3752
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
3753
            goto cleanup;
3754 3755
    }

3756 3757
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
3758 3759 3760 3761 3762 3763 3764 3765 3766
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

static int
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777
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)
3778 3779 3780 3781
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3782
    libxl_domain_sched_params sc_info;
3783 3784 3785 3786
    int sched_id;
    int i;
    int ret = -1;

3787
    virCheckFlags(0, -1);
3788 3789 3790 3791 3792 3793 3794
    if (virTypedParameterArrayValidate(params, nparams,
                                       VIR_DOMAIN_SCHEDULER_WEIGHT,
                                       VIR_TYPED_PARAM_UINT,
                                       VIR_DOMAIN_SCHEDULER_CAP,
                                       VIR_TYPED_PARAM_UINT,
                                       NULL) < 0)
        return -1;
3795

3796 3797 3798 3799 3800
    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);

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

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

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
3814
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3815 3816
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3817 3818 3819
        goto cleanup;
    }

J
Jim Fehlig 已提交
3820
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
3821 3822 3823
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3824 3825 3826 3827
        goto cleanup;
    }

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

3830
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT)) {
3831
            sc_info.weight = params[i].value.ui;
3832
        } else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP)) {
3833 3834 3835 3836
            sc_info.cap = params[i].value.ui;
        }
    }

J
Jim Fehlig 已提交
3837
    if (libxl_domain_sched_params_set(priv->ctx, dom->id, &sc_info) != 0) {
3838 3839 3840
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

3852 3853 3854 3855 3856 3857 3858
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

J
Jim Fehlig 已提交
3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
static int
libxlDomainIsActive(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    libxlDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);
    if (!obj) {
3870
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
        goto cleanup;
    }
    ret = virDomainObjIsActive(obj);

  cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}

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

    libxlDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);
    if (!obj) {
3892
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
3893 3894 3895 3896 3897 3898 3899 3900 3901 3902
        goto cleanup;
    }
    ret = obj->persistent;

  cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}

3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    libxlDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    libxlDriverUnlock(driver);
    if (!vm) {
3914
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
3915 3916 3917 3918 3919 3920 3921 3922 3923 3924
        goto cleanup;
    }
    ret = vm->updated;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

3925 3926 3927 3928 3929 3930 3931 3932 3933
static int
libxlDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                            virConnectDomainEventGenericCallback callback,
                            void *opaque, virFreeCallback freecb)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

    libxlDriverLock(driver);
3934 3935 3936 3937
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
3938
        ret = -1;
3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951
    libxlDriverUnlock(driver);

    return ret;
}


static int
libxlDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

    libxlDriverLock(driver);
3952 3953 3954
    ret = virDomainEventStateDeregisterID(conn,
                                          driver->domainEventState,
                                          callbackID);
3955 3956 3957 3958 3959
    libxlDriverUnlock(driver);

    return ret;
}

J
Jim Fehlig 已提交
3960

3961 3962 3963 3964 3965 3966
static int
libxlIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return 1;
}

3967 3968 3969 3970 3971 3972 3973 3974
static int
libxlListAllDomains(virConnectPtr conn,
                    virDomainPtr **domains,
                    unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
3975
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
3976 3977 3978 3979 3980 3981 3982 3983 3984

    libxlDriverLock(driver);
    ret = virDomainList(conn, driver->domains.objs, domains, flags);
    libxlDriverUnlock(driver);

    return ret;
}


3985

J
Jim Fehlig 已提交
3986
static virDriver libxlDriver = {
3987 3988
    .no = VIR_DRV_LIBXL,
    .name = "xenlight",
3989 3990 3991 3992 3993 3994 3995 3996 3997 3998
    .open = libxlOpen, /* 0.9.0 */
    .close = libxlClose, /* 0.9.0 */
    .type = libxlGetType, /* 0.9.0 */
    .version = libxlGetVersion, /* 0.9.0 */
    .getHostname = virGetHostname, /* 0.9.0 */
    .getMaxVcpus = libxlGetMaxVcpus, /* 0.9.0 */
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
    .getCapabilities = libxlGetCapabilities, /* 0.9.0 */
    .listDomains = libxlListDomains, /* 0.9.0 */
    .numOfDomains = libxlNumDomains, /* 0.9.0 */
3999
    .listAllDomains = libxlListAllDomains, /* 0.9.13 */
4000 4001 4002 4003 4004 4005 4006
    .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 */
4007
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
4008 4009
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
4010
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
4011 4012
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
4013
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
4014 4015 4016 4017
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
4018
    .domainSave = libxlDomainSave, /* 0.9.2 */
4019
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
4020
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
4021
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
4022
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036
    .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 */
    .domainXMLFromNative = libxlDomainXMLFromNative, /* 0.9.0 */
    .domainXMLToNative = libxlDomainXMLToNative, /* 0.9.0 */
    .listDefinedDomains = libxlListDefinedDomains, /* 0.9.0 */
    .numOfDefinedDomains = libxlNumDefinedDomains, /* 0.9.0 */
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
4037
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
4038 4039 4040 4041 4042
    .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 */
4043 4044 4045 4046
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
4047
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
4048
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
4049
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
4050 4051 4052
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
    .domainEventRegister = libxlDomainEventRegister, /* 0.9.0 */
    .domainEventDeregister = libxlDomainEventDeregister, /* 0.9.0 */
4053 4054 4055
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
4056 4057 4058 4059 4060
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
    .domainEventRegisterAny = libxlDomainEventRegisterAny, /* 0.9.0 */
    .domainEventDeregisterAny = libxlDomainEventDeregisterAny, /* 0.9.0 */
4061
    .isAlive = libxlIsAlive, /* 0.9.8 */
J
Jim Fehlig 已提交
4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081
};

static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
    .initialize = libxlStartup,
    .cleanup = libxlShutdown,
    .reload = libxlReload,
};


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

    return 0;
}