libxl_driver.c 161.4 KB
Newer Older
1 2 3
/*
 * libxl_driver.c: core driver methods for managing libxenlight domains
 *
4
 * Copyright (C) 2006-2015 Red Hat, Inc.
5
 * Copyright (C) 2011-2015 SUSE LINUX Products GmbH, Nuernberg, Germany.
6
 * Copyright (C) 2011 Univention GmbH.
J
Jim Fehlig 已提交
7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with this library.  If not, see
O
Osier Yang 已提交
20
 * <http://www.gnu.org/licenses/>.
M
Markus Groß 已提交
21 22 23 24 25
 *
 * Authors:
 *     Jim Fehlig <jfehlig@novell.com>
 *     Markus Groß <gross@univention.de>
 *     Daniel P. Berrange <berrange@redhat.com>
J
Jim Fehlig 已提交
26 27 28 29
 */

#include <config.h>

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

#include "internal.h"
37
#include "virlog.h"
38
#include "virerror.h"
39
#include "virconf.h"
J
Jim Fehlig 已提交
40
#include "datatypes.h"
E
Eric Blake 已提交
41
#include "virfile.h"
42
#include "viralloc.h"
43
#include "viruuid.h"
44
#include "vircommand.h"
J
Jim Fehlig 已提交
45
#include "libxl_domain.h"
J
Jim Fehlig 已提交
46 47
#include "libxl_driver.h"
#include "libxl_conf.h"
J
Jim Fehlig 已提交
48
#include "libxl_migration.h"
49
#include "xen_xm.h"
50
#include "xen_sxpr.h"
51
#include "xen_xl.h"
52
#include "virtypedparam.h"
M
Martin Kletzander 已提交
53
#include "viruri.h"
54
#include "virstring.h"
55
#include "virsysinfo.h"
56
#include "viraccessapicheck.h"
57
#include "viratomic.h"
58
#include "virhostdev.h"
59
#include "network/bridge_driver.h"
60
#include "locking/domain_lock.h"
61
#include "virstats.h"
J
Jim Fehlig 已提交
62 63 64

#define VIR_FROM_THIS VIR_FROM_LIBXL

65 66
VIR_LOG_INIT("libxl.libxl_driver");

J
Jim Fehlig 已提交
67 68 69 70 71 72
#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

73
#define LIBXL_CONFIG_FORMAT_XL "xen-xl"
74
#define LIBXL_CONFIG_FORMAT_XM "xen-xm"
75
#define LIBXL_CONFIG_FORMAT_SEXPR "xen-sxpr"
76

77 78
#define LIBXL_NB_TOTAL_CPU_STAT_PARAM 1

79
#define HYPERVISOR_CAPABILITIES "/proc/xen/capabilities"
R
Roman Bogorodskiy 已提交
80
#define HYPERVISOR_XENSTORED "/dev/xen/xenstored"
81

82 83 84
/* Number of Xen scheduler parameters */
#define XEN_SCHED_CREDIT_NPARAM   2

J
Jim Fehlig 已提交
85 86 87 88 89 90 91 92 93
#define LIBXL_CHECK_DOM0_GOTO(name, label)                               \
    do {                                                                  \
        if (STREQ_NULLABLE(name, "Domain-0")) {                           \
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",               \
                           _("Domain-0 does not support requested operation")); \
            goto label;                                                   \
        }                                                                 \
    } while (0)

94

95
static libxlDriverPrivatePtr libxl_driver;
J
Jim Fehlig 已提交
96

97 98 99 100 101 102 103 104 105
/* Object used to store info related to libxl event registrations */
typedef struct _libxlOSEventHookInfo libxlOSEventHookInfo;
typedef libxlOSEventHookInfo *libxlOSEventHookInfoPtr;
struct _libxlOSEventHookInfo {
    libxl_ctx *ctx;
    void *xl_priv;
    int id;
};

J
Jim Fehlig 已提交
106
/* Function declarations */
107 108
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
109 110
                           void *opaque);

J
Jim Fehlig 已提交
111 112

/* Function definitions */
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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
static void
libxlOSEventHookInfoFree(void *obj)
{
    VIR_FREE(obj);
}

static void
libxlFDEventCallback(int watch ATTRIBUTE_UNUSED,
                     int fd,
                     int vir_events,
                     void *fd_info)
{
    libxlOSEventHookInfoPtr info = fd_info;
    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->ctx, info->xl_priv, fd, 0, events);
}

static int
libxlFDRegisterEventHook(void *priv,
                         int fd,
                         void **hndp,
                         short events,
                         void *xl_priv)
{
    int vir_events = VIR_EVENT_HANDLE_ERROR;
    libxlOSEventHookInfoPtr info;

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

    info->ctx = priv;
    info->xl_priv = xl_priv;

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

    info->id = virEventAddHandle(fd, vir_events, libxlFDEventCallback,
                                 info, libxlOSEventHookInfoFree);
    if (info->id < 0) {
        VIR_FREE(info);
        return -1;
    }

    *hndp = info;

    return 0;
}

static int
libxlFDModifyEventHook(void *priv ATTRIBUTE_UNUSED,
                       int fd ATTRIBUTE_UNUSED,
                       void **hndp,
                       short events)
{
    libxlOSEventHookInfoPtr info = *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(info->id, vir_events);

    return 0;
}

static void
libxlFDDeregisterEventHook(void *priv ATTRIBUTE_UNUSED,
                           int fd ATTRIBUTE_UNUSED,
                           void *hnd)
{
    libxlOSEventHookInfoPtr info = hnd;

    virEventRemoveHandle(info->id);
}

static void
libxlTimerCallback(int timer ATTRIBUTE_UNUSED, void *timer_info)
{
    libxlOSEventHookInfoPtr info = timer_info;

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

static int
libxlTimeoutRegisterEventHook(void *priv,
                              void **hndp,
                              struct timeval abs_t,
                              void *xl_priv)
{
    libxlOSEventHookInfoPtr info;
    struct timeval now;
    struct timeval res;
    static struct timeval zero;
    int timeout;

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

    info->ctx = priv;
    info->xl_priv = xl_priv;

    gettimeofday(&now, NULL);
    timersub(&abs_t, &now, &res);
    /* Ensure timeout is not overflowed */
    if (timercmp(&res, &zero, <)) {
        timeout = 0;
    } else if (res.tv_sec > INT_MAX / 1000) {
        timeout = INT_MAX;
    } else {
        timeout = res.tv_sec * 1000 + (res.tv_usec + 999) / 1000;
    }
    info->id = virEventAddTimeout(timeout, libxlTimerCallback,
                                  info, libxlOSEventHookInfoFree);
    if (info->id < 0) {
        VIR_FREE(info);
        return -1;
    }

    *hndp = info;

    return 0;
}

/*
 * Note:  There are two changes wrt timeouts starting with xen-unstable
 * changeset 26469:
 *
 * 1. Timeout modify callbacks will only be invoked with an abs_t of {0,0},
 * i.e. make the timeout fire immediately.  Prior to this commit, timeout
 * modify callbacks were never invoked.
 *
 * 2. Timeout deregister hooks will no longer be called.
 */
static int
libxlTimeoutModifyEventHook(void *priv ATTRIBUTE_UNUSED,
                            void **hndp,
                            struct timeval abs_t ATTRIBUTE_UNUSED)
{
    libxlOSEventHookInfoPtr info = *hndp;

    /* Make the timeout fire */
    virEventUpdateTimeout(info->id, 0);

    return 0;
}

static void
libxlTimeoutDeregisterEventHook(void *priv ATTRIBUTE_UNUSED,
                                void *hnd)
{
    libxlOSEventHookInfoPtr info = hnd;

    virEventRemoveTimeout(info->id);
}

J
Jim Fehlig 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
static virDomainObjPtr
libxlDomObjFromDomain(virDomainPtr dom)
{
    virDomainObjPtr vm;
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
    if (!vm) {
        virUUIDFormat(dom->uuid, uuidstr);
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching uuid '%s' (%s)"),
                       uuidstr, dom->name);
        return NULL;
    }

    return vm;
}

309 310
static int
libxlAutostartDomain(virDomainObjPtr vm,
311 312 313 314
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    virErrorPtr err;
315
    int ret = -1;
316

317
    virObjectLock(vm);
318 319
    virResetLastError();

320 321 322 323 324
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
        virObjectUnlock(vm);
        return ret;
    }

325
    if (vm->autostart && !virDomainObjIsActive(vm) &&
326
        libxlDomainStart(driver, vm, false, -1) < 0) {
327 328 329 330
        err = virGetLastError();
        VIR_ERROR(_("Failed to autostart VM '%s': %s"),
                  vm->def->name,
                  err ? err->message : _("unknown error"));
331
        goto endjob;
332 333
    }

334
    ret = 0;
335 336 337 338 339

 endjob:
    if (libxlDomainObjEndJob(driver, vm))
        virObjectUnlock(vm);

340
    return ret;
341 342
}

J
Jim Fehlig 已提交
343 344 345 346
/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
347 348
static int
libxlReconnectDomain(virDomainObjPtr vm,
J
Jim Fehlig 已提交
349 350 351
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
352
    libxlDomainObjPrivatePtr priv = vm->privateData;
J
Jim Fehlig 已提交
353
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
354 355 356 357
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;
358
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
J
Jim Fehlig 已提交
359

360
    virObjectLock(vm);
J
Jim Fehlig 已提交
361

362 363
    libxl_dominfo_init(&d_info);

J
Jim Fehlig 已提交
364
    /* Does domain still exist? */
J
Jim Fehlig 已提交
365
    rc = libxl_domain_info(cfg->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
366 367 368 369 370 371 372 373 374
    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 已提交
375
    if (libxl_userdata_retrieve(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
376 377 378 379 380 381 382
                                "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;
383 384

    /* Update hostdev state */
385
    if (virHostdevUpdateActiveDomainDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
386 387 388
                                            vm->def, VIR_HOSTDEV_SP_PCI) < 0)
        goto out;

389
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
390 391
        driver->inhibitCallback(true, driver->inhibitOpaque);

392
    /* Enable domain death events */
J
Jim Fehlig 已提交
393
    libxl_evenable_domain_death(cfg->ctx, vm->def->id, 0, &priv->deathW);
394

395
    libxl_dominfo_dispose(&d_info);
396
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
397
    virObjectUnref(cfg);
398
    return 0;
J
Jim Fehlig 已提交
399

400
 out:
401
    libxl_dominfo_dispose(&d_info);
402
    libxlDomainCleanup(driver, vm);
J
Jim Fehlig 已提交
403
    if (!vm->persistent)
404
        virDomainObjListRemoveLocked(driver->domains, vm);
J
Jim Fehlig 已提交
405
    else
406
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
407
    virObjectUnref(cfg);
408 409

    return -1;
J
Jim Fehlig 已提交
410 411 412 413 414
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
415
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
416 417 418
}

static int
419
libxlStateCleanup(void)
J
Jim Fehlig 已提交
420 421 422 423
{
    if (!libxl_driver)
        return -1;

424
    virObjectUnref(libxl_driver->hostdevMgr);
425
    virObjectUnref(libxl_driver->config);
426
    virObjectUnref(libxl_driver->xmlopt);
427
    virObjectUnref(libxl_driver->domains);
428
    virObjectUnref(libxl_driver->reservedGraphicsPorts);
J
Jim Fehlig 已提交
429
    virObjectUnref(libxl_driver->migrationPorts);
430
    virLockManagerPluginUnref(libxl_driver->lockManager);
J
Jim Fehlig 已提交
431

432
    virObjectEventStateFree(libxl_driver->domainEventState);
433
    virSysinfoDefFree(libxl_driver->hostsysinfo);
434

J
Jim Fehlig 已提交
435 436 437 438 439 440
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

441 442
static bool
libxlDriverShouldLoad(bool privileged)
443
{
444
    bool ret = false;
J
Jim Fehlig 已提交
445

446
    /* Don't load if non-root */
J
Jim Fehlig 已提交
447
    if (!privileged) {
448
        VIR_INFO("Not running privileged, disabling libxenlight driver");
449
        return ret;
J
Jim Fehlig 已提交
450 451
    }

R
Roman Bogorodskiy 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    if (virFileExists(HYPERVISOR_CAPABILITIES)) {
        int status;
        char *output = NULL;
        /*
         * Don't load if not running on a Xen control domain (dom0). It is not
         * sufficient to check for the file to exist as any guest can mount
         * xenfs to /proc/xen.
         */
        status = virFileReadAll(HYPERVISOR_CAPABILITIES, 10, &output);
        if (status >= 0)
            status = strncmp(output, "control_d", 9);
        VIR_FREE(output);
        if (status) {
            VIR_INFO("No Xen capabilities detected, probably not running "
                     "in a Xen Dom0.  Disabling libxenlight driver");

            return ret;
        }
    } else if (!virFileExists(HYPERVISOR_XENSTORED)) {
        VIR_INFO("Disabling driver as neither " HYPERVISOR_CAPABILITIES
                 " nor " HYPERVISOR_XENSTORED " exist");
473 474 475 476
        return ret;
    }

    /* Don't load if legacy xen toolstack (xend) is in use */
477 478 479 480 481 482 483 484 485 486 487
    if (virFileExists("/usr/sbin/xend")) {
        virCommandPtr cmd;

        cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL);
        if (virCommandRun(cmd, NULL) == 0) {
            VIR_INFO("Legacy xen tool stack seems to be in use, disabling "
                     "libxenlight driver.");
        } else {
            ret = true;
        }
        virCommandFree(cmd);
488 489
    } else {
        ret = true;
J
Jim Fehlig 已提交
490 491
    }

492 493 494
    return ret;
}

495 496 497 498 499 500 501 502 503 504
/* Callbacks wrapping libvirt's event loop interface */
static const libxl_osevent_hooks libxl_osevent_callbacks = {
    .fd_register = libxlFDRegisterEventHook,
    .fd_modify = libxlFDModifyEventHook,
    .fd_deregister = libxlFDDeregisterEventHook,
    .timeout_register = libxlTimeoutRegisterEventHook,
    .timeout_modify = libxlTimeoutModifyEventHook,
    .timeout_deregister = libxlTimeoutDeregisterEventHook,
};

505 506 507 508 509 510 511 512
static const libxl_childproc_hooks libxl_child_hooks = {
#ifdef LIBXL_HAVE_SIGCHLD_OWNER_SELECTIVE_REAP
    .chldowner = libxl_sigchld_owner_libxl_always_selective_reap,
#else
    .chldowner = libxl_sigchld_owner_libxl,
#endif
};

513 514 515 516 517 518
const struct libxl_event_hooks ev_hooks = {
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlDomainEventHandler,
    .disaster = NULL,
};

J
Jim Fehlig 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
static int
libxlAddDom0(libxlDriverPrivatePtr driver)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainDefPtr oldDef = NULL;
    libxl_dominfo d_info;
    int ret = -1;

    libxl_dominfo_init(&d_info);

    /* Ensure we have a dom0 */
    if (libxl_domain_info(cfg->ctx, &d_info, 0) != 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("unable to get Domain-0 information from libxenlight"));
        goto cleanup;
    }

    if (!(def = virDomainDefNew()))
        goto cleanup;

    def->id = 0;
    def->virtType = VIR_DOMAIN_VIRT_XEN;
    if (VIR_STRDUP(def->name, "Domain-0") < 0)
        goto cleanup;

    def->os.type = VIR_DOMAIN_OSTYPE_XEN;

    if (virUUIDParse("00000000-0000-0000-0000-000000000000", def->uuid) < 0)
        goto cleanup;

    if (!(vm = virDomainObjListAdd(driver->domains, def,
                                   driver->xmlopt,
                                   0,
                                   &oldDef)))
        goto cleanup;

    def = NULL;

J
Jim Fehlig 已提交
559
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
560 561 562
    if (virDomainDefSetVcpusMax(vm->def, d_info.vcpu_max_id + 1))
        goto cleanup;

563 564
    if (virDomainDefSetVcpus(vm->def, d_info.vcpu_online) < 0)
        goto cleanup;
J
Jim Fehlig 已提交
565
    vm->def->mem.cur_balloon = d_info.current_memkb;
566
    virDomainDefSetMemoryTotal(vm->def, d_info.max_memkb);
J
Jim Fehlig 已提交
567 568 569 570 571 572 573 574 575 576 577 578 579

    ret = 0;

 cleanup:
    libxl_dominfo_dispose(&d_info);
    virDomainDefFree(def);
    virDomainDefFree(oldDef);
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(cfg);
    return ret;
}

