libxl_driver.c 167.1 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"
48
#include "libxl_capabilities.h"
J
Jim Fehlig 已提交
49
#include "libxl_migration.h"
50
#include "xen_xm.h"
51
#include "xen_sxpr.h"
52
#include "xen_xl.h"
53
#include "virtypedparam.h"
M
Martin Kletzander 已提交
54
#include "viruri.h"
55
#include "virstring.h"
56
#include "virsysinfo.h"
57
#include "viraccessapicheck.h"
58
#include "viratomic.h"
59
#include "virhostdev.h"
60
#include "network/bridge_driver.h"
61
#include "locking/domain_lock.h"
62
#include "virstats.h"
J
Jim Fehlig 已提交
63 64 65

#define VIR_FROM_THIS VIR_FROM_LIBXL

66 67
VIR_LOG_INIT("libxl.libxl_driver");

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

74 75
#define LIBXL_NB_TOTAL_CPU_STAT_PARAM 1

76
#define HYPERVISOR_CAPABILITIES "/proc/xen/capabilities"
R
Roman Bogorodskiy 已提交
77
#define HYPERVISOR_XENSTORED "/dev/xen/xenstored"
78

79 80 81
/* Number of Xen scheduler parameters */
#define XEN_SCHED_CREDIT_NPARAM   2

J
Jim Fehlig 已提交
82 83 84 85 86 87 88 89 90
#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)

91

92
static libxlDriverPrivatePtr libxl_driver;
J
Jim Fehlig 已提交
93

94 95 96 97 98 99 100 101 102
/* 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 已提交
103
/* Function declarations */
104 105
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
106 107
                           void *opaque);

J
Jim Fehlig 已提交
108 109

/* Function definitions */
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 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
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 已提交
287 288 289 290 291 292 293
static virDomainObjPtr
libxlDomObjFromDomain(virDomainPtr dom)
{
    virDomainObjPtr vm;
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

W
Wang Yufei 已提交
294
    vm = virDomainObjListFindByUUIDRef(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
295 296 297 298 299 300 301 302 303 304 305
    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;
}

306 307
static int
libxlAutostartDomain(virDomainObjPtr vm,
308 309 310
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
311
    int ret = -1;
312

W
Wang Yufei 已提交
313
    virObjectRef(vm);
314
    virObjectLock(vm);
315 316
    virResetLastError();

W
Wang Yufei 已提交
317 318
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;
319

320
    if (vm->autostart && !virDomainObjIsActive(vm) &&
321
        libxlDomainStartNew(driver, vm, false) < 0) {
322 323 324
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to autostart VM '%s': %s"),
                       vm->def->name, virGetLastErrorMessage());
325
        goto endjob;
326 327
    }

328
    ret = 0;
329 330

 endjob:
W
Wang Yufei 已提交
331 332 333
    libxlDomainObjEndJob(driver, vm);
 cleanup:
    virDomainObjEndAPI(&vm);
334

335
    return ret;
336 337
}

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

355
    virObjectLock(vm);
J
Jim Fehlig 已提交
356

357 358
    libxl_dominfo_init(&d_info);

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

    /* Update hostdev state */
380
    if (virHostdevUpdateActiveDomainDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
381 382 383
                                            vm->def, VIR_HOSTDEV_SP_PCI) < 0)
        goto out;

384
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
385 386
        driver->inhibitCallback(true, driver->inhibitOpaque);

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

390
    libxl_dominfo_dispose(&d_info);
391
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
392
    virObjectUnref(cfg);
393
    return 0;
J
Jim Fehlig 已提交
394

395
 out:
396
    libxl_dominfo_dispose(&d_info);
397
    libxlDomainCleanup(driver, vm);
J
Jim Fehlig 已提交
398
    if (!vm->persistent)
399
        virDomainObjListRemoveLocked(driver->domains, vm);
J
Jim Fehlig 已提交
400
    else
401
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
402
    virObjectUnref(cfg);
403 404

    return -1;
J
Jim Fehlig 已提交
405 406 407 408 409
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
410
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
411 412 413
}

static int
414
libxlStateCleanup(void)
J
Jim Fehlig 已提交
415 416 417 418
{
    if (!libxl_driver)
        return -1;

419
    virObjectUnref(libxl_driver->hostdevMgr);
420
    virObjectUnref(libxl_driver->config);
421
    virObjectUnref(libxl_driver->xmlopt);
422
    virObjectUnref(libxl_driver->domains);
423
    virObjectUnref(libxl_driver->reservedGraphicsPorts);
J
Jim Fehlig 已提交
424
    virObjectUnref(libxl_driver->migrationPorts);
425
    virLockManagerPluginUnref(libxl_driver->lockManager);
J
Jim Fehlig 已提交
426

427
    virObjectEventStateFree(libxl_driver->domainEventState);
428
    virSysinfoDefFree(libxl_driver->hostsysinfo);
429

J
Jim Fehlig 已提交
430 431 432 433 434 435
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

436 437
static bool
libxlDriverShouldLoad(bool privileged)
438
{
439
    bool ret = false;
J
Jim Fehlig 已提交
440

441
    /* Don't load if non-root */
J
Jim Fehlig 已提交
442
    if (!privileged) {
443
        VIR_INFO("Not running privileged, disabling libxenlight driver");
444
        return ret;
J
Jim Fehlig 已提交
445 446
    }

R
Roman Bogorodskiy 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
    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");
468 469 470 471
        return ret;
    }

    /* Don't load if legacy xen toolstack (xend) is in use */
472 473 474 475 476 477 478 479 480 481 482
    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);
483 484
    } else {
        ret = true;
J
Jim Fehlig 已提交
485 486
    }

487 488 489
    return ret;
}

490 491 492 493 494 495 496 497 498 499
/* 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,
};

500 501 502 503 504 505 506 507
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
};

508 509 510 511 512 513
const struct libxl_event_hooks ev_hooks = {
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlDomainEventHandler,
    .disaster = NULL,
};

J
Jim Fehlig 已提交
514 515 516 517 518 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
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 已提交
554
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
555 556 557
    if (virDomainDefSetVcpusMax(vm->def, d_info.vcpu_max_id + 1))
        goto cleanup;

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

    ret = 0;

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

575 576 577 578 579
static int
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
580
    libxlDriverConfigPtr cfg;
581
    char *driverConf = NULL;
582 583 584 585 586
    char ebuf[1024];

    if (!libxlDriverShouldLoad(privileged))
        return 0;

J
Jim Fehlig 已提交
587 588 589 590
    if (VIR_ALLOC(libxl_driver) < 0)
        return -1;

    if (virMutexInit(&libxl_driver->lock) < 0) {
591 592
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
J
Jim Fehlig 已提交
593 594 595 596 597
        VIR_FREE(libxl_driver);
        return -1;
    }

    /* Allocate bitmap for vnc port reservation */
598
    if (!(libxl_driver->reservedGraphicsPorts =
J
Ján Tomko 已提交
599 600
          virPortAllocatorNew(_("VNC"),
                              LIBXL_VNC_PORT_MIN,
601 602
                              LIBXL_VNC_PORT_MAX,
                              0)))
603
        goto error;
J
Jim Fehlig 已提交
604

J
Jim Fehlig 已提交
605 606 607 608
    /* Allocate bitmap for migration port reservation */
    if (!(libxl_driver->migrationPorts =
          virPortAllocatorNew(_("migration"),
                              LIBXL_MIGRATION_PORT_MIN,
609
                              LIBXL_MIGRATION_PORT_MAX, 0)))
J
Jim Fehlig 已提交
610 611
        goto error;

612 613
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
614

615 616 617
    if (!(libxl_driver->hostdevMgr = virHostdevManagerGetDefault()))
        goto error;

618
    if (!(cfg = libxlDriverConfigNew()))
619
        goto error;
J
Jim Fehlig 已提交
620

621 622 623 624 625 626 627
    if (virAsprintf(&driverConf, "%s/libxl.conf", cfg->configBaseDir) < 0)
        goto error;

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

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

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

634 635 636
    /* Register callback to handle domain events */
    libxl_event_register_callbacks(cfg->ctx, &ev_hooks, libxl_driver);

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

667 668 669 670 671 672 673 674
    if (!(libxl_driver->lockManager =
          virLockManagerPluginNew(cfg->lockManagerName ?
                                  cfg->lockManagerName : "nop",
                                  "libxl",
                                  cfg->configBaseDir,
                                  0)))
        goto error;

675
    /* read the host sysinfo */
676
    libxl_driver->hostsysinfo = virSysinfoRead();
677

678
    libxl_driver->domainEventState = virObjectEventStateNew();
E
Eric Blake 已提交
679
    if (!libxl_driver->domainEventState)
680 681
        goto error;

682
    if ((cfg->caps = libxlMakeCapabilities(cfg->ctx)) == NULL) {
683 684
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
685 686 687
        goto error;
    }

688
    if (!(libxl_driver->xmlopt = libxlCreateXMLConf()))
689
        goto error;
J
Jim Fehlig 已提交
690

J
Jim Fehlig 已提交
691 692 693 694
    /* Add Domain-0 */
    if (libxlAddDom0(libxl_driver) < 0)
        goto error;

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

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
708
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
709 710
                                       cfg->configDir,
                                       cfg->autostartDir,
711
                                       0,
712
                                       cfg->caps,
713
                                       libxl_driver->xmlopt,
714
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
715 716
        goto error;

717 718
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
719

J
Jim Fehlig 已提交
720 721
    return 0;

722
 error:
723
    VIR_FREE(driverConf);
724
    libxlStateCleanup();
725
    return -1;
J
Jim Fehlig 已提交
726 727
}

728 729 730 731 732 733 734 735 736 737
static void
libxlStateAutoStart(void)
{
    if (!libxl_driver)
        return;

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

J
Jim Fehlig 已提交
738
static int
739
libxlStateReload(void)
J
Jim Fehlig 已提交
740
{
741 742
    libxlDriverConfigPtr cfg;

J
Jim Fehlig 已提交
743 744 745
    if (!libxl_driver)
        return 0;

746 747
    cfg = libxlDriverConfigGet(libxl_driver);

748
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
749 750
                                   cfg->configDir,
                                   cfg->autostartDir,
751
                                   1,
752
                                   cfg->caps,
753
                                   libxl_driver->xmlopt,
754 755
                                   NULL, libxl_driver);

756 757
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
758

759
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
760 761 762 763 764
    return 0;
}


static virDrvOpenStatus
765 766
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
767
                 virConfPtr conf ATTRIBUTE_UNUSED,
768
                 unsigned int flags)
J
Jim Fehlig 已提交
769
{
E
Eric Blake 已提交
770 771
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
772 773 774 775
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

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

806 807 808
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
809 810 811 812 813 814
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
815
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
816 817 818 819 820 821
{
    conn->privateData = NULL;
    return 0;
}

static const char *
822
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
823
{
824 825 826
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
827
    return "Xen";
J
Jim Fehlig 已提交
828 829 830
}

static int
831
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
832 833
{
    libxlDriverPrivatePtr driver = conn->privateData;
834
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
835

836 837 838
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

839 840 841
    cfg = libxlDriverConfigGet(driver);
    *version = cfg->version;
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
842 843 844
    return 0;
}

845

846
static char *libxlConnectGetHostname(virConnectPtr conn)
847
{
848 849 850
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

851 852 853
    return virGetHostname();
}

854 855 856 857 858 859 860 861
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

862 863 864
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

865 866 867 868 869 870 871 872
    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;
873
    if (virBufferCheckError(&buf) < 0)
874 875 876
        return NULL;
    return virBufferContentAndReset(&buf);
}
877

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

885 886 887
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

888 889
    cfg = libxlDriverConfigGet(driver);
    ret = libxl_get_max_cpus(cfg->ctx);
