libxl_driver.c 191.7 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 <xenstore.h>
34
#include <fcntl.h>
35
#include <regex.h>
J
Jim Fehlig 已提交
36 37

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

#define VIR_FROM_THIS VIR_FROM_LIBXL

69 70
VIR_LOG_INIT("libxl.libxl_driver");

J
Jim Fehlig 已提交
71 72 73 74 75 76
#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

77
#define LIBXL_NB_TOTAL_CPU_STAT_PARAM 1
78
#define LIBXL_NB_TOTAL_BLK_STAT_PARAM 6
79

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

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

J
Jim Fehlig 已提交
86 87 88 89 90 91 92 93 94
#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)

95

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

98 99 100 101 102 103 104 105 106
/* 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;
};

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
/* Object used to store disk statistics across multiple xen backends */
typedef struct _libxlBlockStats libxlBlockStats;
typedef libxlBlockStats *libxlBlockStatsPtr;
struct _libxlBlockStats {
    long long rd_req;
    long long rd_bytes;
    long long wr_req;
    long long wr_bytes;
    long long f_req;

    char *backend;
    union {
        struct {
            long long ds_req;
            long long oo_req;
        } vbd;
    } u;
};

J
Jim Fehlig 已提交
126
/* Function declarations */
127 128
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
129 130
                           void *opaque);

J
Jim Fehlig 已提交
131 132

/* Function definitions */
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
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 已提交
310 311 312 313 314 315 316
static virDomainObjPtr
libxlDomObjFromDomain(virDomainPtr dom)
{
    virDomainObjPtr vm;
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

W
Wang Yufei 已提交
317
    vm = virDomainObjListFindByUUIDRef(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
318 319 320 321 322 323 324 325 326 327 328
    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;
}

329 330
static int
libxlAutostartDomain(virDomainObjPtr vm,
331 332 333
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
334
    int ret = -1;
335

W
Wang Yufei 已提交
336
    virObjectRef(vm);
337
    virObjectLock(vm);
338 339
    virResetLastError();

W
Wang Yufei 已提交
340 341
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;
342

343
    if (vm->autostart && !virDomainObjIsActive(vm) &&
344
        libxlDomainStartNew(driver, vm, false) < 0) {
345 346 347
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to autostart VM '%s': %s"),
                       vm->def->name, virGetLastErrorMessage());
348
        goto endjob;
349 350
    }

351
    ret = 0;
352 353

 endjob:
W
Wang Yufei 已提交
354 355 356
    libxlDomainObjEndJob(driver, vm);
 cleanup:
    virDomainObjEndAPI(&vm);
357

358
    return ret;
359 360
}

J
Jim Fehlig 已提交
361 362 363 364
/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
365 366
static int
libxlReconnectDomain(virDomainObjPtr vm,
J
Jim Fehlig 已提交
367 368 369
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
370
    libxlDomainObjPrivatePtr priv = vm->privateData;
J
Jim Fehlig 已提交
371
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
372 373 374 375
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;
376
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
377
    unsigned int hostdev_flags = VIR_HOSTDEV_SP_PCI;
378
    int ret = -1;
379 380 381 382

#ifdef LIBXL_HAVE_PVUSB
    hostdev_flags |= VIR_HOSTDEV_SP_USB;
#endif
J
Jim Fehlig 已提交
383

384
    virObjectRef(vm);
385
    virObjectLock(vm);
J
Jim Fehlig 已提交
386

387 388
    libxl_dominfo_init(&d_info);

J
Jim Fehlig 已提交
389
    /* Does domain still exist? */
J
Jim Fehlig 已提交
390
    rc = libxl_domain_info(cfg->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
391
    if (rc == ERROR_INVAL) {
392
        goto error;
J
Jim Fehlig 已提交
393 394 395
    } else if (rc != 0) {
        VIR_DEBUG("libxl_domain_info failed (code %d), ignoring domain %d",
                  rc, vm->def->id);
396
        goto error;
J
Jim Fehlig 已提交
397 398 399
    }

    /* Is this a domain that was under libvirt control? */
J
Jim Fehlig 已提交
400
    if (libxl_userdata_retrieve(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
401 402
                                "libvirt-xml", &data, &len)) {
        VIR_DEBUG("libxl_userdata_retrieve failed, ignoring domain %d", vm->def->id);
403
        goto error;
J
Jim Fehlig 已提交
404 405 406 407
    }

    /* Update domid in case it changed (e.g. reboot) while we were gone? */
    vm->def->id = d_info.domid;
408 409

    /* Update hostdev state */
410
    if (virHostdevUpdateActiveDomainDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
411
                                            vm->def, hostdev_flags) < 0)
412
        goto error;
413

414
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
415 416
        driver->inhibitCallback(true, driver->inhibitOpaque);

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

C
Cédric Bosdonnat 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    /* now that we know it's reconnected call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL) &&
        STRNEQ("Domain-0", vm->def->name)) {
        char *xml = virDomainDefFormat(vm->def, cfg->caps, 0);
        int hookret;

        /* we can't stop the operation even if the script raised an error */
        hookret = virHookCall(VIR_HOOK_DRIVER_LIBXL, vm->def->name,
                              VIR_HOOK_LIBXL_OP_RECONNECT, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);
        if (hookret < 0) {
            /* Stop the domain if the hook failed */
            if (virDomainObjIsActive(vm)) {
                libxlDomainDestroyInternal(driver, vm);
                virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);
            }
            goto error;
        }
    }

441 442 443
    ret = 0;

 cleanup:
444
    libxl_dominfo_dispose(&d_info);
445
    virObjectUnlock(vm);
446
    virObjectUnref(vm);
J
Jim Fehlig 已提交
447
    virObjectUnref(cfg);
448
    return ret;
J
Jim Fehlig 已提交
449

450
 error:
451
    libxlDomainCleanup(driver, vm);
452
    if (!vm->persistent) {
453
        virDomainObjListRemoveLocked(driver->domains, vm);
454

455 456 457 458 459
        /* virDomainObjListRemoveLocked leaves the object unlocked,
         * lock it again to factorize more code. */
        virObjectLock(vm);
    }
    goto cleanup;
J
Jim Fehlig 已提交
460 461 462 463 464
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
465
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
466 467 468
}

static int
469
libxlStateCleanup(void)
J
Jim Fehlig 已提交
470 471 472 473
{
    if (!libxl_driver)
        return -1;

474
    virObjectUnref(libxl_driver->hostdevMgr);
475
    virObjectUnref(libxl_driver->config);
476
    virObjectUnref(libxl_driver->xmlopt);
477
    virObjectUnref(libxl_driver->domains);
478
    virObjectUnref(libxl_driver->reservedGraphicsPorts);
J
Jim Fehlig 已提交
479
    virObjectUnref(libxl_driver->migrationPorts);
480
    virLockManagerPluginUnref(libxl_driver->lockManager);
J
Jim Fehlig 已提交
481

482
    virObjectUnref(libxl_driver->domainEventState);
483
    virSysinfoDefFree(libxl_driver->hostsysinfo);
484

J
Jim Fehlig 已提交
485 486 487 488 489 490
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

491 492
static bool
libxlDriverShouldLoad(bool privileged)
493
{
494
    bool ret = false;
J
Jim Fehlig 已提交
495

496
    /* Don't load if non-root */
J
Jim Fehlig 已提交
497
    if (!privileged) {
498
        VIR_INFO("Not running privileged, disabling libxenlight driver");
499
        return ret;
J
Jim Fehlig 已提交
500 501
    }

R
Roman Bogorodskiy 已提交
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    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");
523 524 525 526
        return ret;
    }

    /* Don't load if legacy xen toolstack (xend) is in use */
527 528 529 530 531 532 533 534 535 536 537
    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);
538 539
    } else {
        ret = true;
J
Jim Fehlig 已提交
540 541
    }

542 543 544
    return ret;
}

545 546 547 548 549 550 551 552 553 554
/* 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,
};

555 556 557 558 559 560 561 562
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
};

563 564 565 566 567 568
const struct libxl_event_hooks ev_hooks = {
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlDomainEventHandler,
    .disaster = NULL,
};

J
Jim Fehlig 已提交
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
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 已提交
609
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
610
    if (virDomainDefSetVcpusMax(vm->def, d_info.vcpu_max_id + 1, driver->xmlopt))
611 612
        goto cleanup;

613 614
    if (virDomainDefSetVcpus(vm->def, d_info.vcpu_online) < 0)
        goto cleanup;
J
Jim Fehlig 已提交
615
    vm->def->mem.cur_balloon = d_info.current_memkb;
616
    virDomainDefSetMemoryTotal(vm->def, d_info.max_memkb);
J
Jim Fehlig 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629

    ret = 0;

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

630 631 632 633 634
static int
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
635
    libxlDriverConfigPtr cfg;
636
    char *driverConf = NULL;
637 638 639 640 641
    char ebuf[1024];

    if (!libxlDriverShouldLoad(privileged))
        return 0;

J
Jim Fehlig 已提交
642 643 644 645
    if (VIR_ALLOC(libxl_driver) < 0)
        return -1;

    if (virMutexInit(&libxl_driver->lock) < 0) {
646 647
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
J
Jim Fehlig 已提交
648 649 650 651 652
        VIR_FREE(libxl_driver);
        return -1;
    }

    /* Allocate bitmap for vnc port reservation */
653
    if (!(libxl_driver->reservedGraphicsPorts =
J
Ján Tomko 已提交
654 655
          virPortAllocatorNew(_("VNC"),
                              LIBXL_VNC_PORT_MIN,
656 657
                              LIBXL_VNC_PORT_MAX,
                              0)))
658
        goto error;
J
Jim Fehlig 已提交
659

J
Jim Fehlig 已提交
660 661 662 663
    /* Allocate bitmap for migration port reservation */
    if (!(libxl_driver->migrationPorts =
          virPortAllocatorNew(_("migration"),
                              LIBXL_MIGRATION_PORT_MIN,
664
                              LIBXL_MIGRATION_PORT_MAX, 0)))
J
Jim Fehlig 已提交
665 666
        goto error;

667 668
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
669

670 671 672
    if (!(libxl_driver->hostdevMgr = virHostdevManagerGetDefault()))
        goto error;

673
    if (!(cfg = libxlDriverConfigNew()))
674
        goto error;
J
Jim Fehlig 已提交
675

676 677 678 679 680 681 682
    if (virAsprintf(&driverConf, "%s/libxl.conf", cfg->configBaseDir) < 0)
        goto error;

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

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

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

689 690 691
    /* Register callback to handle domain events */
    libxl_event_register_callbacks(cfg->ctx, &ev_hooks, libxl_driver);

692 693
    libxl_driver->config = cfg;
    if (virFileMakePath(cfg->stateDir) < 0) {
694 695
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create state dir '%s': %s"),
696
                       cfg->stateDir,
697
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
698 699
        goto error;
    }
700
    if (virFileMakePath(cfg->libDir) < 0) {
701 702
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create lib dir '%s': %s"),
703
                       cfg->libDir,
704
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
705 706
        goto error;
    }
707
    if (virFileMakePath(cfg->saveDir) < 0) {
708 709
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create save dir '%s': %s"),
710
                       cfg->saveDir,
711
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
712 713
        goto error;
    }
714 715 716 717 718 719 720
    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
Joao Martins 已提交
721 722 723 724 725 726 727
    if (virFileMakePath(cfg->channelDir) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create channel dir '%s': %s"),
                       cfg->channelDir,
                       virStrerror(errno, ebuf, sizeof(ebuf)));
        goto error;
    }
J
Jim Fehlig 已提交
728

729 730 731 732 733 734 735 736
    if (!(libxl_driver->lockManager =
          virLockManagerPluginNew(cfg->lockManagerName ?
                                  cfg->lockManagerName : "nop",
                                  "libxl",
                                  cfg->configBaseDir,
                                  0)))
        goto error;

737
    /* read the host sysinfo */
738
    libxl_driver->hostsysinfo = virSysinfoRead();
739

740
    libxl_driver->domainEventState = virObjectEventStateNew();
E
Eric Blake 已提交
741
    if (!libxl_driver->domainEventState)
742 743
        goto error;

744
    if ((cfg->caps = libxlMakeCapabilities(cfg->ctx)) == NULL) {
745 746
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
747 748 749
        goto error;
    }

750
    if (!(libxl_driver->xmlopt = libxlCreateXMLConf()))
751
        goto error;
J
Jim Fehlig 已提交
752

J
Jim Fehlig 已提交
753 754 755 756
    /* Add Domain-0 */
    if (libxlAddDom0(libxl_driver) < 0)
        goto error;

J
Jim Fehlig 已提交
757
    /* Load running domains first. */
758
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
759 760
                                       cfg->stateDir,
                                       cfg->autostartDir,
761
                                       1,
762
                                       cfg->caps,
763
                                       libxl_driver->xmlopt,
764
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
765 766 767 768 769
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
770
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
771 772
                                       cfg->configDir,
                                       cfg->autostartDir,
773
                                       0,
774
                                       cfg->caps,
775
                                       libxl_driver->xmlopt,
776
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
777 778
        goto error;

779 780
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
781

J
Jim Fehlig 已提交
782 783
    return 0;

784
 error:
785
    VIR_FREE(driverConf);
786
    libxlStateCleanup();
787
    return -1;
J
Jim Fehlig 已提交
788 789
}

790 791 792 793 794 795 796 797 798 799
static void
libxlStateAutoStart(void)
{
    if (!libxl_driver)
        return;

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

J
Jim Fehlig 已提交
800
static int
801
libxlStateReload(void)
J
Jim Fehlig 已提交
802
{
803 804
    libxlDriverConfigPtr cfg;

J
Jim Fehlig 已提交
805 806 807
    if (!libxl_driver)
        return 0;

808 809
    cfg = libxlDriverConfigGet(libxl_driver);

810
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
811 812
                                   cfg->configDir,
                                   cfg->autostartDir,
813
                                   1,
814
                                   cfg->caps,
815
                                   libxl_driver->xmlopt,
816 817
                                   NULL, libxl_driver);

818 819
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
820

821
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
822 823 824 825 826
    return 0;
}


static virDrvOpenStatus
827 828
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
829
                 virConfPtr conf ATTRIBUTE_UNUSED,
830
                 unsigned int flags)
J
Jim Fehlig 已提交
831
{
E
Eric Blake 已提交
832 833
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
834 835 836 837
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

838
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
839 840 841 842 843 844 845 846 847 848 849 850
            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) {
851 852
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
853 854 855 856 857 858 859 860
            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")) {
861 862 863
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
864 865 866 867
            return VIR_DRV_OPEN_ERROR;
        }
    }

868 869 870
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
871 872 873 874 875 876
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
877
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
878 879 880 881 882 883
{
    conn->privateData = NULL;
    return 0;
}

static const char *
884
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
885
{
886 887 888
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
889
    return "Xen";
J
Jim Fehlig 已提交
890 891 892
}

static int
893
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
894 895
{
    libxlDriverPrivatePtr driver = conn->privateData;
896
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
897

898 899 900
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

901 902 903
    cfg = libxlDriverConfigGet(driver);
    *version = cfg->version;
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
904 905 906
    return 0;
}

907

908
static char *libxlConnectGetHostname(virConnectPtr conn)
909
{
910 911 912
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

913 914 915
    return virGetHostname();
}