580 581 582 583 584
static int
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
585
    libxlDriverConfigPtr cfg;
586
    char *driverConf = NULL;
587 588 589 590 591
    char ebuf[1024];

    if (!libxlDriverShouldLoad(privileged))
        return 0;

J
Jim Fehlig 已提交
592 593 594 595
    if (VIR_ALLOC(libxl_driver) < 0)
        return -1;

    if (virMutexInit(&libxl_driver->lock) < 0) {
596 597
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
J
Jim Fehlig 已提交
598 599 600 601 602
        VIR_FREE(libxl_driver);
        return -1;
    }

    /* Allocate bitmap for vnc port reservation */
603
    if (!(libxl_driver->reservedGraphicsPorts =
J
Ján Tomko 已提交
604 605
          virPortAllocatorNew(_("VNC"),
                              LIBXL_VNC_PORT_MIN,
606 607
                              LIBXL_VNC_PORT_MAX,
                              0)))
608
        goto error;
J
Jim Fehlig 已提交
609

J
Jim Fehlig 已提交
610 611 612 613
    /* Allocate bitmap for migration port reservation */
    if (!(libxl_driver->migrationPorts =
          virPortAllocatorNew(_("migration"),
                              LIBXL_MIGRATION_PORT_MIN,
614
                              LIBXL_MIGRATION_PORT_MAX, 0)))
J
Jim Fehlig 已提交
615 616
        goto error;

617 618
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
619

620 621 622
    if (!(libxl_driver->hostdevMgr = virHostdevManagerGetDefault()))
        goto error;

623
    if (!(cfg = libxlDriverConfigNew()))
624
        goto error;
J
Jim Fehlig 已提交
625

626 627 628 629 630 631 632
    if (virAsprintf(&driverConf, "%s/libxl.conf", cfg->configBaseDir) < 0)
        goto error;

    if (libxlDriverConfigLoadFile(cfg, driverConf) < 0)
        goto error;
    VIR_FREE(driverConf);

633 634 635
    /* Register the callbacks providing access to libvirt's event loop */
    libxl_osevent_register_hooks(cfg->ctx, &libxl_osevent_callbacks, cfg->ctx);

636 637 638
    /* Setup child process handling.  See $xen-src/tools/libxl/libxl_event.h */
    libxl_childproc_setmode(cfg->ctx, &libxl_child_hooks, cfg->ctx);

639 640 641
    /* Register callback to handle domain events */
    libxl_event_register_callbacks(cfg->ctx, &ev_hooks, libxl_driver);

642 643
    libxl_driver->config = cfg;
    if (virFileMakePath(cfg->stateDir) < 0) {
644 645
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create state dir '%s': %s"),
646
                       cfg->stateDir,
647
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
648 649
        goto error;
    }
650
    if (virFileMakePath(cfg->libDir) < 0) {
651 652
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create lib dir '%s': %s"),
653
                       cfg->libDir,
654
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
655 656
        goto error;
    }
657
    if (virFileMakePath(cfg->saveDir) < 0) {
658 659
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create save dir '%s': %s"),
660
                       cfg->saveDir,
661
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
662 663
        goto error;
    }
664 665 666 667 668 669 670
    if (virFileMakePath(cfg->autoDumpDir) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create dump dir '%s': %s"),
                       cfg->autoDumpDir,
                       virStrerror(errno, ebuf, sizeof(ebuf)));
        goto error;
    }
J
Jim Fehlig 已提交
671

672 673 674 675 676 677 678 679
    if (!(libxl_driver->lockManager =
          virLockManagerPluginNew(cfg->lockManagerName ?
                                  cfg->lockManagerName : "nop",
                                  "libxl",
                                  cfg->configBaseDir,
                                  0)))
        goto error;

680
    /* read the host sysinfo */
681
    libxl_driver->hostsysinfo = virSysinfoRead();
682

683
    libxl_driver->domainEventState = virObjectEventStateNew();
E
Eric Blake 已提交
684
    if (!libxl_driver->domainEventState)
685 686
        goto error;

687
    if ((cfg->caps = libxlMakeCapabilities(cfg->ctx)) == NULL) {
688 689
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
690 691 692
        goto error;
    }

693
    if (!(libxl_driver->xmlopt = libxlCreateXMLConf()))
694
        goto error;
J
Jim Fehlig 已提交
695

J
Jim Fehlig 已提交
696 697 698 699
    /* Add Domain-0 */
    if (libxlAddDom0(libxl_driver) < 0)
        goto error;

J
Jim Fehlig 已提交
700
    /* Load running domains first. */
701
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
702 703
                                       cfg->stateDir,
                                       cfg->autostartDir,
704
                                       1,
705
                                       cfg->caps,
706
                                       libxl_driver->xmlopt,
707
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
708 709 710 711 712
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
713
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
714 715
                                       cfg->configDir,
                                       cfg->autostartDir,
716
                                       0,
717
                                       cfg->caps,
718
                                       libxl_driver->xmlopt,
719
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
720 721
        goto error;

722 723
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
724

J
Jim Fehlig 已提交
725 726
    return 0;

727
 error:
728
    VIR_FREE(driverConf);
729
    libxlStateCleanup();
730
    return -1;
J
Jim Fehlig 已提交
731 732
}

733 734 735 736 737 738 739 740 741 742
static void
libxlStateAutoStart(void)
{
    if (!libxl_driver)
        return;

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

J
Jim Fehlig 已提交
743
static int
744
libxlStateReload(void)
J
Jim Fehlig 已提交
745
{
746 747
    libxlDriverConfigPtr cfg;

J
Jim Fehlig 已提交
748 749 750
    if (!libxl_driver)
        return 0;

751 752
    cfg = libxlDriverConfigGet(libxl_driver);

753
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
754 755
                                   cfg->configDir,
                                   cfg->autostartDir,
756
                                   1,
757
                                   cfg->caps,
758
                                   libxl_driver->xmlopt,
759 760
                                   NULL, libxl_driver);

761 762
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
763

764
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
765 766 767 768 769
    return 0;
}


static virDrvOpenStatus
770 771 772
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 unsigned int flags)
J
Jim Fehlig 已提交
773
{
E
Eric Blake 已提交
774 775
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
776 777 778 779
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

780
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
781 782 783 784 785 786 787 788 789 790 791 792
            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) {
793 794
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
795 796 797 798 799 800 801 802
            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")) {
803 804 805
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
806 807 808 809
            return VIR_DRV_OPEN_ERROR;
        }
    }

810 811 812
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
813 814 815 816 817 818
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
819
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
820 821 822 823 824 825
{
    conn->privateData = NULL;
    return 0;
}

static const char *
826
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
827
{
828 829 830
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
831
    return "Xen";
J
Jim Fehlig 已提交
832 833 834
}

static int
835
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
836 837
{
    libxlDriverPrivatePtr driver = conn->privateData;
838
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
839

840 841 842
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

843 844 845
    cfg = libxlDriverConfigGet(driver);
    *version = cfg->version;
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
846 847 848
    return 0;
}

849

850
static char *libxlConnectGetHostname(virConnectPtr conn)
851
{
852 853 854
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

855 856 857
    return virGetHostname();
}

858 859 860 861 862 863 864 865
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

866 867 868
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

869 870 871 872 873 874 875 876
    if (!driver->hostsysinfo) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Host SMBIOS information is not available"));
        return NULL;
    }

    if (virSysinfoFormat(&buf, driver->hostsysinfo) < 0)
        return NULL;
877
    if (virBufferCheckError(&buf) < 0)
878 879 880
        return NULL;
    return virBufferContentAndReset(&buf);
}
881

J
Jim Fehlig 已提交
882
static int
883
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
884 885 886
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;
887
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
888

889 890 891
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

892 893
    cfg = libxlDriverConfigGet(driver);
    ret = libxl_get_max_cpus(cfg->ctx);
894 895 896 897 898
    /* On failure, libxl_get_max_cpus() will return ERROR_FAIL from Xen 4.4
     * onward, but it ever returning 0 is obviously wrong too (and it is
     * what happens, on failure, on Xen 4.3 and earlier). Therefore, a 'less
     * or equal' is the catchall we want. */
    if (ret <= 0)
899
        ret = -1;
J
Jim Fehlig 已提交
900

901
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
902 903 904 905 906 907
    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
908 909 910
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

911
    return libxlDriverNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
912 913 914
}

static char *
915
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
916 917 918
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;
919
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
920

921 922 923
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

924
    cfg = libxlDriverConfigGet(driver);
925
    xml = virCapabilitiesFormatXML(cfg->caps);
J
Jim Fehlig 已提交
926

927
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
928 929 930 931
    return xml;
}

static int
932
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
933 934 935 936
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

937 938 939
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

940 941
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
942 943 944 945 946

    return n;
}

static int
947
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
948 949 950 951
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

952 953 954
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

955 956
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
957 958 959 960 961 962 963 964 965 966 967 968

    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;
969
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
970
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
J
Jim Fehlig 已提交
971

972 973 974 975 976
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_START_VALIDATE)
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE;
J
Jim Fehlig 已提交
977

978
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
979
                                        parse_flags)))
J
Jim Fehlig 已提交
980 981
        goto cleanup;

982 983 984
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

985
    if (!(vm = virDomainObjListAdd(driver->domains, def,
986
                                   driver->xmlopt,
987
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
988 989
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
990 991 992
        goto cleanup;
    def = NULL;

993 994 995 996 997 998 999 1000
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
        goto cleanup;
    }

1001
    if (libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0,
1002
                     -1) < 0) {
1003 1004 1005
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
1006
            goto cleanup;
1007
        }
1008
        goto endjob;
J
Jim Fehlig 已提交
1009 1010 1011 1012 1013 1014
    }

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

1015 1016 1017 1018
 endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1019
 cleanup:
J
Jim Fehlig 已提交
1020 1021
    virDomainDefFree(def);
    if (vm)
1022
        virObjectUnlock(vm);
1023
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
    return dom;
}

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

1034
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
1035
    if (!vm) {
1036
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1037 1038 1039
        goto cleanup;
    }

1040 1041 1042
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1043 1044 1045 1046
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

1047
 cleanup:
J
Jim Fehlig 已提交
1048
    if (vm)
1049
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
    return dom;
}

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

1060
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
1061
    if (!vm) {
1062
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1063 1064 1065
        goto cleanup;
    }

1066 1067 1068
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1069 1070 1071 1072
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

1073
 cleanup:
J
Jim Fehlig 已提交
1074
    if (vm)
1075
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    return dom;
}

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

1086
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
1087
    if (!vm) {
1088
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1089 1090 1091
        goto cleanup;
    }

1092 1093 1094
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1095 1096 1097 1098
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

1099
 cleanup:
1100
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
1101 1102 1103
    return dom;
}

1104 1105 1106 1107
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1108
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1109
    virDomainObjPtr vm;
1110
    virObjectEventPtr event = NULL;
1111 1112
    int ret = -1;

J
Jim Fehlig 已提交
1113
    if (!(vm = libxlDomObjFromDomain(dom)))
1114
        goto cleanup;
1115

J
Jim Fehlig 已提交
1116 1117
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

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

1121 1122 1123
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1124
    if (!virDomainObjIsActive(vm)) {
1125
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1126
        goto endjob;
1127 1128
    }

J
Jiri Denemark 已提交
1129
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1130
        if (libxl_domain_pause(cfg->ctx, vm->def->id) != 0) {
1131 1132
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to suspend domain '%d' with libxenlight"),
1133
                           vm->def->id);
1134
            goto endjob;
1135 1136
        }

J
Jiri Denemark 已提交
1137
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1138

1139
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
1140 1141 1142
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

1143
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
1144
        goto endjob;
1145 1146 1147

    ret = 0;

1148
 endjob:
1149 1150 1151
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1152
 cleanup:
1153
    if (vm)
1154
        virObjectUnlock(vm);
1155
    if (event)
1156
        libxlDomainEventQueue(driver, event);
1157
    virObjectUnref(cfg);
1158 1159 1160 1161 1162 1163 1164 1165
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1166
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1167
    virDomainObjPtr vm;
1168
    virObjectEventPtr event = NULL;
1169 1170
    int ret = -1;

J
Jim Fehlig 已提交
1171
    if (!(vm = libxlDomObjFromDomain(dom)))
1172 1173
        goto cleanup;

J
Jim Fehlig 已提交
1174 1175
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

1176 1177 1178
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1179 1180 1181
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1182
    if (!virDomainObjIsActive(vm)) {
1183
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1184
        goto endjob;
1185 1186
    }

J
Jiri Denemark 已提交
1187
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1188
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
1189 1190
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
1191
                           vm->def->id);
1192
            goto endjob;
1193 1194
        }

J
Jiri Denemark 已提交
1195 1196
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1197

1198
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_RESUMED,
1199 1200 1201
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

1202
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
1203
        goto endjob;
1204 1205 1206

    ret = 0;

1207
 endjob:
1208 1209 1210
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1211
 cleanup:
1212
    if (vm)
1213
        virObjectUnlock(vm);
1214
    if (event)
1215
        libxlDomainEventQueue(driver, event);
1216
    virObjectUnref(cfg);
1217 1218 1219
    return ret;
}

J
Jim Fehlig 已提交
1220
static int
1221
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1222
{
J
Jim Fehlig 已提交
1223 1224
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1225 1226 1227
    virDomainObjPtr vm;
    int ret = -1;

1228 1229 1230 1231 1232
    virCheckFlags(VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN |
                  VIR_DOMAIN_SHUTDOWN_PARAVIRT, -1);
    if (flags == 0)
        flags = VIR_DOMAIN_SHUTDOWN_PARAVIRT |
            VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN;
1233

J
Jim Fehlig 已提交
1234
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1235 1236
        goto cleanup;

J
Jim Fehlig 已提交
1237 1238
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

1239
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1240 1241
        goto cleanup;

J
Jim Fehlig 已提交
1242
    if (!virDomainObjIsActive(vm)) {
1243 1244
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1245 1246 1247
        goto cleanup;
    }

1248
    if (flags & VIR_DOMAIN_SHUTDOWN_PARAVIRT) {
J
Jim Fehlig 已提交
1249
        ret = libxl_domain_shutdown(cfg->ctx, vm->def->id);
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
        if (ret == 0)
            goto cleanup;

        if (ret != ERROR_NOPARAVIRT) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to shutdown domain '%d' with libxenlight"),
                           vm->def->id);
            ret = -1;
            goto cleanup;
        }
        ret = -1;
    }

    if (flags & VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN) {
J
Jim Fehlig 已提交
1264
        ret = libxl_send_trigger(cfg->ctx, vm->def->id,
1265 1266 1267 1268
                                 LIBXL_TRIGGER_POWER, 0);
        if (ret == 0)
            goto cleanup;

1269 1270
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
1271
                       vm->def->id);
1272
        ret = -1;
J
Jim Fehlig 已提交
1273 1274
    }

1275
 cleanup:
J
Jim Fehlig 已提交
1276
    if (vm)
1277
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1278
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1279 1280 1281
    return ret;
}

1282 1283 1284 1285 1286 1287 1288
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
1289
static int
E
Eric Blake 已提交
1290
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1291
{
J
Jim Fehlig 已提交
1292 1293
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1294 1295 1296
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
1297 1298 1299
    virCheckFlags(VIR_DOMAIN_REBOOT_PARAVIRT, -1);
    if (flags == 0)
        flags = VIR_DOMAIN_REBOOT_PARAVIRT;
E
Eric Blake 已提交
1300

J
Jim Fehlig 已提交
1301
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1302 1303
        goto cleanup;

J
Jim Fehlig 已提交
1304 1305
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

1306
    if (virDomainRebootEnsureACL(dom->conn, vm->def, flags) < 0)
1307 1308
        goto cleanup;

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

J
Jim Fehlig 已提交
1315
    if (flags & VIR_DOMAIN_REBOOT_PARAVIRT) {
J
Jim Fehlig 已提交
1316
        ret = libxl_domain_reboot(cfg->ctx, vm->def->id);
J
Jim Fehlig 已提交
1317 1318 1319
        if (ret == 0)
            goto cleanup;

1320 1321
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
1322
                       vm->def->id);
J
Jim Fehlig 已提交
1323
        ret = -1;
J
Jim Fehlig 已提交
1324 1325
    }