890 891 892 893 894
    /* 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)
895
        ret = -1;
J
Jim Fehlig 已提交
896

897
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
898 899 900 901 902 903
    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
904 905 906
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

907
    return libxlDriverNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
908 909 910
}

static char *
911
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
912 913 914
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;
915
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
916

917 918 919
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

920
    cfg = libxlDriverConfigGet(driver);
921
    xml = virCapabilitiesFormatXML(cfg->caps);
J
Jim Fehlig 已提交
922

923
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
924 925 926 927
    return xml;
}

static int
928
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
929 930 931 932
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

933 934 935
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

936 937
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
938 939 940 941 942

    return n;
}

static int
943
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
944 945 946 947
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

948 949 950
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

951 952
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
953 954 955 956 957 958 959 960 961 962 963 964

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

968 969 970 971
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_START_VALIDATE)
972
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE_SCHEMA;
J
Jim Fehlig 已提交
973

974
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
975
                                        parse_flags)))
J
Jim Fehlig 已提交
976 977
        goto cleanup;

978 979 980
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

981
    if (!(vm = virDomainObjListAdd(driver->domains, def,
982
                                   driver->xmlopt,
983
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
984 985
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
986
        goto cleanup;
W
Wang Yufei 已提交
987
    virObjectRef(vm);
J
Jim Fehlig 已提交
988 989
    def = NULL;

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

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

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

1012
 endjob:
W
Wang Yufei 已提交
1013
    libxlDomainObjEndJob(driver, vm);
1014

1015
 cleanup:
J
Jim Fehlig 已提交
1016
    virDomainDefFree(def);
W
Wang Yufei 已提交
1017
    virDomainObjEndAPI(&vm);
1018
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    return dom;
}

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

1029
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
1030
    if (!vm) {
1031
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1032 1033 1034
        goto cleanup;
    }

1035 1036 1037
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1038 1039 1040 1041
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

1042
 cleanup:
J
Jim Fehlig 已提交
1043
    if (vm)
1044
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    return dom;
}

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

1055
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
1056
    if (!vm) {
1057
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1058 1059 1060
        goto cleanup;
    }

1061 1062 1063
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1064 1065 1066 1067
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

1068
 cleanup:
J
Jim Fehlig 已提交
1069
    if (vm)
1070
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    return dom;
}

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

1081
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
1082
    if (!vm) {
1083
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1084 1085 1086
        goto cleanup;
    }

1087 1088 1089
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1090 1091 1092 1093
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

1094
 cleanup:
1095
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
1096 1097 1098
    return dom;
}

1099 1100 1101 1102
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1103
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1104
    virDomainObjPtr vm;
1105
    virObjectEventPtr event = NULL;
1106 1107
    int ret = -1;

J
Jim Fehlig 已提交
1108
    if (!(vm = libxlDomObjFromDomain(dom)))
1109
        goto cleanup;
1110

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

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

1116 1117 1118
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1119
    if (!virDomainObjIsActive(vm)) {
1120
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1121
        goto endjob;
1122 1123
    }

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

J
Jiri Denemark 已提交
1132
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1133

1134
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
1135 1136 1137
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

1138
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
1139
        goto endjob;
1140 1141 1142

    ret = 0;

1143
 endjob:
W
Wang Yufei 已提交
1144
    libxlDomainObjEndJob(driver, vm);
1145

1146
 cleanup:
W
Wang Yufei 已提交
1147
    virDomainObjEndAPI(&vm);
1148
    if (event)
1149
        libxlDomainEventQueue(driver, event);
1150
    virObjectUnref(cfg);
1151 1152 1153 1154 1155 1156 1157 1158
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1159
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1160
    virDomainObjPtr vm;
1161
    virObjectEventPtr event = NULL;
1162 1163
    int ret = -1;

J
Jim Fehlig 已提交
1164
    if (!(vm = libxlDomObjFromDomain(dom)))
1165 1166
        goto cleanup;

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

1169 1170 1171
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1172 1173 1174
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1175
    if (!virDomainObjIsActive(vm)) {
1176
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1177
        goto endjob;
1178 1179
    }

J
Jiri Denemark 已提交
1180
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1181
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
1182 1183
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
1184
                           vm->def->id);
1185
            goto endjob;
1186 1187
        }

J
Jiri Denemark 已提交
1188 1189
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1190

1191
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_RESUMED,
1192 1193 1194
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

1195
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
1196
        goto endjob;
1197 1198 1199

    ret = 0;

1200
 endjob:
W
Wang Yufei 已提交
1201
    libxlDomainObjEndJob(driver, vm);
1202

1203
 cleanup:
W
Wang Yufei 已提交
1204
    virDomainObjEndAPI(&vm);
1205
    if (event)
1206
        libxlDomainEventQueue(driver, event);
1207
    virObjectUnref(cfg);
1208 1209 1210
    return ret;
}

J
Jim Fehlig 已提交
1211
static int
1212
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1213
{
J
Jim Fehlig 已提交
1214 1215
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1216 1217 1218
    virDomainObjPtr vm;
    int ret = -1;

1219 1220 1221 1222 1223
    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;
1224

J
Jim Fehlig 已提交
1225
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1226 1227
        goto cleanup;

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

1230
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1231 1232
        goto cleanup;

J
Jim Fehlig 已提交
1233
    if (!virDomainObjIsActive(vm)) {
1234 1235
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1236 1237 1238
        goto cleanup;
    }

1239
    if (flags & VIR_DOMAIN_SHUTDOWN_PARAVIRT) {
J
Jim Fehlig 已提交
1240
        ret = libxl_domain_shutdown(cfg->ctx, vm->def->id);
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
        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 已提交
1255
        ret = libxl_send_trigger(cfg->ctx, vm->def->id,
1256 1257 1258 1259
                                 LIBXL_TRIGGER_POWER, 0);
        if (ret == 0)
            goto cleanup;

1260 1261
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
1262
                       vm->def->id);
1263
        ret = -1;
J
Jim Fehlig 已提交
1264 1265
    }

1266
 cleanup:
J
Jim Fehlig 已提交
1267
    if (vm)
1268
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1269
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1270 1271 1272
    return ret;
}

1273 1274 1275 1276 1277 1278 1279
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
1280
static int
E
Eric Blake 已提交
1281
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1282
{
J
Jim Fehlig 已提交
1283 1284
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1285 1286 1287
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
1288 1289 1290
    virCheckFlags(VIR_DOMAIN_REBOOT_PARAVIRT, -1);
    if (flags == 0)
        flags = VIR_DOMAIN_REBOOT_PARAVIRT;
E
Eric Blake 已提交
1291

J
Jim Fehlig 已提交
1292
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1293 1294
        goto cleanup;

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

1297
    if (virDomainRebootEnsureACL(dom->conn, vm->def, flags) < 0)
1298 1299
        goto cleanup;

J
Jim Fehlig 已提交
1300
    if (!virDomainObjIsActive(vm)) {
1301 1302
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1303 1304 1305
        goto cleanup;
    }

J
Jim Fehlig 已提交
1306
    if (flags & VIR_DOMAIN_REBOOT_PARAVIRT) {
J
Jim Fehlig 已提交
1307
        ret = libxl_domain_reboot(cfg->ctx, vm->def->id);
J
Jim Fehlig 已提交
1308 1309 1310
        if (ret == 0)
            goto cleanup;

1311 1312
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
1313
                       vm->def->id);
J
Jim Fehlig 已提交
1314
        ret = -1;
J
Jim Fehlig 已提交
1315 1316
    }

1317
 cleanup:
J
Jim Fehlig 已提交
1318
    if (vm)
1319
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1320
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1321 1322 1323 1324
    return ret;
}

static int
1325 1326
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1327 1328
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
1329
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1330 1331
    virDomainObjPtr vm;
    int ret = -1;
1332
    virObjectEventPtr event = NULL;
J
Jim Fehlig 已提交
1333

1334 1335
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1336
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1337 1338
        goto cleanup;

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

1341 1342 1343
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1344 1345 1346
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1347
    if (!virDomainObjIsActive(vm)) {
1348 1349
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
1350
        goto endjob;
J
Jim Fehlig 已提交
1351 1352
    }

1353
    if (libxlDomainDestroyInternal(driver, vm) < 0) {
1354
        virReportError(VIR_ERR_INTERNAL_ERROR,
1355
                       _("Failed to destroy domain '%d'"), vm->def->id);
1356
        goto endjob;
J
Jim Fehlig 已提交
1357 1358
    }

1359 1360 1361 1362 1363 1364 1365
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_DESTROYED);

    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

    libxlDomainCleanup(driver, vm);
1366 1367
    if (!vm->persistent)
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1368 1369 1370

    ret = 0;

1371
 endjob:
W
Wang Yufei 已提交
1372
    libxlDomainObjEndJob(driver, vm);
1373

1374
 cleanup:
W
Wang Yufei 已提交
1375
    virDomainObjEndAPI(&vm);
1376 1377
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1378
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1379 1380 1381
    return ret;
}

1382 1383 1384 1385 1386 1387
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1388 1389 1390 1391 1392 1393
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *type = NULL;

J
Jim Fehlig 已提交
1394
    if (!(vm = libxlDomObjFromDomain(dom)))
1395 1396
        goto cleanup;

1397 1398 1399
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1400
    if (VIR_STRDUP(type, virDomainOSTypeToString(vm->def->os.type)) < 0)
1401
        goto cleanup;
1402

1403
 cleanup:
1404
    if (vm)
1405
        virObjectUnlock(vm);
1406 1407 1408
    return type;
}

1409
static unsigned long long
1410 1411 1412
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    virDomainObjPtr vm;
1413
    unsigned long long ret = 0;
1414

J
Jim Fehlig 已提交
1415
    if (!(vm = libxlDomObjFromDomain(dom)))
1416
        goto cleanup;
1417 1418 1419 1420

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

1421
    ret = virDomainDefGetMemoryActual(vm->def);
1422

1423
 cleanup:
1424
    if (vm)
1425
        virObjectUnlock(vm);
1426 1427 1428 1429
    return ret;
}

static int
1430
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1431 1432 1433
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1434
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1435
    virDomainObjPtr vm;
1436
    virDomainDefPtr persistentDef = NULL;
1437 1438 1439
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1440 1441
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1442

J
Jim Fehlig 已提交
1443
    if (!(vm = libxlDomObjFromDomain(dom)))
1444 1445
        goto cleanup;

1446 1447 1448
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

1449 1450 1451
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1452 1453
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm, &flags,
                                        &persistentDef) < 0)
1454
        goto endjob;
1455

1456 1457
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1458

1459
        if (flags & VIR_DOMAIN_MEM_LIVE) {
J
Jim Fehlig 已提交
1460
            if (libxl_domain_setmaxmem(cfg->ctx, vm->def->id, newmem) < 0) {
1461 1462
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
1463
                                 " with libxenlight"), vm->def->id);
1464
                goto endjob;
1465 1466 1467 1468 1469 1470
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1471
            virDomainDefSetMemoryTotal(persistentDef, newmem);
1472 1473
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
1474
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1475
            goto endjob;
1476 1477
        }

1478 1479
    } else {
        /* resize the current memory */
1480

1481
        if (newmem > virDomainDefGetMemoryActual(vm->def)) {
1482 1483
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1484
            goto endjob;
1485 1486 1487
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
1488 1489 1490 1491
            int res;

            /* Unlock virDomainObj while ballooning memory */
            virObjectUnlock(vm);
J
Jim Fehlig 已提交
1492
            res = libxl_set_memory_target(cfg->ctx, vm->def->id, newmem, 0,
1493 1494 1495
                                          /* force */ 1);
            virObjectLock(vm);
            if (res < 0) {
1496 1497
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
1498
                                 " with libxenlight"), vm->def->id);
1499
                goto endjob;
1500 1501 1502 1503 1504 1505
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1506
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1507
            goto endjob;
1508
        }
1509 1510
    }

1511 1512
    ret = 0;

1513
 endjob:
W
Wang Yufei 已提交
1514
    libxlDomainObjEndJob(driver, vm);
1515

1516
 cleanup:
W
Wang Yufei 已提交
1517
    virDomainObjEndAPI(&vm);
1518
    virObjectUnref(cfg);
1519 1520 1521 1522 1523 1524 1525 1526 1527
    return ret;
}

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

1528 1529 1530 1531 1532 1533
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1534 1535 1536
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
J
Jim Fehlig 已提交
1537 1538
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1539
    virDomainObjPtr vm;
1540
    libxl_dominfo d_info;
J
Jim Fehlig 已提交
1541 1542
    int ret = -1;

J
Jim Fehlig 已提交
1543
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1544 1545
        goto cleanup;

1546 1547 1548
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1549 1550 1551
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1552
        info->maxMem = virDomainDefGetMemoryActual(vm->def);
1553
    } else {
1554 1555
        libxl_dominfo_init(&d_info);

J
Jim Fehlig 已提交
1556
        if (libxl_domain_info(cfg->ctx, &d_info, vm->def->id) != 0) {
1557
            virReportError(VIR_ERR_INTERNAL_ERROR,
1558 1559
                           _("libxl_domain_info failed for domain '%d'"),
                           vm->def->id);
1560 1561 1562 1563
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1564
        info->maxMem = d_info.max_memkb;
1565 1566

        libxl_dominfo_dispose(&d_info);
1567 1568
    }

J
Jiri Denemark 已提交
1569
    info->state = virDomainObjGetState(vm, NULL);
1570
    info->nrVirtCpu = virDomainDefGetVcpus(vm->def);
J
Jim Fehlig 已提交
1571 1572
    ret = 0;

1573
 cleanup:
J
Jim Fehlig 已提交
1574
    if (vm)
1575
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1576
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1577 1578 1579
    return ret;
}