916 917 918 919 920 921 922 923
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

924 925 926
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

927 928 929 930 931 932 933 934
    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;
935
    if (virBufferCheckError(&buf) < 0)
936 937 938
        return NULL;
    return virBufferContentAndReset(&buf);
}
939

J
Jim Fehlig 已提交
940
static int
941
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
942 943 944
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;
945
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
946

947 948 949
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

950 951
    cfg = libxlDriverConfigGet(driver);
    ret = libxl_get_max_cpus(cfg->ctx);
952 953 954 955 956
    /* 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)
957
        ret = -1;
J
Jim Fehlig 已提交
958

959
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
960 961 962 963 964 965
    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
966 967 968
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

969
    return libxlDriverNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
970 971 972
}

static char *
973
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
974 975 976
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;
977
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
978

979 980 981
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

982
    cfg = libxlDriverConfigGet(driver);
983
    xml = virCapabilitiesFormatXML(cfg->caps);
J
Jim Fehlig 已提交
984

985
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
986 987 988 989
    return xml;
}

static int
990
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
991 992 993 994
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

995 996 997
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

998 999
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1000 1001 1002 1003 1004

    return n;
}

static int
1005
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
1006 1007 1008 1009
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1010 1011 1012
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

1013 1014
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026

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

1030 1031 1032 1033
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_VALIDATE, NULL);

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

1036
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
1037
                                        NULL, parse_flags)))
J
Jim Fehlig 已提交
1038 1039
        goto cleanup;

1040 1041 1042
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

1043
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1044
                                   driver->xmlopt,
1045
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
1046 1047
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
1048
        goto cleanup;
W
Wang Yufei 已提交
1049
    virObjectRef(vm);
J
Jim Fehlig 已提交
1050 1051
    def = NULL;

1052 1053 1054 1055 1056 1057 1058 1059
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
        goto cleanup;
    }

1060 1061
    if (libxlDomainStartNew(driver, vm,
                         (flags & VIR_DOMAIN_START_PAUSED) != 0) < 0) {
1062 1063 1064
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
1065
            goto cleanup;
1066
        }
1067
        goto endjob;
J
Jim Fehlig 已提交
1068 1069 1070 1071 1072 1073
    }

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

1074
 endjob:
W
Wang Yufei 已提交
1075
    libxlDomainObjEndJob(driver, vm);
1076

1077
 cleanup:
J
Jim Fehlig 已提交
1078
    virDomainDefFree(def);
W
Wang Yufei 已提交
1079
    virDomainObjEndAPI(&vm);
1080
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    return dom;
}

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

1091
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
1092
    if (!vm) {
1093
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1094 1095 1096
        goto cleanup;
    }

1097 1098 1099
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1100 1101 1102 1103
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

1104
 cleanup:
J
Jim Fehlig 已提交
1105
    if (vm)
1106
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    return dom;
}

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

1117
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
1118
    if (!vm) {
1119
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1120 1121 1122
        goto cleanup;
    }

1123 1124 1125
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1126 1127 1128 1129
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

1130
 cleanup:
J
Jim Fehlig 已提交
1131
    if (vm)
1132
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
    return dom;
}

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

1143
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
1144
    if (!vm) {
1145
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1146 1147 1148
        goto cleanup;
    }

1149 1150 1151
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1152 1153 1154 1155
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

1156
 cleanup:
1157
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
1158 1159 1160
    return dom;
}

1161 1162 1163 1164
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1165
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1166
    virDomainObjPtr vm;
1167
    virObjectEventPtr event = NULL;
1168 1169
    int ret = -1;

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

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

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

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

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

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

J
Jiri Denemark 已提交
1194
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1195

1196
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
1197 1198 1199
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

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

    ret = 0;

1205
 endjob:
W
Wang Yufei 已提交
1206
    libxlDomainObjEndJob(driver, vm);
1207

1208
 cleanup:
W
Wang Yufei 已提交
1209
    virDomainObjEndAPI(&vm);
1210
    if (event)
1211
        libxlDomainEventQueue(driver, event);
1212
    virObjectUnref(cfg);
1213 1214 1215 1216 1217 1218 1219 1220
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1221
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1222
    virDomainObjPtr vm;
1223
    virObjectEventPtr event = NULL;
1224 1225
    int ret = -1;

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

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

1231 1232 1233
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1234 1235 1236
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1237
    if (!virDomainObjIsActive(vm)) {
1238
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1239
        goto endjob;
1240 1241
    }

J
Jiri Denemark 已提交
1242
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1243
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
1244 1245
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
1246
                           vm->def->id);
1247
            goto endjob;
1248 1249
        }

J
Jiri Denemark 已提交
1250 1251
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1252

1253
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_RESUMED,
1254 1255 1256
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

1257
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
1258
        goto endjob;
1259 1260 1261

    ret = 0;

1262
 endjob:
W
Wang Yufei 已提交
1263
    libxlDomainObjEndJob(driver, vm);
1264

1265
 cleanup:
W
Wang Yufei 已提交
1266
    virDomainObjEndAPI(&vm);
1267
    if (event)
1268
        libxlDomainEventQueue(driver, event);
1269
    virObjectUnref(cfg);
1270 1271 1272
    return ret;
}

J
Jim Fehlig 已提交
1273
static int
1274
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1275
{
J
Jim Fehlig 已提交
1276 1277
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1278 1279 1280
    virDomainObjPtr vm;
    int ret = -1;

1281 1282 1283 1284 1285
    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;
1286

J
Jim Fehlig 已提交
1287
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1288 1289
        goto cleanup;

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

1292
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1293 1294
        goto cleanup;

J
Jim Fehlig 已提交
1295
    if (!virDomainObjIsActive(vm)) {
1296 1297
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1298 1299 1300
        goto cleanup;
    }

1301
    if (flags & VIR_DOMAIN_SHUTDOWN_PARAVIRT) {
J
Jim Fehlig 已提交
1302
        ret = libxl_domain_shutdown(cfg->ctx, vm->def->id);
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
        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 已提交
1317
        ret = libxl_send_trigger(cfg->ctx, vm->def->id,
1318 1319 1320 1321
                                 LIBXL_TRIGGER_POWER, 0);
        if (ret == 0)
            goto cleanup;

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

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

1335 1336 1337 1338 1339 1340 1341
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
1342
static int
E
Eric Blake 已提交
1343
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1344
{
J
Jim Fehlig 已提交
1345 1346
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1347 1348 1349
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
1350 1351 1352
    virCheckFlags(VIR_DOMAIN_REBOOT_PARAVIRT, -1);
    if (flags == 0)
        flags = VIR_DOMAIN_REBOOT_PARAVIRT;
E
Eric Blake 已提交
1353

J
Jim Fehlig 已提交
1354
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1355 1356
        goto cleanup;

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

1359
    if (virDomainRebootEnsureACL(dom->conn, vm->def, flags) < 0)
1360 1361
        goto cleanup;

J
Jim Fehlig 已提交
1362
    if (!virDomainObjIsActive(vm)) {
1363 1364
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1365 1366 1367
        goto cleanup;
    }

J
Jim Fehlig 已提交
1368
    if (flags & VIR_DOMAIN_REBOOT_PARAVIRT) {
J
Jim Fehlig 已提交
1369
        ret = libxl_domain_reboot(cfg->ctx, vm->def->id);
J
Jim Fehlig 已提交
1370 1371 1372
        if (ret == 0)
            goto cleanup;

1373 1374
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
1375
                       vm->def->id);
J
Jim Fehlig 已提交
1376
        ret = -1;
J
Jim Fehlig 已提交
1377 1378
    }

1379
 cleanup:
J
Jim Fehlig 已提交
1380
    if (vm)
1381
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1382
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1383 1384 1385 1386
    return ret;
}

static int
1387 1388
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1389 1390
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
1391
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1392 1393
    virDomainObjPtr vm;
    int ret = -1;
1394
    virObjectEventPtr event = NULL;
J
Jim Fehlig 已提交
1395

1396 1397
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1398
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1399 1400
        goto cleanup;

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

1403 1404 1405
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1406 1407 1408
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1409
    if (!virDomainObjIsActive(vm)) {
1410 1411
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
1412
        goto endjob;
J
Jim Fehlig 已提交
1413 1414
    }

1415
    if (libxlDomainDestroyInternal(driver, vm) < 0) {
1416
        virReportError(VIR_ERR_INTERNAL_ERROR,
1417
                       _("Failed to destroy domain '%d'"), vm->def->id);
1418
        goto endjob;
J
Jim Fehlig 已提交
1419 1420
    }

1421 1422 1423 1424 1425 1426 1427
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_DESTROYED);

    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

    libxlDomainCleanup(driver, vm);
1428 1429
    if (!vm->persistent)
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1430 1431 1432

    ret = 0;

1433
 endjob:
W
Wang Yufei 已提交
1434
    libxlDomainObjEndJob(driver, vm);
1435

1436
 cleanup:
W
Wang Yufei 已提交
1437
    virDomainObjEndAPI(&vm);
1438 1439
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1440
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1441 1442 1443
    return ret;
}

1444 1445 1446 1447 1448 1449
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1450 1451 1452 1453 1454 1455
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *type = NULL;

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

1459 1460 1461
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1462
    if (VIR_STRDUP(type, virDomainOSTypeToString(vm->def->os.type)) < 0)
1463
        goto cleanup;
1464

1465
 cleanup:
1466
    if (vm)
1467
        virObjectUnlock(vm);
1468 1469 1470
    return type;
}

1471
static unsigned long long
1472 1473 1474
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    virDomainObjPtr vm;
1475
    unsigned long long ret = 0;
1476

J
Jim Fehlig 已提交
1477
    if (!(vm = libxlDomObjFromDomain(dom)))
1478
        goto cleanup;
1479 1480 1481 1482

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

1483
    ret = virDomainDefGetMemoryTotal(vm->def);
1484

1485
 cleanup:
1486
    if (vm)
1487
        virObjectUnlock(vm);
1488 1489 1490
    return ret;
}

1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520

/*
 * Helper method for --current, --live, and --config options, and check
 * whether domain is active or can get persistent domain configuration.
 *
 * Return 0 if success, also change the flags and get the persistent
 * domain configuration if needed. Return -1 on error.
 */
static int
virDomainLiveConfigHelperMethod(virCapsPtr caps,
                                virDomainXMLOptionPtr xmlopt,
                                virDomainObjPtr dom,
                                unsigned int *flags,
                                virDomainDefPtr *persistentDef)
{
    if (virDomainObjUpdateModificationImpact(dom, flags) < 0)
        return -1;

    if (*flags & VIR_DOMAIN_AFFECT_CONFIG) {
        if (!(*persistentDef = virDomainObjGetPersistentDef(caps, xmlopt, dom))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Get persistent config failed"));
            return -1;
        }
    }

    return 0;
}


1521
static int
1522
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1523 1524 1525
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1526
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1527
    virDomainObjPtr vm;
1528
    virDomainDefPtr persistentDef = NULL;
1529 1530 1531
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1532 1533
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1534

J
Jim Fehlig 已提交
1535
    if (!(vm = libxlDomObjFromDomain(dom)))
1536 1537
        goto cleanup;

1538 1539 1540
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

1541 1542 1543
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1544 1545
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm, &flags,
                                        &persistentDef) < 0)
1546
        goto endjob;
1547

1548 1549
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1550

1551
        if (flags & VIR_DOMAIN_MEM_LIVE) {
J
Jim Fehlig 已提交
1552
            if (libxl_domain_setmaxmem(cfg->ctx, vm->def->id, newmem) < 0) {
1553 1554
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
1555
                                 " with libxenlight"), vm->def->id);
1556
                goto endjob;
1557 1558 1559 1560 1561 1562
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1563
            virDomainDefSetMemoryTotal(persistentDef, newmem);
1564 1565
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
1566
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1567
            goto endjob;
1568 1569
        }

1570 1571
    } else {
        /* resize the current memory */
1572

1573
        if (newmem > virDomainDefGetMemoryTotal(vm->def)) {
1574 1575
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1576
            goto endjob;
1577 1578 1579
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
1580 1581 1582 1583
            int res;

            /* Unlock virDomainObj while ballooning memory */
            virObjectUnlock(vm);
J
Jim Fehlig 已提交
1584
            res = libxl_set_memory_target(cfg->ctx, vm->def->id, newmem, 0,
1585 1586 1587
                                          /* force */ 1);
            virObjectLock(vm);
            if (res < 0) {
1588 1589
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
1590
                                 " with libxenlight"), vm->def->id);
1591
                goto endjob;
1592 1593 1594 1595 1596 1597
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1598
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1599
            goto endjob;
1600
        }
1601 1602
    }

1603 1604
    ret = 0;

1605
 endjob:
W
Wang Yufei 已提交
1606
    libxlDomainObjEndJob(driver, vm);
1607

1608
 cleanup:
W
Wang Yufei 已提交
1609
    virDomainObjEndAPI(&vm);
1610
    virObjectUnref(cfg);
1611 1612 1613 1614 1615 1616 1617 1618 1619
    return ret;
}

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

1620 1621 1622 1623 1624 1625
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1626 1627 1628
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
J
Jim Fehlig 已提交
1629 1630
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1631
    virDomainObjPtr vm;
1632
    libxl_dominfo d_info;
J
Jim Fehlig 已提交
1633 1634
    int ret = -1;

J
Jim Fehlig 已提交
1635
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1636 1637
        goto cleanup;

1638 1639 1640
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1641 1642 1643
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1644
        info->maxMem = virDomainDefGetMemoryTotal(vm->def);
1645
    } else {
1646 1647
        libxl_dominfo_init(&d_info);

J
Jim Fehlig 已提交
1648
        if (libxl_domain_info(cfg->ctx, &d_info, vm->def->id) != 0) {
1649
            virReportError(VIR_ERR_INTERNAL_ERROR,
1650 1651
                           _("libxl_domain_info failed for domain '%d'"),
                           vm->def->id);
1652 1653 1654 1655
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1656
        info->maxMem = d_info.max_memkb;
1657 1658

        libxl_dominfo_dispose(&d_info);
1659 1660
    }

J
Jiri Denemark 已提交
1661
    info->state = virDomainObjGetState(vm, NULL);
1662
    info->nrVirtCpu = virDomainDefGetVcpus(vm->def);
J
Jim Fehlig 已提交
1663 1664
    ret = 0;

1665
 cleanup:
J
Jim Fehlig 已提交
1666
    if (vm)
1667
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1668
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1669 1670 1671
    return ret;
}

1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1683
    if (!(vm = libxlDomObjFromDomain(dom)))
1684 1685
        goto cleanup;

1686 1687 1688
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1689
    *state = virDomainObjGetState(vm, reason);
1690 1691
    ret = 0;

1692
 cleanup:
1693
    if (vm)
1694
        virObjectUnlock(vm);
1695 1696 1697
    return ret;
}

1698 1699 1700
/*
 * virDomainObjPtr must be locked on invocation
 */
1701
static int
1702 1703
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1704
{
J
Jim Fehlig 已提交
1705
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1706
    libxlSavefileHeader hdr;
1707
    virObjectEventPtr event = NULL;
1708 1709
    char *xml = NULL;
    uint32_t xml_len;
1710
    int fd = -1;
1711 1712 1713
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1714 1715 1716
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1717 1718 1719 1720
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1721
                            -1, -1, 0)) < 0) {
1722 1723 1724 1725 1726
        virReportSystemError(-fd,
                             _("Failed to create domain save file '%s'"), to);
        goto cleanup;
    }