1326
 cleanup:
J
Jim Fehlig 已提交
1327
    if (vm)
1328
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1329
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1330 1331 1332 1333
    return ret;
}

static int
1334 1335
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1336 1337
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
1338
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1339 1340
    virDomainObjPtr vm;
    int ret = -1;
1341
    virObjectEventPtr event = NULL;
J
Jim Fehlig 已提交
1342

1343 1344
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1345
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1346 1347
        goto cleanup;

J
Jim Fehlig 已提交
1348 1349
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

1350 1351 1352
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1353 1354 1355
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1356
    if (!virDomainObjIsActive(vm)) {
1357 1358
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
1359
        goto endjob;
J
Jim Fehlig 已提交
1360 1361
    }

1362
    if (libxlDomainDestroyInternal(driver, vm) < 0) {
1363
        virReportError(VIR_ERR_INTERNAL_ERROR,
1364
                       _("Failed to destroy domain '%d'"), vm->def->id);
1365
        goto endjob;
J
Jim Fehlig 已提交
1366 1367
    }

1368 1369 1370 1371 1372 1373 1374
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_DESTROYED);

    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

    libxlDomainCleanup(driver, vm);
1375 1376
    if (!vm->persistent)
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1377 1378 1379

    ret = 0;

1380 1381 1382 1383
 endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1384
 cleanup:
J
Jim Fehlig 已提交
1385
    if (vm)
1386
        virObjectUnlock(vm);
1387 1388
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1389
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1390 1391 1392
    return ret;
}

1393 1394 1395 1396 1397 1398
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1399 1400 1401 1402 1403 1404
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *type = NULL;

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

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

1411
    if (VIR_STRDUP(type, virDomainOSTypeToString(vm->def->os.type)) < 0)
1412
        goto cleanup;
1413

1414
 cleanup:
1415
    if (vm)
1416
        virObjectUnlock(vm);
1417 1418 1419
    return type;
}

1420
static unsigned long long
1421 1422 1423
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    virDomainObjPtr vm;
1424
    unsigned long long ret = 0;
1425

J
Jim Fehlig 已提交
1426
    if (!(vm = libxlDomObjFromDomain(dom)))
1427
        goto cleanup;
1428 1429 1430 1431

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

1432
    ret = virDomainDefGetMemoryActual(vm->def);
1433

1434
 cleanup:
1435
    if (vm)
1436
        virObjectUnlock(vm);
1437 1438 1439 1440
    return ret;
}

static int
1441
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1442 1443 1444
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1445
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1446
    virDomainObjPtr vm;
1447
    virDomainDefPtr persistentDef = NULL;
1448 1449 1450
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1451 1452
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1453

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

1457 1458 1459
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

1460 1461 1462
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1463 1464
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm, &flags,
                                        &persistentDef) < 0)
1465
        goto endjob;
1466

1467 1468
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1469

1470
        if (flags & VIR_DOMAIN_MEM_LIVE) {
J
Jim Fehlig 已提交
1471
            if (libxl_domain_setmaxmem(cfg->ctx, vm->def->id, newmem) < 0) {
1472 1473
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
1474
                                 " with libxenlight"), vm->def->id);
1475
                goto endjob;
1476 1477 1478 1479 1480 1481
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1482
            virDomainDefSetMemoryTotal(persistentDef, newmem);
1483 1484
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
1485
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1486
            goto endjob;
1487 1488
        }

1489 1490
    } else {
        /* resize the current memory */
1491

1492
        if (newmem > virDomainDefGetMemoryActual(vm->def)) {
1493 1494
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1495
            goto endjob;
1496 1497 1498
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
1499 1500 1501 1502
            int res;

            /* Unlock virDomainObj while ballooning memory */
            virObjectUnlock(vm);
J
Jim Fehlig 已提交
1503
            res = libxl_set_memory_target(cfg->ctx, vm->def->id, newmem, 0,
1504 1505 1506
                                          /* force */ 1);
            virObjectLock(vm);
            if (res < 0) {
1507 1508
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
1509
                                 " with libxenlight"), vm->def->id);
1510
                goto endjob;
1511 1512 1513 1514 1515 1516
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1517
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1518
            goto endjob;
1519
        }
1520 1521
    }

1522 1523
    ret = 0;

1524
 endjob:
1525 1526 1527
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1528
 cleanup:
1529
    if (vm)
1530
        virObjectUnlock(vm);
1531
    virObjectUnref(cfg);
1532 1533 1534 1535 1536 1537 1538 1539 1540
    return ret;
}

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

1541 1542 1543 1544 1545 1546
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1547 1548 1549
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
J
Jim Fehlig 已提交
1550 1551
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1552
    virDomainObjPtr vm;
1553
    libxl_dominfo d_info;
J
Jim Fehlig 已提交
1554 1555
    int ret = -1;

J
Jim Fehlig 已提交
1556
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1557 1558
        goto cleanup;

1559 1560 1561
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1562 1563 1564
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1565
        info->maxMem = virDomainDefGetMemoryActual(vm->def);
1566
    } else {
1567 1568
        libxl_dominfo_init(&d_info);

J
Jim Fehlig 已提交
1569
        if (libxl_domain_info(cfg->ctx, &d_info, vm->def->id) != 0) {
1570
            virReportError(VIR_ERR_INTERNAL_ERROR,
1571 1572
                           _("libxl_domain_info failed for domain '%d'"),
                           vm->def->id);
1573 1574 1575 1576
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1577
        info->maxMem = d_info.max_memkb;
1578 1579

        libxl_dominfo_dispose(&d_info);
1580 1581
    }

J
Jiri Denemark 已提交
1582
    info->state = virDomainObjGetState(vm, NULL);
1583
    info->nrVirtCpu = virDomainDefGetVcpus(vm->def);
J
Jim Fehlig 已提交
1584 1585
    ret = 0;

1586
 cleanup:
J
Jim Fehlig 已提交
1587
    if (vm)
1588
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1589
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1590 1591 1592
    return ret;
}

1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1604
    if (!(vm = libxlDomObjFromDomain(dom)))
1605 1606
        goto cleanup;

1607 1608 1609
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1610
    *state = virDomainObjGetState(vm, reason);
1611 1612
    ret = 0;

1613
 cleanup:
1614
    if (vm)
1615
        virObjectUnlock(vm);
1616 1617 1618
    return ret;
}

1619 1620 1621
/*
 * virDomainObjPtr must be locked on invocation
 */
1622
static int
1623 1624
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1625
{
J
Jim Fehlig 已提交
1626
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1627
    libxlSavefileHeader hdr;
1628
    virObjectEventPtr event = NULL;
1629 1630
    char *xml = NULL;
    uint32_t xml_len;
1631
    int fd = -1;
1632 1633 1634
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1635 1636 1637
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1638 1639 1640 1641
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1642
                            -1, -1, 0)) < 0) {
1643 1644 1645 1646 1647
        virReportSystemError(-fd,
                             _("Failed to create domain save file '%s'"), to);
        goto cleanup;
    }

1648
    if ((xml = virDomainDefFormat(vm->def, cfg->caps, 0)) == NULL)
1649 1650 1651 1652 1653 1654 1655 1656 1657
        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)) {
1658 1659
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1660 1661 1662 1663
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1664 1665
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1666 1667 1668
        goto cleanup;
    }

1669 1670
    /* Unlock virDomainObj while saving domain */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
1671
    ret = libxl_domain_suspend(cfg->ctx, vm->def->id, fd, 0, NULL);
1672 1673 1674
    virObjectLock(vm);

    if (ret != 0) {
1675 1676 1677
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1678
        ret = -1;
1679 1680 1681
        goto cleanup;
    }

1682 1683 1684
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_SAVED);

1685
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1686 1687
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

1688
    if (libxlDomainDestroyInternal(driver, vm) < 0) {
1689 1690
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1691 1692 1693
        goto cleanup;
    }

1694
    libxlDomainCleanup(driver, vm);
1695
    vm->hasManagedSave = true;
1696 1697
    ret = 0;

1698
 cleanup:
1699 1700 1701 1702 1703
    VIR_FREE(xml);
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1704
    virObjectUnref(cfg);
1705 1706 1707 1708
    return ret;
}

static int
1709 1710
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1711
{
1712 1713
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1714
    int ret = -1;
1715
    bool remove_dom = false;
1716

1717 1718 1719 1720 1721
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1722 1723
    virCheckFlags(0, -1);
    if (dxml) {
1724 1725
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1726 1727 1728
        return -1;
    }

J
Jim Fehlig 已提交
1729
    if (!(vm = libxlDomObjFromDomain(dom)))
1730 1731
        goto cleanup;

J
Jim Fehlig 已提交
1732 1733
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

1734 1735 1736
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1737 1738 1739
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1740
    if (!virDomainObjIsActive(vm)) {
1741
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1742
        goto endjob;
1743 1744
    }

1745
    if (libxlDoDomainSave(driver, vm, to) < 0)
1746
        goto endjob;
1747

1748 1749
    if (!vm->persistent)
        remove_dom = true;
1750 1751

    ret = 0;
1752

1753
 endjob:
1754 1755 1756
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1757
 cleanup:
1758 1759 1760 1761
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1762
    if (vm)
1763
        virObjectUnlock(vm);
1764 1765
    return ret;
}
1766

1767
static int
1768 1769 1770 1771 1772 1773 1774 1775
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)
1776 1777
{
    libxlDriverPrivatePtr driver = conn->privateData;
1778
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1779 1780 1781 1782 1783
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1784

1785 1786 1787 1788 1789
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1790
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1791
    if (dxml) {
1792 1793
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1794 1795 1796
        return -1;
    }

1797
    fd = libxlDomainSaveImageOpen(driver, cfg, from, &def, &hdr);
1798
    if (fd < 0)
1799
        goto cleanup;
1800

1801
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1802
        goto cleanup;
1803

1804
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1805
                                   driver->xmlopt,
1806 1807 1808
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1809
        goto cleanup;
1810 1811 1812

    def = NULL;

1813 1814 1815 1816 1817 1818 1819 1820
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
        goto cleanup;
    }

1821
    ret = libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_SAVE_PAUSED) != 0, fd);
1822
    if (ret < 0 && !vm->persistent)
1823
        virDomainObjListRemove(driver->domains, vm);
1824 1825

    if (!libxlDomainObjEndJob(driver, vm))
1826 1827
        vm = NULL;

1828
 cleanup:
1829 1830
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1831 1832
    virDomainDefFree(def);
    if (vm)
1833
        virObjectUnlock(vm);
1834
    virObjectUnref(cfg);
1835 1836 1837
    return ret;
}

1838 1839 1840 1841 1842 1843
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

1844
static int
1845
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1846 1847
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
1848
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1849
    virDomainObjPtr vm;
1850
    virObjectEventPtr event = NULL;
1851
    bool remove_dom = false;
1852 1853 1854 1855 1856
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

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

J
Jim Fehlig 已提交
1860 1861
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

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

1865 1866 1867
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1868
    if (!virDomainObjIsActive(vm)) {
1869
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1870
        goto endjob;
1871 1872 1873 1874
    }

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
1875
        if (libxl_domain_pause(cfg->ctx, vm->def->id) != 0) {
1876 1877 1878
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
1879
                           vm->def->id);
1880
            goto endjob;
1881 1882 1883 1884 1885
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

1886 1887
    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
1888
    ret = libxl_domain_core_dump(cfg->ctx, vm->def->id, to, NULL);
1889 1890
    virObjectLock(vm);
    if (ret != 0) {
1891 1892
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
1893
                       vm->def->id);
1894 1895
        ret = -1;
        goto unpause;
1896 1897 1898
    }

    if (flags & VIR_DUMP_CRASH) {
1899
        if (libxlDomainDestroyInternal(driver, vm) < 0) {
1900
            virReportError(VIR_ERR_INTERNAL_ERROR,
1901
                           _("Failed to destroy domain '%d'"), vm->def->id);
1902
            goto unpause;
1903 1904
        }

1905 1906 1907
        libxlDomainCleanup(driver, vm);
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_CRASHED);
1908
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1909
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
1910 1911
        if (!vm->persistent)
            remove_dom = true;
1912 1913 1914 1915
    }

    ret = 0;

1916
 unpause:
1917
    if (virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
1918
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
1919 1920
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
1921
                             " libxenlight"), vm->def->id);
1922 1923 1924 1925 1926
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
1927

1928
 endjob:
1929 1930 1931
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1932
 cleanup:
1933 1934 1935 1936
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1937
    if (vm)
1938
        virObjectUnlock(vm);
1939
    if (event)
1940
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1941
    virObjectUnref(cfg);
1942 1943 1944
    return ret;
}

1945 1946 1947 1948 1949 1950 1951
static int
libxlDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;
1952
    bool remove_dom = false;
1953 1954 1955

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1956
    if (!(vm = libxlDomObjFromDomain(dom)))
1957 1958
        goto cleanup;

J
Jim Fehlig 已提交
1959 1960
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

1961 1962 1963
    if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1964 1965 1966
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1967
    if (!virDomainObjIsActive(vm)) {
1968
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1969
        goto endjob;
1970
    }
1971
    if (!vm->persistent) {
1972 1973
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
1974
        goto endjob;
1975
    }
1976 1977 1978

    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
1979
        goto endjob;
1980 1981 1982

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

1983
    if (libxlDoDomainSave(driver, vm, name) < 0)
1984
        goto endjob;
1985

1986 1987
    if (!vm->persistent)
        remove_dom = true;
1988 1989

    ret = 0;
1990

1991
 endjob:
1992 1993 1994
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1995
 cleanup:
1996 1997 1998 1999
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
2000
    if (vm)
2001
        virObjectUnlock(vm);
2002 2003 2004 2005
    VIR_FREE(name);
    return ret;
}

2006 2007
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
2008 2009 2010 2011
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
2012
    int ret = -1;
2013

2014
    virObjectLock(vm);
2015 2016 2017 2018 2019 2020

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

    vm->hasManagedSave = virFileExists(name);

2021
    ret = 0;
2022
 cleanup:
2023
    virObjectUnlock(vm);
2024
    VIR_FREE(name);
2025
    return ret;
2026 2027
}

2028 2029 2030 2031 2032 2033 2034 2035
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2036
    if (!(vm = libxlDomObjFromDomain(dom)))
2037 2038
        goto cleanup;

2039 2040 2041
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2042
    ret = vm->hasManagedSave;
2043

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

static int
libxlDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    char *name = NULL;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2060
    if (!(vm = libxlDomObjFromDomain(dom)))
2061 2062
        goto cleanup;

2063 2064 2065
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2066 2067 2068 2069 2070
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
2071
    vm->hasManagedSave = false;
2072

2073
 cleanup:
2074 2075
    VIR_FREE(name);
    if (vm)
2076
        virObjectUnlock(vm);
2077 2078 2079
    return ret;
}

2080 2081 2082 2083 2084
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2085
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2086 2087
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
2088
    libxl_bitmap map;
2089 2090
    uint8_t *bitmask = NULL;
    unsigned int maplen;
2091 2092
    size_t i;
    unsigned int pos;
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
    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)) {
2105 2106
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2107 2108 2109 2110
        return -1;
    }

    if (!nvcpus) {
2111
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2112 2113 2114
        return -1;
    }

J
Jim Fehlig 已提交
2115
    if (!(vm = libxlDomObjFromDomain(dom)))
2116 2117
        goto cleanup;

2118 2119 2120
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2121 2122 2123
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2124
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2125 2126
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2127
        goto endjob;
2128 2129 2130
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2131 2132
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2133
        goto endjob;
2134 2135
    }

2136
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2137 2138
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2139
        goto endjob;
2140 2141
    }

2142 2143
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && virDomainDefGetVcpusMax(vm->def) < max)
        max = virDomainDefGetVcpusMax(vm->def);
2144 2145

    if (nvcpus > max) {
2146 2147 2148
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2149
        goto endjob;
2150 2151
    }

2152
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm)))
2153
        goto endjob;
2154

E
Eric Blake 已提交
2155
    maplen = VIR_CPU_MAPLEN(nvcpus);