1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

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

1594 1595 1596
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1597
    *state = virDomainObjGetState(vm, reason);
1598 1599
    ret = 0;

1600
 cleanup:
1601
    if (vm)
1602
        virObjectUnlock(vm);
1603 1604 1605
    return ret;
}

1606 1607 1608
/*
 * virDomainObjPtr must be locked on invocation
 */
1609
static int
1610 1611
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1612
{
J
Jim Fehlig 已提交
1613
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1614
    libxlSavefileHeader hdr;
1615
    virObjectEventPtr event = NULL;
1616 1617
    char *xml = NULL;
    uint32_t xml_len;
1618
    int fd = -1;
1619 1620 1621
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1622 1623 1624
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1625 1626 1627 1628
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1629
                            -1, -1, 0)) < 0) {
1630 1631 1632 1633 1634
        virReportSystemError(-fd,
                             _("Failed to create domain save file '%s'"), to);
        goto cleanup;
    }

1635
    if ((xml = virDomainDefFormat(vm->def, cfg->caps, 0)) == NULL)
1636 1637 1638 1639 1640 1641 1642 1643 1644
        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)) {
1645 1646
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1647 1648 1649 1650
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1651 1652
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1653 1654 1655
        goto cleanup;
    }

1656 1657
    /* Unlock virDomainObj while saving domain */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
1658
    ret = libxl_domain_suspend(cfg->ctx, vm->def->id, fd, 0, NULL);
1659 1660 1661
    virObjectLock(vm);

    if (ret != 0) {
1662 1663 1664
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1665
        ret = -1;
1666 1667 1668
        goto cleanup;
    }

1669 1670 1671
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_SAVED);

1672
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1673 1674
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

1675
    if (libxlDomainDestroyInternal(driver, vm) < 0) {
1676 1677
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1678 1679 1680
        goto cleanup;
    }

1681
    libxlDomainCleanup(driver, vm);
1682
    vm->hasManagedSave = true;
1683 1684
    ret = 0;

1685
 cleanup:
1686 1687 1688 1689 1690
    VIR_FREE(xml);
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1691
    virObjectUnref(cfg);
1692 1693 1694 1695
    return ret;
}

static int
1696 1697
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1698
{
1699 1700
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1701
    int ret = -1;
1702
    bool remove_dom = false;
1703

1704 1705 1706 1707 1708
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1709 1710
    virCheckFlags(0, -1);
    if (dxml) {
1711 1712
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1713 1714 1715
        return -1;
    }

J
Jim Fehlig 已提交
1716
    if (!(vm = libxlDomObjFromDomain(dom)))
1717 1718
        goto cleanup;

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

1721 1722 1723
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1724 1725 1726
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1727
    if (!virDomainObjIsActive(vm)) {
1728
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1729
        goto endjob;
1730 1731
    }

1732
    if (libxlDoDomainSave(driver, vm, to) < 0)
1733
        goto endjob;
1734

1735 1736
    if (!vm->persistent)
        remove_dom = true;
1737 1738

    ret = 0;
1739

1740
 endjob:
W
Wang Yufei 已提交
1741
    libxlDomainObjEndJob(driver, vm);
1742

1743
 cleanup:
1744 1745 1746 1747
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
W
Wang Yufei 已提交
1748
    virDomainObjEndAPI(&vm);
1749 1750
    return ret;
}
1751

1752
static int
1753 1754 1755 1756 1757 1758 1759 1760
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)
1761 1762
{
    libxlDriverPrivatePtr driver = conn->privateData;
1763
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1764 1765 1766 1767 1768
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1769

1770 1771 1772 1773 1774
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1775
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1776
    if (dxml) {
1777 1778
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1779 1780 1781
        return -1;
    }

1782
    fd = libxlDomainSaveImageOpen(driver, cfg, from, &def, &hdr);
1783
    if (fd < 0)
1784
        goto cleanup;
1785

1786
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1787
        goto cleanup;
1788

1789
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1790
                                   driver->xmlopt,
1791 1792 1793
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1794
        goto cleanup;
W
Wang Yufei 已提交
1795
    virObjectRef(vm);
1796 1797
    def = NULL;

1798 1799 1800 1801 1802 1803 1804 1805
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
        goto cleanup;
    }

1806 1807 1808
    ret = libxlDomainStartRestore(driver, vm,
                                  (flags & VIR_DOMAIN_SAVE_PAUSED) != 0,
                                  fd, hdr.version);
1809
    if (ret < 0 && !vm->persistent)
1810
        virDomainObjListRemove(driver->domains, vm);
1811

W
Wang Yufei 已提交
1812
    libxlDomainObjEndJob(driver, vm);
1813

1814
 cleanup:
1815 1816
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1817
    virDomainDefFree(def);
W
Wang Yufei 已提交
1818
    virDomainObjEndAPI(&vm);
1819
    virObjectUnref(cfg);
1820 1821 1822
    return ret;
}

1823 1824 1825 1826 1827 1828
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

1829
static int
1830
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1831 1832
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
1833
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1834
    virDomainObjPtr vm;
1835
    virObjectEventPtr event = NULL;
1836
    bool remove_dom = false;
1837 1838 1839 1840 1841
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

J
Jim Fehlig 已提交
1842
    if (!(vm = libxlDomObjFromDomain(dom)))
1843 1844
        goto cleanup;

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

1847 1848 1849
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1850 1851 1852
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1853
    if (!virDomainObjIsActive(vm)) {
1854
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1855
        goto endjob;
1856 1857 1858 1859
    }

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
1860
        if (libxl_domain_pause(cfg->ctx, vm->def->id) != 0) {
1861 1862 1863
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
1864
                           vm->def->id);
1865
            goto endjob;
1866 1867 1868 1869 1870
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

1871 1872
    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
1873
    ret = libxl_domain_core_dump(cfg->ctx, vm->def->id, to, NULL);
1874 1875
    virObjectLock(vm);
    if (ret != 0) {
1876 1877
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
1878
                       vm->def->id);
1879 1880
        ret = -1;
        goto unpause;
1881 1882 1883
    }

    if (flags & VIR_DUMP_CRASH) {
1884
        if (libxlDomainDestroyInternal(driver, vm) < 0) {
1885
            virReportError(VIR_ERR_INTERNAL_ERROR,
1886
                           _("Failed to destroy domain '%d'"), vm->def->id);
1887
            goto unpause;
1888 1889
        }

1890 1891 1892
        libxlDomainCleanup(driver, vm);
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_CRASHED);
1893
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1894
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
1895 1896
        if (!vm->persistent)
            remove_dom = true;
1897 1898 1899 1900
    }

    ret = 0;

1901
 unpause:
1902
    if (virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
1903
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
1904 1905
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
1906
                             " libxenlight"), vm->def->id);
1907 1908 1909 1910 1911
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
1912

1913
 endjob:
W
Wang Yufei 已提交
1914
    libxlDomainObjEndJob(driver, vm);
1915

1916
 cleanup:
1917 1918 1919 1920
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
W
Wang Yufei 已提交
1921
    virDomainObjEndAPI(&vm);
1922
    if (event)
1923
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1924
    virObjectUnref(cfg);
1925 1926 1927
    return ret;
}

1928 1929 1930 1931 1932 1933 1934
static int
libxlDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;
1935
    bool remove_dom = false;
1936 1937 1938

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1939
    if (!(vm = libxlDomObjFromDomain(dom)))
1940 1941
        goto cleanup;

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

1944 1945 1946
    if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1947 1948 1949
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1950
    if (!virDomainObjIsActive(vm)) {
1951
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1952
        goto endjob;
1953
    }
1954
    if (!vm->persistent) {
1955 1956
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
1957
        goto endjob;
1958
    }
1959 1960 1961

    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
1962
        goto endjob;
1963 1964 1965

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

1966
    if (libxlDoDomainSave(driver, vm, name) < 0)
1967
        goto endjob;
1968

1969 1970
    if (!vm->persistent)
        remove_dom = true;
1971 1972

    ret = 0;
1973

1974
 endjob:
W
Wang Yufei 已提交
1975
    libxlDomainObjEndJob(driver, vm);
1976

1977
 cleanup:
1978 1979 1980 1981
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
W
Wang Yufei 已提交
1982
    virDomainObjEndAPI(&vm);
1983 1984 1985 1986
    VIR_FREE(name);
    return ret;
}

1987 1988
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
1989 1990 1991 1992
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
1993
    int ret = -1;
1994

1995
    virObjectLock(vm);
1996 1997 1998 1999 2000 2001

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

    vm->hasManagedSave = virFileExists(name);

2002
    ret = 0;
2003
 cleanup:
2004
    virObjectUnlock(vm);
2005
    VIR_FREE(name);
2006
    return ret;
2007 2008
}

2009 2010 2011 2012 2013 2014 2015 2016
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2017
    if (!(vm = libxlDomObjFromDomain(dom)))
2018 2019
        goto cleanup;

2020 2021 2022
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2023
    ret = vm->hasManagedSave;
2024

2025
 cleanup:
2026
    if (vm)
2027
        virObjectUnlock(vm);
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
    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 已提交
2041
    if (!(vm = libxlDomObjFromDomain(dom)))
2042 2043
        goto cleanup;

2044 2045 2046
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2047 2048 2049 2050 2051
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
2052
    vm->hasManagedSave = false;
2053

2054
 cleanup:
2055 2056
    VIR_FREE(name);
    if (vm)
2057
        virObjectUnlock(vm);
2058 2059 2060
    return ret;
}

2061 2062 2063 2064 2065
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2066
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2067 2068
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
2069
    libxl_bitmap map;
2070 2071
    uint8_t *bitmask = NULL;
    unsigned int maplen;
2072 2073
    size_t i;
    unsigned int pos;
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
    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)) {
2086 2087
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2088 2089 2090 2091
        return -1;
    }

    if (!nvcpus) {
2092
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2093 2094 2095
        return -1;
    }

J
Jim Fehlig 已提交
2096
    if (!(vm = libxlDomObjFromDomain(dom)))
2097 2098
        goto cleanup;

2099 2100 2101
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2102 2103 2104
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2105
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2106 2107
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2108
        goto endjob;
2109 2110 2111
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2112 2113
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2114
        goto endjob;
2115 2116
    }

2117
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2118 2119
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2120
        goto endjob;
2121 2122
    }

2123 2124
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && virDomainDefGetVcpusMax(vm->def) < max)
        max = virDomainDefGetVcpusMax(vm->def);
2125 2126

    if (nvcpus > max) {
2127 2128 2129
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2130
        goto endjob;
2131 2132
    }

2133
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm)))
2134
        goto endjob;
2135

E
Eric Blake 已提交
2136
    maplen = VIR_CPU_MAPLEN(nvcpus);
2137
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
2138
        goto endjob;
2139 2140

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2141
        pos = i / 8;
2142 2143 2144 2145 2146 2147 2148 2149
        bitmask[pos] |= 1 << (i % 8);
    }

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

    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
2150 2151
        if (virDomainDefSetVcpusMax(def, nvcpus) < 0)
            goto cleanup;
2152 2153 2154
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
2155 2156
        if (virDomainDefSetVcpus(def, nvcpus) < 0)
            goto cleanup;
2157 2158 2159
        break;

    case VIR_DOMAIN_VCPU_LIVE:
J
Jim Fehlig 已提交
2160
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2161 2162
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2163
                             " with libxenlight"), vm->def->id);
2164
            goto endjob;
2165
        }
2166 2167
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0)
            goto endjob;
2168 2169 2170
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2171
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2172 2173
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2174
                             " with libxenlight"), vm->def->id);
2175
            goto endjob;
2176
        }
2177 2178 2179
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0 ||
            virDomainDefSetVcpus(def, nvcpus) < 0)
            goto endjob;
2180 2181 2182 2183 2184
        break;
    }

    ret = 0;

2185
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2186
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0) {
2187 2188 2189 2190 2191
            VIR_WARN("Unable to save status on vm %s after changing vcpus",
                     vm->def->name);
        }
    }
    if (flags & VIR_DOMAIN_VCPU_CONFIG) {
2192
        if (virDomainSaveConfig(cfg->configDir, cfg->caps, def) < 0) {
2193 2194 2195 2196
            VIR_WARN("Unable to save configuration of vm %s after changing vcpus",
                     vm->def->name);
        }
    }