1727
    if ((xml = virDomainDefFormat(vm->def, cfg->caps, 0)) == NULL)
1728 1729 1730 1731 1732 1733 1734 1735 1736
        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)) {
1737 1738
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1739 1740 1741 1742
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1743 1744
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1745 1746 1747
        goto cleanup;
    }

1748 1749
    /* Unlock virDomainObj while saving domain */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
1750
    ret = libxl_domain_suspend(cfg->ctx, vm->def->id, fd, 0, NULL);
1751 1752 1753
    virObjectLock(vm);

    if (ret != 0) {
1754 1755 1756
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1757
        ret = -1;
1758 1759 1760
        goto cleanup;
    }

1761 1762 1763
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_SAVED);

1764
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1765 1766
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

1767
    if (libxlDomainDestroyInternal(driver, vm) < 0) {
1768 1769
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1770 1771 1772
        goto cleanup;
    }

1773
    libxlDomainCleanup(driver, vm);
1774
    vm->hasManagedSave = true;
1775 1776
    ret = 0;

1777
 cleanup:
1778 1779 1780 1781 1782
    VIR_FREE(xml);
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1783
    virObjectUnref(cfg);
1784 1785 1786 1787
    return ret;
}

static int
1788 1789
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1790
{
1791 1792
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1793
    int ret = -1;
1794
    bool remove_dom = false;
1795

1796 1797 1798 1799 1800
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1801 1802
    virCheckFlags(0, -1);
    if (dxml) {
1803 1804
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1805 1806 1807
        return -1;
    }

J
Jim Fehlig 已提交
1808
    if (!(vm = libxlDomObjFromDomain(dom)))
1809 1810
        goto cleanup;

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

1813 1814 1815
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1816 1817 1818
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1819
    if (!virDomainObjIsActive(vm)) {
1820
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1821
        goto endjob;
1822 1823
    }

1824
    if (libxlDoDomainSave(driver, vm, to) < 0)
1825
        goto endjob;
1826

1827 1828
    if (!vm->persistent)
        remove_dom = true;
1829 1830

    ret = 0;
1831

1832
 endjob:
W
Wang Yufei 已提交
1833
    libxlDomainObjEndJob(driver, vm);
1834

1835
 cleanup:
1836 1837 1838 1839
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
W
Wang Yufei 已提交
1840
    virDomainObjEndAPI(&vm);
1841 1842
    return ret;
}
1843

1844
static int
1845 1846 1847 1848 1849 1850 1851 1852
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)
1853 1854
{
    libxlDriverPrivatePtr driver = conn->privateData;
1855
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1856 1857 1858 1859 1860
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1861

1862 1863 1864 1865 1866
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1867
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1868
    if (dxml) {
1869 1870
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1871 1872 1873
        return -1;
    }

1874
    fd = libxlDomainSaveImageOpen(driver, cfg, from, &def, &hdr);
1875
    if (fd < 0)
1876
        goto cleanup;
1877

1878
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1879
        goto cleanup;
1880

1881
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1882
                                   driver->xmlopt,
1883 1884 1885
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1886
        goto cleanup;
W
Wang Yufei 已提交
1887
    virObjectRef(vm);
1888 1889
    def = NULL;

1890 1891 1892 1893 1894 1895 1896 1897
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
        goto cleanup;
    }

1898 1899 1900
    ret = libxlDomainStartRestore(driver, vm,
                                  (flags & VIR_DOMAIN_SAVE_PAUSED) != 0,
                                  fd, hdr.version);
1901
    if (ret < 0 && !vm->persistent)
1902
        virDomainObjListRemove(driver->domains, vm);
1903

W
Wang Yufei 已提交
1904
    libxlDomainObjEndJob(driver, vm);
1905

1906
 cleanup:
1907 1908
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1909
    virDomainDefFree(def);
W
Wang Yufei 已提交
1910
    virDomainObjEndAPI(&vm);
1911
    virObjectUnref(cfg);
1912 1913 1914
    return ret;
}

1915 1916 1917 1918 1919 1920
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

1921
static int
1922
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1923 1924
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
1925
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1926
    virDomainObjPtr vm;
1927
    virObjectEventPtr event = NULL;
1928
    bool remove_dom = false;
1929 1930 1931 1932 1933
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

J
Jim Fehlig 已提交
1934
    if (!(vm = libxlDomObjFromDomain(dom)))
1935 1936
        goto cleanup;

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

1939 1940 1941
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1942 1943 1944
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1945
    if (!virDomainObjIsActive(vm)) {
1946
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1947
        goto endjob;
1948 1949 1950 1951
    }

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
1952
        if (libxl_domain_pause(cfg->ctx, vm->def->id) != 0) {
1953 1954 1955
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
1956
                           vm->def->id);
1957
            goto endjob;
1958 1959 1960 1961 1962
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

1963 1964
    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
1965
    ret = libxl_domain_core_dump(cfg->ctx, vm->def->id, to, NULL);
1966 1967
    virObjectLock(vm);
    if (ret != 0) {
1968 1969
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
1970
                       vm->def->id);
1971 1972
        ret = -1;
        goto unpause;
1973 1974 1975
    }

    if (flags & VIR_DUMP_CRASH) {
1976
        if (libxlDomainDestroyInternal(driver, vm) < 0) {
1977
            virReportError(VIR_ERR_INTERNAL_ERROR,
1978
                           _("Failed to destroy domain '%d'"), vm->def->id);
1979
            goto unpause;
1980 1981
        }

1982 1983 1984
        libxlDomainCleanup(driver, vm);
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_CRASHED);
1985
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1986
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
1987 1988
        if (!vm->persistent)
            remove_dom = true;
1989 1990 1991 1992
    }

    ret = 0;

1993
 unpause:
1994
    if (virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
1995
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
1996 1997
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
1998
                             " libxenlight"), vm->def->id);
1999 2000 2001 2002 2003
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
2004

2005
 endjob:
W
Wang Yufei 已提交
2006
    libxlDomainObjEndJob(driver, vm);
2007

2008
 cleanup:
2009 2010 2011 2012
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
W
Wang Yufei 已提交
2013
    virDomainObjEndAPI(&vm);
2014
    if (event)
2015
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
2016
    virObjectUnref(cfg);
2017 2018 2019
    return ret;
}

2020 2021 2022 2023 2024 2025 2026
static int
libxlDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;
2027
    bool remove_dom = false;
2028 2029 2030

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2031
    if (!(vm = libxlDomObjFromDomain(dom)))
2032 2033
        goto cleanup;

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

2036 2037 2038
    if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2039 2040 2041
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2042
    if (!virDomainObjIsActive(vm)) {
2043
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2044
        goto endjob;
2045
    }
2046
    if (!vm->persistent) {
2047 2048
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
2049
        goto endjob;
2050
    }
2051 2052 2053

    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
2054
        goto endjob;
2055 2056 2057

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

2058
    if (libxlDoDomainSave(driver, vm, name) < 0)
2059
        goto endjob;
2060

2061 2062
    if (!vm->persistent)
        remove_dom = true;
2063 2064

    ret = 0;
2065

2066
 endjob:
W
Wang Yufei 已提交
2067
    libxlDomainObjEndJob(driver, vm);
2068

2069
 cleanup:
2070 2071 2072 2073
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
W
Wang Yufei 已提交
2074
    virDomainObjEndAPI(&vm);
2075 2076 2077 2078
    VIR_FREE(name);
    return ret;
}

2079 2080
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
2081 2082 2083 2084
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
2085
    int ret = -1;
2086

2087
    virObjectLock(vm);
2088 2089 2090 2091 2092 2093

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

    vm->hasManagedSave = virFileExists(name);

2094
    ret = 0;
2095
 cleanup:
2096
    virObjectUnlock(vm);
2097
    VIR_FREE(name);
2098
    return ret;
2099 2100
}

2101 2102 2103 2104 2105 2106 2107 2108
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2109
    if (!(vm = libxlDomObjFromDomain(dom)))
2110 2111
        goto cleanup;

2112 2113 2114
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2115
    ret = vm->hasManagedSave;
2116

2117
 cleanup:
2118
    if (vm)
2119
        virObjectUnlock(vm);
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
    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 已提交
2133
    if (!(vm = libxlDomObjFromDomain(dom)))
2134 2135
        goto cleanup;

2136 2137 2138
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2139 2140 2141 2142 2143
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
2144
    vm->hasManagedSave = false;
2145

2146
 cleanup:
2147 2148
    VIR_FREE(name);
    if (vm)
2149
        virObjectUnlock(vm);
2150 2151 2152
    return ret;
}

2153 2154 2155 2156 2157
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2158
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2159 2160
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
2161
    libxl_bitmap map;
2162 2163
    uint8_t *bitmask = NULL;
    unsigned int maplen;
2164 2165
    size_t i;
    unsigned int pos;
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
    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)) {
2178 2179
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2180 2181 2182 2183
        return -1;
    }

    if (!nvcpus) {
2184
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2185 2186 2187
        return -1;
    }

J
Jim Fehlig 已提交
2188
    if (!(vm = libxlDomObjFromDomain(dom)))
2189 2190
        goto cleanup;

2191 2192 2193
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2194 2195 2196
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2197
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2198 2199
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2200
        goto endjob;
2201 2202 2203
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2204 2205
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2206
        goto endjob;
2207 2208
    }

2209
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2210 2211
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2212
        goto endjob;
2213 2214
    }

2215 2216
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && virDomainDefGetVcpusMax(vm->def) < max)
        max = virDomainDefGetVcpusMax(vm->def);
2217 2218

    if (nvcpus > max) {
2219 2220 2221
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2222
        goto endjob;
2223 2224
    }

2225
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm)))
2226
        goto endjob;
2227

E
Eric Blake 已提交
2228
    maplen = VIR_CPU_MAPLEN(nvcpus);
2229
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
2230
        goto endjob;
2231 2232

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2233
        pos = i / 8;
2234 2235 2236 2237 2238 2239 2240 2241
        bitmask[pos] |= 1 << (i % 8);
    }

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

    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
2242
        if (virDomainDefSetVcpusMax(def, nvcpus, driver->xmlopt) < 0)
2243
            goto cleanup;
2244 2245 2246
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
2247 2248
        if (virDomainDefSetVcpus(def, nvcpus) < 0)
            goto cleanup;
2249 2250 2251
        break;

    case VIR_DOMAIN_VCPU_LIVE:
J
Jim Fehlig 已提交
2252
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2253 2254
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2255
                             " with libxenlight"), vm->def->id);
2256
            goto endjob;
2257
        }
2258 2259
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0)
            goto endjob;
2260 2261 2262
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2263
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2264 2265
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2266
                             " with libxenlight"), vm->def->id);
2267
            goto endjob;
2268
        }
2269 2270 2271
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0 ||
            virDomainDefSetVcpus(def, nvcpus) < 0)
            goto endjob;
2272 2273 2274 2275 2276
        break;
    }

    ret = 0;

2277
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2278
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0) {
2279 2280 2281 2282 2283
            VIR_WARN("Unable to save status on vm %s after changing vcpus",
                     vm->def->name);
        }
    }
    if (flags & VIR_DOMAIN_VCPU_CONFIG) {
2284
        if (virDomainSaveConfig(cfg->configDir, cfg->caps, def) < 0) {
2285 2286 2287 2288
            VIR_WARN("Unable to save configuration of vm %s after changing vcpus",
                     vm->def->name);
        }
    }
2289

2290
 endjob:
W
Wang Yufei 已提交
2291
    libxlDomainObjEndJob(driver, vm);
2292

2293
 cleanup:
2294
    VIR_FREE(bitmask);
W
Wang Yufei 已提交
2295 2296
    virDomainObjEndAPI(&vm);
    virObjectUnref(cfg);
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
    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;
2312
    bool active;
2313 2314 2315 2316 2317

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

J
Jim Fehlig 已提交
2318
    if (!(vm = libxlDomObjFromDomain(dom)))
2319 2320
        goto cleanup;

2321
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2322 2323
        goto cleanup;

2324 2325 2326 2327 2328 2329 2330 2331 2332
    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)) {
2333 2334
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2335 2336 2337
        return -1;
    }

2338
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2339
        if (!active) {
2340 2341
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2342 2343 2344 2345
            goto cleanup;
        }
        def = vm->def;
    } else {
2346
        if (!vm->persistent) {
2347 2348
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2349 2350
            goto cleanup;
        }
2351 2352 2353
        def = vm->newDef ? vm->newDef : vm->def;
    }

2354 2355 2356
    if (flags & VIR_DOMAIN_VCPU_MAXIMUM)
        ret = virDomainDefGetVcpusMax(def);
    else
2357
        ret = virDomainDefGetVcpus(def);
2358

2359
 cleanup:
2360
    if (vm)
2361
        virObjectUnlock(vm);
2362 2363 2364 2365
    return ret;
}

static int
2366 2367 2368
libxlDomainPinVcpuFlags(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen,
                        unsigned int flags)
2369 2370
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2371
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2372
    virDomainDefPtr targetDef = NULL;
2373
    virBitmapPtr pcpumap = NULL;
2374
    virDomainVcpuDefPtr vcpuinfo;
2375 2376
    virDomainObjPtr vm;
    int ret = -1;
2377 2378 2379

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
2380

J
Jim Fehlig 已提交
2381
    if (!(vm = libxlDomObjFromDomain(dom)))
2382 2383
        goto cleanup;

2384
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2385 2386
        goto cleanup;

2387 2388 2389
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2390 2391
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
2392
        goto endjob;
2393

2394
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2395 2396 2397 2398 2399
        targetDef = vm->def;

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

2400 2401
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
2402
        goto endjob;
2403

2404 2405 2406 2407 2408 2409 2410
    if (!(vcpuinfo = virDomainDefGetVcpu(targetDef, vcpu)) ||
        !vcpuinfo->online) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("vcpu '%u' is not active"), vcpu);
        goto endjob;
    }

2411 2412
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        libxl_bitmap map = { .size = maplen, .map = cpumap };
J
Jim Fehlig 已提交
2413
        if (libxl_set_vcpuaffinity(cfg->ctx, vm->def->id, vcpu, &map) != 0) {
2414 2415 2416
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"),
                           vcpu);
2417
            goto endjob;
2418
        }
2419
    }
2420

2421 2422 2423
    virBitmapFree(vcpuinfo->cpumask);
    vcpuinfo->cpumask = pcpumap;
    pcpumap = NULL;
2424

2425 2426
    ret = 0;

2427
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
2428
        ret = virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps);
2429
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2430
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, targetDef);
2431 2432
    }

2433
 endjob:
W
Wang Yufei 已提交
2434
    libxlDomainObjEndJob(driver, vm);
2435

2436
 cleanup:
W
Wang Yufei 已提交
2437
    virDomainObjEndAPI(&vm);
2438
    virBitmapFree(pcpumap);
2439
    virObjectUnref(cfg);
2440 2441 2442
    return ret;
}

2443 2444 2445 2446 2447 2448 2449 2450
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

2451 2452 2453 2454 2455 2456 2457 2458 2459
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;
2460
    int ret = -1;
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474

    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;