2156
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
2157
        goto endjob;
2158 2159

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2160
        pos = i / 8;
2161 2162 2163 2164 2165 2166 2167 2168
        bitmask[pos] |= 1 << (i % 8);
    }

    map.size = maplen;
    map.map = bitmask;

    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
2169 2170
        if (virDomainDefSetVcpusMax(def, nvcpus) < 0)
            goto cleanup;
2171 2172 2173
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
2174 2175
        if (virDomainDefSetVcpus(def, nvcpus) < 0)
            goto cleanup;
2176 2177 2178
        break;

    case VIR_DOMAIN_VCPU_LIVE:
J
Jim Fehlig 已提交
2179
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2180 2181
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2182
                             " with libxenlight"), vm->def->id);
2183
            goto endjob;
2184
        }
2185 2186
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0)
            goto endjob;
2187 2188 2189
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2190
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2191 2192
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2193
                             " with libxenlight"), vm->def->id);
2194
            goto endjob;
2195
        }
2196 2197 2198
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0 ||
            virDomainDefSetVcpus(def, nvcpus) < 0)
            goto endjob;
2199 2200 2201 2202 2203
        break;
    }

    ret = 0;

2204
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2205
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0) {
2206 2207 2208 2209 2210
            VIR_WARN("Unable to save status on vm %s after changing vcpus",
                     vm->def->name);
        }
    }
    if (flags & VIR_DOMAIN_VCPU_CONFIG) {
2211
        if (virDomainSaveConfig(cfg->configDir, cfg->caps, def) < 0) {
2212 2213 2214 2215
            VIR_WARN("Unable to save configuration of vm %s after changing vcpus",
                     vm->def->name);
        }
    }
2216

2217
 endjob:
2218 2219 2220
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2221
 cleanup:
2222 2223
    VIR_FREE(bitmask);
     if (vm)
2224
        virObjectUnlock(vm);
2225
     virObjectUnref(cfg);
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
    return ret;
}

static int
libxlDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
    return libxlDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_VCPU_LIVE);
}

static int
libxlDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm;
    virDomainDefPtr def;
    int ret = -1;
2241
    bool active;
2242 2243 2244 2245 2246

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

J
Jim Fehlig 已提交
2247
    if (!(vm = libxlDomObjFromDomain(dom)))
2248 2249
        goto cleanup;

2250
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2251 2252
        goto cleanup;

2253 2254 2255 2256 2257 2258 2259 2260 2261
    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)) {
2262 2263
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2264 2265 2266
        return -1;
    }

2267
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2268
        if (!active) {
2269 2270
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2271 2272 2273 2274
            goto cleanup;
        }
        def = vm->def;
    } else {
2275
        if (!vm->persistent) {
2276 2277
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2278 2279
            goto cleanup;
        }
2280 2281 2282
        def = vm->newDef ? vm->newDef : vm->def;
    }

2283 2284 2285
    if (flags & VIR_DOMAIN_VCPU_MAXIMUM)
        ret = virDomainDefGetVcpusMax(def);
    else
2286
        ret = virDomainDefGetVcpus(def);
2287

2288
 cleanup:
2289
    if (vm)
2290
        virObjectUnlock(vm);
2291 2292 2293 2294
    return ret;
}

static int
2295 2296 2297
libxlDomainPinVcpuFlags(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen,
                        unsigned int flags)
2298 2299
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2300
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2301
    virDomainDefPtr targetDef = NULL;
2302
    virBitmapPtr pcpumap = NULL;
2303
    virDomainVcpuInfoPtr vcpuinfo;
2304 2305
    virDomainObjPtr vm;
    int ret = -1;
2306 2307 2308

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
2309

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

2313
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2314 2315
        goto cleanup;

2316 2317 2318
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2319 2320
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
2321
        goto endjob;
2322

2323
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2324 2325 2326 2327 2328
        targetDef = vm->def;

    /* Make sure coverity knows targetDef is valid at this point. */
    sa_assert(targetDef);

2329 2330
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
2331
        goto endjob;
2332

2333 2334 2335 2336 2337 2338 2339
    if (!(vcpuinfo = virDomainDefGetVcpu(targetDef, vcpu)) ||
        !vcpuinfo->online) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("vcpu '%u' is not active"), vcpu);
        goto endjob;
    }

2340 2341
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        libxl_bitmap map = { .size = maplen, .map = cpumap };
J
Jim Fehlig 已提交
2342
        if (libxl_set_vcpuaffinity(cfg->ctx, vm->def->id, vcpu, &map) != 0) {
2343 2344 2345
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"),
                           vcpu);
2346
            goto endjob;
2347
        }
2348
    }
2349

2350 2351 2352
    virBitmapFree(vcpuinfo->cpumask);
    vcpuinfo->cpumask = pcpumap;
    pcpumap = NULL;
2353

2354 2355
    ret = 0;

2356
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
2357
        ret = virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps);
2358
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2359
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, targetDef);
2360 2361
    }

2362
 endjob:
2363 2364 2365
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2366
 cleanup:
2367
    if (vm)
2368
        virObjectUnlock(vm);
2369
    virBitmapFree(pcpumap);
2370
    virObjectUnref(cfg);
2371 2372 2373
    return ret;
}

2374 2375 2376 2377 2378 2379 2380 2381
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

2382 2383 2384 2385 2386 2387 2388 2389 2390
static int
libxlDomainGetVcpuPinInfo(virDomainPtr dom, int ncpumaps,
                          unsigned char *cpumaps, int maplen,
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    virDomainObjPtr vm = NULL;
    virDomainDefPtr targetDef = NULL;
2391
    int ret = -1;
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    if (!(vm = libxlDomObjFromDomain(dom)))
        goto cleanup;

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

    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
        goto cleanup;

2406
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2407 2408 2409 2410 2411
        targetDef = vm->def;

    /* Make sure coverity knows targetDef is valid at this point. */
    sa_assert(targetDef);

2412 2413
    ret = virDomainDefGetVcpuPinInfoHelper(targetDef, maplen, ncpumaps, cpumaps,
                                           libxl_get_max_cpus(cfg->ctx), NULL);
2414

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

static int
libxlDomainGetVcpus(virDomainPtr dom, virVcpuInfoPtr info, int maxinfo,
                    unsigned char *cpumaps, int maplen)
{
J
Jim Fehlig 已提交
2426 2427
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2428 2429 2430 2431
    virDomainObjPtr vm;
    int ret = -1;
    libxl_vcpuinfo *vcpuinfo;
    int maxcpu, hostcpus;
2432
    size_t i;
2433 2434
    unsigned char *cpumap;

J
Jim Fehlig 已提交
2435
    if (!(vm = libxlDomObjFromDomain(dom)))
2436 2437
        goto cleanup;

2438 2439 2440
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2441
    if (!virDomainObjIsActive(vm)) {
2442
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2443 2444 2445
        goto cleanup;
    }

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

    ret = maxinfo;

2479
 cleanup:
2480
    if (vm)
2481
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2482
    virObjectUnref(cfg);
2483 2484 2485
    return ret;
}

J
Jim Fehlig 已提交
2486
static char *
2487
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2488
{
2489 2490
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2491
    virDomainObjPtr vm;
2492
    virDomainDefPtr def;
J
Jim Fehlig 已提交
2493 2494
    char *ret = NULL;

2495 2496
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2497
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2498 2499
        goto cleanup;

2500 2501 2502
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2503 2504 2505 2506 2507
    if ((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef)
        def = vm->newDef;
    else
        def = vm->def;

2508
    ret = virDomainDefFormat(def, cfg->caps,
2509
                             virDomainDefFormatConvertXMLFlags(flags));
J
Jim Fehlig 已提交
2510

2511
 cleanup:
J
Jim Fehlig 已提交
2512
    if (vm)
2513
        virObjectUnlock(vm);
2514
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2515 2516 2517
    return ret;
}

2518
static char *
2519 2520 2521
libxlConnectDomainXMLFromNative(virConnectPtr conn,
                                const char *nativeFormat,
                                const char *nativeConfig,
2522
                                unsigned int flags)
2523 2524
{
    libxlDriverPrivatePtr driver = conn->privateData;
2525
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2526 2527 2528 2529
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2530 2531
    virCheckFlags(0, NULL);

2532 2533 2534
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

2535 2536 2537 2538 2539
    if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_XL)) {
        if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
            goto cleanup;
        if (!(def = xenParseXL(conf,
                               cfg->caps,
2540
                               driver->xmlopt)))
2541 2542
            goto cleanup;
    } else if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2543 2544 2545 2546
        if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
            goto cleanup;

        if (!(def = xenParseXM(conf,
2547 2548
                               cfg->caps,
                               driver->xmlopt)))
2549 2550 2551 2552 2553
            goto cleanup;
    } else if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_SEXPR)) {
        /* only support latest xend config format */
        if (!(def = xenParseSxprString(nativeConfig,
                                       NULL,
2554 2555 2556
                                       -1,
                                       cfg->caps,
                                       driver->xmlopt))) {
2557 2558 2559 2560 2561
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("parsing sxpr config failed"));
            goto cleanup;
        }
    } else {
2562 2563
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2564 2565 2566
        goto cleanup;
    }

2567
    xml = virDomainDefFormat(def, cfg->caps, VIR_DOMAIN_DEF_FORMAT_INACTIVE);
2568

2569
 cleanup:
2570 2571 2572
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2573
    virObjectUnref(cfg);
2574 2575 2576 2577 2578
    return xml;
}

#define MAX_CONFIG_SIZE (1024 * 65)
static char *
2579 2580 2581
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
2582 2583
{
    libxlDriverPrivatePtr driver = conn->privateData;
2584
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2585 2586 2587 2588 2589
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    int len = MAX_CONFIG_SIZE;
    char *ret = NULL;

E
Eric Blake 已提交
2590 2591
    virCheckFlags(0, NULL);

2592 2593 2594
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

2595
    if (!(def = virDomainDefParseString(domainXml,
2596
                                        cfg->caps, driver->xmlopt,
2597
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE)))
2598 2599
        goto cleanup;

2600
    if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_XL)) {
2601
        if (!(conf = xenFormatXL(def, conn)))
2602 2603
            goto cleanup;
    } else if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2604
        if (!(conf = xenFormatXM(conn, def)))
2605 2606 2607 2608 2609
            goto cleanup;
    } else {

        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2610
        goto cleanup;
2611
    }
2612

2613
    if (VIR_ALLOC_N(ret, len) < 0)
2614 2615 2616 2617 2618 2619 2620
        goto cleanup;

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

2621
 cleanup:
2622 2623 2624
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2625
    virObjectUnref(cfg);
2626 2627 2628
    return ret;
}

J
Jim Fehlig 已提交
2629
static int
2630 2631
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
2632 2633 2634 2635
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2636 2637 2638
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2639 2640
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
2641 2642 2643 2644
    return n;
}

static int
2645
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
2646 2647 2648 2649
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2650 2651 2652
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2653
    n = virDomainObjListNumOfDomains(driver->domains, false,
2654 2655
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
2656 2657 2658 2659 2660
    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
2661
                           unsigned int flags)
J
Jim Fehlig 已提交
2662 2663 2664 2665 2666 2667 2668
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

J
Jim Fehlig 已提交
2669
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2670 2671
        goto cleanup;

2672 2673 2674
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2675 2676 2677
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2678
    if (virDomainObjIsActive(vm)) {
2679 2680
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
2681
        goto endjob;
J
Jim Fehlig 已提交
2682 2683
    }

2684
    ret = libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0, -1);
2685
    if (ret < 0)
2686
        goto endjob;
2687
    dom->id = vm->def->id;
J
Jim Fehlig 已提交
2688

2689 2690 2691 2692
 endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2693
 cleanup:
J
Jim Fehlig 已提交
2694
    if (vm)
2695
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
    return ret;
}

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

static virDomainPtr
2706
libxlDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags)
J
Jim Fehlig 已提交
2707 2708
{
    libxlDriverPrivatePtr driver = conn->privateData;
2709
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2710 2711 2712
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
2713
    virObjectEventPtr event = NULL;
2714
    virDomainDefPtr oldDef = NULL;
2715
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
J
Jim Fehlig 已提交
2716

2717 2718 2719 2720
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_DEFINE_VALIDATE)
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE;
2721

2722
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
2723
                                        parse_flags)))
2724
        goto cleanup;
J
Jim Fehlig 已提交
2725

2726
    if (virDomainDefineXMLFlagsEnsureACL(conn, def) < 0)
2727
        goto cleanup;
2728

2729
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2730
                                   driver->xmlopt,
2731 2732
                                   0,
                                   &oldDef)))
2733
        goto cleanup;
2734

J
Jim Fehlig 已提交
2735 2736 2737
    def = NULL;
    vm->persistent = 1;

2738
    if (virDomainSaveConfig(cfg->configDir,
2739
                            cfg->caps,
J
Jim Fehlig 已提交
2740
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2741
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
2742 2743 2744 2745 2746 2747 2748 2749
        vm = NULL;
        goto cleanup;
    }

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

2750
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2751
                                     !oldDef ?
2752 2753 2754
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

2755
 cleanup:
J
Jim Fehlig 已提交
2756
    virDomainDefFree(def);
2757
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
2758
    if (vm)
2759
        virObjectUnlock(vm);
2760 2761
    if (event)
        libxlDomainEventQueue(driver, event);
2762
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2763 2764 2765
    return dom;
}

2766 2767 2768 2769 2770 2771
static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    return libxlDomainDefineXMLFlags(conn, xml, 0);
}

J
Jim Fehlig 已提交
2772
static int
2773 2774
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2775 2776
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2777
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2778
    virDomainObjPtr vm;
2779
    virObjectEventPtr event = NULL;
2780
    char *name = NULL;
J
Jim Fehlig 已提交
2781 2782
    int ret = -1;

2783 2784
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2785
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2786 2787
        goto cleanup;

2788 2789 2790
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2791
    if (!vm->persistent) {
2792 2793
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2794 2795 2796
        goto cleanup;
    }

2797 2798 2799 2800 2801 2802 2803
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2804 2805
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2806 2807 2808
                goto cleanup;
            }
        } else {
2809 2810 2811
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2812 2813 2814 2815
            goto cleanup;
        }
    }

2816
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2817 2818
        goto cleanup;

2819
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2820 2821
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2822 2823 2824
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
2825
        virDomainObjListRemove(driver->domains, vm);
2826 2827 2828
        vm = NULL;
    }

J
Jim Fehlig 已提交
2829 2830
    ret = 0;

2831
 cleanup:
2832
    VIR_FREE(name);
J
Jim Fehlig 已提交
2833
    if (vm)
2834
        virObjectUnlock(vm);
2835 2836
    if (event)
        libxlDomainEventQueue(driver, event);
2837
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2838 2839 2840
    return ret;
}

2841 2842 2843 2844 2845 2846
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2847
static int
J
Jim Fehlig 已提交
2848
libxlDomainChangeEjectableMedia(virDomainObjPtr vm, virDomainDiskDefPtr disk)
2849
{
J
Jim Fehlig 已提交
2850
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
2851 2852
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2853
    size_t i;
2854 2855
    int ret = -1;

2856
    for (i = 0; i < vm->def->ndisks; i++) {
2857 2858 2859 2860 2861 2862 2863 2864
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
2865 2866 2867
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
2868 2869 2870 2871
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2872 2873 2874
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
2875 2876 2877
        return -1;
    }

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

J
Jim Fehlig 已提交
2881
    if ((ret = libxl_cdrom_insert(cfg->ctx, vm->def->id, &x_disk, NULL)) < 0) {
2882 2883 2884
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
2885 2886 2887
        goto cleanup;
    }

2888 2889 2890
    if (virDomainDiskSetSource(origdisk, virDomainDiskGetSource(disk)) < 0)
        goto cleanup;
    virDomainDiskSetType(origdisk, virDomainDiskGetType(disk));
2891 2892 2893 2894 2895

    virDomainDiskDefFree(disk);

    ret = 0;

2896
 cleanup:
J
Jim Fehlig 已提交
2897
    virObjectUnref(cfg);
2898 2899 2900 2901
    return ret;
}