2197

2198
 endjob:
W
Wang Yufei 已提交
2199
    libxlDomainObjEndJob(driver, vm);
2200

2201
 cleanup:
2202
    VIR_FREE(bitmask);
W
Wang Yufei 已提交
2203 2204
    virDomainObjEndAPI(&vm);
    virObjectUnref(cfg);
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
    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;
2220
    bool active;
2221 2222 2223 2224 2225

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

J
Jim Fehlig 已提交
2226
    if (!(vm = libxlDomObjFromDomain(dom)))
2227 2228
        goto cleanup;

2229
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2230 2231
        goto cleanup;

2232 2233 2234 2235 2236 2237 2238 2239 2240
    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)) {
2241 2242
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2243 2244 2245
        return -1;
    }

2246
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2247
        if (!active) {
2248 2249
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2250 2251 2252 2253
            goto cleanup;
        }
        def = vm->def;
    } else {
2254
        if (!vm->persistent) {
2255 2256
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2257 2258
            goto cleanup;
        }
2259 2260 2261
        def = vm->newDef ? vm->newDef : vm->def;
    }

2262 2263 2264
    if (flags & VIR_DOMAIN_VCPU_MAXIMUM)
        ret = virDomainDefGetVcpusMax(def);
    else
2265
        ret = virDomainDefGetVcpus(def);
2266

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

static int
2274 2275 2276
libxlDomainPinVcpuFlags(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen,
                        unsigned int flags)
2277 2278
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2279
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2280
    virDomainDefPtr targetDef = NULL;
2281
    virBitmapPtr pcpumap = NULL;
2282
    virDomainVcpuInfoPtr vcpuinfo;
2283 2284
    virDomainObjPtr vm;
    int ret = -1;
2285 2286 2287

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
2288

J
Jim Fehlig 已提交
2289
    if (!(vm = libxlDomObjFromDomain(dom)))
2290 2291
        goto cleanup;

2292
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2293 2294
        goto cleanup;

2295 2296 2297
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2298 2299
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
2300
        goto endjob;
2301

2302
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2303 2304 2305 2306 2307
        targetDef = vm->def;

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

2308 2309
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
2310
        goto endjob;
2311

2312 2313 2314 2315 2316 2317 2318
    if (!(vcpuinfo = virDomainDefGetVcpu(targetDef, vcpu)) ||
        !vcpuinfo->online) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("vcpu '%u' is not active"), vcpu);
        goto endjob;
    }

2319 2320
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        libxl_bitmap map = { .size = maplen, .map = cpumap };
J
Jim Fehlig 已提交
2321
        if (libxl_set_vcpuaffinity(cfg->ctx, vm->def->id, vcpu, &map) != 0) {
2322 2323 2324
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"),
                           vcpu);
2325
            goto endjob;
2326
        }
2327
    }
2328

2329 2330 2331
    virBitmapFree(vcpuinfo->cpumask);
    vcpuinfo->cpumask = pcpumap;
    pcpumap = NULL;
2332

2333 2334
    ret = 0;

2335
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
2336
        ret = virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps);
2337
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2338
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, targetDef);
2339 2340
    }

2341
 endjob:
W
Wang Yufei 已提交
2342
    libxlDomainObjEndJob(driver, vm);
2343

2344
 cleanup:
W
Wang Yufei 已提交
2345
    virDomainObjEndAPI(&vm);
2346
    virBitmapFree(pcpumap);
2347
    virObjectUnref(cfg);
2348 2349 2350
    return ret;
}

2351 2352 2353 2354 2355 2356 2357 2358
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

2359 2360 2361 2362 2363 2364 2365 2366 2367
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;
2368
    int ret = -1;
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382

    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;

2383
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2384 2385 2386 2387 2388
        targetDef = vm->def;

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

2389 2390
    ret = virDomainDefGetVcpuPinInfoHelper(targetDef, maplen, ncpumaps, cpumaps,
                                           libxl_get_max_cpus(cfg->ctx), NULL);
2391

2392
 cleanup:
2393 2394 2395 2396 2397
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(cfg);
    return ret;
}
2398 2399 2400 2401 2402

static int
libxlDomainGetVcpus(virDomainPtr dom, virVcpuInfoPtr info, int maxinfo,
                    unsigned char *cpumaps, int maplen)
{
J
Jim Fehlig 已提交
2403 2404
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2405 2406 2407 2408
    virDomainObjPtr vm;
    int ret = -1;
    libxl_vcpuinfo *vcpuinfo;
    int maxcpu, hostcpus;
2409
    size_t i;
2410 2411
    unsigned char *cpumap;

J
Jim Fehlig 已提交
2412
    if (!(vm = libxlDomObjFromDomain(dom)))
2413 2414
        goto cleanup;

2415 2416 2417
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

J
Jim Fehlig 已提交
2423
    if ((vcpuinfo = libxl_list_vcpu(cfg->ctx, vm->def->id, &maxcpu,
2424
                                    &hostcpus)) == NULL) {
2425 2426
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
2427
                       vm->def->id);
2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
        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 已提交
2450
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2451 2452 2453 2454 2455
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

2456
 cleanup:
2457
    if (vm)
2458
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2459
    virObjectUnref(cfg);
2460 2461 2462
    return ret;
}

J
Jim Fehlig 已提交
2463
static char *
2464
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2465
{
2466 2467
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2468
    virDomainObjPtr vm;
2469
    virDomainDefPtr def;
J
Jim Fehlig 已提交
2470 2471
    char *ret = NULL;

2472 2473
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2474
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2475 2476
        goto cleanup;

2477 2478 2479
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2480 2481 2482 2483 2484
    if ((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef)
        def = vm->newDef;
    else
        def = vm->def;

2485
    ret = virDomainDefFormat(def, cfg->caps,
2486
                             virDomainDefFormatConvertXMLFlags(flags));
J
Jim Fehlig 已提交
2487

2488
 cleanup:
J
Jim Fehlig 已提交
2489
    if (vm)
2490
        virObjectUnlock(vm);
2491
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2492 2493 2494
    return ret;
}

2495
static char *
2496 2497 2498
libxlConnectDomainXMLFromNative(virConnectPtr conn,
                                const char *nativeFormat,
                                const char *nativeConfig,
2499
                                unsigned int flags)
2500 2501
{
    libxlDriverPrivatePtr driver = conn->privateData;
2502
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2503 2504 2505 2506
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2507 2508
    virCheckFlags(0, NULL);

2509 2510 2511
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

2512
    if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XL)) {
2513 2514 2515 2516
        if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
            goto cleanup;
        if (!(def = xenParseXL(conf,
                               cfg->caps,
2517
                               driver->xmlopt)))
2518
            goto cleanup;
2519
    } else if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XM)) {
2520 2521 2522 2523
        if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
            goto cleanup;

        if (!(def = xenParseXM(conf,
2524 2525
                               cfg->caps,
                               driver->xmlopt)))
2526
            goto cleanup;
2527
    } else if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_SEXPR)) {
2528 2529 2530
        /* only support latest xend config format */
        if (!(def = xenParseSxprString(nativeConfig,
                                       NULL,
2531 2532 2533
                                       -1,
                                       cfg->caps,
                                       driver->xmlopt))) {
2534 2535 2536 2537 2538
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("parsing sxpr config failed"));
            goto cleanup;
        }
    } else {
2539 2540
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2541 2542 2543
        goto cleanup;
    }

2544
    xml = virDomainDefFormat(def, cfg->caps, VIR_DOMAIN_DEF_FORMAT_INACTIVE);
2545

2546
 cleanup:
2547 2548 2549
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2550
    virObjectUnref(cfg);
2551 2552 2553 2554 2555
    return xml;
}

#define MAX_CONFIG_SIZE (1024 * 65)
static char *
2556 2557 2558
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
2559 2560
{
    libxlDriverPrivatePtr driver = conn->privateData;
2561
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2562 2563 2564 2565 2566
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    int len = MAX_CONFIG_SIZE;
    char *ret = NULL;

E
Eric Blake 已提交
2567 2568
    virCheckFlags(0, NULL);

2569 2570 2571
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

2572
    if (!(def = virDomainDefParseString(domainXml,
2573
                                        cfg->caps, driver->xmlopt,
2574
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE)))
2575 2576
        goto cleanup;

2577
    if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XL)) {
2578
        if (!(conf = xenFormatXL(def, conn)))
2579
            goto cleanup;
2580
    } else if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XM)) {
2581
        if (!(conf = xenFormatXM(conn, def)))
2582 2583 2584 2585 2586
            goto cleanup;
    } else {

        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2587
        goto cleanup;
2588
    }
2589

2590
    if (VIR_ALLOC_N(ret, len) < 0)
2591 2592 2593 2594 2595 2596 2597
        goto cleanup;

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

2598
 cleanup:
2599 2600 2601
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2602
    virObjectUnref(cfg);
2603 2604 2605
    return ret;
}

J
Jim Fehlig 已提交
2606
static int
2607 2608
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
2609 2610 2611 2612
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2613 2614 2615
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2616 2617
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
2618 2619 2620 2621
    return n;
}

static int
2622
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
2623 2624 2625 2626
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2627 2628 2629
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2630
    n = virDomainObjListNumOfDomains(driver->domains, false,
2631 2632
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
2633 2634 2635 2636 2637
    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
2638
                           unsigned int flags)
J
Jim Fehlig 已提交
2639 2640 2641 2642 2643 2644 2645
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

J
Jim Fehlig 已提交
2646
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2647 2648
        goto cleanup;

2649 2650 2651
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2652 2653 2654
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2655
    if (virDomainObjIsActive(vm)) {
2656 2657
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
2658
        goto endjob;
J
Jim Fehlig 已提交
2659 2660
    }

2661 2662
    ret = libxlDomainStartNew(driver, vm,
                              (flags & VIR_DOMAIN_START_PAUSED) != 0);
2663
    if (ret < 0)
2664
        goto endjob;
2665
    dom->id = vm->def->id;
J
Jim Fehlig 已提交
2666

2667
 endjob:
W
Wang Yufei 已提交
2668
    libxlDomainObjEndJob(driver, vm);
2669

2670
 cleanup:
W
Wang Yufei 已提交
2671
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
    return ret;
}

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

static virDomainPtr
2682
libxlDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags)
J
Jim Fehlig 已提交
2683 2684
{
    libxlDriverPrivatePtr driver = conn->privateData;
2685
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2686 2687 2688
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
2689
    virObjectEventPtr event = NULL;
2690
    virDomainDefPtr oldDef = NULL;
2691
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
J
Jim Fehlig 已提交
2692

2693 2694 2695
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_DEFINE_VALIDATE)
2696
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE_SCHEMA;
2697

2698
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
2699
                                        parse_flags)))
2700
        goto cleanup;
J
Jim Fehlig 已提交
2701

2702
    if (virDomainDefineXMLFlagsEnsureACL(conn, def) < 0)
2703
        goto cleanup;
2704

2705
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2706
                                   driver->xmlopt,
2707 2708
                                   0,
                                   &oldDef)))
2709
        goto cleanup;
2710

J
Jim Fehlig 已提交
2711 2712 2713
    def = NULL;
    vm->persistent = 1;

2714
    if (virDomainSaveConfig(cfg->configDir,
2715
                            cfg->caps,
J
Jim Fehlig 已提交
2716
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2717
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
2718 2719 2720 2721 2722 2723 2724 2725
        vm = NULL;
        goto cleanup;
    }

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

2726
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2727
                                     !oldDef ?
2728 2729 2730
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

2731
 cleanup:
J
Jim Fehlig 已提交
2732
    virDomainDefFree(def);
2733
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
2734
    if (vm)
2735
        virObjectUnlock(vm);
2736 2737
    if (event)
        libxlDomainEventQueue(driver, event);
2738
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2739 2740 2741
    return dom;
}

2742 2743 2744 2745 2746 2747
static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    return libxlDomainDefineXMLFlags(conn, xml, 0);
}

J
Jim Fehlig 已提交
2748
static int
2749 2750
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2751 2752
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2753
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2754
    virDomainObjPtr vm;
2755
    virObjectEventPtr event = NULL;
2756
    char *name = NULL;
J
Jim Fehlig 已提交
2757 2758
    int ret = -1;

2759 2760
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2761
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2762 2763
        goto cleanup;

2764 2765 2766
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2767
    if (!vm->persistent) {
2768 2769
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2770 2771 2772
        goto cleanup;
    }

2773 2774 2775 2776 2777 2778 2779
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2780 2781
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2782 2783 2784
                goto cleanup;
            }
        } else {
2785 2786 2787
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2788 2789 2790 2791
            goto cleanup;
        }
    }