2475
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2476 2477 2478 2479 2480
        targetDef = vm->def;

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

2481 2482
    ret = virDomainDefGetVcpuPinInfoHelper(targetDef, maplen, ncpumaps, cpumaps,
                                           libxl_get_max_cpus(cfg->ctx), NULL);
2483

2484
 cleanup:
2485 2486 2487 2488 2489
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(cfg);
    return ret;
}
2490 2491 2492 2493 2494

static int
libxlDomainGetVcpus(virDomainPtr dom, virVcpuInfoPtr info, int maxinfo,
                    unsigned char *cpumaps, int maplen)
{
J
Jim Fehlig 已提交
2495 2496
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2497 2498 2499 2500
    virDomainObjPtr vm;
    int ret = -1;
    libxl_vcpuinfo *vcpuinfo;
    int maxcpu, hostcpus;
2501
    size_t i;
2502 2503
    unsigned char *cpumap;

J
Jim Fehlig 已提交
2504
    if (!(vm = libxlDomObjFromDomain(dom)))
2505 2506
        goto cleanup;

2507 2508 2509
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

J
Jim Fehlig 已提交
2515
    if ((vcpuinfo = libxl_list_vcpu(cfg->ctx, vm->def->id, &maxcpu,
2516
                                    &hostcpus)) == NULL) {
2517 2518
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
2519
                       vm->def->id);
2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
        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 已提交
2542
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2543 2544 2545 2546 2547
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

2548
 cleanup:
2549
    if (vm)
2550
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2551
    virObjectUnref(cfg);
2552 2553 2554
    return ret;
}

J
Jim Fehlig 已提交
2555
static char *
2556
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2557
{
2558 2559
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2560
    virDomainObjPtr vm;
2561
    virDomainDefPtr def;
J
Jim Fehlig 已提交
2562 2563
    char *ret = NULL;

2564 2565
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2566
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2567 2568
        goto cleanup;

2569 2570 2571
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2572 2573 2574 2575 2576
    if ((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef)
        def = vm->newDef;
    else
        def = vm->def;

2577
    ret = virDomainDefFormat(def, cfg->caps,
2578
                             virDomainDefFormatConvertXMLFlags(flags));
J
Jim Fehlig 已提交
2579

2580
 cleanup:
J
Jim Fehlig 已提交
2581
    if (vm)
2582
        virObjectUnlock(vm);
2583
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2584 2585 2586
    return ret;
}

2587
static char *
2588 2589 2590
libxlConnectDomainXMLFromNative(virConnectPtr conn,
                                const char *nativeFormat,
                                const char *nativeConfig,
2591
                                unsigned int flags)
2592 2593
{
    libxlDriverPrivatePtr driver = conn->privateData;
2594
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2595 2596 2597 2598
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2599 2600
    virCheckFlags(0, NULL);

2601 2602 2603
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

2604
    if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XL)) {
2605 2606 2607 2608
        if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
            goto cleanup;
        if (!(def = xenParseXL(conf,
                               cfg->caps,
2609
                               driver->xmlopt)))
2610
            goto cleanup;
2611
    } else if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XM)) {
2612 2613 2614 2615
        if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
            goto cleanup;

        if (!(def = xenParseXM(conf,
2616 2617
                               cfg->caps,
                               driver->xmlopt)))
2618
            goto cleanup;
2619
    } else if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_SEXPR)) {
2620 2621 2622
        /* only support latest xend config format */
        if (!(def = xenParseSxprString(nativeConfig,
                                       NULL,
2623 2624 2625
                                       -1,
                                       cfg->caps,
                                       driver->xmlopt))) {
2626 2627 2628 2629 2630
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("parsing sxpr config failed"));
            goto cleanup;
        }
    } else {
2631 2632
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2633 2634 2635
        goto cleanup;
    }

2636
    xml = virDomainDefFormat(def, cfg->caps, VIR_DOMAIN_DEF_FORMAT_INACTIVE);
2637

2638
 cleanup:
2639 2640 2641
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2642
    virObjectUnref(cfg);
2643 2644 2645 2646 2647
    return xml;
}

#define MAX_CONFIG_SIZE (1024 * 65)
static char *
2648 2649 2650
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
2651 2652
{
    libxlDriverPrivatePtr driver = conn->privateData;
2653
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2654 2655 2656 2657 2658
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    int len = MAX_CONFIG_SIZE;
    char *ret = NULL;

E
Eric Blake 已提交
2659 2660
    virCheckFlags(0, NULL);

2661 2662 2663
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

2664
    if (!(def = virDomainDefParseString(domainXml,
2665
                                        cfg->caps, driver->xmlopt, NULL,
2666
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE)))
2667 2668
        goto cleanup;

2669
    if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XL)) {
2670
        if (!(conf = xenFormatXL(def, conn)))
2671
            goto cleanup;
2672
    } else if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XM)) {
2673
        if (!(conf = xenFormatXM(conn, def)))
2674 2675 2676 2677 2678
            goto cleanup;
    } else {

        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2679
        goto cleanup;
2680
    }
2681

2682
    if (VIR_ALLOC_N(ret, len) < 0)
2683 2684 2685 2686 2687 2688 2689
        goto cleanup;

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

2690
 cleanup:
2691 2692 2693
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2694
    virObjectUnref(cfg);
2695 2696 2697
    return ret;
}

J
Jim Fehlig 已提交
2698
static int
2699 2700
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
2701 2702 2703 2704
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2705 2706 2707
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2708 2709
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
2710 2711 2712 2713
    return n;
}

static int
2714
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
2715 2716 2717 2718
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2719 2720 2721
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2722
    n = virDomainObjListNumOfDomains(driver->domains, false,
2723 2724
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
2725 2726 2727 2728 2729
    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
2730
                           unsigned int flags)
J
Jim Fehlig 已提交
2731 2732 2733 2734 2735 2736 2737
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

J
Jim Fehlig 已提交
2738
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2739 2740
        goto cleanup;

2741 2742 2743
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2744 2745 2746
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2747
    if (virDomainObjIsActive(vm)) {
2748 2749
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
2750
        goto endjob;
J
Jim Fehlig 已提交
2751 2752
    }

2753 2754
    ret = libxlDomainStartNew(driver, vm,
                              (flags & VIR_DOMAIN_START_PAUSED) != 0);
2755
    if (ret < 0)
2756
        goto endjob;
2757
    dom->id = vm->def->id;
J
Jim Fehlig 已提交
2758

2759
 endjob:
W
Wang Yufei 已提交
2760
    libxlDomainObjEndJob(driver, vm);
2761

2762
 cleanup:
W
Wang Yufei 已提交
2763
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
    return ret;
}

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

static virDomainPtr
2774
libxlDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags)
J
Jim Fehlig 已提交
2775 2776
{
    libxlDriverPrivatePtr driver = conn->privateData;
2777
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2778 2779 2780
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
2781
    virObjectEventPtr event = NULL;
2782
    virDomainDefPtr oldDef = NULL;
2783
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
J
Jim Fehlig 已提交
2784

2785 2786 2787
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_DEFINE_VALIDATE)
2788
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE_SCHEMA;
2789

2790
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
2791
                                        NULL, parse_flags)))
2792
        goto cleanup;
J
Jim Fehlig 已提交
2793

2794 2795 2796
    if (virXMLCheckIllegalChars("name", def->name, "\n") < 0)
        goto cleanup;

2797
    if (virDomainDefineXMLFlagsEnsureACL(conn, def) < 0)
2798
        goto cleanup;
2799

2800
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2801
                                   driver->xmlopt,
2802 2803
                                   0,
                                   &oldDef)))
2804
        goto cleanup;
2805

J
Jim Fehlig 已提交
2806 2807 2808
    def = NULL;
    vm->persistent = 1;

2809
    if (virDomainSaveConfig(cfg->configDir,
2810
                            cfg->caps,
J
Jim Fehlig 已提交
2811
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2812
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
2813 2814 2815 2816 2817 2818 2819 2820
        vm = NULL;
        goto cleanup;
    }

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

2821
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2822
                                     !oldDef ?
2823 2824 2825
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

2826
 cleanup:
J
Jim Fehlig 已提交
2827
    virDomainDefFree(def);
2828
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
2829
    if (vm)
2830
        virObjectUnlock(vm);
2831 2832
    if (event)
        libxlDomainEventQueue(driver, event);
2833
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2834 2835 2836
    return dom;
}

2837 2838 2839 2840 2841 2842
static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    return libxlDomainDefineXMLFlags(conn, xml, 0);
}

J
Jim Fehlig 已提交
2843
static int
2844 2845
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2846 2847
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2848
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2849
    virDomainObjPtr vm;
2850
    virObjectEventPtr event = NULL;
2851
    char *name = NULL;
J
Jim Fehlig 已提交
2852 2853
    int ret = -1;

2854 2855
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2856
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2857 2858
        goto cleanup;

2859 2860 2861
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2862
    if (!vm->persistent) {
2863 2864
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2865 2866 2867
        goto cleanup;
    }

2868 2869 2870 2871 2872 2873 2874
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2875 2876
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2877 2878 2879
                goto cleanup;
            }
        } else {
2880 2881 2882
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2883 2884 2885 2886
            goto cleanup;
        }
    }

2887
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2888 2889
        goto cleanup;

2890
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2891 2892
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2893 2894 2895
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
2896
        virDomainObjListRemove(driver->domains, vm);
2897 2898 2899
        vm = NULL;
    }

J
Jim Fehlig 已提交
2900 2901
    ret = 0;

2902
 cleanup:
2903
    VIR_FREE(name);
J
Jim Fehlig 已提交
2904
    if (vm)
2905
        virObjectUnlock(vm);
2906 2907
    if (event)
        libxlDomainEventQueue(driver, event);
2908
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2909 2910 2911
    return ret;
}

2912 2913 2914 2915 2916 2917
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2918
static int
J
Jim Fehlig 已提交
2919
libxlDomainChangeEjectableMedia(virDomainObjPtr vm, virDomainDiskDefPtr disk)
2920
{
J
Jim Fehlig 已提交
2921
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
2922 2923
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2924
    size_t i;
2925 2926
    int ret = -1;

2927
    for (i = 0; i < vm->def->ndisks; i++) {
2928 2929 2930 2931 2932 2933 2934 2935
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
2936 2937 2938
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
2939 2940 2941 2942
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2943 2944 2945
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
2946 2947 2948
        return -1;
    }

J
Jim Fehlig 已提交
2949
    if (libxlMakeDisk(disk, &x_disk) < 0)
2950 2951
        goto cleanup;

J
Jim Fehlig 已提交
2952
    if ((ret = libxl_cdrom_insert(cfg->ctx, vm->def->id, &x_disk, NULL)) < 0) {
2953 2954 2955
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
2956 2957 2958
        goto cleanup;
    }

2959 2960 2961
    if (virDomainDiskSetSource(origdisk, virDomainDiskGetSource(disk)) < 0)
        goto cleanup;
    virDomainDiskSetType(origdisk, virDomainDiskGetType(disk));
2962 2963 2964 2965 2966

    virDomainDiskDefFree(disk);

    ret = 0;

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

static int
J
Jim Fehlig 已提交
2973
libxlDomainAttachDeviceDiskLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
2974
{
J
Jim Fehlig 已提交
2975
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
2976 2977 2978 2979 2980 2981
    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 已提交
2982
            ret = libxlDomainChangeEjectableMedia(vm, l_disk);
2983 2984 2985
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (l_disk->bus == VIR_DOMAIN_DISK_BUS_XEN) {
2986
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
2987 2988
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
2989 2990 2991
                    goto cleanup;
                }

2992
                if (!virDomainDiskGetSource(l_disk)) {
2993 2994
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
2995 2996 2997
                    goto cleanup;
                }

2998
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
2999 3000
                    goto cleanup;

J
Jim Fehlig 已提交
3001
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3002 3003
                    goto cleanup;

3004 3005 3006 3007 3008
                if (virDomainLockDiskAttach(libxl_driver->lockManager,
                                            "xen:///system",
                                            vm, l_disk) < 0)
                    goto cleanup;

J
Jim Fehlig 已提交
3009
                if ((ret = libxl_device_disk_add(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
3010
                                                &x_disk, NULL)) < 0) {
3011 3012 3013
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
3014 3015 3016 3017 3018
                    if (virDomainLockDiskDetach(libxl_driver->lockManager,
                                                vm, l_disk) < 0) {
                        VIR_WARN("Unable to release lock on %s",
                                 virDomainDiskGetSource(l_disk));
                    }
3019 3020 3021 3022 3023 3024
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
3025 3026 3027
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
3028 3029 3030
            }
            break;
        default:
3031 3032 3033
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
3034 3035 3036
            break;
    }

3037
 cleanup:
J
Jim Fehlig 已提交
3038
    virObjectUnref(cfg);
3039 3040 3041
    return ret;
}

3042 3043 3044 3045 3046
static int
libxlDomainAttachHostPCIDevice(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
J
Jim Fehlig 已提交
3047
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3048
    libxl_device_pci pcidev;
3049 3050
    virDomainHostdevDefPtr found;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
3051
    virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
J
Jim Fehlig 已提交
3052
    int ret = -1;
3053

3054 3055
    libxl_device_pci_init(&pcidev);

3056 3057 3058
    if (virDomainHostdevFind(vm->def, hostdev, &found) >= 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("target pci device %.4x:%.2x:%.2x.%.1x already exists"),
3059 3060
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
J
Jim Fehlig 已提交
3061
        goto cleanup;
3062 3063 3064
    }

    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs + 1) < 0)
J
Jim Fehlig 已提交
3065
        goto cleanup;
3066 3067 3068 3069

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

3072
    if (libxlMakePCI(hostdev, &pcidev) < 0)
C
Chunyan Liu 已提交
3073
        goto error;
3074

J
Jim Fehlig 已提交
3075
    if (libxl_device_pci_add(cfg->ctx, vm->def->id, &pcidev, 0) < 0) {
3076 3077
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to attach pci device %.4x:%.2x:%.2x.%.1x"),
3078 3079
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3080
        goto error;
3081 3082 3083
    }

    vm->def->hostdevs[vm->def->nhostdevs++] = hostdev;
J
Jim Fehlig 已提交
3084 3085
    ret = 0;
    goto cleanup;
3086

3087
 error:
3088 3089
    virHostdevReAttachPCIDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                 vm->def->name, &hostdev, 1, NULL);
J
Jim Fehlig 已提交
3090 3091 3092

 cleanup:
    virObjectUnref(cfg);
3093
    libxl_device_pci_dispose(&pcidev);
J
Jim Fehlig 已提交
3094
    return ret;
3095 3096
}