static int
J
Jim Fehlig 已提交
2902
libxlDomainAttachDeviceDiskLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
2903
{
J
Jim Fehlig 已提交
2904
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
2905 2906 2907 2908 2909 2910
    virDomainDiskDefPtr l_disk = dev->data.disk;
    libxl_device_disk x_disk;
    int ret = -1;

    switch (l_disk->device)  {
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
J
Jim Fehlig 已提交
2911
            ret = libxlDomainChangeEjectableMedia(vm, l_disk);
2912 2913 2914
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (l_disk->bus == VIR_DOMAIN_DISK_BUS_XEN) {
2915
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
2916 2917
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
2918 2919 2920
                    goto cleanup;
                }

2921
                if (!virDomainDiskGetSource(l_disk)) {
2922 2923
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
2924 2925 2926
                    goto cleanup;
                }

2927
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
2928 2929
                    goto cleanup;

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

2933 2934 2935 2936 2937
                if (virDomainLockDiskAttach(libxl_driver->lockManager,
                                            "xen:///system",
                                            vm, l_disk) < 0)
                    goto cleanup;

J
Jim Fehlig 已提交
2938
                if ((ret = libxl_device_disk_add(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
2939
                                                &x_disk, NULL)) < 0) {
2940 2941 2942
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
2943 2944 2945 2946 2947
                    if (virDomainLockDiskDetach(libxl_driver->lockManager,
                                                vm, l_disk) < 0) {
                        VIR_WARN("Unable to release lock on %s",
                                 virDomainDiskGetSource(l_disk));
                    }
2948 2949 2950 2951 2952 2953
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
2954 2955 2956
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
2957 2958 2959
            }
            break;
        default:
2960 2961 2962
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
2963 2964 2965
            break;
    }

2966
 cleanup:
J
Jim Fehlig 已提交
2967
    virObjectUnref(cfg);
2968 2969 2970
    return ret;
}

2971 2972 2973 2974 2975
static int
libxlDomainAttachHostPCIDevice(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
J
Jim Fehlig 已提交
2976
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2977
    libxl_device_pci pcidev;
2978 2979
    virDomainHostdevDefPtr found;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
2980
    virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
J
Jim Fehlig 已提交
2981
    int ret = -1;
2982

2983 2984
    libxl_device_pci_init(&pcidev);

2985 2986 2987
    if (virDomainHostdevFind(vm->def, hostdev, &found) >= 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("target pci device %.4x:%.2x:%.2x.%.1x already exists"),
2988 2989
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
J
Jim Fehlig 已提交
2990
        goto cleanup;
2991 2992 2993
    }

    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs + 1) < 0)
J
Jim Fehlig 已提交
2994
        goto cleanup;
2995 2996 2997 2998

    if (virHostdevPreparePCIDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                    vm->def->name, vm->def->uuid,
                                    &hostdev, 1, 0) < 0)
J
Jim Fehlig 已提交
2999
        goto cleanup;
3000

3001
    if (libxlMakePCI(hostdev, &pcidev) < 0)
C
Chunyan Liu 已提交
3002
        goto error;
3003

J
Jim Fehlig 已提交
3004
    if (libxl_device_pci_add(cfg->ctx, vm->def->id, &pcidev, 0) < 0) {
3005 3006
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to attach pci device %.4x:%.2x:%.2x.%.1x"),
3007 3008
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3009
        goto error;
3010 3011 3012
    }

    vm->def->hostdevs[vm->def->nhostdevs++] = hostdev;
J
Jim Fehlig 已提交
3013 3014
    ret = 0;
    goto cleanup;
3015

3016
 error:
3017 3018
    virHostdevReAttachPCIDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                 vm->def->name, &hostdev, 1, NULL);
J
Jim Fehlig 已提交
3019 3020 3021

 cleanup:
    virObjectUnref(cfg);
3022
    libxl_device_pci_dispose(&pcidev);
J
Jim Fehlig 已提交
3023
    return ret;
3024 3025 3026 3027 3028
}

static int
libxlDomainAttachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3029
                            virDomainHostdevDefPtr hostdev)
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
{
    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
        return -1;
    }

    switch (hostdev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
J
Jim Fehlig 已提交
3040
        if (libxlDomainAttachHostPCIDevice(driver, vm, hostdev) < 0)
C
Chunyan Liu 已提交
3041
            return -1;
3042 3043 3044 3045 3046 3047
        break;

    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
C
Chunyan Liu 已提交
3048
        return -1;
3049 3050 3051 3052 3053
    }

    return 0;
}

3054
static int
J
Jim Fehlig 已提交
3055
libxlDomainDetachDeviceDiskLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3056
{
J
Jim Fehlig 已提交
3057
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
3058 3059
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
3060
    int idx;
3061 3062 3063 3064 3065 3066
    int ret = -1;

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

3067 3068 3069
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
3070 3071
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3072 3073 3074
                    goto cleanup;
                }

3075
                l_disk = vm->def->disks[idx];
3076

J
Jim Fehlig 已提交
3077
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3078 3079
                    goto cleanup;

J
Jim Fehlig 已提交
3080
                if ((ret = libxl_device_disk_remove(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
3081
                                                    &x_disk, NULL)) < 0) {
3082 3083 3084
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3085 3086 3087
                    goto cleanup;
                }

3088 3089 3090 3091 3092
                if (virDomainLockDiskDetach(libxl_driver->lockManager,
                                            vm, l_disk) < 0)
                    VIR_WARN("Unable to release lock on %s",
                             virDomainDiskGetSource(l_disk));

3093
                virDomainDiskRemove(vm->def, idx);
3094 3095 3096
                virDomainDiskDefFree(l_disk);

            } else {
3097 3098 3099
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3100 3101 3102
            }
            break;
        default:
3103 3104 3105
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3106 3107 3108
            break;
    }

3109
 cleanup:
J
Jim Fehlig 已提交
3110
    virObjectUnref(cfg);
3111 3112 3113
    return ret;
}

3114 3115 3116 3117 3118
static int
libxlDomainAttachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3119
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3120 3121 3122
    int actualType;
    libxl_device_nic nic;
    int ret = -1;
3123
    char mac[VIR_MAC_STRING_BUFLEN];
3124

3125 3126
    libxl_device_nic_init(&nic);

3127 3128
    /* preallocate new slot for device */
    if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets + 1) < 0)
3129
        goto cleanup;
3130 3131 3132 3133 3134 3135

    /* If appropriate, grab a physical device from the configured
     * network's pool of devices, or resolve bridge device name
     * to the one defined in the network definition.
     */
    if (networkAllocateActualDevice(vm->def, net) < 0)
3136
        goto cleanup;
3137 3138 3139

    actualType = virDomainNetGetActualType(net);

3140 3141 3142 3143
    if (virDomainHasNet(vm->def, net)) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("network device with mac %s already exists"),
                       virMacAddrFormat(&net->mac, mac));
3144
        goto cleanup;
3145 3146
    }

3147
    if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
        virDomainHostdevDefPtr hostdev = virDomainNetGetActualHostdev(net);
        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;

        /* For those just allocated from a network pool whose backend is
         * still VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT, we need to set
         * backend correctly.
         */
        if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
            hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
            pcisrc->backend = VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN;

3159 3160 3161
        /* This is really a "smart hostdev", so it should be attached
         * as a hostdev (the hostdev code will reach over into the
         * netdev-specific code as appropriate), then also added to
3162
         * the nets list if successful.
3163
         */
3164
        ret = libxlDomainAttachHostDevice(driver, vm, hostdev);
3165
        goto cleanup;
3166 3167 3168 3169 3170
    }

    if (libxlMakeNic(vm->def, net, &nic) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
3171
    if (libxl_device_nic_add(cfg->ctx, vm->def->id, &nic, 0)) {
3172 3173 3174 3175 3176
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to attach network device"));
        goto cleanup;
    }

3177
    vm->def->nets[vm->def->nnets++] = net;
3178 3179 3180 3181
    ret = 0;

 cleanup:
    libxl_device_nic_dispose(&nic);
3182 3183 3184 3185
    if (ret) {
        virDomainNetRemoveHostdev(vm->def, net);
        networkReleaseActualDevice(vm->def, net);
    }
J
Jim Fehlig 已提交
3186
    virObjectUnref(cfg);
3187 3188 3189
    return ret;
}

3190
static int
3191 3192
libxlDomainAttachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3193 3194 3195 3196 3197 3198
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
J
Jim Fehlig 已提交
3199
            ret = libxlDomainAttachDeviceDiskLive(vm, dev);
3200 3201 3202 3203
            if (!ret)
                dev->data.disk = NULL;
            break;

3204
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3205
            ret = libxlDomainAttachNetDevice(driver, vm,
3206 3207 3208 3209 3210
                                             dev->data.net);
            if (!ret)
                dev->data.net = NULL;
            break;

3211
        case VIR_DOMAIN_DEVICE_HOSTDEV:
J
Jim Fehlig 已提交
3212
            ret = libxlDomainAttachHostDevice(driver, vm,
3213
                                              dev->data.hostdev);
3214 3215 3216 3217
            if (!ret)
                dev->data.hostdev = NULL;
            break;

3218
        default:
3219 3220 3221
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3222 3223 3224 3225 3226 3227 3228 3229 3230 3231
            break;
    }

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
3232
    virDomainNetDefPtr net;
3233 3234
    virDomainHostdevDefPtr hostdev;
    virDomainHostdevDefPtr found;
3235
    virDomainHostdevSubsysPCIPtr pcisrc;
3236
    char mac[VIR_MAC_STRING_BUFLEN];
3237 3238 3239 3240

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3241
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3242 3243
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3244 3245
                return -1;
            }
3246
            if (virDomainDiskInsert(vmdef, disk))
3247 3248 3249 3250
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;
3251 3252 3253

        case VIR_DOMAIN_DEVICE_NET:
            net = dev->data.net;
3254 3255 3256 3257 3258 3259
            if (virDomainHasNet(vmdef, net)) {
                virReportError(VIR_ERR_INVALID_ARG,
                               _("network device with mac %s already exists"),
                               virMacAddrFormat(&net->mac, mac));
                return -1;
            }
3260 3261 3262 3263 3264
            if (virDomainNetInsert(vmdef, net))
                return -1;
            dev->data.net = NULL;
            break;

3265 3266 3267 3268 3269 3270 3271
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            hostdev = dev->data.hostdev;

            if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
                return -1;

            if (virDomainHostdevFind(vmdef, hostdev, &found) >= 0) {
3272
                pcisrc = &hostdev->source.subsys.u.pci;
3273 3274 3275
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("target pci device %.4x:%.2x:%.2x.%.1x\
                                  already exists"),
3276 3277
                               pcisrc->addr.domain, pcisrc->addr.bus,
                               pcisrc->addr.slot, pcisrc->addr.function);
3278 3279 3280
                return -1;
            }

3281 3282
            if (virDomainHostdevInsert(vmdef, hostdev) < 0)
                return -1;
3283
            dev->data.hostdev = NULL;
3284
            break;
3285 3286

        default:
3287 3288
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3289 3290 3291 3292 3293 3294
            return -1;
    }
    return 0;
}

static int
3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
libxlComparePCIDevice(virDomainDefPtr def ATTRIBUTE_UNUSED,
                      virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
                      virDomainDeviceInfoPtr info1,
                      void *opaque)
{
    virDomainDeviceInfoPtr info2 = opaque;

    if (info1->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI ||
        info2->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
        return 0;

    if (info1->addr.pci.domain == info2->addr.pci.domain &&
        info1->addr.pci.bus == info2->addr.pci.bus &&
        info1->addr.pci.slot == info2->addr.pci.slot &&
        info1->addr.pci.function != info2->addr.pci.function)
        return -1;
    return 0;
}

static bool
libxlIsMultiFunctionDevice(virDomainDefPtr def,
                           virDomainDeviceInfoPtr dev)
{
    if (virDomainDeviceInfoIterate(def, libxlComparePCIDevice, dev) < 0)
        return true;
    return false;
}

static int
libxlDomainDetachHostPCIDevice(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
J
Jim Fehlig 已提交
3328
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3329
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
3330
    virDomainHostdevSubsysPCIPtr pcisrc = &subsys->u.pci;
3331 3332 3333 3334
    libxl_device_pci pcidev;
    virDomainHostdevDefPtr detach;
    int idx;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
J
Jim Fehlig 已提交
3335
    int ret = -1;
3336

3337 3338
    libxl_device_pci_init(&pcidev);

3339 3340 3341 3342
    idx = virDomainHostdevFind(vm->def, hostdev, &detach);
    if (idx < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("host pci device %.4x:%.2x:%.2x.%.1x not found"),
3343 3344
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
J
Jim Fehlig 已提交
3345
        goto cleanup;
3346 3347 3348 3349 3350
    }

    if (libxlIsMultiFunctionDevice(vm->def, detach->info)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %.4x:%.2x:%.2x.%.1x"),
3351 3352
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3353
        goto error;
3354 3355 3356
    }


3357
    if (libxlMakePCI(detach, &pcidev) < 0)
C
Chunyan Liu 已提交
3358
        goto error;
3359

J
Jim Fehlig 已提交
3360
    if (libxl_device_pci_remove(cfg->ctx, vm->def->id, &pcidev, 0) < 0) {
3361 3362 3363
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to detach pci device\
                          %.4x:%.2x:%.2x.%.1x"),
3364 3365
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3366
        goto error;
3367 3368 3369 3370 3371 3372 3373 3374
    }


    virDomainHostdevRemove(vm->def, idx);

    virHostdevReAttachPCIDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                 vm->def->name, &hostdev, 1, NULL);

J
Jim Fehlig 已提交
3375
    ret = 0;
3376

3377
 error:
3378
    virDomainHostdevDefFree(detach);
J
Jim Fehlig 已提交
3379 3380 3381

 cleanup:
    virObjectUnref(cfg);
3382
    libxl_device_pci_dispose(&pcidev);
J
Jim Fehlig 已提交
3383
    return ret;
3384 3385 3386 3387 3388
}

static int
libxlDomainDetachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3389
                            virDomainHostdevDefPtr hostdev)
3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401
{
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;

    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
        return -1;
    }

    switch (subsys->type) {
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
J
Jim Fehlig 已提交
3402
            return libxlDomainDetachHostPCIDevice(driver, vm, hostdev);
3403 3404 3405 3406 3407 3408 3409 3410 3411 3412

        default:
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected hostdev type %d"), subsys->type);
            break;
    }

    return -1;
}

3413 3414 3415 3416 3417
static int
libxlDomainDetachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3418
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3419 3420 3421 3422 3423 3424
    int detachidx;
    virDomainNetDefPtr detach = NULL;
    libxl_device_nic nic;
    char mac[VIR_MAC_STRING_BUFLEN];
    int ret = -1;

3425 3426
    libxl_device_nic_init(&nic);

3427
    if ((detachidx = virDomainNetFindIdx(vm->def, net)) < 0)
3428
        goto cleanup;
3429 3430 3431 3432 3433 3434 3435

    detach = vm->def->nets[detachidx];

    if (virDomainNetGetActualType(detach) == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        /* This is really a "smart hostdev", so it should be attached as a
         * hostdev, then also removed from nets list (see out:) if successful.
         */
J
Jim Fehlig 已提交
3436
        ret = libxlDomainDetachHostDevice(driver, vm,
3437
                                          virDomainNetGetActualHostdev(detach));
3438
        goto cleanup;
3439 3440
    }

J
Jim Fehlig 已提交
3441
    if (libxl_mac_to_device_nic(cfg->ctx, vm->def->id,
3442 3443 3444
                                virMacAddrFormat(&detach->mac, mac), &nic))
        goto cleanup;

J
Jim Fehlig 已提交
3445
    if (libxl_device_nic_remove(cfg->ctx, vm->def->id, &nic, 0)) {
3446 3447 3448 3449 3450
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to detach network device"));
        goto cleanup;
    }

3451
    networkReleaseActualDevice(vm->def, detach);
3452
    virDomainNetRemove(vm->def, detachidx);
3453 3454 3455 3456
    ret = 0;

 cleanup:
    libxl_device_nic_dispose(&nic);
J
Jim Fehlig 已提交
3457
    virObjectUnref(cfg);
3458 3459 3460
    return ret;
}