2792
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2793 2794
        goto cleanup;

2795
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2796 2797
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2798 2799 2800
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
2801
        virDomainObjListRemove(driver->domains, vm);
2802 2803 2804
        vm = NULL;
    }

J
Jim Fehlig 已提交
2805 2806
    ret = 0;

2807
 cleanup:
2808
    VIR_FREE(name);
J
Jim Fehlig 已提交
2809
    if (vm)
2810
        virObjectUnlock(vm);
2811 2812
    if (event)
        libxlDomainEventQueue(driver, event);
2813
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2814 2815 2816
    return ret;
}

2817 2818 2819 2820 2821 2822
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2823
static int
J
Jim Fehlig 已提交
2824
libxlDomainChangeEjectableMedia(virDomainObjPtr vm, virDomainDiskDefPtr disk)
2825
{
J
Jim Fehlig 已提交
2826
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
2827 2828
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2829
    size_t i;
2830 2831
    int ret = -1;

2832
    for (i = 0; i < vm->def->ndisks; i++) {
2833 2834 2835 2836 2837 2838 2839 2840
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
2841 2842 2843
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
2844 2845 2846 2847
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2848 2849 2850
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
2851 2852 2853
        return -1;
    }

J
Jim Fehlig 已提交
2854
    if (libxlMakeDisk(disk, &x_disk) < 0)
2855 2856
        goto cleanup;

J
Jim Fehlig 已提交
2857
    if ((ret = libxl_cdrom_insert(cfg->ctx, vm->def->id, &x_disk, NULL)) < 0) {
2858 2859 2860
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
2861 2862 2863
        goto cleanup;
    }

2864 2865 2866
    if (virDomainDiskSetSource(origdisk, virDomainDiskGetSource(disk)) < 0)
        goto cleanup;
    virDomainDiskSetType(origdisk, virDomainDiskGetType(disk));
2867 2868 2869 2870 2871

    virDomainDiskDefFree(disk);

    ret = 0;

2872
 cleanup:
J
Jim Fehlig 已提交
2873
    virObjectUnref(cfg);
2874 2875 2876 2877
    return ret;
}

static int
J
Jim Fehlig 已提交
2878
libxlDomainAttachDeviceDiskLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
2879
{
J
Jim Fehlig 已提交
2880
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
2881 2882 2883 2884 2885 2886
    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 已提交
2887
            ret = libxlDomainChangeEjectableMedia(vm, l_disk);
2888 2889 2890
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (l_disk->bus == VIR_DOMAIN_DISK_BUS_XEN) {
2891
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
2892 2893
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
2894 2895 2896
                    goto cleanup;
                }

2897
                if (!virDomainDiskGetSource(l_disk)) {
2898 2899
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
2900 2901 2902
                    goto cleanup;
                }

2903
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
2904 2905
                    goto cleanup;

J
Jim Fehlig 已提交
2906
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
2907 2908
                    goto cleanup;

2909 2910 2911 2912 2913
                if (virDomainLockDiskAttach(libxl_driver->lockManager,
                                            "xen:///system",
                                            vm, l_disk) < 0)
                    goto cleanup;

J
Jim Fehlig 已提交
2914
                if ((ret = libxl_device_disk_add(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
2915
                                                &x_disk, NULL)) < 0) {
2916 2917 2918
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
2919 2920 2921 2922 2923
                    if (virDomainLockDiskDetach(libxl_driver->lockManager,
                                                vm, l_disk) < 0) {
                        VIR_WARN("Unable to release lock on %s",
                                 virDomainDiskGetSource(l_disk));
                    }
2924 2925 2926 2927 2928 2929
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
2930 2931 2932
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
2933 2934 2935
            }
            break;
        default:
2936 2937 2938
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
2939 2940 2941
            break;
    }

2942
 cleanup:
J
Jim Fehlig 已提交
2943
    virObjectUnref(cfg);
2944 2945 2946
    return ret;
}

2947 2948 2949 2950 2951
static int
libxlDomainAttachHostPCIDevice(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
J
Jim Fehlig 已提交
2952
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2953
    libxl_device_pci pcidev;
2954 2955
    virDomainHostdevDefPtr found;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
2956
    virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
J
Jim Fehlig 已提交
2957
    int ret = -1;
2958

2959 2960
    libxl_device_pci_init(&pcidev);

2961 2962 2963
    if (virDomainHostdevFind(vm->def, hostdev, &found) >= 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("target pci device %.4x:%.2x:%.2x.%.1x already exists"),
2964 2965
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
J
Jim Fehlig 已提交
2966
        goto cleanup;
2967 2968 2969
    }

    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs + 1) < 0)
J
Jim Fehlig 已提交
2970
        goto cleanup;
2971 2972 2973 2974

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

2977
    if (libxlMakePCI(hostdev, &pcidev) < 0)
C
Chunyan Liu 已提交
2978
        goto error;
2979

J
Jim Fehlig 已提交
2980
    if (libxl_device_pci_add(cfg->ctx, vm->def->id, &pcidev, 0) < 0) {
2981 2982
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to attach pci device %.4x:%.2x:%.2x.%.1x"),
2983 2984
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
2985
        goto error;
2986 2987 2988
    }

    vm->def->hostdevs[vm->def->nhostdevs++] = hostdev;
J
Jim Fehlig 已提交
2989 2990
    ret = 0;
    goto cleanup;
2991

2992
 error:
2993 2994
    virHostdevReAttachPCIDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                 vm->def->name, &hostdev, 1, NULL);
J
Jim Fehlig 已提交
2995 2996 2997

 cleanup:
    virObjectUnref(cfg);
2998
    libxl_device_pci_dispose(&pcidev);
J
Jim Fehlig 已提交
2999
    return ret;
3000 3001 3002 3003 3004
}

static int
libxlDomainAttachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3005
                            virDomainHostdevDefPtr hostdev)
3006 3007 3008 3009 3010 3011 3012 3013 3014 3015
{
    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 已提交
3016
        if (libxlDomainAttachHostPCIDevice(driver, vm, hostdev) < 0)
C
Chunyan Liu 已提交
3017
            return -1;
3018 3019 3020 3021 3022 3023
        break;

    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
C
Chunyan Liu 已提交
3024
        return -1;
3025 3026 3027 3028 3029
    }

    return 0;
}

3030
static int
J
Jim Fehlig 已提交
3031
libxlDomainDetachDeviceDiskLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3032
{
J
Jim Fehlig 已提交
3033
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
3034 3035
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
3036
    int idx;
3037 3038 3039 3040 3041 3042
    int ret = -1;

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

3043 3044 3045
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
3046 3047
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3048 3049 3050
                    goto cleanup;
                }

3051
                l_disk = vm->def->disks[idx];
3052

J
Jim Fehlig 已提交
3053
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3054 3055
                    goto cleanup;

J
Jim Fehlig 已提交
3056
                if ((ret = libxl_device_disk_remove(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
3057
                                                    &x_disk, NULL)) < 0) {
3058 3059 3060
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3061 3062 3063
                    goto cleanup;
                }

3064 3065 3066 3067 3068
                if (virDomainLockDiskDetach(libxl_driver->lockManager,
                                            vm, l_disk) < 0)
                    VIR_WARN("Unable to release lock on %s",
                             virDomainDiskGetSource(l_disk));

3069
                virDomainDiskRemove(vm->def, idx);
3070 3071 3072
                virDomainDiskDefFree(l_disk);

            } else {
3073 3074 3075
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3076 3077 3078
            }
            break;
        default:
3079 3080 3081
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3082 3083 3084
            break;
    }

3085
 cleanup:
J
Jim Fehlig 已提交
3086
    virObjectUnref(cfg);
3087 3088 3089
    return ret;
}

3090 3091 3092 3093 3094
static int
libxlDomainAttachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3095
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3096 3097 3098
    int actualType;
    libxl_device_nic nic;
    int ret = -1;
3099
    char mac[VIR_MAC_STRING_BUFLEN];
3100

3101 3102
    libxl_device_nic_init(&nic);

3103 3104
    /* preallocate new slot for device */
    if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets + 1) < 0)
3105
        goto cleanup;
3106 3107 3108 3109 3110 3111

    /* 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)
3112
        goto cleanup;
3113 3114 3115

    actualType = virDomainNetGetActualType(net);

3116 3117 3118 3119
    if (virDomainHasNet(vm->def, net)) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("network device with mac %s already exists"),
                       virMacAddrFormat(&net->mac, mac));
3120
        goto cleanup;
3121 3122
    }

3123
    if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
        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;

3135 3136 3137
        /* 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
3138
         * the nets list if successful.
3139
         */
3140
        ret = libxlDomainAttachHostDevice(driver, vm, hostdev);
3141
        goto cleanup;
3142 3143 3144 3145 3146
    }

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

J
Jim Fehlig 已提交
3147
    if (libxl_device_nic_add(cfg->ctx, vm->def->id, &nic, 0)) {
3148 3149 3150 3151 3152 3153 3154 3155 3156
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to attach network device"));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    libxl_device_nic_dispose(&nic);
3157 3158 3159
    if (!ret) {
        vm->def->nets[vm->def->nnets++] = net;
    } else {
3160 3161 3162
        virDomainNetRemoveHostdev(vm->def, net);
        networkReleaseActualDevice(vm->def, net);
    }
J
Jim Fehlig 已提交
3163
    virObjectUnref(cfg);
3164 3165 3166
    return ret;
}

3167
static int
3168 3169
libxlDomainAttachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3170 3171 3172 3173 3174 3175
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
J
Jim Fehlig 已提交
3176
            ret = libxlDomainAttachDeviceDiskLive(vm, dev);
3177 3178 3179 3180
            if (!ret)
                dev->data.disk = NULL;
            break;

3181
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3182
            ret = libxlDomainAttachNetDevice(driver, vm,
3183 3184 3185 3186 3187
                                             dev->data.net);
            if (!ret)
                dev->data.net = NULL;
            break;

3188
        case VIR_DOMAIN_DEVICE_HOSTDEV:
J
Jim Fehlig 已提交
3189
            ret = libxlDomainAttachHostDevice(driver, vm,
3190
                                              dev->data.hostdev);
3191 3192 3193 3194
            if (!ret)
                dev->data.hostdev = NULL;
            break;

3195
        default:
3196 3197 3198
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
            break;
    }

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
3209
    virDomainNetDefPtr net;
3210 3211
    virDomainHostdevDefPtr hostdev;
    virDomainHostdevDefPtr found;
3212
    virDomainHostdevSubsysPCIPtr pcisrc;
3213
    char mac[VIR_MAC_STRING_BUFLEN];
3214 3215 3216 3217

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3218
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3219 3220
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3221 3222
                return -1;
            }
3223
            if (virDomainDiskInsert(vmdef, disk))
3224 3225 3226 3227
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;
3228 3229 3230

        case VIR_DOMAIN_DEVICE_NET:
            net = dev->data.net;
3231 3232 3233 3234 3235 3236
            if (virDomainHasNet(vmdef, net)) {
                virReportError(VIR_ERR_INVALID_ARG,
                               _("network device with mac %s already exists"),
                               virMacAddrFormat(&net->mac, mac));
                return -1;
            }
3237 3238 3239 3240 3241
            if (virDomainNetInsert(vmdef, net))
                return -1;
            dev->data.net = NULL;
            break;

3242 3243 3244 3245 3246 3247 3248
        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) {
3249
                pcisrc = &hostdev->source.subsys.u.pci;
3250 3251 3252
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("target pci device %.4x:%.2x:%.2x.%.1x\
                                  already exists"),
3253 3254
                               pcisrc->addr.domain, pcisrc->addr.bus,
                               pcisrc->addr.slot, pcisrc->addr.function);
3255 3256 3257
                return -1;
            }

3258 3259
            if (virDomainHostdevInsert(vmdef, hostdev) < 0)
                return -1;
3260
            dev->data.hostdev = NULL;
3261
            break;
3262 3263

        default:
3264 3265
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3266 3267 3268 3269 3270 3271
            return -1;
    }
    return 0;
}

static int
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304
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 已提交
3305
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3306
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
3307
    virDomainHostdevSubsysPCIPtr pcisrc = &subsys->u.pci;
3308 3309 3310 3311
    libxl_device_pci pcidev;
    virDomainHostdevDefPtr detach;
    int idx;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
J
Jim Fehlig 已提交
3312
    int ret = -1;
3313

3314 3315
    libxl_device_pci_init(&pcidev);