3097
#ifdef LIBXL_HAVE_PVUSB
3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
static int
libxlDomainAttachControllerDevice(libxlDriverPrivatePtr driver,
                                  virDomainObjPtr vm,
                                  virDomainControllerDefPtr controller)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    const char *type = virDomainControllerTypeToString(controller->type);
    libxl_device_usbctrl usbctrl;
    int ret = -1;

    libxl_device_usbctrl_init(&usbctrl);

    if (controller->type != VIR_DOMAIN_CONTROLLER_TYPE_USB) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("'%s' controller cannot be hot plugged."),
                       type);
        goto cleanup;
    }

    if (controller->idx == -1)
        controller->idx = virDomainControllerFindUnusedIndex(vm->def,
                                                             controller->type);

    if (controller->opts.usbopts.ports == -1)
        controller->opts.usbopts.ports = 8;

    if (virDomainControllerFind(vm->def, controller->type, controller->idx) >= 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("target %s:%d already exists"),
                       type, controller->idx);
        goto cleanup;
    }

    if (VIR_REALLOC_N(vm->def->controllers, vm->def->ncontrollers + 1) < 0)
        goto cleanup;

    if (libxlMakeUSBController(controller, &usbctrl) < 0)
        goto cleanup;

    if (libxl_device_usbctrl_add(cfg->ctx, vm->def->id, &usbctrl, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to attach USB controller"));
        goto cleanup;
    }

    virDomainControllerInsertPreAlloced(vm->def, controller);
    ret = 0;

 cleanup:
    virObjectUnref(cfg);
    libxl_device_usbctrl_dispose(&usbctrl);
    return ret;
}

3152 3153 3154 3155 3156 3157 3158 3159 3160
static int
libxlDomainAttachHostUSBDevice(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    libxl_device_usbdev usbdev;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
    int ret = -1;
3161 3162
    size_t i;
    int ports = 0, usbdevs = 0;
3163 3164 3165 3166 3167 3168 3169

    libxl_device_usbdev_init(&usbdev);

    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
        hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
        goto cleanup;

3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
    /* search for available controller:port */
    for (i = 0; i < vm->def->ncontrollers; i++)
        ports += vm->def->controllers[i]->opts.usbopts.ports;

    for (i = 0; i < vm->def->nhostdevs; i++) {
        if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
            hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
            usbdevs++;
    }

    if (ports <= usbdevs) {
        /* no free ports, we will create a new usb controller */
        virDomainControllerDefPtr controller;

        if (!(controller = virDomainControllerDefNew(VIR_DOMAIN_CONTROLLER_TYPE_USB)))
            goto cleanup;

        controller->model = VIR_DOMAIN_CONTROLLER_MODEL_USB_QUSB2;
        controller->idx = -1;
        controller->opts.usbopts.ports = 8;

        if (libxlDomainAttachControllerDevice(driver, vm, controller) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("No available USB controller and port, and "
                             "failed to attach a new one"));
            virDomainControllerDefFree(controller);
            goto cleanup;
        }
    }

3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs + 1) < 0)
        goto cleanup;

    if (virHostdevPrepareUSBDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                    vm->def->name, &hostdev, 1, 0) < 0)
        goto cleanup;

    if (libxlMakeUSB(hostdev, &usbdev) < 0)
        goto reattach;

    if (libxl_device_usbdev_add(cfg->ctx, vm->def->id, &usbdev, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to attach usb device Busnum:%3x, Devnum:%3x"),
                       hostdev->source.subsys.u.usb.bus,
                       hostdev->source.subsys.u.usb.device);
        goto reattach;
    }

    vm->def->hostdevs[vm->def->nhostdevs++] = hostdev;
    ret = 0;
    goto cleanup;

 reattach:
    virHostdevReAttachUSBDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                 vm->def->name, &hostdev, 1);

 cleanup:
    virObjectUnref(cfg);
    libxl_device_usbdev_dispose(&usbdev);
    return ret;
}
#endif

3233 3234 3235
static int
libxlDomainAttachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3236
                            virDomainHostdevDefPtr hostdev)
3237 3238 3239 3240 3241 3242 3243 3244 3245 3246
{
    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 已提交
3247
        if (libxlDomainAttachHostPCIDevice(driver, vm, hostdev) < 0)
C
Chunyan Liu 已提交
3248
            return -1;
3249 3250
        break;

3251 3252 3253 3254 3255 3256 3257
#ifdef LIBXL_HAVE_PVUSB
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
        if (libxlDomainAttachHostUSBDevice(driver, vm, hostdev) < 0)
            return -1;
        break;
#endif

3258 3259 3260 3261
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
C
Chunyan Liu 已提交
3262
        return -1;
3263 3264 3265 3266 3267
    }

    return 0;
}

3268
static int
J
Jim Fehlig 已提交
3269
libxlDomainDetachDeviceDiskLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3270
{
J
Jim Fehlig 已提交
3271
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
3272 3273
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
3274
    int idx;
3275 3276 3277 3278 3279 3280
    int ret = -1;

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

3281 3282 3283
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
3284 3285
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3286 3287 3288
                    goto cleanup;
                }

3289
                l_disk = vm->def->disks[idx];
3290

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

J
Jim Fehlig 已提交
3294
                if ((ret = libxl_device_disk_remove(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
3295
                                                    &x_disk, NULL)) < 0) {
3296 3297 3298
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3299 3300 3301
                    goto cleanup;
                }

3302 3303 3304 3305 3306
                if (virDomainLockDiskDetach(libxl_driver->lockManager,
                                            vm, l_disk) < 0)
                    VIR_WARN("Unable to release lock on %s",
                             virDomainDiskGetSource(l_disk));

3307
                virDomainDiskRemove(vm->def, idx);
3308 3309 3310
                virDomainDiskDefFree(l_disk);

            } else {
3311 3312 3313
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3314 3315 3316
            }
            break;
        default:
3317 3318 3319
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3320 3321 3322
            break;
    }

3323
 cleanup:
J
Jim Fehlig 已提交
3324
    virObjectUnref(cfg);
3325 3326 3327
    return ret;
}

3328 3329 3330 3331 3332
static int
libxlDomainAttachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3333
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3334
    virDomainNetType actualType;
3335 3336
    libxl_device_nic nic;
    int ret = -1;
3337
    char mac[VIR_MAC_STRING_BUFLEN];
3338

3339 3340
    libxl_device_nic_init(&nic);

3341 3342
    /* preallocate new slot for device */
    if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets + 1) < 0)
3343
        goto cleanup;
3344 3345 3346 3347 3348 3349

    /* 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)
3350
        goto cleanup;
3351 3352 3353

    actualType = virDomainNetGetActualType(net);

3354 3355 3356 3357
    if (virDomainHasNet(vm->def, net)) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("network device with mac %s already exists"),
                       virMacAddrFormat(&net->mac, mac));
3358
        goto cleanup;
3359 3360
    }

3361
    if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
        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;

3373 3374 3375
        /* 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
3376
         * the nets list if successful.
3377
         */
3378
        ret = libxlDomainAttachHostDevice(driver, vm, hostdev);
3379
        goto cleanup;
3380 3381
    }

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

J
Jim Fehlig 已提交
3385
    if (libxl_device_nic_add(cfg->ctx, vm->def->id, &nic, 0)) {
3386 3387 3388 3389 3390 3391 3392 3393 3394
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to attach network device"));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    libxl_device_nic_dispose(&nic);
3395 3396 3397
    if (!ret) {
        vm->def->nets[vm->def->nnets++] = net;
    } else {
3398 3399 3400
        virDomainNetRemoveHostdev(vm->def, net);
        networkReleaseActualDevice(vm->def, net);
    }
J
Jim Fehlig 已提交
3401
    virObjectUnref(cfg);
3402 3403 3404
    return ret;
}

3405
static int
3406 3407
libxlDomainAttachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3408 3409 3410 3411 3412 3413
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
J
Jim Fehlig 已提交
3414
            ret = libxlDomainAttachDeviceDiskLive(vm, dev);
3415 3416 3417 3418
            if (!ret)
                dev->data.disk = NULL;
            break;

3419
#ifdef LIBXL_HAVE_PVUSB
3420 3421 3422 3423 3424
        case VIR_DOMAIN_DEVICE_CONTROLLER:
            ret = libxlDomainAttachControllerDevice(driver, vm, dev->data.controller);
            if (!ret)
                dev->data.controller = NULL;
            break;
3425
#endif
3426

3427
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3428
            ret = libxlDomainAttachNetDevice(driver, vm,
3429 3430 3431 3432 3433
                                             dev->data.net);
            if (!ret)
                dev->data.net = NULL;
            break;

3434
        case VIR_DOMAIN_DEVICE_HOSTDEV:
J
Jim Fehlig 已提交
3435
            ret = libxlDomainAttachHostDevice(driver, vm,
3436
                                              dev->data.hostdev);
3437 3438 3439 3440
            if (!ret)
                dev->data.hostdev = NULL;
            break;

3441
        default:
3442 3443 3444
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
            break;
    }

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
3455
    virDomainNetDefPtr net;
3456
    virDomainHostdevDefPtr hostdev;
3457
    virDomainControllerDefPtr controller;
3458
    virDomainHostdevDefPtr found;
3459
    char mac[VIR_MAC_STRING_BUFLEN];
3460 3461 3462 3463

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3464
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3465 3466
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3467 3468
                return -1;
            }
3469
            if (virDomainDiskInsert(vmdef, disk))
3470 3471 3472 3473
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;
3474

3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489
        case VIR_DOMAIN_DEVICE_CONTROLLER:
            controller = dev->data.controller;
            if (controller->idx != -1 &&
                virDomainControllerFind(vmdef, controller->type,
                                        controller->idx) >= 0) {
                virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                               _("Target already exists"));
                return -1;
            }

            if (virDomainControllerInsert(vmdef, controller) < 0)
                return -1;
            dev->data.controller = NULL;
            break;

3490 3491
        case VIR_DOMAIN_DEVICE_NET:
            net = dev->data.net;
3492 3493 3494 3495 3496 3497
            if (virDomainHasNet(vmdef, net)) {
                virReportError(VIR_ERR_INVALID_ARG,
                               _("network device with mac %s already exists"),
                               virMacAddrFormat(&net->mac, mac));
                return -1;
            }
3498 3499 3500 3501 3502
            if (virDomainNetInsert(vmdef, net))
                return -1;
            dev->data.net = NULL;
            break;

3503 3504 3505
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            hostdev = dev->data.hostdev;

3506 3507 3508 3509 3510 3511
            switch (hostdev->source.subsys.type) {
            case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
#ifndef LIBXL_HAVE_PVUSB
            case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
#endif
            case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
3512
                return -1;
3513
            }
3514 3515

            if (virDomainHostdevFind(vmdef, hostdev, &found) >= 0) {
3516 3517
                virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                               _("device is already in the domain configuration"));
3518 3519 3520
                return -1;
            }

3521 3522
            if (virDomainHostdevInsert(vmdef, hostdev) < 0)
                return -1;
3523
            dev->data.hostdev = NULL;
3524
            break;
3525 3526

        default:
3527 3528
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3529 3530 3531 3532 3533 3534
            return -1;
    }
    return 0;
}

static int
3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567
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 已提交
3568
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3569
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
3570
    virDomainHostdevSubsysPCIPtr pcisrc = &subsys->u.pci;
3571 3572 3573 3574
    libxl_device_pci pcidev;
    virDomainHostdevDefPtr detach;
    int idx;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
J
Jim Fehlig 已提交
3575
    int ret = -1;
3576

3577 3578
    libxl_device_pci_init(&pcidev);

3579 3580 3581 3582
    idx = virDomainHostdevFind(vm->def, hostdev, &detach);
    if (idx < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("host pci device %.4x:%.2x:%.2x.%.1x not found"),
3583 3584
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
J
Jim Fehlig 已提交
3585
        goto cleanup;
3586 3587 3588 3589 3590
    }

    if (libxlIsMultiFunctionDevice(vm->def, detach->info)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %.4x:%.2x:%.2x.%.1x"),
3591 3592
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3593
        goto error;
3594 3595 3596
    }


3597
    if (libxlMakePCI(detach, &pcidev) < 0)
C
Chunyan Liu 已提交
3598
        goto error;
3599

J
Jim Fehlig 已提交
3600
    if (libxl_device_pci_remove(cfg->ctx, vm->def->id, &pcidev, 0) < 0) {
3601 3602 3603
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to detach pci device\
                          %.4x:%.2x:%.2x.%.1x"),
3604 3605
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3606
        goto error;
3607 3608 3609 3610 3611 3612 3613 3614
    }


    virDomainHostdevRemove(vm->def, idx);

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

J
Jim Fehlig 已提交
3615
    ret = 0;
3616

3617
 error:
3618
    virDomainHostdevDefFree(detach);
J
Jim Fehlig 已提交
3619 3620 3621

 cleanup:
    virObjectUnref(cfg);
3622
    libxl_device_pci_dispose(&pcidev);
J
Jim Fehlig 已提交
3623
    return ret;
3624 3625
}

3626
#ifdef LIBXL_HAVE_PVUSB
3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677
static int
libxlDomainDetachControllerDevice(libxlDriverPrivatePtr driver,
                                  virDomainObjPtr vm,
                                  virDomainDeviceDefPtr dev)
{
    int idx, ret = -1;
    virDomainControllerDefPtr detach = NULL;
    virDomainControllerDefPtr controller = dev->data.controller;
    const char *type = virDomainControllerTypeToString(controller->type);
    libxl_device_usbctrl usbctrl;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);

    libxl_device_usbctrl_init(&usbctrl);

    if (controller->type != VIR_DOMAIN_CONTROLLER_TYPE_USB) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("'%s' controller cannot be hot plugged."),
                       type);
        goto cleanup;
    }

    if ((idx = virDomainControllerFind(vm->def,
                                       controller->type,
                                       controller->idx)) < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("controller %s:%d not found"),
                       type, controller->idx);
        goto cleanup;
    }

    detach = vm->def->controllers[idx];

    if (libxlMakeUSBController(controller, &usbctrl) < 0)
        goto cleanup;

    if (libxl_device_usbctrl_remove(cfg->ctx, vm->def->id, &usbctrl, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to detach USB controller"));
        goto cleanup;
    }

    virDomainControllerRemove(vm->def, idx);
    ret = 0;

 cleanup:
    virDomainControllerDefFree(detach);
    virObjectUnref(cfg);
    libxl_device_usbctrl_dispose(&usbctrl);
    return ret;
}

3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746
static int
libxlDomainDetachHostUSBDevice(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
    virDomainHostdevSubsysUSBPtr usbsrc = &subsys->u.usb;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
    libxl_device_usbdev usbdev;
    libxl_device_usbdev *usbdevs = NULL;
    int num = 0;
    virDomainHostdevDefPtr detach;
    int idx;
    size_t i;
    bool found = false;
    int ret = -1;

    libxl_device_usbdev_init(&usbdev);

    idx = virDomainHostdevFind(vm->def, hostdev, &detach);
    if (idx < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("host USB device Busnum: %3x, Devnum: %3x not found"),
                       usbsrc->bus, usbsrc->device);
        goto cleanup;
    }

    usbdevs = libxl_device_usbdev_list(cfg->ctx, vm->def->id, &num);
    for (i = 0; i < num; i++) {
        if (usbdevs[i].u.hostdev.hostbus == usbsrc->bus &&
            usbdevs[i].u.hostdev.hostaddr == usbsrc->device) {
            libxl_device_usbdev_copy(cfg->ctx, &usbdev, &usbdevs[i]);
            found = true;
            break;
        }
    }
    libxl_device_usbdev_list_free(usbdevs, num);

    if (!found) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("host USB device Busnum: %3x, Devnum: %3x not found"),
                       usbsrc->bus, usbsrc->device);
        goto cleanup;
    }

    if (libxl_device_usbdev_remove(cfg->ctx, vm->def->id, &usbdev, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to detach USB device\
                          Busnum: %3x, Devnum: %3x"),
                       usbsrc->bus, usbsrc->device);
        goto cleanup;
    }

    virDomainHostdevRemove(vm->def, idx);

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

    ret = 0;

 cleanup:
    virDomainHostdevDefFree(detach);
    virObjectUnref(cfg);
    libxl_device_usbdev_dispose(&usbdev);
    return ret;
}
#endif