3461 3462 3463
static int
libxlDomainDetachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3464 3465
                            virDomainDeviceDefPtr dev)
{
3466
    virDomainHostdevDefPtr hostdev;
3467 3468 3469 3470
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
J
Jim Fehlig 已提交
3471
            ret = libxlDomainDetachDeviceDiskLive(vm, dev);
3472 3473
            break;

3474
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3475
            ret = libxlDomainDetachNetDevice(driver, vm,
3476 3477 3478
                                             dev->data.net);
            break;

3479
        case VIR_DOMAIN_DEVICE_HOSTDEV:
3480 3481 3482 3483 3484 3485 3486 3487 3488 3489
            hostdev = dev->data.hostdev;

            /* If this is a network hostdev, we need to use the higher-level
             * detach function so that mac address / virtualport are reset
             */
            if (hostdev->parent.type == VIR_DOMAIN_DEVICE_NET)
                ret = libxlDomainDetachNetDevice(driver, vm,
                                                 hostdev->parent.data.net);
            else
                ret = libxlDomainDetachHostDevice(driver, vm, hostdev);
3490 3491
            break;

3492
        default:
3493 3494 3495
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3496 3497 3498 3499 3500 3501
            break;
    }

    return ret;
}

3502

3503 3504 3505
static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3506
    virDomainDiskDefPtr disk, detach;
3507
    virDomainHostdevDefPtr hostdev, det_hostdev;
3508
    virDomainNetDefPtr net;
3509
    int idx;
3510 3511 3512 3513

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3514
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3515 3516
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3517
                return -1;
3518
            }
3519
            virDomainDiskDefFree(detach);
3520
            break;
3521

3522 3523 3524 3525 3526 3527 3528 3529 3530
        case VIR_DOMAIN_DEVICE_NET:
            net = dev->data.net;
            if ((idx = virDomainNetFindIdx(vmdef, net)) < 0)
                return -1;

            /* this is guaranteed to succeed */
            virDomainNetDefFree(virDomainNetRemove(vmdef, idx));
            break;

3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
        case VIR_DOMAIN_DEVICE_HOSTDEV: {
            hostdev = dev->data.hostdev;
            if ((idx = virDomainHostdevFind(vmdef, hostdev, &det_hostdev)) < 0) {
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("device not present in domain configuration"));
                return -1;
            }
            virDomainHostdevRemove(vmdef, idx);
            virDomainHostdevDefFree(det_hostdev);
            break;
        }

3543
        default:
3544 3545
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3546
            return -1;
3547 3548
    }

3549
    return 0;
3550 3551 3552
}

static int
J
Jim Fehlig 已提交
3553
libxlDomainUpdateDeviceLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3554 3555 3556 3557 3558 3559 3560 3561 3562
{
    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:
J
Jim Fehlig 已提交
3563
                    ret = libxlDomainChangeEjectableMedia(vm, disk);
3564 3565 3566 3567
                    if (ret == 0)
                        dev->data.disk = NULL;
                    break;
                default:
3568 3569 3570
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3571 3572 3573 3574
                    break;
            }
            break;
        default:
3575 3576 3577
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
            break;
    }

    return ret;
}

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

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3594
            if (!(orig = virDomainDiskByName(vmdef, disk->dst, false))) {
3595 3596
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3597 3598 3599
                goto cleanup;
            }
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3600 3601
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3602 3603 3604
                goto cleanup;
            }

3605 3606 3607 3608 3609 3610
            if (virDomainDiskSetSource(orig, virDomainDiskGetSource(disk)) < 0)
                goto cleanup;
            virDomainDiskSetType(orig, virDomainDiskGetType(disk));
            virDomainDiskSetFormat(orig, virDomainDiskGetFormat(disk));
            if (virDomainDiskSetDriver(orig, virDomainDiskGetDriver(disk)) < 0)
                goto cleanup;
3611 3612
            break;
        default:
3613 3614
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3615 3616 3617 3618 3619
            goto cleanup;
    }

    ret = 0;

3620
 cleanup:
3621 3622 3623 3624 3625
    return ret;
}


static int
3626 3627
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3628 3629
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3630
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3631 3632 3633 3634 3635 3636 3637 3638
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3639
    if (!(vm = libxlDomObjFromDomain(dom)))
3640 3641
        goto cleanup;

3642 3643 3644
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3645 3646 3647
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

3648 3649
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto endjob;
3650 3651

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3652
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3653
                                            cfg->caps, driver->xmlopt,
3654
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3655
            goto endjob;
3656 3657

        /* Make a copy for updated domain. */
3658
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3659
                                                    driver->xmlopt)))
3660
            goto endjob;
3661

3662
        if (libxlDomainAttachDeviceConfig(vmdef, dev) < 0)
3663
            goto endjob;
3664
    }
3665 3666 3667 3668

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
3669
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3670
                                            cfg->caps, driver->xmlopt,
3671
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3672
            goto endjob;
3673

J
Jim Fehlig 已提交
3674
        if (libxlDomainAttachDeviceLive(driver, vm, dev) < 0)
3675
            goto endjob;
3676

3677 3678 3679 3680
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3681
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
3682
            goto endjob;
3683 3684
    }

3685 3686
    ret = 0;

3687
    /* Finally, if no error until here, we can save config. */
3688
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3689
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
3690
        if (!ret) {
3691
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3692 3693 3694 3695
            vmdef = NULL;
        }
    }

3696
 endjob:
3697 3698 3699
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3700
 cleanup:
3701 3702 3703
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3704
        virObjectUnlock(vm);
3705
    virObjectUnref(cfg);
3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719
    return ret;
}

static int
libxlDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return libxlDomainAttachDeviceFlags(dom, xml,
                                        VIR_DOMAIN_DEVICE_MODIFY_LIVE);
}

static int
libxlDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
{
3720
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3721
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3722 3723 3724 3725 3726 3727 3728 3729
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3730
    if (!(vm = libxlDomObjFromDomain(dom)))
3731 3732
        goto cleanup;

3733 3734 3735
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3736 3737 3738
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

3739 3740
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto endjob;
3741 3742 3743

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3744
                                            cfg->caps, driver->xmlopt,
3745
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3746
            goto endjob;
3747 3748

        /* Make a copy for updated domain. */
3749
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3750
                                                    driver->xmlopt)))
3751
            goto endjob;
3752

3753
        if (libxlDomainDetachDeviceConfig(vmdef, dev) < 0)
3754
            goto endjob;
3755 3756 3757 3758 3759 3760
    }

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3761
                                            cfg->caps, driver->xmlopt,
3762
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3763
            goto endjob;
3764

J
Jim Fehlig 已提交
3765
        if (libxlDomainDetachDeviceLive(driver, vm, dev) < 0)
3766
            goto endjob;
3767 3768 3769 3770 3771

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3772
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
3773
            goto endjob;
3774 3775
    }

3776 3777
    ret = 0;

3778
    /* Finally, if no error until here, we can save config. */
3779
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3780
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
3781 3782 3783 3784 3785 3786
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3787
 endjob:
3788 3789 3790
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3791
 cleanup:
3792 3793 3794 3795
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3796
    virObjectUnref(cfg);
3797
    return ret;
3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810
}

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)
{
3811
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3812
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3813 3814 3815 3816 3817 3818 3819 3820
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3821
    if (!(vm = libxlDomObjFromDomain(dom)))
3822 3823
        goto cleanup;

3824 3825 3826
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3827 3828
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto cleanup;
3829 3830 3831

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3832
                                            cfg->caps, driver->xmlopt,
3833
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3834 3835 3836
            goto cleanup;

        /* Make a copy for updated domain. */
3837
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850
                                                    driver->xmlopt)))
            goto cleanup;

        if ((ret = libxlDomainUpdateDeviceConfig(vmdef, dev)) < 0)
            goto cleanup;
    } else {
        ret = 0;
    }

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3851
                                            cfg->caps, driver->xmlopt,
3852
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3853 3854
            goto cleanup;

J
Jim Fehlig 已提交
3855
        if ((ret = libxlDomainUpdateDeviceLive(vm, dev)) < 0)
3856 3857 3858 3859 3860 3861
            goto cleanup;

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3862
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
3863 3864 3865 3866 3867
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3868
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
3869 3870 3871 3872 3873 3874
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3875
 cleanup:
3876 3877 3878 3879
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3880
    virObjectUnref(cfg);
3881
    return ret;
3882 3883
}

3884 3885 3886 3887 3888
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
3889 3890
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
3891

3892
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
3893
        goto cleanup;
3894

3895
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
3896 3897
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3898
        goto cleanup;
3899 3900
    }

3901 3902
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

3903
 cleanup:
3904 3905
    virObjectUnref(cfg);
    return ret;
3906 3907
}

3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
static int
libxlNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;
    int ret = -1, nr_nodes = 0;
    libxl_numainfo *numa_info = NULL;
    libxlDriverPrivatePtr driver = conn->privateData;
3918
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3919 3920

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
3921
        goto cleanup;
3922

3923
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
3924
    if (numa_info == NULL || nr_nodes == 0) {
3925 3926 3927
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
3928 3929 3930
    }

    /* Check/sanitize the cell range */
3931
    if (startCell >= nr_nodes) {
3932 3933
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
3934
                       startCell, nr_nodes - 1);
3935 3936 3937
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
3938 3939
    if (lastCell >= nr_nodes)
        lastCell = nr_nodes - 1;
3940 3941 3942 3943 3944 3945 3946

    for (numCells = 0, n = startCell; n <= lastCell; n++) {
        if (numa_info[n].size == LIBXL_NUMAINFO_INVALID_ENTRY)
            freeMems[numCells++] = 0;
        else
            freeMems[numCells++] = numa_info[n].free;
    }
3947

3948 3949
    ret = numCells;

3950
 cleanup:
3951
    libxl_numainfo_list_free(numa_info, nr_nodes);
3952
    virObjectUnref(cfg);
3953 3954 3955
    return ret;
}

3956
static int
3957
libxlConnectDomainEventRegister(virConnectPtr conn,
3958 3959
                                virConnectDomainEventCallback callback,
                                void *opaque,
3960
                                virFreeCallback freecb)
3961 3962 3963
{
    libxlDriverPrivatePtr driver = conn->privateData;

3964 3965 3966
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

3967 3968 3969 3970
    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        return -1;
3971

3972
    return 0;
3973 3974 3975 3976
}


static int
3977 3978
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
3979 3980 3981
{
    libxlDriverPrivatePtr driver = conn->privateData;

3982 3983 3984
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

3985 3986 3987 3988
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
3989

3990
    return 0;
3991 3992
}

3993 3994 3995 3996 3997 3998
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
3999
    if (!(vm = libxlDomObjFromDomain(dom)))
4000 4001
        goto cleanup;

4002 4003 4004
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4005 4006 4007
    *autostart = vm->autostart;
    ret = 0;

4008
 cleanup:
4009
    if (vm)
4010
        virObjectUnlock(vm);
4011 4012 4013 4014 4015 4016 4017
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4018
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4019 4020 4021 4022
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
4023
    if (!(vm = libxlDomObjFromDomain(dom)))
4024 4025
        goto cleanup;

J
Jim Fehlig 已提交
4026 4027
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

4028 4029 4030
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4031 4032 4033
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4034
    if (!vm->persistent) {
4035 4036
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
4037
        goto endjob;
4038 4039 4040 4041 4042
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
4043
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
4044
            goto endjob;
4045
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
4046
            goto endjob;
4047 4048

        if (autostart) {
4049
            if (virFileMakePath(cfg->autostartDir) < 0) {
4050
                virReportSystemError(errno,
4051
                                     _("cannot create autostart directory %s"),
4052
                                     cfg->autostartDir);
4053
                goto endjob;
4054 4055 4056 4057 4058 4059
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4060
                goto endjob;
4061 4062 4063 4064 4065 4066
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4067
                goto endjob;
4068 4069 4070 4071 4072 4073 4074
            }
        }

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

4075
 endjob:
4076 4077 4078
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

4079
 cleanup:
4080 4081 4082
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    if (vm)
4083
        virObjectUnlock(vm);
4084
    virObjectUnref(cfg);
4085 4086 4087
    return ret;
}

4088 4089 4090
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
J
Jim Fehlig 已提交
4091 4092
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4093 4094
    virDomainObjPtr vm;
    char * ret = NULL;
4095
    const char *name = NULL;
J
Jim Fehlig 已提交
4096
    libxl_scheduler sched_id;
4097

J
Jim Fehlig 已提交
4098
    if (!(vm = libxlDomObjFromDomain(dom)))
4099 4100
        goto cleanup;

4101 4102 4103
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4104
    if (!virDomainObjIsActive(vm)) {
4105
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4106 4107 4108
        goto cleanup;
    }

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

4111 4112
    if (nparams)
        *nparams = 0;
4113
    switch (sched_id) {
J
Jim Fehlig 已提交
4114
    case LIBXL_SCHEDULER_SEDF:
4115
        name = "sedf";
4116
        break;
J
Jim Fehlig 已提交
4117
    case LIBXL_SCHEDULER_CREDIT:
4118
        name = "credit";
4119 4120
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
4121
        break;
J
Jim Fehlig 已提交
4122
    case LIBXL_SCHEDULER_CREDIT2:
4123
        name = "credit2";
4124
        break;
J
Jim Fehlig 已提交
4125
    case LIBXL_SCHEDULER_ARINC653:
4126
        name = "arinc653";
4127 4128
        break;
    default:
J
Jim Fehlig 已提交
4129 4130
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
4131
                     " with libxenlight"), vm->def->id);
4132 4133 4134
        goto cleanup;
    }

4135
    ignore_value(VIR_STRDUP(ret, name));
4136

4137
 cleanup:
4138
    if (vm)
4139
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4140
    virObjectUnref(cfg);
4141 4142 4143
    return ret;
}

4144
static int
4145 4146 4147 4148
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
4149
{
J
Jim Fehlig 已提交
4150 4151
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4152
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4153 4154
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
4155 4156
    int ret = -1;

4157 4158 4159 4160
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

J
Jim Fehlig 已提交
4162
    if (!(vm = libxlDomObjFromDomain(dom)))
4163 4164
        goto cleanup;

4165 4166 4167
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4168
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
4169 4170
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
4171 4172 4173
        goto cleanup;
    }

J
Jim Fehlig 已提交
4174
    sched_id = libxl_get_scheduler(cfg->ctx);
4175

J
Jim Fehlig 已提交
4176
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4177 4178
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4179 4180 4181
        goto cleanup;
    }

J
Jim Fehlig 已提交
4182
    if (libxl_domain_sched_params_get(cfg->ctx, vm->def->id, &sc_info) != 0) {
4183 4184
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
4185
                         " with libxenlight"), vm->def->id);
4186 4187 4188
        goto cleanup;
    }

4189 4190
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
4191 4192
        goto cleanup;

4193
    if (*nparams > 1) {
4194 4195
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
4196
            goto cleanup;
4197 4198
    }

4199 4200
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
4201 4202
    ret = 0;

4203
 cleanup:
4204
    if (vm)
4205
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4206
    virObjectUnref(cfg);
4207 4208 4209 4210
    return ret;
}

static int
4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221
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)
4222
{
4223
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
4224
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4225
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4226
    libxl_domain_sched_params sc_info;
4227
    int sched_id;
4228
    size_t i;
4229 4230
    int ret = -1;

4231
    virCheckFlags(0, -1);
4232 4233 4234 4235 4236 4237
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
4238
        return -1;
4239

J
Jim Fehlig 已提交
4240
    if (!(vm = libxlDomObjFromDomain(dom)))
4241 4242
        goto cleanup;

4243 4244 4245
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4246 4247 4248
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4249
    if (!virDomainObjIsActive(vm)) {
4250
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4251
        goto endjob;
4252 4253
    }

J
Jim Fehlig 已提交
4254
    sched_id = libxl_get_scheduler(cfg->ctx);
4255

J
Jim Fehlig 已提交
4256
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4257 4258
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4259
        goto endjob;
4260 4261
    }

J
Jim Fehlig 已提交
4262
    if (libxl_domain_sched_params_get(cfg->ctx, vm->def->id, &sc_info) != 0) {
4263 4264
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
4265
                         " with libxenlight"), vm->def->id);
4266
        goto endjob;
4267 4268 4269
    }

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

4272
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
4273
            sc_info.weight = params[i].value.ui;
4274
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
4275 4276 4277
            sc_info.cap = params[i].value.ui;
    }