3316 3317 3318 3319
    idx = virDomainHostdevFind(vm->def, hostdev, &detach);
    if (idx < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("host pci device %.4x:%.2x:%.2x.%.1x not found"),
3320 3321
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
J
Jim Fehlig 已提交
3322
        goto cleanup;
3323 3324 3325 3326 3327
    }

    if (libxlIsMultiFunctionDevice(vm->def, detach->info)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %.4x:%.2x:%.2x.%.1x"),
3328 3329
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3330
        goto error;
3331 3332 3333
    }


3334
    if (libxlMakePCI(detach, &pcidev) < 0)
C
Chunyan Liu 已提交
3335
        goto error;
3336

J
Jim Fehlig 已提交
3337
    if (libxl_device_pci_remove(cfg->ctx, vm->def->id, &pcidev, 0) < 0) {
3338 3339 3340
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to detach pci device\
                          %.4x:%.2x:%.2x.%.1x"),
3341 3342
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3343
        goto error;
3344 3345 3346 3347 3348 3349 3350 3351
    }


    virDomainHostdevRemove(vm->def, idx);

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

J
Jim Fehlig 已提交
3352
    ret = 0;
3353

3354
 error:
3355
    virDomainHostdevDefFree(detach);
J
Jim Fehlig 已提交
3356 3357 3358

 cleanup:
    virObjectUnref(cfg);
3359
    libxl_device_pci_dispose(&pcidev);
J
Jim Fehlig 已提交
3360
    return ret;
3361 3362 3363 3364 3365
}

static int
libxlDomainDetachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3366
                            virDomainHostdevDefPtr hostdev)
3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378
{
    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 已提交
3379
            return libxlDomainDetachHostPCIDevice(driver, vm, hostdev);
3380 3381 3382 3383 3384 3385 3386 3387 3388 3389

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

    return -1;
}

3390 3391 3392 3393 3394
static int
libxlDomainDetachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3395
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3396 3397 3398 3399 3400 3401
    int detachidx;
    virDomainNetDefPtr detach = NULL;
    libxl_device_nic nic;
    char mac[VIR_MAC_STRING_BUFLEN];
    int ret = -1;

3402 3403
    libxl_device_nic_init(&nic);

3404
    if ((detachidx = virDomainNetFindIdx(vm->def, net)) < 0)
3405
        goto cleanup;
3406 3407 3408 3409 3410 3411 3412

    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 已提交
3413
        ret = libxlDomainDetachHostDevice(driver, vm,
3414
                                          virDomainNetGetActualHostdev(detach));
3415
        goto cleanup;
3416 3417
    }

J
Jim Fehlig 已提交
3418
    if (libxl_mac_to_device_nic(cfg->ctx, vm->def->id,
3419 3420 3421
                                virMacAddrFormat(&detach->mac, mac), &nic))
        goto cleanup;

J
Jim Fehlig 已提交
3422
    if (libxl_device_nic_remove(cfg->ctx, vm->def->id, &nic, 0)) {
3423 3424 3425 3426 3427 3428 3429 3430 3431
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to detach network device"));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    libxl_device_nic_dispose(&nic);
J
Jim Fehlig 已提交
3432 3433 3434 3435
    if (!ret) {
        networkReleaseActualDevice(vm->def, detach);
        virDomainNetRemove(vm->def, detachidx);
    }
J
Jim Fehlig 已提交
3436
    virObjectUnref(cfg);
3437 3438 3439
    return ret;
}

3440 3441 3442
static int
libxlDomainDetachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3443 3444
                            virDomainDeviceDefPtr dev)
{
3445
    virDomainHostdevDefPtr hostdev;
3446 3447 3448 3449
    int ret = -1;

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

3453
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3454
            ret = libxlDomainDetachNetDevice(driver, vm,
3455 3456 3457
                                             dev->data.net);
            break;

3458
        case VIR_DOMAIN_DEVICE_HOSTDEV:
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
            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);
3469 3470
            break;

3471
        default:
3472 3473 3474
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3475 3476 3477 3478 3479 3480
            break;
    }

    return ret;
}

3481

3482 3483 3484
static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3485
    virDomainDiskDefPtr disk, detach;
3486
    virDomainHostdevDefPtr hostdev, det_hostdev;
3487
    virDomainNetDefPtr net;
3488
    int idx;
3489 3490 3491 3492

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3493
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3494 3495
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3496
                return -1;
3497
            }
3498
            virDomainDiskDefFree(detach);
3499
            break;
3500

3501 3502 3503 3504 3505 3506 3507 3508 3509
        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;

3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521
        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;
        }

3522
        default:
3523 3524
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3525
            return -1;
3526 3527
    }

3528
    return 0;
3529 3530 3531
}

static int
J
Jim Fehlig 已提交
3532
libxlDomainUpdateDeviceLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3533 3534 3535 3536 3537 3538 3539 3540 3541
{
    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 已提交
3542
                    ret = libxlDomainChangeEjectableMedia(vm, disk);
3543 3544 3545 3546
                    if (ret == 0)
                        dev->data.disk = NULL;
                    break;
                default:
3547 3548 3549
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3550 3551 3552 3553
                    break;
            }
            break;
        default:
3554 3555 3556
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572
            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;
3573
            if (!(orig = virDomainDiskByName(vmdef, disk->dst, false))) {
3574 3575
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3576 3577 3578
                goto cleanup;
            }
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3579 3580
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3581 3582 3583
                goto cleanup;
            }

3584 3585 3586 3587 3588 3589
            if (virDomainDiskSetSource(orig, virDomainDiskGetSource(disk)) < 0)
                goto cleanup;
            virDomainDiskSetType(orig, virDomainDiskGetType(disk));
            virDomainDiskSetFormat(orig, virDomainDiskGetFormat(disk));
            if (virDomainDiskSetDriver(orig, virDomainDiskGetDriver(disk)) < 0)
                goto cleanup;
3590 3591
            break;
        default:
3592 3593
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3594 3595 3596 3597 3598
            goto cleanup;
    }

    ret = 0;

3599
 cleanup:
3600 3601 3602 3603 3604
    return ret;
}


static int
3605 3606
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3607 3608
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3609
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3610 3611 3612 3613 3614 3615 3616 3617
    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 已提交
3618
    if (!(vm = libxlDomObjFromDomain(dom)))
3619 3620
        goto cleanup;

3621 3622 3623
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3624 3625 3626
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

3627 3628
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto endjob;
3629 3630

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3631
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3632
                                            cfg->caps, driver->xmlopt,
3633
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3634
            goto endjob;
3635 3636

        /* Make a copy for updated domain. */
3637
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3638
                                                    driver->xmlopt)))
3639
            goto endjob;
3640

3641
        if (libxlDomainAttachDeviceConfig(vmdef, dev) < 0)
3642
            goto endjob;
3643
    }
3644 3645 3646 3647

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

J
Jim Fehlig 已提交
3653
        if (libxlDomainAttachDeviceLive(driver, vm, dev) < 0)
3654
            goto endjob;
3655

3656 3657 3658 3659
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3660
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
3661
            goto endjob;
3662 3663
    }

3664 3665
    ret = 0;

3666
    /* Finally, if no error until here, we can save config. */
3667
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3668
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
3669
        if (!ret) {
3670
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3671 3672 3673 3674
            vmdef = NULL;
        }
    }

3675
 endjob:
W
Wang Yufei 已提交
3676
    libxlDomainObjEndJob(driver, vm);
3677

3678
 cleanup:
3679 3680
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
W
Wang Yufei 已提交
3681
    virDomainObjEndAPI(&vm);
3682
    virObjectUnref(cfg);
3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696
    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)
{
3697
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3698
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3699 3700 3701 3702 3703 3704 3705 3706
    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 已提交
3707
    if (!(vm = libxlDomObjFromDomain(dom)))
3708 3709
        goto cleanup;

3710 3711 3712
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3713 3714 3715
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

3716 3717
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto endjob;
3718 3719 3720

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3721
                                            cfg->caps, driver->xmlopt,
3722 3723
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                            VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
3724
            goto endjob;
3725 3726

        /* Make a copy for updated domain. */
3727
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3728
                                                    driver->xmlopt)))
3729
            goto endjob;
3730

3731
        if (libxlDomainDetachDeviceConfig(vmdef, dev) < 0)
3732
            goto endjob;
3733 3734 3735 3736 3737 3738
    }

    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,
3739
                                            cfg->caps, driver->xmlopt,
3740 3741
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                            VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
3742
            goto endjob;
3743

J
Jim Fehlig 已提交
3744
        if (libxlDomainDetachDeviceLive(driver, vm, dev) < 0)
3745
            goto endjob;
3746 3747 3748 3749 3750

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

3755 3756
    ret = 0;

3757
    /* Finally, if no error until here, we can save config. */
3758
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3759
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
3760 3761 3762 3763 3764 3765
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3766
 endjob:
W
Wang Yufei 已提交
3767
    libxlDomainObjEndJob(driver, vm);
3768

3769
 cleanup:
3770 3771
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
W
Wang Yufei 已提交
3772
    virDomainObjEndAPI(&vm);
3773
    virObjectUnref(cfg);
3774
    return ret;
3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787
}

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)
{
3788
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3789
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3790 3791 3792 3793 3794 3795 3796 3797
    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 已提交
3798
    if (!(vm = libxlDomObjFromDomain(dom)))
3799 3800
        goto cleanup;

3801 3802 3803
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3804 3805
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto cleanup;
3806 3807 3808

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3809
                                            cfg->caps, driver->xmlopt,
3810
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3811 3812 3813
            goto cleanup;

        /* Make a copy for updated domain. */
3814
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827
                                                    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,
3828
                                            cfg->caps, driver->xmlopt,
3829
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3830 3831
            goto cleanup;

J
Jim Fehlig 已提交
3832
        if ((ret = libxlDomainUpdateDeviceLive(vm, dev)) < 0)
3833 3834 3835 3836 3837 3838
            goto cleanup;

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3839
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
3840 3841 3842 3843 3844
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3845
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
3846 3847 3848 3849 3850 3851
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3852
 cleanup:
3853 3854 3855 3856
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3857
    virObjectUnref(cfg);
3858
    return ret;
3859 3860
}

3861 3862 3863 3864 3865
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
3866 3867
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
3868

3869
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
3870
        goto cleanup;
3871

3872
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
3873 3874
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3875
        goto cleanup;
3876 3877
    }

3878 3879
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

3880
 cleanup:
3881 3882
    virObjectUnref(cfg);
    return ret;
3883 3884
}

3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
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;
3895
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3896 3897

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
3898
        goto cleanup;
3899

3900
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
3901
    if (numa_info == NULL || nr_nodes == 0) {
3902 3903 3904
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
3905 3906 3907
    }

    /* Check/sanitize the cell range */
3908
    if (startCell >= nr_nodes) {
3909 3910
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
3911
                       startCell, nr_nodes - 1);
3912 3913 3914
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
3915 3916
    if (lastCell >= nr_nodes)
        lastCell = nr_nodes - 1;
3917 3918 3919 3920 3921 3922 3923

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

3925 3926
    ret = numCells;

3927
 cleanup:
3928
    libxl_numainfo_list_free(numa_info, nr_nodes);
3929
    virObjectUnref(cfg);
3930 3931 3932
    return ret;
}

3933
static int
3934
libxlConnectDomainEventRegister(virConnectPtr conn,
3935 3936
                                virConnectDomainEventCallback callback,
                                void *opaque,
3937
                                virFreeCallback freecb)
3938 3939 3940
{
    libxlDriverPrivatePtr driver = conn->privateData;

3941 3942 3943
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

3944 3945 3946 3947
    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        return -1;
3948

3949
    return 0;
3950 3951 3952 3953
}


static int
3954 3955
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
3956 3957 3958
{
    libxlDriverPrivatePtr driver = conn->privateData;

3959 3960 3961
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

3962 3963 3964 3965
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
3966

3967
    return 0;
3968 3969
}

3970 3971 3972 3973 3974 3975
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
3976
    if (!(vm = libxlDomObjFromDomain(dom)))
3977 3978
        goto cleanup;

3979 3980 3981
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3982 3983 3984
    *autostart = vm->autostart;
    ret = 0;

3985
 cleanup:
3986
    if (vm)
3987
        virObjectUnlock(vm);
3988 3989 3990 3991 3992 3993 3994
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3995
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3996 3997 3998 3999
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

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

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