3747 3748 3749
static int
libxlDomainDetachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3750
                            virDomainHostdevDefPtr hostdev)
3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762
{
    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 已提交
3763
            return libxlDomainDetachHostPCIDevice(driver, vm, hostdev);
3764

3765 3766 3767 3768 3769
#ifdef LIBXL_HAVE_PVUSB
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            return libxlDomainDetachHostUSBDevice(driver, vm, hostdev);
#endif

3770 3771 3772 3773 3774 3775 3776 3777 3778
        default:
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected hostdev type %d"), subsys->type);
            break;
    }

    return -1;
}

3779 3780 3781 3782 3783
static int
libxlDomainDetachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3784
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3785 3786 3787 3788 3789 3790
    int detachidx;
    virDomainNetDefPtr detach = NULL;
    libxl_device_nic nic;
    char mac[VIR_MAC_STRING_BUFLEN];
    int ret = -1;

3791 3792
    libxl_device_nic_init(&nic);

3793
    if ((detachidx = virDomainNetFindIdx(vm->def, net)) < 0)
3794
        goto cleanup;
3795 3796 3797 3798 3799 3800 3801

    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 已提交
3802
        ret = libxlDomainDetachHostDevice(driver, vm,
3803
                                          virDomainNetGetActualHostdev(detach));
3804
        goto cleanup;
3805 3806
    }

J
Jim Fehlig 已提交
3807
    if (libxl_mac_to_device_nic(cfg->ctx, vm->def->id,
3808 3809 3810
                                virMacAddrFormat(&detach->mac, mac), &nic))
        goto cleanup;

J
Jim Fehlig 已提交
3811
    if (libxl_device_nic_remove(cfg->ctx, vm->def->id, &nic, 0)) {
3812 3813 3814 3815 3816 3817 3818 3819 3820
        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 已提交
3821 3822 3823 3824
    if (!ret) {
        networkReleaseActualDevice(vm->def, detach);
        virDomainNetRemove(vm->def, detachidx);
    }
J
Jim Fehlig 已提交
3825
    virObjectUnref(cfg);
3826 3827 3828
    return ret;
}

3829 3830 3831
static int
libxlDomainDetachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3832 3833
                            virDomainDeviceDefPtr dev)
{
3834
    virDomainHostdevDefPtr hostdev;
3835 3836 3837 3838
    int ret = -1;

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

3842
#ifdef LIBXL_HAVE_PVUSB
3843 3844 3845
        case VIR_DOMAIN_DEVICE_CONTROLLER:
            ret = libxlDomainDetachControllerDevice(driver, vm, dev);
            break;
3846
#endif
3847

3848
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3849
            ret = libxlDomainDetachNetDevice(driver, vm,
3850 3851 3852
                                             dev->data.net);
            break;

3853
        case VIR_DOMAIN_DEVICE_HOSTDEV:
3854 3855 3856 3857 3858 3859 3860 3861 3862 3863
            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);
3864 3865
            break;

3866
        default:
3867 3868 3869
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3870 3871 3872 3873 3874 3875
            break;
    }

    return ret;
}

3876

3877 3878 3879
static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3880
    virDomainDiskDefPtr disk, detach;
3881
    virDomainHostdevDefPtr hostdev, det_hostdev;
3882
    virDomainControllerDefPtr cont, det_cont;
3883
    virDomainNetDefPtr net;
3884
    int idx;
3885 3886 3887 3888

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3889
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3890 3891
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3892
                return -1;
3893
            }
3894
            virDomainDiskDefFree(detach);
3895
            break;
3896

3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908
        case VIR_DOMAIN_DEVICE_CONTROLLER:
            cont = dev->data.controller;
            if ((idx = virDomainControllerFind(vmdef, cont->type,
                                               cont->idx)) < 0) {
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("device not present in domain configuration"));
                return -1;
            }
            det_cont = virDomainControllerRemove(vmdef, idx);
            virDomainControllerDefFree(det_cont);
            break;

3909 3910 3911 3912 3913 3914 3915 3916 3917
        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;

3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929
        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;
        }

3930
        default:
3931 3932
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3933
            return -1;
3934 3935
    }

3936
    return 0;
3937 3938 3939
}

static int
J
Jim Fehlig 已提交
3940
libxlDomainUpdateDeviceLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3941 3942 3943 3944 3945 3946 3947 3948 3949
{
    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 已提交
3950
                    ret = libxlDomainChangeEjectableMedia(vm, disk);
3951 3952 3953 3954
                    if (ret == 0)
                        dev->data.disk = NULL;
                    break;
                default:
3955 3956 3957
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3958 3959 3960 3961
                    break;
            }
            break;
        default:
3962 3963 3964
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980
            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;
3981
            if (!(orig = virDomainDiskByName(vmdef, disk->dst, false))) {
3982 3983
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3984 3985 3986
                goto cleanup;
            }
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3987 3988
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3989 3990 3991
                goto cleanup;
            }

3992 3993 3994 3995 3996 3997
            if (virDomainDiskSetSource(orig, virDomainDiskGetSource(disk)) < 0)
                goto cleanup;
            virDomainDiskSetType(orig, virDomainDiskGetType(disk));
            virDomainDiskSetFormat(orig, virDomainDiskGetFormat(disk));
            if (virDomainDiskSetDriver(orig, virDomainDiskGetDriver(disk)) < 0)
                goto cleanup;
3998 3999
            break;
        default:
4000 4001
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
4002 4003 4004 4005 4006
            goto cleanup;
    }

    ret = 0;

4007
 cleanup:
4008 4009 4010 4011 4012
    return ret;
}


static int
4013 4014
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
4015 4016
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4017
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4018 4019 4020 4021 4022 4023 4024 4025
    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 已提交
4026
    if (!(vm = libxlDomObjFromDomain(dom)))
4027 4028
        goto cleanup;

4029 4030 4031
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

4035 4036
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto endjob;
4037 4038

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
4039
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
4040
                                            cfg->caps, driver->xmlopt,
4041
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
4042
            goto endjob;
4043 4044

        /* Make a copy for updated domain. */
4045
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
4046
                                                    driver->xmlopt)))
4047
            goto endjob;
4048

4049
        if (libxlDomainAttachDeviceConfig(vmdef, dev) < 0)
4050
            goto endjob;
4051
    }
4052 4053 4054 4055

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

J
Jim Fehlig 已提交
4061
        if (libxlDomainAttachDeviceLive(driver, vm, dev) < 0)
4062
            goto endjob;
4063

4064 4065 4066 4067
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
4068
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
4069
            goto endjob;
4070 4071
    }

4072 4073
    ret = 0;

4074
    /* Finally, if no error until here, we can save config. */
4075
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
4076
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
4077
        if (!ret) {
4078
            virDomainObjAssignDef(vm, vmdef, false, NULL);
4079 4080 4081 4082
            vmdef = NULL;
        }
    }

4083
 endjob:
W
Wang Yufei 已提交
4084
    libxlDomainObjEndJob(driver, vm);
4085

4086
 cleanup:
4087 4088
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
W
Wang Yufei 已提交
4089
    virDomainObjEndAPI(&vm);
4090
    virObjectUnref(cfg);
4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104
    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)
{
4105
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4106
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4107 4108 4109 4110 4111 4112 4113 4114
    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 已提交
4115
    if (!(vm = libxlDomObjFromDomain(dom)))
4116 4117
        goto cleanup;

4118 4119 4120
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4121 4122 4123
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4124 4125
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto endjob;
4126 4127 4128

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
4129
                                            cfg->caps, driver->xmlopt,
4130 4131
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                            VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
4132
            goto endjob;
4133 4134

        /* Make a copy for updated domain. */
4135
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
4136
                                                    driver->xmlopt)))
4137
            goto endjob;
4138

4139
        if (libxlDomainDetachDeviceConfig(vmdef, dev) < 0)
4140
            goto endjob;
4141 4142 4143 4144 4145 4146
    }

    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,
4147
                                            cfg->caps, driver->xmlopt,
4148 4149
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                            VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
4150
            goto endjob;
4151

J
Jim Fehlig 已提交
4152
        if (libxlDomainDetachDeviceLive(driver, vm, dev) < 0)
4153
            goto endjob;
4154 4155 4156 4157 4158

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

4163 4164
    ret = 0;

4165
    /* Finally, if no error until here, we can save config. */
4166
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
4167
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
4168 4169 4170 4171 4172 4173
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

4174
 endjob:
W
Wang Yufei 已提交
4175
    libxlDomainObjEndJob(driver, vm);
4176

4177
 cleanup:
4178 4179
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
W
Wang Yufei 已提交
4180
    virDomainObjEndAPI(&vm);
4181
    virObjectUnref(cfg);
4182
    return ret;
4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195
}

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)
{
4196
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4197
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4198 4199 4200 4201 4202 4203 4204 4205
    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 已提交
4206
    if (!(vm = libxlDomObjFromDomain(dom)))
4207 4208
        goto cleanup;

4209 4210 4211
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4212 4213
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto cleanup;
4214 4215 4216

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
4217
                                            cfg->caps, driver->xmlopt,
4218
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
4219 4220 4221
            goto cleanup;

        /* Make a copy for updated domain. */
4222
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235
                                                    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,
4236
                                            cfg->caps, driver->xmlopt,
4237
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
4238 4239
            goto cleanup;

J
Jim Fehlig 已提交
4240
        if ((ret = libxlDomainUpdateDeviceLive(vm, dev)) < 0)
4241 4242 4243 4244 4245 4246
            goto cleanup;

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
4247
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
4248 4249 4250 4251 4252
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
4253
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
4254 4255 4256 4257 4258 4259
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

4260
 cleanup:
4261 4262 4263 4264
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
4265
    virObjectUnref(cfg);
4266
    return ret;
4267 4268
}

4269 4270 4271 4272 4273
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
4274 4275
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
4276

4277
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
4278
        goto cleanup;
4279

4280
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
4281 4282
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
4283
        goto cleanup;
4284 4285
    }

4286 4287
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

4288
 cleanup:
4289 4290
    virObjectUnref(cfg);
    return ret;
4291 4292
}

4293 4294 4295 4296 4297 4298 4299 4300 4301 4302
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;
4303
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4304 4305

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
4306
        goto cleanup;
4307

4308
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
4309
    if (numa_info == NULL || nr_nodes == 0) {
4310 4311 4312
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
4313 4314 4315
    }

    /* Check/sanitize the cell range */
4316
    if (startCell >= nr_nodes) {
4317 4318
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
4319
                       startCell, nr_nodes - 1);
4320 4321 4322
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
4323 4324
    if (lastCell >= nr_nodes)
        lastCell = nr_nodes - 1;
4325 4326 4327 4328 4329 4330 4331

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

4333 4334
    ret = numCells;

4335
 cleanup:
4336
    libxl_numainfo_list_free(numa_info, nr_nodes);
4337
    virObjectUnref(cfg);
4338 4339 4340
    return ret;
}

4341
static int
4342
libxlConnectDomainEventRegister(virConnectPtr conn,
4343 4344
                                virConnectDomainEventCallback callback,
                                void *opaque,
4345
                                virFreeCallback freecb)
4346 4347 4348
{
    libxlDriverPrivatePtr driver = conn->privateData;

4349 4350 4351
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

4352 4353 4354 4355
    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        return -1;
4356

4357
    return 0;
4358 4359 4360 4361
}


static int
4362 4363
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
4364 4365 4366
{
    libxlDriverPrivatePtr driver = conn->privateData;

4367 4368 4369
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

4370 4371 4372 4373
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
4374

4375
    return 0;
4376 4377
}

4378 4379 4380 4381 4382 4383
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4384
    if (!(vm = libxlDomObjFromDomain(dom)))
4385 4386
        goto cleanup;

4387 4388 4389
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4390 4391 4392
    *autostart = vm->autostart;
    ret = 0;

4393
 cleanup:
4394
    if (vm)
4395
        virObjectUnlock(vm);
4396 4397 4398 4399 4400 4401 4402
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4403
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4404 4405 4406 4407
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
4408
    if (!(vm = libxlDomObjFromDomain(dom)))
4409 4410
        goto cleanup;

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

4413 4414 4415
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4416 4417 4418
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4419
    if (!vm->persistent) {
4420 4421
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
4422
        goto endjob;
4423 4424 4425 4426 4427
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
4428
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
4429
            goto endjob;
4430
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
4431
            goto endjob;
4432 4433

        if (autostart) {
4434
            if (virFileMakePath(cfg->autostartDir) < 0) {
4435
                virReportSystemError(errno,
4436
                                     _("cannot create autostart directory %s"),
4437
                                     cfg->autostartDir);
4438
                goto endjob;
4439 4440 4441 4442 4443 4444
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4445
                goto endjob;
4446 4447 4448 4449 4450 4451
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4452
                goto endjob;
4453 4454 4455 4456 4457 4458 4459
            }
        }

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

4460
 endjob:
W
Wang Yufei 已提交
4461
    libxlDomainObjEndJob(driver, vm);
4462

4463
 cleanup:
4464 4465
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
W
Wang Yufei 已提交
4466
    virDomainObjEndAPI(&vm);
4467
    virObjectUnref(cfg);
4468 4469 4470
    return ret;
}

4471 4472 4473
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
J
Jim Fehlig 已提交
4474 4475
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4476 4477
    virDomainObjPtr vm;
    char * ret = NULL;
4478
    const char *name = NULL;
J
Jim Fehlig 已提交
4479
    libxl_scheduler sched_id;
4480

J
Jim Fehlig 已提交
4481
    if (!(vm = libxlDomObjFromDomain(dom)))
4482 4483
        goto cleanup;

4484 4485 4486
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

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

4494 4495
    if (nparams)
        *nparams = 0;
4496
    switch (sched_id) {
J
Jim Fehlig 已提交
4497
    case LIBXL_SCHEDULER_SEDF:
4498
        name = "sedf";
4499
        break;
J
Jim Fehlig 已提交
4500
    case LIBXL_SCHEDULER_CREDIT:
4501
        name = "credit";
4502 4503
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
4504
        break;
J
Jim Fehlig 已提交
4505
    case LIBXL_SCHEDULER_CREDIT2:
4506
        name = "credit2";
4507
        break;
J
Jim Fehlig 已提交
4508
    case LIBXL_SCHEDULER_ARINC653:
4509
        name = "arinc653";
4510 4511
        break;
    default:
J
Jim Fehlig 已提交
4512 4513
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
4514
                     " with libxenlight"), vm->def->id);
4515 4516 4517
        goto cleanup;
    }

4518
    ignore_value(VIR_STRDUP(ret, name));
4519

4520
 cleanup:
4521
    if (vm)
4522
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4523
    virObjectUnref(cfg);
4524 4525 4526
    return ret;
}