J
Jim Fehlig 已提交
4278
    if (libxl_domain_sched_params_set(cfg->ctx, vm->def->id, &sc_info) != 0) {
4279 4280
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
4281
                         " with libxenlight"), vm->def->id);
4282
        goto endjob;
4283 4284 4285 4286
    }

    ret = 0;

4287
 endjob:
4288 4289 4290
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

4291
 cleanup:
4292
    if (vm)
4293
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4294
    virObjectUnref(cfg);
4295 4296 4297
    return ret;
}

B
Bamvor Jian Zhang 已提交
4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318

static int
libxlDomainOpenConsole(virDomainPtr dom,
                       const char *dev_name,
                       virStreamPtr st,
                       unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainChrDefPtr chr = NULL;
    libxlDomainObjPrivatePtr priv;

    virCheckFlags(VIR_DOMAIN_CONSOLE_FORCE, -1);

    if (dev_name) {
        /* XXX support device aliases in future */
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Named device aliases are not supported"));
        goto cleanup;
    }

J
Jim Fehlig 已提交
4319
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
4320 4321
        goto cleanup;

J
Jim Fehlig 已提交
4322 4323
    LIBXL_CHECK_DOM0_GOTO(vm->def->name, cleanup);

B
Bamvor Jian Zhang 已提交
4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334
    if (virDomainOpenConsoleEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto cleanup;
    }

    priv = vm->privateData;

I
Ian Campbell 已提交
4335 4336
    if (vm->def->nconsoles)
        chr = vm->def->consoles[0];
B
Bamvor Jian Zhang 已提交
4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347

    if (!chr) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot find character device %s"),
                       NULLSTR(dev_name));
        goto cleanup;
    }

    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("character device %s is not using a PTY"),
4348
                       dev_name ? dev_name : NULLSTR(chr->info.alias));
B
Bamvor Jian Zhang 已提交
4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363
        goto cleanup;
    }

    /* handle mutually exclusive access to console devices */
    ret = virChrdevOpen(priv->devs,
                        &chr->source,
                        st,
                        (flags & VIR_DOMAIN_CONSOLE_FORCE) != 0);

    if (ret == 1) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Active console session exists for this domain"));
        ret = -1;
    }

4364
 cleanup:
B
Bamvor Jian Zhang 已提交
4365 4366 4367 4368 4369
    if (vm)
        virObjectUnlock(vm);
    return ret;
}

4370 4371 4372 4373 4374 4375 4376
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389
/* NUMA node affinity information is available through libxl
 * starting from Xen 4.3. */
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY

/* Number of Xen NUMA parameters */
# define LIBXL_NUMA_NPARAM 2

static int
libxlDomainGetNumaParameters(virDomainPtr dom,
                             virTypedParameterPtr params,
                             int *nparams,
                             unsigned int flags)
{
J
Jim Fehlig 已提交
4390 4391
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407
    virDomainObjPtr vm;
    libxl_bitmap nodemap;
    virBitmapPtr nodes = NULL;
    char *nodeset = NULL;
    int rc, ret = -1;
    size_t i, j;

    /* In Xen 4.3, it is possible to query the NUMA node affinity of a domain
     * via libxl, but not to change it. We therefore only allow AFFECT_LIVE. */
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We blindly return a string, and let libvirt.c and remote_driver.c do
     * the filtering on behalf of older clients that can't parse it. */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

4408 4409
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
4410
    if (!(vm = libxlDomObjFromDomain(dom)))
4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429
        goto cleanup;

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

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

    if ((*nparams) == 0) {
        *nparams = LIBXL_NUMA_NPARAM;
        ret = 0;
        goto cleanup;
    }

    for (i = 0; i < LIBXL_NUMA_NPARAM && i < *nparams; i++) {
        virMemoryParameterPtr param = &params[i];
4430
        int numnodes;
4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448

        switch (i) {
        case 0:
            /* NUMA mode */

            /* Xen implements something that is really close to numactl's
             * 'interleave' policy (see `man 8 numactl' for details). */
            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_MODE,
                                        VIR_TYPED_PARAM_INT,
                                        VIR_DOMAIN_NUMATUNE_MEM_INTERLEAVE) < 0)
                goto cleanup;

            break;

        case 1:
            /* Node affinity */

            /* Let's allocate both libxl and libvirt bitmaps */
J
Jim Fehlig 已提交
4449
            numnodes = libxl_get_max_nodes(cfg->ctx);
4450 4451 4452
            if (numnodes <= 0)
                goto cleanup;

J
Jim Fehlig 已提交
4453
            if (libxl_node_bitmap_alloc(cfg->ctx, &nodemap, 0)) {
4454 4455 4456
                virReportOOMError();
                goto cleanup;
            }
J
Ján Tomko 已提交
4457 4458
            if (!(nodes = virBitmapNew(numnodes)))
                goto cleanup;
4459

J
Jim Fehlig 已提交
4460
            rc = libxl_domain_get_nodeaffinity(cfg->ctx,
4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479
                                               vm->def->id,
                                               &nodemap);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get numa affinity"));
                goto cleanup;
            }

            /* First, we convert libxl_bitmap into virBitmap. After that,
             * we format virBitmap as a string that can be returned. */
            virBitmapClearAll(nodes);
            libxl_for_each_set_bit(j, nodemap) {
                if (virBitmapSetBit(nodes, j)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Node %zu out of range"), j);
                    goto cleanup;
                }
            }

4480
            if (!(nodeset = virBitmapFormat(nodes)))
4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496
                goto cleanup;

            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_NODESET,
                                        VIR_TYPED_PARAM_STRING, nodeset) < 0)
                goto cleanup;

            nodeset = NULL;

            break;
        }
    }

    if (*nparams > LIBXL_NUMA_NPARAM)
        *nparams = LIBXL_NUMA_NPARAM;
    ret = 0;

4497
 cleanup:
4498 4499 4500 4501 4502
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
    if (vm)
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4503
    virObjectUnref(cfg);
4504 4505 4506 4507
    return ret;
}
#endif

J
Jim Fehlig 已提交
4508 4509 4510 4511 4512 4513
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4514
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4515
        goto cleanup;
4516 4517 4518 4519

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

J
Jim Fehlig 已提交
4520 4521
    ret = virDomainObjIsActive(obj);

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

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

J
Jim Fehlig 已提交
4534
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4535
        goto cleanup;
4536 4537 4538 4539

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

J
Jim Fehlig 已提交
4540 4541
    ret = obj->persistent;

4542
 cleanup:
J
Jim Fehlig 已提交
4543
    if (obj)
4544
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4545 4546 4547
    return ret;
}

4548 4549 4550 4551 4552 4553
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4554
    if (!(vm = libxlDomObjFromDomain(dom)))
4555
        goto cleanup;
4556 4557 4558 4559

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

4560 4561
    ret = vm->updated;

4562
 cleanup:
4563
    if (vm)
4564
        virObjectUnlock(vm);
4565 4566 4567
    return ret;
}

4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617
static int
libxlDomainInterfaceStats(virDomainPtr dom,
                          const char *path,
                          virDomainInterfaceStatsPtr stats)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    size_t i;
    int ret = -1;

    if (!(vm = libxlDomObjFromDomain(dom)))
        goto cleanup;

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

    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_QUERY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto endjob;
    }

    /* Check the path is one of the domain's network interfaces. */
    for (i = 0; i < vm->def->nnets; i++) {
        if (vm->def->nets[i]->ifname &&
            STREQ(vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
    }

    if (ret == 0)
        ret = virNetInterfaceStats(path, stats);
    else
        virReportError(VIR_ERR_INVALID_ARG,
                       _("'%s' is not a known interface"), path);

 endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

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

4618 4619 4620 4621 4622 4623
static int
libxlDomainGetTotalCPUStats(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
                            virTypedParameterPtr params,
                            unsigned int nparams)
{
J
Jim Fehlig 已提交
4624
    libxlDriverConfigPtr cfg;
4625 4626 4627 4628 4629 4630
    libxl_dominfo d_info;
    int ret = -1;

    if (nparams == 0)
        return LIBXL_NB_TOTAL_CPU_STAT_PARAM;

J
Jim Fehlig 已提交
4631 4632 4633
    libxl_dominfo_init(&d_info);
    cfg = libxlDriverConfigGet(driver);

4634 4635 4636 4637
    if (libxl_domain_info(cfg->ctx, &d_info, vm->def->id) != 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxl_domain_info failed for domain '%d'"),
                       vm->def->id);
J
Jim Fehlig 已提交
4638
        goto cleanup;
4639 4640 4641 4642 4643 4644 4645 4646 4647 4648
    }

    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_CPU_STATS_CPUTIME,
                                VIR_TYPED_PARAM_ULLONG, d_info.cpu_time) < 0)
        goto cleanup;

    ret = nparams;

 cleanup:
    libxl_dominfo_dispose(&d_info);
J
Jim Fehlig 已提交
4649
    virObjectUnref(cfg);
4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663
    return ret;
}

static int
libxlDomainGetPerCPUStats(libxlDriverPrivatePtr driver,
                          virDomainObjPtr vm,
                          virTypedParameterPtr params,
                          unsigned int nparams,
                          int start_cpu,
                          unsigned int ncpus)
{
    libxl_vcpuinfo *vcpuinfo;
    int maxcpu, hostcpus;
    size_t i;
J
Jim Fehlig 已提交
4664
    libxlDriverConfigPtr cfg;
4665 4666 4667 4668 4669
    int ret = -1;

    if (nparams == 0 && ncpus != 0)
        return LIBXL_NB_TOTAL_CPU_STAT_PARAM;
    else if (nparams == 0)
4670
        return virDomainDefGetVcpusMax(vm->def);
4671

J
Jim Fehlig 已提交
4672
    cfg = libxlDriverConfigGet(driver);
4673 4674 4675 4676 4677
    if ((vcpuinfo = libxl_list_vcpu(cfg->ctx, vm->def->id, &maxcpu,
                                    &hostcpus)) == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
                       vm->def->id);
J
Jim Fehlig 已提交
4678
        goto cleanup;
4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690
    }

    for (i = start_cpu; i < maxcpu && i < ncpus; ++i) {
        if (virTypedParameterAssign(&params[(i-start_cpu)],
                                    VIR_DOMAIN_CPU_STATS_CPUTIME,
                                    VIR_TYPED_PARAM_ULLONG,
                                    vcpuinfo[i].vcpu_time) < 0)
            goto cleanup;
    }
    ret = nparams;

 cleanup:
J
Jim Fehlig 已提交
4691 4692 4693
    if (vcpuinfo)
        libxl_vcpuinfo_list_free(vcpuinfo, maxcpu);
    virObjectUnref(cfg);
4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734
    return ret;
}

static int
libxlDomainGetCPUStats(virDomainPtr dom,
                       virTypedParameterPtr params,
                       unsigned int nparams,
                       int start_cpu,
                       unsigned int ncpus,
                       unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

    if (!(vm = libxlDomObjFromDomain(dom)))
        goto cleanup;

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

    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto cleanup;
    }

    if (start_cpu == -1)
        ret = libxlDomainGetTotalCPUStats(driver, vm, params, nparams);
    else
        ret = libxlDomainGetPerCPUStats(driver, vm, params, nparams,
                                          start_cpu, ncpus);

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

4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748
#define LIBXL_SET_MEMSTAT(TAG, VAL) \
        if (i < nr_stats) { \
            stats[i].tag = TAG; \
            stats[i].val = VAL; \
            i++; \
        }

static int
libxlDomainMemoryStats(virDomainPtr dom,
                       virDomainMemoryStatPtr stats,
                       unsigned int nr_stats,
                       unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
4749
    libxlDriverConfigPtr cfg;
4750 4751 4752 4753 4754 4755 4756 4757
    virDomainObjPtr vm;
    libxl_dominfo d_info;
    unsigned mem, maxmem;
    size_t i = 0;
    int ret = -1;

    virCheckFlags(0, -1);

4758
    libxl_dominfo_init(&d_info);
J
Jim Fehlig 已提交
4759 4760
    cfg = libxlDriverConfigGet(driver);

4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790
    if (!(vm = libxlDomObjFromDomain(dom)))
        goto cleanup;

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

    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_QUERY) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto endjob;
    }

    if (libxl_domain_info(cfg->ctx, &d_info, vm->def->id) != 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxl_domain_info failed for domain '%d'"),
                       vm->def->id);
        goto endjob;
    }
    mem = d_info.current_memkb;
    maxmem = d_info.max_memkb;

    LIBXL_SET_MEMSTAT(VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON, mem);
    LIBXL_SET_MEMSTAT(VIR_DOMAIN_MEMORY_STAT_AVAILABLE, maxmem);

    ret = i;

 endjob:
4791
    if (!libxlDomainObjEndJob(driver, vm))
4792 4793 4794
        vm = NULL;

 cleanup:
4795
    libxl_dominfo_dispose(&d_info);
4796 4797
    if (vm)
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4798
    virObjectUnref(cfg);
4799 4800 4801 4802 4803
    return ret;
}

#undef LIBXL_SET_MEMSTAT

4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840
static int
libxlDomainGetJobInfo(virDomainPtr dom,
                      virDomainJobInfoPtr info)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    int ret = -1;

    if (!(vm = libxlDomObjFromDomain(dom)))
        goto cleanup;

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

    priv = vm->privateData;
    if (!priv->job.active) {
        memset(info, 0, sizeof(*info));
        info->type = VIR_DOMAIN_JOB_NONE;
        ret = 0;
        goto cleanup;
    }

    /* In libxl we don't have an estimated completion time
     * thus we always set to unbounded and update time
     * for the active job. */
    if (libxlDomainJobUpdateTime(&priv->job) < 0)
        goto cleanup;

    memcpy(info, priv->job.current, sizeof(virDomainJobInfo));
    ret = 0;

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

4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891
static int
libxlDomainGetJobStats(virDomainPtr dom,
                       int *type,
                       virTypedParameterPtr *params,
                       int *nparams,
                       unsigned int flags)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    virDomainJobInfoPtr jobInfo;
    int ret = -1;
    int maxparams = 0;

    /* VIR_DOMAIN_JOB_STATS_COMPLETED not supported yet */
    virCheckFlags(0, -1);

    if (!(vm = libxlDomObjFromDomain(dom)))
        goto cleanup;

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

    priv = vm->privateData;
    jobInfo = priv->job.current;
    if (!priv->job.active) {
        *type = VIR_DOMAIN_JOB_NONE;
        *params = NULL;
        *nparams = 0;
        ret = 0;
        goto cleanup;
    }

    /* In libxl we don't have an estimated completion time
     * thus we always set to unbounded and update time
     * for the active job. */
    if (libxlDomainJobUpdateTime(&priv->job) < 0)
        goto cleanup;

    if (virTypedParamsAddULLong(params, nparams, &maxparams,
                                VIR_DOMAIN_JOB_TIME_ELAPSED,
                                jobInfo->timeElapsed) < 0)
        goto cleanup;

    *type = jobInfo->type;
    ret = 0;

 cleanup:
    if (vm)
        virObjectUnlock(vm);
    return ret;
}
4892

4893
static int
4894 4895 4896
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4897 4898 4899 4900
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4901 4902 4903
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4904 4905 4906 4907
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4908
        ret = -1;
4909 4910 4911 4912 4913 4914

    return ret;
}


static int
4915
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4916 4917 4918
{
    libxlDriverPrivatePtr driver = conn->privateData;

4919 4920 4921
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4922 4923 4924 4925
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        return -1;
4926

4927
    return 0;
4928 4929
}

J
Jim Fehlig 已提交
4930

4931
static int
4932
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4933 4934 4935 4936
{
    return 1;
}

4937
static int
4938 4939 4940
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4941 4942 4943 4944
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4945
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4946

4947 4948 4949
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4950 4951
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
4952 4953 4954 4955

    return ret;
}

4956 4957 4958 4959 4960 4961 4962 4963 4964
/* Which features are supported by this driver? */
static int
libxlConnectSupportsFeature(virConnectPtr conn, int feature)
{
    if (virConnectSupportsFeatureEnsureACL(conn) < 0)
        return -1;

    switch (feature) {
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
J
Jim Fehlig 已提交
4965
    case VIR_DRV_FEATURE_MIGRATION_PARAMS:
J
Joao Martins 已提交
4966
    case VIR_DRV_FEATURE_MIGRATION_P2P:
4967 4968 4969 4970 4971
        return 1;
    default:
        return 0;
    }
}
4972