4005 4006 4007
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4008 4009 4010
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4011
    if (!vm->persistent) {
4012 4013
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
4014
        goto endjob;
4015 4016 4017 4018 4019
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
4020
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
4021
            goto endjob;
4022
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
4023
            goto endjob;
4024 4025

        if (autostart) {
4026
            if (virFileMakePath(cfg->autostartDir) < 0) {
4027
                virReportSystemError(errno,
4028
                                     _("cannot create autostart directory %s"),
4029
                                     cfg->autostartDir);
4030
                goto endjob;
4031 4032 4033 4034 4035 4036
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4037
                goto endjob;
4038 4039 4040 4041 4042 4043
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4044
                goto endjob;
4045 4046 4047 4048 4049 4050 4051
            }
        }

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

4052
 endjob:
W
Wang Yufei 已提交
4053
    libxlDomainObjEndJob(driver, vm);
4054

4055
 cleanup:
4056 4057
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
W
Wang Yufei 已提交
4058
    virDomainObjEndAPI(&vm);
4059
    virObjectUnref(cfg);
4060 4061 4062
    return ret;
}

4063 4064 4065
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
J
Jim Fehlig 已提交
4066 4067
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4068 4069
    virDomainObjPtr vm;
    char * ret = NULL;
4070
    const char *name = NULL;
J
Jim Fehlig 已提交
4071
    libxl_scheduler sched_id;
4072

J
Jim Fehlig 已提交
4073
    if (!(vm = libxlDomObjFromDomain(dom)))
4074 4075
        goto cleanup;

4076 4077 4078
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

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

4086 4087
    if (nparams)
        *nparams = 0;
4088
    switch (sched_id) {
J
Jim Fehlig 已提交
4089
    case LIBXL_SCHEDULER_SEDF:
4090
        name = "sedf";
4091
        break;
J
Jim Fehlig 已提交
4092
    case LIBXL_SCHEDULER_CREDIT:
4093
        name = "credit";
4094 4095
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
4096
        break;
J
Jim Fehlig 已提交
4097
    case LIBXL_SCHEDULER_CREDIT2:
4098
        name = "credit2";
4099
        break;
J
Jim Fehlig 已提交
4100
    case LIBXL_SCHEDULER_ARINC653:
4101
        name = "arinc653";
4102 4103
        break;
    default:
J
Jim Fehlig 已提交
4104 4105
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
4106
                     " with libxenlight"), vm->def->id);
4107 4108 4109
        goto cleanup;
    }

4110
    ignore_value(VIR_STRDUP(ret, name));
4111

4112
 cleanup:
4113
    if (vm)
4114
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4115
    virObjectUnref(cfg);
4116 4117 4118
    return ret;
}

4119
static int
4120 4121 4122 4123
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
4124
{
J
Jim Fehlig 已提交
4125 4126
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4127
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4128 4129
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
4130 4131
    int ret = -1;

4132 4133 4134 4135
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

J
Jim Fehlig 已提交
4137
    if (!(vm = libxlDomObjFromDomain(dom)))
4138 4139
        goto cleanup;

4140 4141 4142
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4143
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
4144 4145
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
4146 4147 4148
        goto cleanup;
    }

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

J
Jim Fehlig 已提交
4151
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4152 4153
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4154 4155 4156
        goto cleanup;
    }

J
Jim Fehlig 已提交
4157
    if (libxl_domain_sched_params_get(cfg->ctx, vm->def->id, &sc_info) != 0) {
4158 4159
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
4160
                         " with libxenlight"), vm->def->id);
4161 4162 4163
        goto cleanup;
    }

4164 4165
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
4166 4167
        goto cleanup;

4168
    if (*nparams > 1) {
4169 4170
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
4171
            goto cleanup;
4172 4173
    }

4174 4175
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
4176 4177
    ret = 0;

4178
 cleanup:
4179
    if (vm)
4180
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4181
    virObjectUnref(cfg);
4182 4183 4184 4185
    return ret;
}

static int
4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196
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)
4197
{
4198
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
4199
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4200
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4201
    libxl_domain_sched_params sc_info;
4202
    int sched_id;
4203
    size_t i;
4204 4205
    int ret = -1;

4206
    virCheckFlags(0, -1);
4207 4208 4209 4210 4211 4212
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
4213
        return -1;
4214

J
Jim Fehlig 已提交
4215
    if (!(vm = libxlDomObjFromDomain(dom)))
4216 4217
        goto cleanup;

4218 4219 4220
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4221 4222 4223
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4224
    if (!virDomainObjIsActive(vm)) {
4225
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4226
        goto endjob;
4227 4228
    }

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

J
Jim Fehlig 已提交
4231
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4232 4233
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4234
        goto endjob;
4235 4236
    }

J
Jim Fehlig 已提交
4237
    if (libxl_domain_sched_params_get(cfg->ctx, vm->def->id, &sc_info) != 0) {
4238 4239
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
4240
                         " with libxenlight"), vm->def->id);
4241
        goto endjob;
4242 4243 4244
    }

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

4247
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
4248
            sc_info.weight = params[i].value.ui;
4249
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
4250 4251 4252
            sc_info.cap = params[i].value.ui;
    }

J
Jim Fehlig 已提交
4253
    if (libxl_domain_sched_params_set(cfg->ctx, vm->def->id, &sc_info) != 0) {
4254 4255
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
4256
                         " with libxenlight"), vm->def->id);
4257
        goto endjob;
4258 4259 4260 4261
    }

    ret = 0;

4262
 endjob:
W
Wang Yufei 已提交
4263
    libxlDomainObjEndJob(driver, vm);
4264

4265
 cleanup:
W
Wang Yufei 已提交
4266
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
4267
    virObjectUnref(cfg);
4268 4269 4270
    return ret;
}

B
Bamvor Jian Zhang 已提交
4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291

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 已提交
4292
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
4293 4294
        goto cleanup;

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

B
Bamvor Jian Zhang 已提交
4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307
    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 已提交
4308 4309
    if (vm->def->nconsoles)
        chr = vm->def->consoles[0];
B
Bamvor Jian Zhang 已提交
4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320

    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"),
4321
                       dev_name ? dev_name : NULLSTR(chr->info.alias));
B
Bamvor Jian Zhang 已提交
4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336
        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;
    }

4337
 cleanup:
B
Bamvor Jian Zhang 已提交
4338 4339 4340 4341 4342
    if (vm)
        virObjectUnlock(vm);
    return ret;
}