4527
static int
4528 4529 4530 4531
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
4532
{
J
Jim Fehlig 已提交
4533 4534
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4535
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4536 4537
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
4538 4539
    int ret = -1;

4540 4541 4542 4543
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

J
Jim Fehlig 已提交
4545
    if (!(vm = libxlDomObjFromDomain(dom)))
4546 4547
        goto cleanup;

4548 4549 4550
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4551
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
4552 4553
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
4554 4555 4556
        goto cleanup;
    }

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

J
Jim Fehlig 已提交
4559
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4560 4561
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4562 4563 4564
        goto cleanup;
    }

J
Jim Fehlig 已提交
4565
    if (libxl_domain_sched_params_get(cfg->ctx, vm->def->id, &sc_info) != 0) {
4566 4567
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
4568
                         " with libxenlight"), vm->def->id);
4569 4570 4571
        goto cleanup;
    }

4572 4573
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
4574 4575
        goto cleanup;

4576
    if (*nparams > 1) {
4577
        if (virTypedParameterAssign(&params[1], VIR_DOMAIN_SCHEDULER_CAP,
4578
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
4579
            goto cleanup;
4580 4581
    }

4582 4583
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
4584 4585
    ret = 0;

4586
 cleanup:
4587
    if (vm)
4588
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4589
    virObjectUnref(cfg);
4590 4591 4592 4593
    return ret;
}

static int
4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604
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)
4605
{
4606
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
4607
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4608
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4609
    libxl_domain_sched_params sc_info;
4610
    int sched_id;
4611
    size_t i;
4612 4613
    int ret = -1;

4614
    virCheckFlags(0, -1);
4615 4616 4617 4618 4619 4620
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
4621
        return -1;
4622

J
Jim Fehlig 已提交
4623
    if (!(vm = libxlDomObjFromDomain(dom)))
4624 4625
        goto cleanup;

4626 4627 4628
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4629 4630 4631
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4632
    if (!virDomainObjIsActive(vm)) {
4633
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4634
        goto endjob;
4635 4636
    }

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

J
Jim Fehlig 已提交
4639
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4640 4641
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4642
        goto endjob;
4643 4644
    }

J
Jim Fehlig 已提交
4645
    if (libxl_domain_sched_params_get(cfg->ctx, vm->def->id, &sc_info) != 0) {
4646 4647
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
4648
                         " with libxenlight"), vm->def->id);
4649
        goto endjob;
4650 4651 4652
    }

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

4655
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
4656
            sc_info.weight = params[i].value.ui;
4657
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
4658 4659 4660
            sc_info.cap = params[i].value.ui;
    }

J
Jim Fehlig 已提交
4661
    if (libxl_domain_sched_params_set(cfg->ctx, vm->def->id, &sc_info) != 0) {
4662 4663
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
4664
                         " with libxenlight"), vm->def->id);
4665
        goto endjob;
4666 4667 4668 4669
    }

    ret = 0;

4670
 endjob:
W
Wang Yufei 已提交
4671
    libxlDomainObjEndJob(driver, vm);
4672

4673
 cleanup:
W
Wang Yufei 已提交
4674
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
4675
    virObjectUnref(cfg);
4676 4677 4678
    return ret;
}

B
Bamvor Jian Zhang 已提交
4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692

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

J
Jim Fehlig 已提交
4693
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
4694 4695
        goto cleanup;

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

B
Bamvor Jian Zhang 已提交
4698 4699 4700 4701 4702 4703 4704 4705 4706 4707
    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;
B
Bob Liu 已提交
4708 4709
    if (dev_name) {
        size_t i;
B
Bamvor Jian Zhang 已提交
4710

B
Bob Liu 已提交
4711 4712 4713 4714 4715 4716 4717
        for (i = 0; !chr && i < vm->def->nserials; i++) {
            if (STREQ(dev_name, vm->def->serials[i]->info.alias)) {
                chr = vm->def->serials[i];
                break;
            }
        }
    } else if (vm->def->nconsoles) {
I
Ian Campbell 已提交
4718
        chr = vm->def->consoles[0];
4719 4720 4721
        if (chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL)
            chr = vm->def->serials[0];
    }
B
Bamvor Jian Zhang 已提交
4722 4723 4724 4725 4726 4727 4728 4729

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

4730
    if (chr->source->type != VIR_DOMAIN_CHR_TYPE_PTY) {
B
Bamvor Jian Zhang 已提交
4731 4732
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("character device %s is not using a PTY"),
4733
                       dev_name ? dev_name : NULLSTR(chr->info.alias));
B
Bamvor Jian Zhang 已提交
4734 4735 4736 4737 4738
        goto cleanup;
    }

    /* handle mutually exclusive access to console devices */
    ret = virChrdevOpen(priv->devs,
4739
                        chr->source,
B
Bamvor Jian Zhang 已提交
4740 4741 4742 4743 4744 4745 4746 4747 4748
                        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;
    }

4749
 cleanup:
B
Bamvor Jian Zhang 已提交
4750 4751 4752 4753 4754
    if (vm)
        virObjectUnlock(vm);
    return ret;
}

4755 4756 4757 4758 4759 4760 4761
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774
/* 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 已提交
4775 4776
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792
    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;

4793 4794
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
4795
    if (!(vm = libxlDomObjFromDomain(dom)))
4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814
        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];
4815
        int numnodes;
4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833

        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 已提交
4834
            numnodes = libxl_get_max_nodes(cfg->ctx);
4835 4836 4837
            if (numnodes <= 0)
                goto cleanup;

J
Jim Fehlig 已提交
4838
            if (libxl_node_bitmap_alloc(cfg->ctx, &nodemap, 0)) {
4839 4840 4841
                virReportOOMError();
                goto cleanup;
            }
J
Ján Tomko 已提交
4842 4843
            if (!(nodes = virBitmapNew(numnodes)))
                goto cleanup;
4844

J
Jim Fehlig 已提交
4845
            rc = libxl_domain_get_nodeaffinity(cfg->ctx,
4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864
                                               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;
                }
            }

4865
            if (!(nodeset = virBitmapFormat(nodes)))
4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881
                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;

4882
 cleanup:
4883 4884 4885 4886 4887
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
    if (vm)
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4888
    virObjectUnref(cfg);
4889 4890 4891 4892
    return ret;
}
#endif

J
Jim Fehlig 已提交
4893 4894 4895 4896 4897 4898
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4899
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4900
        goto cleanup;
4901 4902 4903 4904

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

J
Jim Fehlig 已提交
4905 4906
    ret = virDomainObjIsActive(obj);

4907
 cleanup:
J
Jim Fehlig 已提交
4908
    if (obj)
4909
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4910 4911 4912 4913 4914 4915 4916 4917 4918
    return ret;
}

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

J
Jim Fehlig 已提交
4919
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4920
        goto cleanup;
4921 4922 4923 4924

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

J
Jim Fehlig 已提交
4925 4926
    ret = obj->persistent;

4927
 cleanup:
J
Jim Fehlig 已提交
4928
    if (obj)
4929
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4930 4931 4932
    return ret;
}

4933 4934 4935 4936 4937 4938
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4939
    if (!(vm = libxlDomObjFromDomain(dom)))
4940
        goto cleanup;
4941 4942 4943 4944

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

4945 4946
    ret = vm->updated;

4947
 cleanup:
4948
    if (vm)
4949
        virObjectUnlock(vm);
4950 4951 4952
    return ret;
}

4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987
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)
4988
        ret = virNetDevTapInterfaceStats(path, stats);
4989 4990 4991 4992 4993
    else
        virReportError(VIR_ERR_INVALID_ARG,
                       _("'%s' is not a known interface"), path);

 endjob:
W
Wang Yufei 已提交
4994
    libxlDomainObjEndJob(driver, vm);
4995 4996

 cleanup:
W
Wang Yufei 已提交
4997
    virDomainObjEndAPI(&vm);
4998 4999 5000
    return ret;
}

5001 5002 5003 5004 5005 5006
static int
libxlDomainGetTotalCPUStats(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
                            virTypedParameterPtr params,
                            unsigned int nparams)
{
J
Jim Fehlig 已提交
5007
    libxlDriverConfigPtr cfg;
5008 5009 5010 5011 5012 5013
    libxl_dominfo d_info;
    int ret = -1;

    if (nparams == 0)
        return LIBXL_NB_TOTAL_CPU_STAT_PARAM;

J
Jim Fehlig 已提交
5014 5015 5016
    libxl_dominfo_init(&d_info);
    cfg = libxlDriverConfigGet(driver);

5017 5018 5019 5020
    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 已提交
5021
        goto cleanup;
5022 5023 5024 5025 5026 5027 5028 5029 5030 5031
    }

    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 已提交
5032
    virObjectUnref(cfg);
5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046
    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 已提交
5047
    libxlDriverConfigPtr cfg;
5048 5049 5050 5051 5052
    int ret = -1;

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

J
Jim Fehlig 已提交
5055
    cfg = libxlDriverConfigGet(driver);
5056 5057 5058 5059 5060
    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 已提交
5061
        goto cleanup;
5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073
    }

    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 已提交
5074 5075 5076
    if (vcpuinfo)
        libxl_vcpuinfo_list_free(vcpuinfo, maxcpu);
    virObjectUnref(cfg);
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 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117
    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;
}

5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131
#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 已提交
5132
    libxlDriverConfigPtr cfg;
5133 5134 5135 5136 5137 5138 5139 5140
    virDomainObjPtr vm;
    libxl_dominfo d_info;
    unsigned mem, maxmem;
    size_t i = 0;
    int ret = -1;

    virCheckFlags(0, -1);

5141
    libxl_dominfo_init(&d_info);
J
Jim Fehlig 已提交
5142 5143
    cfg = libxlDriverConfigGet(driver);

5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173
    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 已提交
5174
    libxlDomainObjEndJob(driver, vm);
5175 5176

 cleanup:
5177
    libxl_dominfo_dispose(&d_info);
W
Wang Yufei 已提交
5178
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
5179
    virObjectUnref(cfg);
5180 5181 5182 5183 5184
    return ret;
}

#undef LIBXL_SET_MEMSTAT

5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221
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;
}

5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272
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;
}
5273

R
Roman Bogorodskiy 已提交
5274
#ifdef __linux__
5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321
static int
libxlDiskPathToID(const char *virtpath)
{
    static char const* drive_prefix[] = {"xvd", "hd", "sd"};
    int disk, partition, chrused;
    int fmt, id;
    size_t i;

    fmt = id = -1;

    /* Find any disk prefixes we know about */
    for (i = 0; i < ARRAY_CARDINALITY(drive_prefix); i++) {
        if (STRPREFIX(virtpath, drive_prefix[i]) &&
            !virDiskNameParse(virtpath, &disk, &partition)) {
            fmt = i;
            break;
        }
    }

    /* Handle it same way as xvd */
    if (fmt < 0 &&
        (sscanf(virtpath, "d%ip%i%n", &disk, &partition, &chrused) >= 2
         && chrused == strlen(virtpath)))
        fmt = 0;

    /* Test indexes ranges and calculate the device id */
    switch (fmt) {
    case 0: /* xvd */
        if (disk <= 15 && partition <= 15)
            id = (202 << 8) | (disk << 4) | partition;
        else if ((disk <= ((1<<20)-1)) || partition <= 255)
            id = (1 << 28) | (disk << 8) | partition;
        break;
    case 1: /* hd */
        if (disk <= 3 && partition <= 63)
            id = ((disk < 2 ? 3 : 22) << 8) | ((disk & 1) << 6) | partition;
        break;
    case 2: /* sd */
        if (disk <= 15 && (partition <= 15))
            id = (8 << 8) | (disk << 4) | partition;
        break;
    default: /* invalid */
        break;
    }
    return id;
}

5322
# define LIBXL_VBD_SECTOR_SIZE 512
5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 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 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 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620

static int
libxlDiskSectorSize(int domid, int devno)
{
    char *path, *val;
    struct xs_handle *handle;
    int ret = LIBXL_VBD_SECTOR_SIZE;
    unsigned int len;

    handle = xs_daemon_open_readonly();
    if (!handle) {
        VIR_WARN("cannot read sector size");
        return ret;
    }

    path = val = NULL;
    if (virAsprintf(&path, "/local/domain/%d/device/vbd/%d/backend",
                    domid, devno) < 0)
        goto cleanup;

    if ((val = xs_read(handle, XBT_NULL, path, &len)) == NULL)
        goto cleanup;

    VIR_FREE(path);
    if (virAsprintf(&path, "%s/physical-sector-size", val) < 0)
        goto cleanup;

    VIR_FREE(val);
    if ((val = xs_read(handle, XBT_NULL, path, &len)) == NULL)
        goto cleanup;

    if (sscanf(val, "%d", &ret) != 1)
        ret = LIBXL_VBD_SECTOR_SIZE;

 cleanup:
    VIR_FREE(val);
    VIR_FREE(path);
    xs_daemon_close(handle);
    return ret;
}

static int
libxlDomainBlockStatsVBD(virDomainObjPtr vm,
                         const char *dev,
                         libxlBlockStatsPtr stats)
{
    int ret = -1;
    int devno = libxlDiskPathToID(dev);
    int size;
    char *path, *name, *val;
    unsigned long long stat;

    path = name = val = NULL;
    if (devno < 0) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot find device number"));
        return ret;
    }

    size = libxlDiskSectorSize(vm->def->id, devno);

    if (VIR_STRDUP(stats->backend, "vbd") < 0)
        return ret;

    if (virAsprintf(&path, "/sys/bus/xen-backend/devices/vbd-%d-%d/statistics",
                    vm->def->id, devno) < 0)
        return ret;

    if (!virFileExists(path)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("cannot open bus path"));
        goto cleanup;
    }

# define LIBXL_SET_VBDSTAT(FIELD, VAR, MUL)           \
    if ((virAsprintf(&name, "%s/"FIELD, path) < 0) || \
        (virFileReadAll(name, 256, &val) < 0) ||      \
        (sscanf(val, "%llu", &stat) != 1)) {          \
        virReportError(VIR_ERR_OPERATION_FAILED,      \
                       _("cannot read %s"), name);    \
        goto cleanup;                                 \
    }                                                 \
    VAR += (stat * MUL);                              \
    VIR_FREE(name);                                   \
    VIR_FREE(val);

    LIBXL_SET_VBDSTAT("f_req",  stats->f_req,  1)
    LIBXL_SET_VBDSTAT("wr_req", stats->wr_req, 1)
    LIBXL_SET_VBDSTAT("rd_req", stats->rd_req, 1)
    LIBXL_SET_VBDSTAT("wr_sect", stats->wr_bytes, size)
    LIBXL_SET_VBDSTAT("rd_sect", stats->rd_bytes, size)

    LIBXL_SET_VBDSTAT("ds_req", stats->u.vbd.ds_req, size)
    LIBXL_SET_VBDSTAT("oo_req", stats->u.vbd.oo_req, 1)
    ret = 0;

 cleanup:
    VIR_FREE(name);
    VIR_FREE(path);
    VIR_FREE(val);

# undef LIBXL_SET_VBDSTAT

    return ret;
}
#else
static int
libxlDomainBlockStatsVBD(virDomainObjPtr vm ATTRIBUTE_UNUSED,
                         const char *dev ATTRIBUTE_UNUSED,
                         libxlBlockStatsPtr stats ATTRIBUTE_UNUSED)
{
    virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                   "%s", _("platform unsupported"));
    return -1;
}
#endif