4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983
static int
libxlNodeDeviceGetPCIInfo(virNodeDeviceDefPtr def,
                          unsigned *domain,
                          unsigned *bus,
                          unsigned *slot,
                          unsigned *function)
{
    virNodeDevCapsDefPtr cap;

    cap = def->caps;
    while (cap) {
4984
        if (cap->data.type == VIR_NODE_DEV_CAP_PCI_DEV) {
4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997
            *domain   = cap->data.pci_dev.domain;
            *bus      = cap->data.pci_dev.bus;
            *slot     = cap->data.pci_dev.slot;
            *function = cap->data.pci_dev.function;
            break;
        }

        cap = cap->next;
    }

    if (!cap) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("device %s is not a PCI device"), def->name);
C
Chunyan Liu 已提交
4998
        return -1;
4999 5000
    }

C
Chunyan Liu 已提交
5001
    return 0;
5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037
}

static int
libxlNodeDeviceDetachFlags(virNodeDevicePtr dev,
                           const char *driverName,
                           unsigned int flags)
{
    virPCIDevicePtr pci = NULL;
    unsigned domain = 0, bus = 0, slot = 0, function = 0;
    int ret = -1;
    virNodeDeviceDefPtr def = NULL;
    char *xml = NULL;
    libxlDriverPrivatePtr driver = dev->conn->privateData;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

    virCheckFlags(0, -1);

    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto cleanup;

    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
    if (!def)
        goto cleanup;

    if (virNodeDeviceDetachFlagsEnsureACL(dev->conn, def) < 0)
        goto cleanup;

    if (libxlNodeDeviceGetPCIInfo(def, &domain, &bus, &slot, &function) < 0)
        goto cleanup;

    pci = virPCIDeviceNew(domain, bus, slot, function);
    if (!pci)
        goto cleanup;

    if (!driverName || STREQ(driverName, "xen")) {
5038
        virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_XEN);
5039 5040 5041 5042 5043 5044 5045 5046 5047 5048
    } else {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported driver name '%s'"), driverName);
        goto cleanup;
    }

    if (virHostdevPCINodeDeviceDetach(hostdev_mgr, pci) < 0)
        goto cleanup;

    ret = 0;
5049
 cleanup:
5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091
    virPCIDeviceFree(pci);
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceDettach(virNodeDevicePtr dev)
{
    return libxlNodeDeviceDetachFlags(dev, NULL, 0);
}

static int
libxlNodeDeviceReAttach(virNodeDevicePtr dev)
{
    virPCIDevicePtr pci = NULL;
    unsigned domain = 0, bus = 0, slot = 0, function = 0;
    int ret = -1;
    virNodeDeviceDefPtr def = NULL;
    char *xml = NULL;
    libxlDriverPrivatePtr driver = dev->conn->privateData;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto cleanup;

    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
    if (!def)
        goto cleanup;

    if (virNodeDeviceReAttachEnsureACL(dev->conn, def) < 0)
        goto cleanup;

    if (libxlNodeDeviceGetPCIInfo(def, &domain, &bus, &slot, &function) < 0)
        goto cleanup;

    pci = virPCIDeviceNew(domain, bus, slot, function);
    if (!pci)
        goto cleanup;

    if (virHostdevPCINodeDeviceReAttach(hostdev_mgr, pci) < 0)
C
Chunyan Liu 已提交
5092
        goto cleanup;
5093 5094

    ret = 0;
C
Chunyan Liu 已提交
5095

5096
 cleanup:
C
Chunyan Liu 已提交
5097
    virPCIDeviceFree(pci);
5098 5099 5100 5101 5102 5103 5104 5105
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
C
Chunyan Liu 已提交
5106
    virPCIDevicePtr pci = NULL;
5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132
    unsigned domain = 0, bus = 0, slot = 0, function = 0;
    int ret = -1;
    virNodeDeviceDefPtr def = NULL;
    char *xml = NULL;
    libxlDriverPrivatePtr driver = dev->conn->privateData;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto cleanup;

    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
    if (!def)
        goto cleanup;

    if (virNodeDeviceResetEnsureACL(dev->conn, def) < 0)
        goto cleanup;

    if (libxlNodeDeviceGetPCIInfo(def, &domain, &bus, &slot, &function) < 0)
        goto cleanup;

    pci = virPCIDeviceNew(domain, bus, slot, function);
    if (!pci)
        goto cleanup;

    if (virHostdevPCINodeDeviceReset(hostdev_mgr, pci) < 0)
C
Chunyan Liu 已提交
5133
        goto cleanup;
5134 5135

    ret = 0;
C
Chunyan Liu 已提交
5136

5137
 cleanup:
C
Chunyan Liu 已提交
5138
    virPCIDeviceFree(pci);
5139 5140 5141 5142 5143
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

J
Jim Fehlig 已提交
5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154
static char *
libxlDomainMigrateBegin3Params(virDomainPtr domain,
                               virTypedParameterPtr params,
                               int nparams,
                               char **cookieout ATTRIBUTE_UNUSED,
                               int *cookieoutlen ATTRIBUTE_UNUSED,
                               unsigned int flags)
{
    const char *xmlin = NULL;
    virDomainObjPtr vm = NULL;

5155 5156 5157 5158 5159
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return NULL;
#endif

J
Jim Fehlig 已提交
5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171
    virCheckFlags(LIBXL_MIGRATION_FLAGS, NULL);
    if (virTypedParamsValidate(params, nparams, LIBXL_MIGRATION_PARAMETERS) < 0)
        return NULL;

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_XML,
                                &xmlin) < 0)
        return NULL;

    if (!(vm = libxlDomObjFromDomain(domain)))
        return NULL;

J
Jim Fehlig 已提交
5172 5173 5174 5175 5176 5177
    if (STREQ_NULLABLE(vm->def->name, "Domain-0")) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Domain-0 cannot be migrated"));
            return NULL;
    }

J
Jim Fehlig 已提交
5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209
    if (virDomainMigrateBegin3ParamsEnsureACL(domain->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return NULL;
    }

    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        virObjectUnlock(vm);
        return NULL;
    }

    return libxlDomainMigrationBegin(domain->conn, vm, xmlin);
}

static int
libxlDomainMigratePrepare3Params(virConnectPtr dconn,
                                 virTypedParameterPtr params,
                                 int nparams,
                                 const char *cookiein ATTRIBUTE_UNUSED,
                                 int cookieinlen ATTRIBUTE_UNUSED,
                                 char **cookieout ATTRIBUTE_UNUSED,
                                 int *cookieoutlen ATTRIBUTE_UNUSED,
                                 char **uri_out,
                                 unsigned int flags)
{
    libxlDriverPrivatePtr driver = dconn->privateData;
    virDomainDefPtr def = NULL;
    const char *dom_xml = NULL;
    const char *dname = NULL;
    const char *uri_in = NULL;

5210 5211 5212 5213 5214
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236
    virCheckFlags(LIBXL_MIGRATION_FLAGS, -1);
    if (virTypedParamsValidate(params, nparams, LIBXL_MIGRATION_PARAMETERS) < 0)
        goto error;

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_XML,
                                &dom_xml) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME,
                                &dname) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_URI,
                                &uri_in) < 0)

        goto error;

    if (!(def = libxlDomainMigrationPrepareDef(driver, dom_xml, dname)))
        goto error;

    if (virDomainMigratePrepare3ParamsEnsureACL(dconn, def) < 0)
        goto error;

5237
    if (libxlDomainMigrationPrepare(dconn, &def, uri_in, uri_out, flags) < 0)
J
Jim Fehlig 已提交
5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264
        goto error;

    return 0;

 error:
    virDomainDefFree(def);
    return -1;
}

static int
libxlDomainMigratePerform3Params(virDomainPtr dom,
                                 const char *dconnuri,
                                 virTypedParameterPtr params,
                                 int nparams,
                                 const char *cookiein ATTRIBUTE_UNUSED,
                                 int cookieinlen ATTRIBUTE_UNUSED,
                                 char **cookieout ATTRIBUTE_UNUSED,
                                 int *cookieoutlen ATTRIBUTE_UNUSED,
                                 unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    const char *dom_xml = NULL;
    const char *dname = NULL;
    const char *uri = NULL;
    int ret = -1;

5265 5266 5267 5268 5269
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291
    virCheckFlags(LIBXL_MIGRATION_FLAGS, -1);
    if (virTypedParamsValidate(params, nparams, LIBXL_MIGRATION_PARAMETERS) < 0)
        goto cleanup;

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_XML,
                                &dom_xml) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME,
                                &dname) < 0 ||
        virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_URI,
                                &uri) < 0)

        goto cleanup;

    if (!(vm = libxlDomObjFromDomain(dom)))
        goto cleanup;

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

J
Joao Martins 已提交
5292 5293 5294 5295 5296 5297 5298 5299 5300
    if (flags & VIR_MIGRATE_PEER2PEER) {
        if (libxlDomainMigrationPerformP2P(driver, vm, dom->conn, dom_xml,
                                           dconnuri, uri, dname, flags) < 0)
            goto cleanup;
    } else {
        if (libxlDomainMigrationPerform(driver, vm, dom_xml, dconnuri,
                                        uri, dname, flags) < 0)
            goto cleanup;
    }
J
Jim Fehlig 已提交
5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323

    ret = 0;

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

static virDomainPtr
libxlDomainMigrateFinish3Params(virConnectPtr dconn,
                                virTypedParameterPtr params,
                                int nparams,
                                const char *cookiein ATTRIBUTE_UNUSED,
                                int cookieinlen ATTRIBUTE_UNUSED,
                                char **cookieout ATTRIBUTE_UNUSED,
                                int *cookieoutlen ATTRIBUTE_UNUSED,
                                unsigned int flags,
                                int cancelled)
{
    libxlDriverPrivatePtr driver = dconn->privateData;
    virDomainObjPtr vm = NULL;
    const char *dname = NULL;
5324
    virDomainPtr ret = NULL;
J
Jim Fehlig 已提交
5325

5326 5327 5328 5329 5330
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return NULL;
#endif

J
Jim Fehlig 已提交
5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350
    virCheckFlags(LIBXL_MIGRATION_FLAGS, NULL);
    if (virTypedParamsValidate(params, nparams, LIBXL_MIGRATION_PARAMETERS) < 0)
        return NULL;

    if (virTypedParamsGetString(params, nparams,
                                VIR_MIGRATE_PARAM_DEST_NAME,
                                &dname) < 0)
        return NULL;

    if (!dname ||
        !(vm = virDomainObjListFindByName(driver->domains, dname))) {
        /* Migration obviously failed if the domain doesn't exist */
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Migration failed. No domain on destination host "
                         "with matching name '%s'"),
                       NULLSTR(dname));
        return NULL;
    }

    if (virDomainMigrateFinish3ParamsEnsureACL(dconn, vm->def) < 0) {
5351
        virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
5352 5353 5354
        return NULL;
    }

5355
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
5356
        virDomainObjEndAPI(&vm);
5357 5358 5359 5360 5361 5362 5363 5364
        return NULL;
    }

    ret = libxlDomainMigrationFinish(dconn, vm, flags, cancelled);

    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

5365
    virDomainObjEndAPI(&vm);
5366 5367

    return ret;
J
Jim Fehlig 已提交
5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381
}

static int
libxlDomainMigrateConfirm3Params(virDomainPtr domain,
                                 virTypedParameterPtr params,
                                 int nparams,
                                 const char *cookiein ATTRIBUTE_UNUSED,
                                 int cookieinlen ATTRIBUTE_UNUSED,
                                 unsigned int flags,
                                 int cancelled)
{
    libxlDriverPrivatePtr driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;

5382 5383 5384 5385 5386
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401
    virCheckFlags(LIBXL_MIGRATION_FLAGS, -1);
    if (virTypedParamsValidate(params, nparams, LIBXL_MIGRATION_PARAMETERS) < 0)
        return -1;

    if (!(vm = libxlDomObjFromDomain(domain)))
        return -1;

    if (virDomainMigrateConfirm3ParamsEnsureACL(domain->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return -1;
    }

    return libxlDomainMigrationConfirm(driver, vm, flags, cancelled);
}

5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418
static int libxlNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
{
    memset(secmodel, 0, sizeof(*secmodel));

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

    /*
     * Currently the libxl driver does not support security model.
     * Similar to the qemu driver, treat this as success and simply
     * return no data in secmodel.  Avoids spamming the libvirt log
     * with "this function is not supported by the connection driver:
     * virNodeGetSecurityModel"
     */
    return 0;
}
5419

5420
static virHypervisorDriver libxlHypervisorDriver = {
5421
    .name = LIBXL_DRIVER_NAME,
5422 5423 5424 5425
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
5426
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
5427
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
5428
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
5429
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
5430 5431 5432 5433
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
5434 5435 5436 5437 5438 5439 5440
    .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 */
5441
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
5442 5443
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
5444
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
5445 5446
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
5447
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
5448 5449 5450 5451
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
5452
    .domainSave = libxlDomainSave, /* 0.9.2 */
5453
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
5454
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
5455
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
5456
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
5457 5458 5459 5460
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
5461
    .domainPinVcpuFlags = libxlDomainPinVcpuFlags, /* 1.2.1 */
5462
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
5463
    .domainGetVcpuPinInfo = libxlDomainGetVcpuPinInfo, /* 1.2.1 */
5464
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
5465 5466 5467 5468
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
5469 5470 5471
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
5472
    .domainDefineXMLFlags = libxlDomainDefineXMLFlags, /* 1.2.12 */
5473
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
5474
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
5475 5476 5477 5478 5479
    .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 */
5480 5481 5482 5483
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
5484
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
5485
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
5486
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
5487 5488 5489
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
5490
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
5491
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
5492
    .domainGetJobInfo = libxlDomainGetJobInfo, /* 1.3.1 */
5493
    .domainGetJobStats = libxlDomainGetJobStats, /* 1.3.1 */
P
Pavel Hrdina 已提交
5494 5495
    .domainMemoryStats = libxlDomainMemoryStats, /* 1.3.0 */
    .domainGetCPUStats = libxlDomainGetCPUStats, /* 1.3.0 */
5496
    .domainInterfaceStats = libxlDomainInterfaceStats, /* 1.3.2 */
5497 5498
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
5499 5500 5501
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
5502
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
5503 5504 5505
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
5506 5507 5508
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
5509
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
5510 5511 5512 5513
    .nodeDeviceDettach = libxlNodeDeviceDettach, /* 1.2.3 */
    .nodeDeviceDetachFlags = libxlNodeDeviceDetachFlags, /* 1.2.3 */
    .nodeDeviceReAttach = libxlNodeDeviceReAttach, /* 1.2.3 */
    .nodeDeviceReset = libxlNodeDeviceReset, /* 1.2.3 */
5514 5515 5516 5517 5518
    .domainMigrateBegin3Params = libxlDomainMigrateBegin3Params, /* 1.2.6 */
    .domainMigratePrepare3Params = libxlDomainMigratePrepare3Params, /* 1.2.6 */
    .domainMigratePerform3Params = libxlDomainMigratePerform3Params, /* 1.2.6 */
    .domainMigrateFinish3Params = libxlDomainMigrateFinish3Params, /* 1.2.6 */
    .domainMigrateConfirm3Params = libxlDomainMigrateConfirm3Params, /* 1.2.6 */
5519
    .nodeGetSecurityModel = libxlNodeGetSecurityModel, /* 1.2.16 */
J
Jim Fehlig 已提交
5520 5521
};

5522 5523 5524 5525
static virConnectDriver libxlConnectDriver = {
    .hypervisorDriver = &libxlHypervisorDriver,
};

J
Jim Fehlig 已提交
5526 5527
static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
5528
    .stateInitialize = libxlStateInitialize,
5529
    .stateAutoStart = libxlStateAutoStart,
5530 5531
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
5532 5533 5534 5535 5536 5537
};


int
libxlRegister(void)
{
5538 5539
    if (virRegisterConnectDriver(&libxlConnectDriver,
                                 true) < 0)
J
Jim Fehlig 已提交
5540 5541 5542 5543 5544 5545
        return -1;
    if (virRegisterStateDriver(&libxlStateDriver) < 0)
        return -1;

    return 0;
}