4343 4344 4345 4346 4347 4348 4349
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362
/* 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 已提交
4363 4364
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380
    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;

4381 4382
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
4383
    if (!(vm = libxlDomObjFromDomain(dom)))
4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402
        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];
4403
        int numnodes;
4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421

        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 已提交
4422
            numnodes = libxl_get_max_nodes(cfg->ctx);
4423 4424 4425
            if (numnodes <= 0)
                goto cleanup;

J
Jim Fehlig 已提交
4426
            if (libxl_node_bitmap_alloc(cfg->ctx, &nodemap, 0)) {
4427 4428 4429
                virReportOOMError();
                goto cleanup;
            }
J
Ján Tomko 已提交
4430 4431
            if (!(nodes = virBitmapNew(numnodes)))
                goto cleanup;
4432

J
Jim Fehlig 已提交
4433
            rc = libxl_domain_get_nodeaffinity(cfg->ctx,
4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452
                                               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;
                }
            }

4453
            if (!(nodeset = virBitmapFormat(nodes)))
4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469
                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;

4470
 cleanup:
4471 4472 4473 4474 4475
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
    if (vm)
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4476
    virObjectUnref(cfg);
4477 4478 4479 4480
    return ret;
}
#endif

J
Jim Fehlig 已提交
4481 4482 4483 4484 4485 4486
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4487
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4488
        goto cleanup;
4489 4490 4491 4492

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

J
Jim Fehlig 已提交
4493 4494
    ret = virDomainObjIsActive(obj);

4495
 cleanup:
J
Jim Fehlig 已提交
4496
    if (obj)
4497
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4498 4499 4500 4501 4502 4503 4504 4505 4506
    return ret;
}

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

J
Jim Fehlig 已提交
4507
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4508
        goto cleanup;
4509 4510 4511 4512

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

J
Jim Fehlig 已提交
4513 4514
    ret = obj->persistent;

4515
 cleanup:
J
Jim Fehlig 已提交
4516
    if (obj)
4517
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4518 4519 4520
    return ret;
}

4521 4522 4523 4524 4525 4526
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4527
    if (!(vm = libxlDomObjFromDomain(dom)))
4528
        goto cleanup;
4529 4530 4531 4532

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

4533 4534
    ret = vm->updated;

4535
 cleanup:
4536
    if (vm)
4537
        virObjectUnlock(vm);
4538 4539 4540
    return ret;
}

4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581
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:
W
Wang Yufei 已提交
4582
    libxlDomainObjEndJob(driver, vm);
4583 4584

 cleanup:
W
Wang Yufei 已提交
4585
    virDomainObjEndAPI(&vm);
4586 4587 4588
    return ret;
}

4589 4590 4591 4592 4593 4594
static int
libxlDomainGetTotalCPUStats(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
                            virTypedParameterPtr params,
                            unsigned int nparams)
{
J
Jim Fehlig 已提交
4595
    libxlDriverConfigPtr cfg;
4596 4597 4598 4599 4600 4601
    libxl_dominfo d_info;
    int ret = -1;

    if (nparams == 0)
        return LIBXL_NB_TOTAL_CPU_STAT_PARAM;

J
Jim Fehlig 已提交
4602 4603 4604
    libxl_dominfo_init(&d_info);
    cfg = libxlDriverConfigGet(driver);

4605 4606 4607 4608
    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 已提交
4609
        goto cleanup;
4610 4611 4612 4613 4614 4615 4616 4617 4618 4619
    }

    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 已提交
4620
    virObjectUnref(cfg);
4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634
    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 已提交
4635
    libxlDriverConfigPtr cfg;
4636 4637 4638 4639 4640
    int ret = -1;

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

J
Jim Fehlig 已提交
4643
    cfg = libxlDriverConfigGet(driver);
4644 4645 4646 4647 4648
    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 已提交
4649
        goto cleanup;
4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661
    }

    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 已提交
4662 4663 4664
    if (vcpuinfo)
        libxl_vcpuinfo_list_free(vcpuinfo, maxcpu);
    virObjectUnref(cfg);
4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705
    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;
}

4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719
#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 已提交
4720
    libxlDriverConfigPtr cfg;
4721 4722 4723 4724 4725 4726 4727 4728
    virDomainObjPtr vm;
    libxl_dominfo d_info;
    unsigned mem, maxmem;
    size_t i = 0;
    int ret = -1;

    virCheckFlags(0, -1);

4729
    libxl_dominfo_init(&d_info);
J
Jim Fehlig 已提交
4730 4731
    cfg = libxlDriverConfigGet(driver);

4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761
    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:
W
Wang Yufei 已提交
4762
    libxlDomainObjEndJob(driver, vm);
4763 4764

 cleanup:
4765
    libxl_dominfo_dispose(&d_info);
W
Wang Yufei 已提交
4766
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
4767
    virObjectUnref(cfg);
4768 4769 4770 4771 4772
    return ret;
}

#undef LIBXL_SET_MEMSTAT

4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809
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;
}

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 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860
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;
}
4861

4862
static int
4863 4864 4865
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4866 4867 4868 4869
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4870 4871 4872
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4873 4874 4875 4876
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4877
        ret = -1;
4878 4879 4880 4881 4882 4883

    return ret;
}


static int
4884
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4885 4886 4887
{
    libxlDriverPrivatePtr driver = conn->privateData;

4888 4889 4890
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4891 4892 4893 4894
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        return -1;
4895

4896
    return 0;
4897 4898
}

J
Jim Fehlig 已提交
4899

4900
static int
4901
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4902 4903 4904 4905
{
    return 1;
}

4906
static int
4907 4908 4909
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4910 4911 4912 4913
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4914
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4915

4916 4917 4918
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4919 4920
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
4921 4922 4923 4924

    return ret;
}

4925 4926 4927 4928 4929 4930 4931 4932 4933
/* 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 已提交
4934
    case VIR_DRV_FEATURE_MIGRATION_PARAMS:
J
Joao Martins 已提交
4935
    case VIR_DRV_FEATURE_MIGRATION_P2P:
4936 4937 4938 4939 4940
        return 1;
    default:
        return 0;
    }
}
4941

4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952
static int
libxlNodeDeviceGetPCIInfo(virNodeDeviceDefPtr def,
                          unsigned *domain,
                          unsigned *bus,
                          unsigned *slot,
                          unsigned *function)
{
    virNodeDevCapsDefPtr cap;

    cap = def->caps;
    while (cap) {
4953
        if (cap->data.type == VIR_NODE_DEV_CAP_PCI_DEV) {
4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966
            *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 已提交
4967
        return -1;
4968 4969
    }

C
Chunyan Liu 已提交
4970
    return 0;
4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006
}

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")) {
5007
        virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_XEN);
5008 5009 5010 5011 5012 5013 5014 5015 5016 5017
    } else {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported driver name '%s'"), driverName);
        goto cleanup;
    }

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

    ret = 0;
5018
 cleanup:
5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060
    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 已提交
5061
        goto cleanup;
5062 5063

    ret = 0;
C
Chunyan Liu 已提交
5064

5065
 cleanup:
C
Chunyan Liu 已提交
5066
    virPCIDeviceFree(pci);
5067 5068 5069 5070 5071 5072 5073 5074
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
C
Chunyan Liu 已提交
5075
    virPCIDevicePtr pci = NULL;
5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101
    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 已提交
5102
        goto cleanup;
5103 5104

    ret = 0;
C
Chunyan Liu 已提交
5105

5106
 cleanup:
C
Chunyan Liu 已提交
5107
    virPCIDeviceFree(pci);
5108 5109 5110 5111 5112
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

J
Jim Fehlig 已提交
5113 5114 5115 5116
static char *
libxlDomainMigrateBegin3Params(virDomainPtr domain,
                               virTypedParameterPtr params,
                               int nparams,
5117 5118
                               char **cookieout,
                               int *cookieoutlen,
J
Jim Fehlig 已提交
5119 5120 5121 5122 5123
                               unsigned int flags)
{
    const char *xmlin = NULL;
    virDomainObjPtr vm = NULL;

5124 5125 5126 5127 5128
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return NULL;
#endif

J
Jim Fehlig 已提交
5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140
    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 已提交
5141 5142 5143 5144 5145 5146
    if (STREQ_NULLABLE(vm->def->name, "Domain-0")) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Domain-0 cannot be migrated"));
            return NULL;
    }

J
Jim Fehlig 已提交
5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158
    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;
    }

5159 5160
    return libxlDomainMigrationBegin(domain->conn, vm, xmlin,
                                     cookieout, cookieoutlen);
J
Jim Fehlig 已提交
5161 5162 5163 5164 5165 5166
}

static int
libxlDomainMigratePrepare3Params(virConnectPtr dconn,
                                 virTypedParameterPtr params,
                                 int nparams,
5167 5168
                                 const char *cookiein,
                                 int cookieinlen,
J
Jim Fehlig 已提交
5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179
                                 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;

5180 5181 5182 5183 5184
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206
    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;

5207 5208
    if (libxlDomainMigrationPrepare(dconn, &def, uri_in, uri_out,
                                    cookiein, cookieinlen, flags) < 0)
J
Jim Fehlig 已提交
5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235
        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;

5236 5237 5238 5239 5240
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262
    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 已提交
5263 5264 5265 5266 5267 5268 5269 5270 5271
    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 已提交
5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294

    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;
5295
    virDomainPtr ret = NULL;
J
Jim Fehlig 已提交
5296

5297 5298 5299 5300 5301
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return NULL;
#endif

J
Jim Fehlig 已提交
5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321
    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) {
5322
        virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
5323 5324 5325
        return NULL;
    }

5326
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
5327
        virDomainObjEndAPI(&vm);
5328 5329 5330 5331 5332
        return NULL;
    }

    ret = libxlDomainMigrationFinish(dconn, vm, flags, cancelled);

W
Wang Yufei 已提交
5333
    libxlDomainObjEndJob(driver, vm);
5334

5335
    virDomainObjEndAPI(&vm);
5336 5337

    return ret;
J
Jim Fehlig 已提交
5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351
}

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;

5352 5353 5354 5355 5356
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371
    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);
}

5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388
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;
}
5389

5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528
static int
libxlGetDHCPInterfaces(virDomainPtr dom,
                       virDomainObjPtr vm,
                       virDomainInterfacePtr **ifaces)
{
    int rv = -1;
    int n_leases = 0;
    size_t i, j;
    size_t ifaces_count = 0;
    virNetworkPtr network = NULL;
    char macaddr[VIR_MAC_STRING_BUFLEN];
    virDomainInterfacePtr iface = NULL;
    virNetworkDHCPLeasePtr *leases = NULL;
    virDomainInterfacePtr *ifaces_ret = NULL;

    if (!dom->conn->networkDriver ||
        !dom->conn->networkDriver->networkGetDHCPLeases) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Network driver does not support DHCP lease query"));
        return -1;
    }

    for (i = 0; i < vm->def->nnets; i++) {
        if (vm->def->nets[i]->type != VIR_DOMAIN_NET_TYPE_NETWORK)
            continue;

        virMacAddrFormat(&(vm->def->nets[i]->mac), macaddr);
        virObjectUnref(network);
        network = virNetworkLookupByName(dom->conn,
                                         vm->def->nets[i]->data.network.name);

        if ((n_leases = virNetworkGetDHCPLeases(network, macaddr,
                                                &leases, 0)) < 0)
            goto error;

        if (n_leases) {
            if (VIR_EXPAND_N(ifaces_ret, ifaces_count, 1) < 0)
                goto error;

            if (VIR_ALLOC(ifaces_ret[ifaces_count - 1]) < 0)
                goto error;

            iface = ifaces_ret[ifaces_count - 1];
            /* Assuming each lease corresponds to a separate IP */
            iface->naddrs = n_leases;

            if (VIR_ALLOC_N(iface->addrs, iface->naddrs) < 0)
                goto error;

            if (VIR_STRDUP(iface->name, vm->def->nets[i]->ifname) < 0)
                goto cleanup;

            if (VIR_STRDUP(iface->hwaddr, macaddr) < 0)
                goto cleanup;
        }

        for (j = 0; j < n_leases; j++) {
            virNetworkDHCPLeasePtr lease = leases[j];
            virDomainIPAddressPtr ip_addr = &iface->addrs[j];

            if (VIR_STRDUP(ip_addr->addr, lease->ipaddr) < 0)
                goto cleanup;

            ip_addr->type = lease->type;
            ip_addr->prefix = lease->prefix;
        }

        for (j = 0; j < n_leases; j++)
            virNetworkDHCPLeaseFree(leases[j]);

        VIR_FREE(leases);
    }

    *ifaces = ifaces_ret;
    ifaces_ret = NULL;
    rv = ifaces_count;

 cleanup:
    virObjectUnref(network);
    if (leases) {
        for (i = 0; i < n_leases; i++)
            virNetworkDHCPLeaseFree(leases[i]);
    }
    VIR_FREE(leases);

    return rv;

 error:
    if (ifaces_ret) {
        for (i = 0; i < ifaces_count; i++)
            virDomainInterfaceFree(ifaces_ret[i]);
    }
    VIR_FREE(ifaces_ret);

    goto cleanup;
}


static int
libxlDomainInterfaceAddresses(virDomainPtr dom,
                              virDomainInterfacePtr **ifaces,
                              unsigned int source,
                              unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

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

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

    switch (source) {
    case VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE:
        ret = libxlGetDHCPInterfaces(dom, vm, ifaces);
        break;

    default:
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED,
                       _("Unsupported IP address data source %d"),
                       source);
        break;
    }

 cleanup:
    virDomainObjEndAPI(&vm);
    return ret;
}


5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601
static char *
libxlConnectGetDomainCapabilities(virConnectPtr conn,
                                  const char *emulatorbin,
                                  const char *arch_str,
                                  const char *machine,
                                  const char *virttype_str,
                                  unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    libxlDriverConfigPtr cfg;
    char *ret = NULL;
    int virttype = VIR_DOMAIN_VIRT_XEN;
    virDomainCapsPtr domCaps = NULL;
    int arch = virArchFromHost(); /* virArch */

    virCheckFlags(0, ret);

    if (virConnectGetDomainCapabilitiesEnsureACL(conn) < 0)
        return ret;

    cfg = libxlDriverConfigGet(driver);

    if (virttype_str &&
        (virttype = virDomainVirtTypeFromString(virttype_str)) < 0) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown virttype: %s"),
                       virttype_str);
        goto cleanup;
    }

    if (virttype != VIR_DOMAIN_VIRT_XEN) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown virttype: %s"),
                       virttype_str);
        goto cleanup;
    }

    if (arch_str && (arch = virArchFromString(arch_str)) == VIR_ARCH_NONE) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unknown architecture: %s"),
                       arch_str);
        goto cleanup;
    }

    if (emulatorbin == NULL)
        emulatorbin = "/usr/bin/qemu-system-x86_64";

    if (machine) {
        if (STRNEQ(machine, "xenpv") && STRNEQ(machine, "xenfv")) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("Xen only supports 'xenpv' and 'xenfv' machines"));
            goto cleanup;
        }
    } else {
        machine = "xenpv";
    }

    if (!(domCaps = virDomainCapsNew(emulatorbin, machine, arch, virttype)))
        goto cleanup;

    if (libxlMakeDomainCapabilities(domCaps, cfg->firmwares,
                                    cfg->nfirmwares) < 0)
        goto cleanup;

    ret = virDomainCapsFormat(domCaps);

 cleanup:
    virObjectUnref(domCaps);
    virObjectUnref(cfg);
    return ret;
}


5602
static virHypervisorDriver libxlHypervisorDriver = {
5603
    .name = LIBXL_DRIVER_NAME,
5604 5605 5606 5607
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
5608
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
5609
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
5610
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
5611
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
5612 5613 5614 5615
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
5616 5617 5618 5619 5620 5621 5622
    .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 */
5623
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
5624 5625
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
5626
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
5627 5628
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
5629
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
5630 5631 5632 5633
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
5634
    .domainSave = libxlDomainSave, /* 0.9.2 */
5635
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
5636
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
5637
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
5638
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
5639 5640 5641 5642
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
5643
    .domainPinVcpuFlags = libxlDomainPinVcpuFlags, /* 1.2.1 */
5644
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
5645
    .domainGetVcpuPinInfo = libxlDomainGetVcpuPinInfo, /* 1.2.1 */
5646
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
5647 5648 5649 5650
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
5651 5652 5653
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
5654
    .domainDefineXMLFlags = libxlDomainDefineXMLFlags, /* 1.2.12 */
5655
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
5656
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
5657 5658 5659 5660 5661
    .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 */
5662 5663 5664 5665
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
5666
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
5667
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
5668
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
5669 5670 5671
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
5672
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
5673
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
5674
    .domainGetJobInfo = libxlDomainGetJobInfo, /* 1.3.1 */
5675
    .domainGetJobStats = libxlDomainGetJobStats, /* 1.3.1 */
P
Pavel Hrdina 已提交
5676 5677
    .domainMemoryStats = libxlDomainMemoryStats, /* 1.3.0 */
    .domainGetCPUStats = libxlDomainGetCPUStats, /* 1.3.0 */
5678
    .domainInterfaceStats = libxlDomainInterfaceStats, /* 1.3.2 */
5679 5680
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
5681 5682 5683
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
5684
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
5685 5686 5687
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
5688 5689 5690
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
5691
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
5692 5693 5694 5695
    .nodeDeviceDettach = libxlNodeDeviceDettach, /* 1.2.3 */
    .nodeDeviceDetachFlags = libxlNodeDeviceDetachFlags, /* 1.2.3 */
    .nodeDeviceReAttach = libxlNodeDeviceReAttach, /* 1.2.3 */
    .nodeDeviceReset = libxlNodeDeviceReset, /* 1.2.3 */
5696 5697 5698 5699 5700
    .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 */
5701
    .nodeGetSecurityModel = libxlNodeGetSecurityModel, /* 1.2.16 */
5702
    .domainInterfaceAddresses = libxlDomainInterfaceAddresses, /* 1.3.5 */
5703
    .connectGetDomainCapabilities = libxlConnectGetDomainCapabilities, /* 1.3.6 */
J
Jim Fehlig 已提交
5704 5705
};

5706 5707 5708 5709
static virConnectDriver libxlConnectDriver = {
    .hypervisorDriver = &libxlHypervisorDriver,
};

J
Jim Fehlig 已提交
5710 5711
static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
5712
    .stateInitialize = libxlStateInitialize,
5713
    .stateAutoStart = libxlStateAutoStart,
5714 5715
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
5716 5717 5718 5719 5720 5721
};


int
libxlRegister(void)
{
5722 5723
    if (virRegisterConnectDriver(&libxlConnectDriver,
                                 true) < 0)
J
Jim Fehlig 已提交
5724 5725 5726 5727 5728 5729
        return -1;
    if (virRegisterStateDriver(&libxlStateDriver) < 0)
        return -1;

    return 0;
}