static int
libxlDomainBlockStatsGatherSingle(virDomainObjPtr vm,
                                  const char *path,
                                  libxlBlockStatsPtr stats)
{
    virDomainDiskDefPtr disk;
    const char *disk_drv;
    int ret = -1, disk_fmt;

    if (!(disk = virDomainDiskByName(vm->def, path, false))) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("invalid path: %s"), path);
        return ret;
    }

    disk_fmt = virDomainDiskGetFormat(disk);
    if (!(disk_drv = virDomainDiskGetDriver(disk)))
        disk_drv = "qemu";

    if (STREQ(disk_drv, "phy")) {
        if (disk_fmt != VIR_STORAGE_FILE_RAW &&
            disk_fmt != VIR_STORAGE_FILE_NONE) {
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                           _("unsupported format %s"),
                           virStorageFileFormatTypeToString(disk_fmt));
            return ret;
        }

        ret = libxlDomainBlockStatsVBD(vm, disk->dst, stats);
    } else {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("unsupported disk driver %s"),
                       disk_drv);
    }
    return ret;
}

static int
libxlDomainBlockStatsGather(virDomainObjPtr vm,
                            const char *path,
                            libxlBlockStatsPtr stats)
{
    int ret = -1;

    if (*path) {
        if (libxlDomainBlockStatsGatherSingle(vm, path, stats) < 0)
            return ret;
    } else {
        size_t i;

        for (i = 0; i < vm->def->ndisks; ++i) {
            if (libxlDomainBlockStatsGatherSingle(vm, vm->def->disks[i]->dst,
                                                  stats) < 0)
                return ret;
        }
    }
    return 0;
}

static int
libxlDomainBlockStats(virDomainPtr dom,
                      const char *path,
                      virDomainBlockStatsPtr stats)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    libxlBlockStats blkstats;
    int ret = -1;

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

    if (virDomainBlockStatsEnsureACL(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;
    }

    memset(&blkstats, 0, sizeof(libxlBlockStats));
    if ((ret = libxlDomainBlockStatsGather(vm, path, &blkstats)) < 0)
        goto endjob;

    stats->rd_req = blkstats.rd_req;
    stats->rd_bytes = blkstats.rd_bytes;
    stats->wr_req = blkstats.wr_req;
    stats->wr_bytes = blkstats.wr_bytes;
    if (STREQ_NULLABLE(blkstats.backend, "vbd"))
        stats->errs = blkstats.u.vbd.oo_req;
    else
        stats->errs = -1;

 endjob:
    libxlDomainObjEndJob(driver, vm);

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

static int
libxlDomainBlockStatsFlags(virDomainPtr dom,
                           const char *path,
                           virTypedParameterPtr params,
                           int *nparams,
                           unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    libxlBlockStats blkstats;
    int nstats;
    int ret = -1;

    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

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

    if (virDomainBlockStatsFlagsEnsureACL(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;
    }

    /* return count of supported stats */
    if (*nparams == 0) {
        *nparams = LIBXL_NB_TOTAL_BLK_STAT_PARAM;
        ret = 0;
        goto endjob;
    }

    memset(&blkstats, 0, sizeof(libxlBlockStats));
    if ((ret = libxlDomainBlockStatsGather(vm, path, &blkstats)) < 0)
        goto endjob;

    nstats = 0;

#define LIBXL_BLKSTAT_ASSIGN_PARAM(VAR, NAME)                              \
    if (nstats < *nparams && (blkstats.VAR) != -1) {                       \
        if (virTypedParameterAssign(params + nstats, NAME,                 \
                                    VIR_TYPED_PARAM_LLONG, (blkstats.VAR)) < 0) \
            goto endjob;                                                   \
        nstats++;                                                          \
    }

    LIBXL_BLKSTAT_ASSIGN_PARAM(wr_bytes, VIR_DOMAIN_BLOCK_STATS_WRITE_BYTES);
    LIBXL_BLKSTAT_ASSIGN_PARAM(wr_req, VIR_DOMAIN_BLOCK_STATS_WRITE_REQ);

    LIBXL_BLKSTAT_ASSIGN_PARAM(rd_bytes, VIR_DOMAIN_BLOCK_STATS_READ_BYTES);
    LIBXL_BLKSTAT_ASSIGN_PARAM(rd_req, VIR_DOMAIN_BLOCK_STATS_READ_REQ);

    LIBXL_BLKSTAT_ASSIGN_PARAM(f_req, VIR_DOMAIN_BLOCK_STATS_FLUSH_REQ);

    if (STREQ_NULLABLE(blkstats.backend, "vbd"))
        LIBXL_BLKSTAT_ASSIGN_PARAM(u.vbd.oo_req, VIR_DOMAIN_BLOCK_STATS_ERRS);

    *nparams = nstats;

#undef LIBXL_BLKSTAT_ASSIGN_PARAM

 endjob:
    libxlDomainObjEndJob(driver, vm);

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

5621
static int
5622 5623 5624
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
5625 5626 5627 5628
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

5629 5630 5631
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

5632 5633 5634 5635
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
5636
        ret = -1;
5637 5638 5639 5640 5641 5642

    return ret;
}


static int
5643
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
5644 5645 5646
{
    libxlDriverPrivatePtr driver = conn->privateData;

5647 5648 5649
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

5650 5651 5652 5653
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        return -1;
5654

5655
    return 0;
5656 5657
}

J
Jim Fehlig 已提交
5658

5659
static int
5660
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
5661 5662 5663 5664
{
    return 1;
}

5665
static int
5666 5667 5668
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
5669 5670 5671 5672
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
5673
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
5674

5675 5676 5677
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

5678 5679
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
5680 5681 5682 5683

    return ret;
}

5684 5685 5686 5687 5688 5689 5690 5691
/* Which features are supported by this driver? */
static int
libxlConnectSupportsFeature(virConnectPtr conn, int feature)
{
    if (virConnectSupportsFeatureEnsureACL(conn) < 0)
        return -1;

    switch (feature) {
5692
    case VIR_DRV_FEATURE_MIGRATION_V3:
5693
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
J
Jim Fehlig 已提交
5694
    case VIR_DRV_FEATURE_MIGRATION_PARAMS:
J
Joao Martins 已提交
5695
    case VIR_DRV_FEATURE_MIGRATION_P2P:
5696 5697 5698 5699 5700
        return 1;
    default:
        return 0;
    }
}
5701

5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712
static int
libxlNodeDeviceGetPCIInfo(virNodeDeviceDefPtr def,
                          unsigned *domain,
                          unsigned *bus,
                          unsigned *slot,
                          unsigned *function)
{
    virNodeDevCapsDefPtr cap;

    cap = def->caps;
    while (cap) {
5713
        if (cap->data.type == VIR_NODE_DEV_CAP_PCI_DEV) {
5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726
            *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 已提交
5727
        return -1;
5728 5729
    }

C
Chunyan Liu 已提交
5730
    return 0;
5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766
}

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")) {
5767
        virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_XEN);
5768 5769 5770 5771 5772 5773 5774 5775 5776 5777
    } else {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported driver name '%s'"), driverName);
        goto cleanup;
    }

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

    ret = 0;
5778
 cleanup:
5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820
    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 已提交
5821
        goto cleanup;
5822 5823

    ret = 0;
C
Chunyan Liu 已提交
5824

5825
 cleanup:
C
Chunyan Liu 已提交
5826
    virPCIDeviceFree(pci);
5827 5828 5829 5830 5831 5832 5833 5834
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
C
Chunyan Liu 已提交
5835
    virPCIDevicePtr pci = NULL;
5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861
    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 已提交
5862
        goto cleanup;
5863 5864

    ret = 0;
C
Chunyan Liu 已提交
5865

5866
 cleanup:
C
Chunyan Liu 已提交
5867
    virPCIDeviceFree(pci);
5868 5869 5870 5871 5872
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

J
Jim Fehlig 已提交
5873 5874 5875 5876
static char *
libxlDomainMigrateBegin3Params(virDomainPtr domain,
                               virTypedParameterPtr params,
                               int nparams,
5877 5878
                               char **cookieout,
                               int *cookieoutlen,
J
Jim Fehlig 已提交
5879 5880 5881 5882 5883
                               unsigned int flags)
{
    const char *xmlin = NULL;
    virDomainObjPtr vm = NULL;

5884 5885 5886 5887 5888
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return NULL;
#endif

J
Jim Fehlig 已提交
5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900
    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 已提交
5901 5902 5903 5904 5905 5906
    if (STREQ_NULLABLE(vm->def->name, "Domain-0")) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Domain-0 cannot be migrated"));
            return NULL;
    }

J
Jim Fehlig 已提交
5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918
    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;
    }

5919 5920
    return libxlDomainMigrationBegin(domain->conn, vm, xmlin,
                                     cookieout, cookieoutlen);
J
Jim Fehlig 已提交
5921 5922 5923 5924 5925 5926
}

static int
libxlDomainMigratePrepare3Params(virConnectPtr dconn,
                                 virTypedParameterPtr params,
                                 int nparams,
5927 5928
                                 const char *cookiein,
                                 int cookieinlen,
J
Jim Fehlig 已提交
5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939
                                 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;

5940 5941 5942 5943 5944
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966
    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;

5967 5968
    if (libxlDomainMigrationPrepare(dconn, &def, uri_in, uri_out,
                                    cookiein, cookieinlen, flags) < 0)
J
Jim Fehlig 已提交
5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995
        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;

5996 5997 5998 5999 6000
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022
    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 已提交
6023 6024 6025 6026 6027 6028 6029 6030 6031
    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 已提交
6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054

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

6057 6058 6059 6060 6061
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return NULL;
#endif

J
Jim Fehlig 已提交
6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081
    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) {
6082
        virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
6083 6084 6085
        return NULL;
    }

6086
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
6087
        virDomainObjEndAPI(&vm);
6088 6089 6090 6091 6092
        return NULL;
    }

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

W
Wang Yufei 已提交
6093
    libxlDomainObjEndJob(driver, vm);
6094

6095
    virDomainObjEndAPI(&vm);
6096 6097

    return ret;
J
Jim Fehlig 已提交
6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111
}

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;

6112 6113 6114 6115 6116
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131
    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);
}

6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148
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;
}
6149

6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288
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;
}


6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361
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;
}


6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381
static int
libxlConnectCompareCPU(virConnectPtr conn,
                       const char *xmlDesc,
                       unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    libxlDriverConfigPtr cfg;
    int ret = VIR_CPU_COMPARE_ERROR;
    bool failIncompatible;

    virCheckFlags(VIR_CONNECT_COMPARE_CPU_FAIL_INCOMPATIBLE,
                  VIR_CPU_COMPARE_ERROR);

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

    failIncompatible = !!(flags & VIR_CONNECT_COMPARE_CPU_FAIL_INCOMPATIBLE);

    cfg = libxlDriverConfigGet(driver);

J
Jiri Denemark 已提交
6382 6383
    ret = virCPUCompareXML(cfg->caps->host.arch, cfg->caps->host.cpu,
                           xmlDesc, failIncompatible);
6384 6385 6386 6387 6388

    virObjectUnref(cfg);
    return ret;
}

6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408
static char *
libxlConnectBaselineCPU(virConnectPtr conn,
                        const char **xmlCPUs,
                        unsigned int ncpus,
                        unsigned int flags)
{
    char *cpu = NULL;

    virCheckFlags(VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES |
                  VIR_CONNECT_BASELINE_CPU_MIGRATABLE, NULL);

    if (virConnectBaselineCPUEnsureACL(conn) < 0)
        goto cleanup;

    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0, flags);

 cleanup:
    return cpu;
}

6409
static virHypervisorDriver libxlHypervisorDriver = {
6410
    .name = LIBXL_DRIVER_NAME,
6411 6412 6413 6414
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
6415
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
6416
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
6417
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
6418
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
6419 6420 6421 6422
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
6423 6424 6425 6426 6427 6428 6429
    .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 */
6430
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
6431 6432
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
6433
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
6434 6435
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
6436
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
6437 6438 6439 6440
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
6441
    .domainSave = libxlDomainSave, /* 0.9.2 */
6442
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
6443
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
6444
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
6445
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
6446 6447 6448 6449
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
6450
    .domainPinVcpuFlags = libxlDomainPinVcpuFlags, /* 1.2.1 */
6451
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
6452
    .domainGetVcpuPinInfo = libxlDomainGetVcpuPinInfo, /* 1.2.1 */
6453
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
6454 6455 6456 6457
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
6458 6459 6460
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
6461
    .domainDefineXMLFlags = libxlDomainDefineXMLFlags, /* 1.2.12 */
6462
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
6463
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
6464 6465 6466 6467 6468
    .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 */
6469 6470 6471 6472
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
6473
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
6474
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
6475
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
6476 6477 6478
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
6479
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
6480
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
6481
    .domainGetJobInfo = libxlDomainGetJobInfo, /* 1.3.1 */
6482
    .domainGetJobStats = libxlDomainGetJobStats, /* 1.3.1 */
P
Pavel Hrdina 已提交
6483 6484
    .domainMemoryStats = libxlDomainMemoryStats, /* 1.3.0 */
    .domainGetCPUStats = libxlDomainGetCPUStats, /* 1.3.0 */
6485
    .domainInterfaceStats = libxlDomainInterfaceStats, /* 1.3.2 */
6486 6487
    .domainBlockStats = libxlDomainBlockStats, /* 2.1.0 */
    .domainBlockStatsFlags = libxlDomainBlockStatsFlags, /* 2.1.0 */
6488 6489
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
6490 6491 6492
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
6493
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
6494 6495 6496
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
6497 6498 6499
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
6500
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
6501 6502 6503 6504
    .nodeDeviceDettach = libxlNodeDeviceDettach, /* 1.2.3 */
    .nodeDeviceDetachFlags = libxlNodeDeviceDetachFlags, /* 1.2.3 */
    .nodeDeviceReAttach = libxlNodeDeviceReAttach, /* 1.2.3 */
    .nodeDeviceReset = libxlNodeDeviceReset, /* 1.2.3 */
6505 6506 6507 6508 6509
    .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 */
6510
    .nodeGetSecurityModel = libxlNodeGetSecurityModel, /* 1.2.16 */
6511
    .domainInterfaceAddresses = libxlDomainInterfaceAddresses, /* 1.3.5 */
6512
    .connectGetDomainCapabilities = libxlConnectGetDomainCapabilities, /* 2.0.0 */
6513
    .connectCompareCPU = libxlConnectCompareCPU, /* 2.3.0 */
6514
    .connectBaselineCPU = libxlConnectBaselineCPU, /* 2.3.0 */
J
Jim Fehlig 已提交
6515 6516
};

6517 6518 6519 6520
static virConnectDriver libxlConnectDriver = {
    .hypervisorDriver = &libxlHypervisorDriver,
};

J
Jim Fehlig 已提交
6521 6522
static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
6523
    .stateInitialize = libxlStateInitialize,
6524
    .stateAutoStart = libxlStateAutoStart,
6525 6526
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
6527 6528 6529 6530 6531 6532
};


int
libxlRegister(void)
{
6533 6534
    if (virRegisterConnectDriver(&libxlConnectDriver,
                                 true) < 0)
J
Jim Fehlig 已提交
6535 6536 6537 6538 6539 6540
        return -1;
    if (virRegisterStateDriver(&libxlStateDriver) < 0)
        return -1;

    return 0;
}