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

#include <config.h>

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

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

#define VIR_FROM_THIS VIR_FROM_LIBXL

64 65
VIR_LOG_INIT("libxl.libxl_driver");

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

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

76 77
#define LIBXL_NB_TOTAL_CPU_STAT_PARAM 1

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

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

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

93

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

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

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

J
Jim Fehlig 已提交
110 111

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

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

    return vm;
}

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

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

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

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

333
    ret = 0;
334 335 336 337 338

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

339
    return ret;
340 341
}

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

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

361 362
    libxl_dominfo_init(&d_info);

J
Jim Fehlig 已提交
363
    /* Does domain still exist? */
J
Jim Fehlig 已提交
364
    rc = libxl_domain_info(cfg->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
365 366 367 368 369 370 371 372 373
    if (rc == ERROR_INVAL) {
        goto out;
    } else if (rc != 0) {
        VIR_DEBUG("libxl_domain_info failed (code %d), ignoring domain %d",
                  rc, vm->def->id);
        goto out;
    }

    /* Is this a domain that was under libvirt control? */
J
Jim Fehlig 已提交
374
    if (libxl_userdata_retrieve(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
375 376 377 378 379 380 381
                                "libvirt-xml", &data, &len)) {
        VIR_DEBUG("libxl_userdata_retrieve failed, ignoring domain %d", vm->def->id);
        goto out;
    }

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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
}

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

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

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

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

491 492 493
    return ret;
}

494 495 496 497 498 499 500 501 502 503
/* 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,
};

504 505 506 507 508 509 510 511
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
};

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

J
Jim Fehlig 已提交
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
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 已提交
558
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
559 560 561
    if (virDomainDefSetVcpusMax(vm->def, d_info.vcpu_max_id + 1))
        goto cleanup;

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

    ret = 0;

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

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

    if (!libxlDriverShouldLoad(privileged))
        return 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    libxlReconnectDomains(libxl_driver);

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

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

J
Jim Fehlig 已提交
724 725
    return 0;

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

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

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

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

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

750 751
    cfg = libxlDriverConfigGet(libxl_driver);

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

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

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


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

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

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

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

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

    return VIR_DRV_OPEN_SUCCESS;
};

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

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

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

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

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

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

848

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

854 855 856
    return virGetHostname();
}

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

    virCheckFlags(0, NULL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return n;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ret = 0;

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

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


static int
libxlDomainResume(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 1172
        goto cleanup;

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

1175 1176 1177
    if (virDomainResumeEnsureACL(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_unpause(cfg->ctx, vm->def->id) != 0) {
1188 1189
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
1190
                           vm->def->id);
1191
            goto endjob;
1192 1193
        }

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

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

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

    ret = 0;

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

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

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

1227 1228 1229 1230 1231
    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;
1232

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

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

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

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

1247
    if (flags & VIR_DOMAIN_SHUTDOWN_PARAVIRT) {
J
Jim Fehlig 已提交
1248
        ret = libxl_domain_shutdown(cfg->ctx, vm->def->id);
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        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 已提交
1263
        ret = libxl_send_trigger(cfg->ctx, vm->def->id,
1264 1265 1266 1267
                                 LIBXL_TRIGGER_POWER, 0);
        if (ret == 0)
            goto cleanup;

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

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

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


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

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

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

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

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

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

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

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

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

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

1342 1343
    virCheckFlags(0, -1);

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

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

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

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

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

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

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

    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

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

    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    isActive = virDomainObjIsActive(vm);

    if (flags == VIR_DOMAIN_MEM_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE;
        else
            flags = VIR_DOMAIN_MEM_CONFIG;
    }
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
        else
            flags = VIR_DOMAIN_MEM_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1476 1477
    }

1478
    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
1479 1480
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set memory on an inactive domain"));
1481
        goto endjob;
1482 1483 1484 1485
    }

    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
1486 1487
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a transient domain"));
1488
            goto endjob;
1489
        }
1490
        if (!(persistentDef = virDomainObjGetPersistentDef(cfg->caps,
1491
                                                           driver->xmlopt,
1492
                                                           vm)))
1493
            goto endjob;
1494 1495
    }

1496 1497
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1498

1499
        if (flags & VIR_DOMAIN_MEM_LIVE) {
J
Jim Fehlig 已提交
1500
            if (libxl_domain_setmaxmem(cfg->ctx, vm->def->id, newmem) < 0) {
1501 1502
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
1503
                                 " with libxenlight"), vm->def->id);
1504
                goto endjob;
1505 1506 1507 1508 1509 1510
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1511
            virDomainDefSetMemoryTotal(persistentDef, newmem);
1512 1513
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
1514
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1515
            goto endjob;
1516 1517
        }

1518 1519
    } else {
        /* resize the current memory */
1520

1521
        if (newmem > virDomainDefGetMemoryActual(vm->def)) {
1522 1523
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1524
            goto endjob;
1525 1526 1527
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
1528 1529 1530 1531
            int res;

            /* Unlock virDomainObj while ballooning memory */
            virObjectUnlock(vm);
J
Jim Fehlig 已提交
1532
            res = libxl_set_memory_target(cfg->ctx, vm->def->id, newmem, 0,
1533 1534 1535
                                          /* force */ 1);
            virObjectLock(vm);
            if (res < 0) {
1536 1537
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
1538
                                 " with libxenlight"), vm->def->id);
1539
                goto endjob;
1540 1541 1542 1543 1544 1545
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1546
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1547
            goto endjob;
1548
        }
1549 1550
    }

1551 1552
    ret = 0;

1553
 endjob:
1554 1555 1556
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1557
 cleanup:
1558
    if (vm)
1559
        virObjectUnlock(vm);
1560
    virObjectUnref(cfg);
1561 1562 1563 1564 1565 1566 1567 1568 1569
    return ret;
}

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

1570 1571 1572 1573 1574 1575
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1576 1577 1578
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
J
Jim Fehlig 已提交
1579 1580
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1581
    virDomainObjPtr vm;
1582
    libxl_dominfo d_info;
J
Jim Fehlig 已提交
1583 1584
    int ret = -1;

J
Jim Fehlig 已提交
1585
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1586 1587
        goto cleanup;

1588 1589 1590
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1591 1592 1593
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1594
        info->maxMem = virDomainDefGetMemoryActual(vm->def);
1595
    } else {
1596 1597
        libxl_dominfo_init(&d_info);

J
Jim Fehlig 已提交
1598
        if (libxl_domain_info(cfg->ctx, &d_info, vm->def->id) != 0) {
1599
            virReportError(VIR_ERR_INTERNAL_ERROR,
1600 1601
                           _("libxl_domain_info failed for domain '%d'"),
                           vm->def->id);
1602 1603 1604 1605
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1606
        info->maxMem = d_info.max_memkb;
1607 1608

        libxl_dominfo_dispose(&d_info);
1609 1610
    }

J
Jiri Denemark 已提交
1611
    info->state = virDomainObjGetState(vm, NULL);
1612
    info->nrVirtCpu = virDomainDefGetVcpus(vm->def);
J
Jim Fehlig 已提交
1613 1614
    ret = 0;

1615
 cleanup:
J
Jim Fehlig 已提交
1616
    if (vm)
1617
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1618
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1619 1620 1621
    return ret;
}

1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

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

1636 1637 1638
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1639
    *state = virDomainObjGetState(vm, reason);
1640 1641
    ret = 0;

1642
 cleanup:
1643
    if (vm)
1644
        virObjectUnlock(vm);
1645 1646 1647
    return ret;
}

1648 1649 1650
/*
 * virDomainObjPtr must be locked on invocation
 */
1651
static int
1652 1653
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1654
{
J
Jim Fehlig 已提交
1655
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1656
    libxlSavefileHeader hdr;
1657
    virObjectEventPtr event = NULL;
1658 1659
    char *xml = NULL;
    uint32_t xml_len;
1660
    int fd = -1;
1661 1662 1663
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1664 1665 1666
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1667 1668 1669 1670
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1671
                            -1, -1, 0)) < 0) {
1672 1673 1674 1675 1676
        virReportSystemError(-fd,
                             _("Failed to create domain save file '%s'"), to);
        goto cleanup;
    }

1677
    if ((xml = virDomainDefFormat(vm->def, cfg->caps, 0)) == NULL)
1678 1679 1680 1681 1682 1683 1684 1685 1686
        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)) {
1687 1688
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1689 1690 1691 1692
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1693 1694
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1695 1696 1697
        goto cleanup;
    }

1698 1699
    /* Unlock virDomainObj while saving domain */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
1700
    ret = libxl_domain_suspend(cfg->ctx, vm->def->id, fd, 0, NULL);
1701 1702 1703
    virObjectLock(vm);

    if (ret != 0) {
1704 1705 1706
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1707
        ret = -1;
1708 1709 1710
        goto cleanup;
    }

1711 1712 1713
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_SAVED);

1714
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1715 1716
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

1717
    if (libxlDomainDestroyInternal(driver, vm) < 0) {
1718 1719
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1720 1721 1722
        goto cleanup;
    }

1723
    libxlDomainCleanup(driver, vm);
1724
    vm->hasManagedSave = true;
1725 1726
    ret = 0;

1727
 cleanup:
1728 1729 1730 1731 1732
    VIR_FREE(xml);
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1733
    virObjectUnref(cfg);
1734 1735 1736 1737
    return ret;
}

static int
1738 1739
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1740
{
1741 1742
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1743
    int ret = -1;
1744
    bool remove_dom = false;
1745

1746 1747 1748 1749 1750
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1751 1752
    virCheckFlags(0, -1);
    if (dxml) {
1753 1754
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1755 1756 1757
        return -1;
    }

J
Jim Fehlig 已提交
1758
    if (!(vm = libxlDomObjFromDomain(dom)))
1759 1760
        goto cleanup;

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

1763 1764 1765
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1766 1767 1768
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1769
    if (!virDomainObjIsActive(vm)) {
1770
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1771
        goto endjob;
1772 1773
    }

1774
    if (libxlDoDomainSave(driver, vm, to) < 0)
1775
        goto endjob;
1776

1777 1778
    if (!vm->persistent)
        remove_dom = true;
1779 1780

    ret = 0;
1781

1782
 endjob:
1783 1784 1785
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1786
 cleanup:
1787 1788 1789 1790
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1791
    if (vm)
1792
        virObjectUnlock(vm);
1793 1794
    return ret;
}
1795

1796
static int
1797 1798 1799 1800 1801 1802 1803 1804
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)
1805 1806
{
    libxlDriverPrivatePtr driver = conn->privateData;
1807
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1808 1809 1810 1811 1812
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1813

1814 1815 1816 1817 1818
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1819
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1820
    if (dxml) {
1821 1822
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1823 1824 1825
        return -1;
    }

1826
    fd = libxlDomainSaveImageOpen(driver, cfg, from, &def, &hdr);
1827
    if (fd < 0)
1828
        goto cleanup;
1829

1830
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1831
        goto cleanup;
1832

1833
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1834
                                   driver->xmlopt,
1835 1836 1837
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1838
        goto cleanup;
1839 1840 1841

    def = NULL;

1842 1843 1844 1845 1846 1847 1848 1849
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
        goto cleanup;
    }

1850
    ret = libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_SAVE_PAUSED) != 0, fd);
1851
    if (ret < 0 && !vm->persistent)
1852
        virDomainObjListRemove(driver->domains, vm);
1853 1854

    if (!libxlDomainObjEndJob(driver, vm))
1855 1856
        vm = NULL;

1857
 cleanup:
1858 1859
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1860 1861
    virDomainDefFree(def);
    if (vm)
1862
        virObjectUnlock(vm);
1863
    virObjectUnref(cfg);
1864 1865 1866
    return ret;
}

1867 1868 1869 1870 1871 1872
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

1873
static int
1874
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1875 1876
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
1877
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1878
    virDomainObjPtr vm;
1879
    virObjectEventPtr event = NULL;
1880
    bool remove_dom = false;
1881 1882 1883 1884 1885
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

J
Jim Fehlig 已提交
1886
    if (!(vm = libxlDomObjFromDomain(dom)))
1887 1888
        goto cleanup;

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

1891 1892 1893
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1894 1895 1896
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1897
    if (!virDomainObjIsActive(vm)) {
1898
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1899
        goto endjob;
1900 1901 1902 1903
    }

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
1904
        if (libxl_domain_pause(cfg->ctx, vm->def->id) != 0) {
1905 1906 1907
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
1908
                           vm->def->id);
1909
            goto endjob;
1910 1911 1912 1913 1914
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

1915 1916
    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
1917
    ret = libxl_domain_core_dump(cfg->ctx, vm->def->id, to, NULL);
1918 1919
    virObjectLock(vm);
    if (ret != 0) {
1920 1921
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
1922
                       vm->def->id);
1923 1924
        ret = -1;
        goto unpause;
1925 1926 1927
    }

    if (flags & VIR_DUMP_CRASH) {
1928
        if (libxlDomainDestroyInternal(driver, vm) < 0) {
1929
            virReportError(VIR_ERR_INTERNAL_ERROR,
1930
                           _("Failed to destroy domain '%d'"), vm->def->id);
1931
            goto unpause;
1932 1933
        }

1934 1935 1936
        libxlDomainCleanup(driver, vm);
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_CRASHED);
1937
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1938
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
1939 1940
        if (!vm->persistent)
            remove_dom = true;
1941 1942 1943 1944
    }

    ret = 0;

1945
 unpause:
1946
    if (virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
1947
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
1948 1949
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
1950
                             " libxenlight"), vm->def->id);
1951 1952 1953 1954 1955
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
1956

1957
 endjob:
1958 1959 1960
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1961
 cleanup:
1962 1963 1964 1965
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1966
    if (vm)
1967
        virObjectUnlock(vm);
1968
    if (event)
1969
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1970
    virObjectUnref(cfg);
1971 1972 1973
    return ret;
}

1974 1975 1976 1977 1978 1979 1980
static int
libxlDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;
1981
    bool remove_dom = false;
1982 1983 1984

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1985
    if (!(vm = libxlDomObjFromDomain(dom)))
1986 1987
        goto cleanup;

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

1990 1991 1992
    if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1993 1994 1995
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1996
    if (!virDomainObjIsActive(vm)) {
1997
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1998
        goto endjob;
1999
    }
2000
    if (!vm->persistent) {
2001 2002
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
2003
        goto endjob;
2004
    }
2005 2006 2007

    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
2008
        goto endjob;
2009 2010 2011

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

2012
    if (libxlDoDomainSave(driver, vm, name) < 0)
2013
        goto endjob;
2014

2015 2016
    if (!vm->persistent)
        remove_dom = true;
2017 2018

    ret = 0;
2019

2020
 endjob:
2021 2022 2023
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2024
 cleanup:
2025 2026 2027 2028
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
2029
    if (vm)
2030
        virObjectUnlock(vm);
2031 2032 2033 2034
    VIR_FREE(name);
    return ret;
}

2035 2036
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
2037 2038 2039 2040
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
2041
    int ret = -1;
2042

2043
    virObjectLock(vm);
2044 2045 2046 2047 2048 2049

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

    vm->hasManagedSave = virFileExists(name);

2050
    ret = 0;
2051
 cleanup:
2052
    virObjectUnlock(vm);
2053
    VIR_FREE(name);
2054
    return ret;
2055 2056
}

2057 2058 2059 2060 2061 2062 2063 2064
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
2065
    if (!(vm = libxlDomObjFromDomain(dom)))
2066 2067
        goto cleanup;

2068 2069 2070
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2071
    ret = vm->hasManagedSave;
2072

2073
 cleanup:
2074
    if (vm)
2075
        virObjectUnlock(vm);
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
    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 已提交
2089
    if (!(vm = libxlDomObjFromDomain(dom)))
2090 2091
        goto cleanup;

2092 2093 2094
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2095 2096 2097 2098 2099
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
2100
    vm->hasManagedSave = false;
2101

2102
 cleanup:
2103 2104
    VIR_FREE(name);
    if (vm)
2105
        virObjectUnlock(vm);
2106 2107 2108
    return ret;
}

2109 2110 2111 2112 2113
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2114
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2115 2116
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
2117
    libxl_bitmap map;
2118 2119
    uint8_t *bitmask = NULL;
    unsigned int maplen;
2120 2121
    size_t i;
    unsigned int pos;
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
    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)) {
2134 2135
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2136 2137 2138 2139
        return -1;
    }

    if (!nvcpus) {
2140
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2141 2142 2143
        return -1;
    }

J
Jim Fehlig 已提交
2144
    if (!(vm = libxlDomObjFromDomain(dom)))
2145 2146
        goto cleanup;

2147 2148 2149
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2150 2151 2152
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2153
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2154 2155
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2156
        goto endjob;
2157 2158 2159
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2160 2161
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2162
        goto endjob;
2163 2164
    }

2165
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2166 2167
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2168
        goto endjob;
2169 2170
    }

2171 2172
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && virDomainDefGetVcpusMax(vm->def) < max)
        max = virDomainDefGetVcpusMax(vm->def);
2173 2174

    if (nvcpus > max) {
2175 2176 2177
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2178
        goto endjob;
2179 2180
    }

2181
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm)))
2182
        goto endjob;
2183

E
Eric Blake 已提交
2184
    maplen = VIR_CPU_MAPLEN(nvcpus);
2185
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
2186
        goto endjob;
2187 2188

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2189
        pos = i / 8;
2190 2191 2192 2193 2194 2195 2196 2197
        bitmask[pos] |= 1 << (i % 8);
    }

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

    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
2198 2199
        if (virDomainDefSetVcpusMax(def, nvcpus) < 0)
            goto cleanup;
2200 2201 2202
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
2203 2204
        if (virDomainDefSetVcpus(def, nvcpus) < 0)
            goto cleanup;
2205 2206 2207
        break;

    case VIR_DOMAIN_VCPU_LIVE:
J
Jim Fehlig 已提交
2208
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2209 2210
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2211
                             " with libxenlight"), vm->def->id);
2212
            goto endjob;
2213
        }
2214 2215
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0)
            goto endjob;
2216 2217 2218
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2219
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2220 2221
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2222
                             " with libxenlight"), vm->def->id);
2223
            goto endjob;
2224
        }
2225 2226 2227
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0 ||
            virDomainDefSetVcpus(def, nvcpus) < 0)
            goto endjob;
2228 2229 2230 2231 2232
        break;
    }

    ret = 0;

2233 2234 2235 2236 2237 2238 2239
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0) {
            VIR_WARN("Unable to save status on vm %s after changing vcpus",
                     vm->def->name);
        }
    }
    if (flags & VIR_DOMAIN_VCPU_CONFIG) {
2240
        if (virDomainSaveConfig(cfg->configDir, cfg->caps, def) < 0) {
2241 2242 2243 2244
            VIR_WARN("Unable to save configuration of vm %s after changing vcpus",
                     vm->def->name);
        }
    }
2245

2246
 endjob:
2247 2248 2249
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2250
 cleanup:
2251 2252
    VIR_FREE(bitmask);
     if (vm)
2253
        virObjectUnlock(vm);
2254
     virObjectUnref(cfg);
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
    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;
2270
    bool active;
2271 2272 2273 2274 2275

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

J
Jim Fehlig 已提交
2276
    if (!(vm = libxlDomObjFromDomain(dom)))
2277 2278
        goto cleanup;

2279
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2280 2281
        goto cleanup;

2282 2283 2284 2285 2286 2287 2288 2289 2290
    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)) {
2291 2292
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2293 2294 2295
        return -1;
    }

2296
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2297
        if (!active) {
2298 2299
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2300 2301 2302 2303
            goto cleanup;
        }
        def = vm->def;
    } else {
2304
        if (!vm->persistent) {
2305 2306
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2307 2308
            goto cleanup;
        }
2309 2310 2311
        def = vm->newDef ? vm->newDef : vm->def;
    }

2312 2313 2314
    if (flags & VIR_DOMAIN_VCPU_MAXIMUM)
        ret = virDomainDefGetVcpusMax(def);
    else
2315
        ret = virDomainDefGetVcpus(def);
2316

2317
 cleanup:
2318
    if (vm)
2319
        virObjectUnlock(vm);
2320 2321 2322 2323
    return ret;
}

static int
2324 2325 2326
libxlDomainPinVcpuFlags(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen,
                        unsigned int flags)
2327 2328
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2329
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2330
    virDomainDefPtr targetDef = NULL;
2331
    virBitmapPtr pcpumap = NULL;
2332 2333
    virDomainObjPtr vm;
    int ret = -1;
2334 2335 2336

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
2337

J
Jim Fehlig 已提交
2338
    if (!(vm = libxlDomObjFromDomain(dom)))
2339 2340
        goto cleanup;

2341
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2342 2343
        goto cleanup;

2344 2345 2346
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2347
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) && !virDomainObjIsActive(vm)) {
2348
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2349
                       _("domain is inactive"));
2350
        goto endjob;
2351 2352
    }

2353 2354
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
2355
        goto endjob;
2356

2357
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2358 2359 2360 2361 2362
        targetDef = vm->def;

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

2363 2364
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
2365
        goto endjob;
2366

2367 2368
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        libxl_bitmap map = { .size = maplen, .map = cpumap };
J
Jim Fehlig 已提交
2369
        if (libxl_set_vcpuaffinity(cfg->ctx, vm->def->id, vcpu, &map) != 0) {
2370 2371 2372
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"),
                           vcpu);
2373
            goto endjob;
2374
        }
2375
    }
2376

2377 2378
    if (!targetDef->cputune.vcpupin) {
        if (VIR_ALLOC(targetDef->cputune.vcpupin) < 0)
2379
            goto endjob;
2380
        targetDef->cputune.nvcpupin = 0;
H
Hu Tao 已提交
2381
    }
2382 2383 2384 2385 2386
    if (virDomainPinAdd(&targetDef->cputune.vcpupin,
                        &targetDef->cputune.nvcpupin,
                        cpumap,
                        maplen,
                        vcpu) < 0) {
2387 2388
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to update or add vcpupin xml"));
2389
        goto endjob;
2390 2391
    }

2392 2393
    ret = 0;

2394 2395 2396
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        ret = virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm);
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2397
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, targetDef);
2398 2399
    }

2400
 endjob:
2401 2402 2403
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2404
 cleanup:
2405
    if (vm)
2406
        virObjectUnlock(vm);
2407
    virBitmapFree(pcpumap);
2408
    virObjectUnref(cfg);
2409 2410 2411
    return ret;
}

2412 2413 2414 2415 2416 2417 2418 2419
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

2420 2421 2422 2423 2424 2425 2426 2427 2428
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;
2429 2430
    int hostcpus, vcpu, ret = -1;
    virBitmapPtr allcpumap = NULL;
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444

    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;

2445
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2446 2447 2448 2449 2450 2451
        targetDef = vm->def;

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

    /* Clamp to actual number of vcpus */
2452 2453
    if (ncpumaps > virDomainDefGetVcpus(targetDef))
        ncpumaps = virDomainDefGetVcpus(targetDef);
2454 2455 2456 2457

    if ((hostcpus = libxl_get_max_cpus(cfg->ctx)) < 0)
        goto cleanup;

2458 2459
    if (!(allcpumap = virBitmapNew(hostcpus)))
        goto cleanup;
2460

2461
    virBitmapSetAll(allcpumap);
2462

2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
    memset(cpumaps, 0x00, maplen * ncpumaps);

    for (vcpu = 0; vcpu < ncpumaps; vcpu++) {
        virDomainPinDefPtr pininfo;
        virBitmapPtr bitmap = NULL;

        pininfo = virDomainPinFind(targetDef->cputune.vcpupin,
                                   targetDef->cputune.nvcpupin,
                                   vcpu);

        if (pininfo && pininfo->cpumask)
            bitmap = pininfo->cpumask;
        else
            bitmap = allcpumap;

        virBitmapToDataBuf(bitmap, VIR_GET_CPUMAP(cpumaps, maplen, vcpu), maplen);
2479
    }
2480

2481 2482
    ret = ncpumaps;

2483
 cleanup:
2484
    virBitmapFree(allcpumap);
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 2605 2606 2607 2608
    if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_XL)) {
        if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
            goto cleanup;
        if (!(def = xenParseXL(conf,
                               cfg->caps,
2609
                               driver->xmlopt)))
2610 2611
            goto cleanup;
    } else if (STREQ(nativeFormat, LIBXL_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 2619 2620 2621 2622
            goto cleanup;
    } else if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_SEXPR)) {
        /* 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,
2666
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE)))
2667 2668
        goto cleanup;

2669
    if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_XL)) {
2670
        if (!(conf = xenFormatXL(def, conn)))
2671 2672
            goto cleanup;
    } else if (STREQ(nativeFormat, LIBXL_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
    ret = libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0, -1);
2754
    if (ret < 0)
2755
        goto endjob;
2756
    dom->id = vm->def->id;
J
Jim Fehlig 已提交
2757

2758 2759 2760 2761
 endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2762
 cleanup:
J
Jim Fehlig 已提交
2763
    if (vm)
2764
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
    return ret;
}

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

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

2786 2787 2788 2789
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

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

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

2795
    if (virDomainDefineXMLFlagsEnsureACL(conn, def) < 0)
2796
        goto cleanup;
2797

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

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

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

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

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

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

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

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

2852 2853
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

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

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

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

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

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

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

2888
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2889 2890
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

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

J
Jim Fehlig 已提交
2898 2899
    ret = 0;

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

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

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

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

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

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

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

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

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

    virDomainDiskDefFree(disk);

    ret = 0;

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

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

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

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

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

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

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

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

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

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

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

3052 3053
    libxl_device_pci_init(&pcidev);

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

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

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

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

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

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

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

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

static int
libxlDomainAttachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3098
                            virDomainHostdevDefPtr hostdev)
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108
{
    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 已提交
3109
        if (libxlDomainAttachHostPCIDevice(driver, vm, hostdev) < 0)
C
Chunyan Liu 已提交
3110
            return -1;
3111 3112 3113 3114 3115 3116
        break;

    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
C
Chunyan Liu 已提交
3117
        return -1;
3118 3119 3120 3121 3122
    }

    return 0;
}

3123
static int
J
Jim Fehlig 已提交
3124
libxlDomainDetachDeviceDiskLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3125
{
J
Jim Fehlig 已提交
3126
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
3127 3128
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
3129
    int idx;
3130 3131 3132 3133 3134 3135
    int ret = -1;

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

3136 3137 3138
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
3139 3140
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3141 3142 3143
                    goto cleanup;
                }

3144
                l_disk = vm->def->disks[idx];
3145

J
Jim Fehlig 已提交
3146
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3147 3148
                    goto cleanup;

J
Jim Fehlig 已提交
3149
                if ((ret = libxl_device_disk_remove(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
3150
                                                    &x_disk, NULL)) < 0) {
3151 3152 3153
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3154 3155 3156
                    goto cleanup;
                }

3157 3158 3159 3160 3161
                if (virDomainLockDiskDetach(libxl_driver->lockManager,
                                            vm, l_disk) < 0)
                    VIR_WARN("Unable to release lock on %s",
                             virDomainDiskGetSource(l_disk));

3162
                virDomainDiskRemove(vm->def, idx);
3163 3164 3165
                virDomainDiskDefFree(l_disk);

            } else {
3166 3167 3168
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3169 3170 3171
            }
            break;
        default:
3172 3173 3174
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3175 3176 3177
            break;
    }

3178
 cleanup:
J
Jim Fehlig 已提交
3179
    virObjectUnref(cfg);
3180 3181 3182
    return ret;
}

3183 3184 3185 3186 3187
static int
libxlDomainAttachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3188
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3189 3190 3191
    int actualType;
    libxl_device_nic nic;
    int ret = -1;
3192
    char mac[VIR_MAC_STRING_BUFLEN];
3193 3194 3195

    /* preallocate new slot for device */
    if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets + 1) < 0)
J
Jim Fehlig 已提交
3196
        goto out;
3197 3198 3199 3200 3201 3202

    /* 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)
J
Jim Fehlig 已提交
3203
        goto out;
3204 3205 3206

    actualType = virDomainNetGetActualType(net);

3207 3208 3209 3210 3211 3212 3213
    if (virDomainHasNet(vm->def, net)) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("network device with mac %s already exists"),
                       virMacAddrFormat(&net->mac, mac));
        return -1;
    }

3214 3215 3216 3217 3218 3219
    if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
        /* 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
         * the nets list (see out:) if successful.
         */
J
Jim Fehlig 已提交
3220
        ret = libxlDomainAttachHostDevice(driver, vm,
3221 3222 3223 3224 3225 3226 3227 3228
                                          virDomainNetGetActualHostdev(net));
        goto out;
    }

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

J
Jim Fehlig 已提交
3229
    if (libxl_device_nic_add(cfg->ctx, vm->def->id, &nic, 0)) {
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to attach network device"));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    libxl_device_nic_dispose(&nic);
 out:
    if (!ret)
        vm->def->nets[vm->def->nnets++] = net;
J
Jim Fehlig 已提交
3242
    virObjectUnref(cfg);
3243 3244 3245
    return ret;
}

3246
static int
3247 3248
libxlDomainAttachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3249 3250 3251 3252 3253 3254
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
J
Jim Fehlig 已提交
3255
            ret = libxlDomainAttachDeviceDiskLive(vm, dev);
3256 3257 3258 3259
            if (!ret)
                dev->data.disk = NULL;
            break;

3260
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3261
            ret = libxlDomainAttachNetDevice(driver, vm,
3262 3263 3264 3265 3266
                                             dev->data.net);
            if (!ret)
                dev->data.net = NULL;
            break;

3267
        case VIR_DOMAIN_DEVICE_HOSTDEV:
J
Jim Fehlig 已提交
3268
            ret = libxlDomainAttachHostDevice(driver, vm,
3269
                                              dev->data.hostdev);
3270 3271 3272 3273
            if (!ret)
                dev->data.hostdev = NULL;
            break;

3274
        default:
3275 3276 3277
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3278 3279 3280 3281 3282 3283 3284 3285 3286 3287
            break;
    }

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
3288
    virDomainNetDefPtr net;
3289 3290
    virDomainHostdevDefPtr hostdev;
    virDomainHostdevDefPtr found;
3291
    virDomainHostdevSubsysPCIPtr pcisrc;
3292
    char mac[VIR_MAC_STRING_BUFLEN];
3293 3294 3295 3296

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3297
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3298 3299
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3300 3301
                return -1;
            }
3302
            if (virDomainDiskInsert(vmdef, disk))
3303 3304 3305 3306
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;
3307 3308 3309

        case VIR_DOMAIN_DEVICE_NET:
            net = dev->data.net;
3310 3311 3312 3313 3314 3315
            if (virDomainHasNet(vmdef, net)) {
                virReportError(VIR_ERR_INVALID_ARG,
                               _("network device with mac %s already exists"),
                               virMacAddrFormat(&net->mac, mac));
                return -1;
            }
3316 3317 3318 3319 3320
            if (virDomainNetInsert(vmdef, net))
                return -1;
            dev->data.net = NULL;
            break;

3321 3322 3323 3324 3325 3326 3327
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            hostdev = dev->data.hostdev;

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

            if (virDomainHostdevFind(vmdef, hostdev, &found) >= 0) {
3328
                pcisrc = &hostdev->source.subsys.u.pci;
3329 3330 3331
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("target pci device %.4x:%.2x:%.2x.%.1x\
                                  already exists"),
3332 3333
                               pcisrc->addr.domain, pcisrc->addr.bus,
                               pcisrc->addr.slot, pcisrc->addr.function);
3334 3335 3336
                return -1;
            }

3337 3338
            if (virDomainHostdevInsert(vmdef, hostdev) < 0)
                return -1;
3339
            dev->data.hostdev = NULL;
3340
            break;
3341 3342

        default:
3343 3344
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3345 3346 3347 3348 3349 3350
            return -1;
    }
    return 0;
}

static int
3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
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 已提交
3384
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3385
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
3386
    virDomainHostdevSubsysPCIPtr pcisrc = &subsys->u.pci;
3387 3388 3389 3390
    libxl_device_pci pcidev;
    virDomainHostdevDefPtr detach;
    int idx;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
J
Jim Fehlig 已提交
3391
    int ret = -1;
3392

3393 3394
    libxl_device_pci_init(&pcidev);

3395 3396 3397 3398
    idx = virDomainHostdevFind(vm->def, hostdev, &detach);
    if (idx < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("host pci device %.4x:%.2x:%.2x.%.1x not found"),
3399 3400
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
J
Jim Fehlig 已提交
3401
        goto cleanup;
3402 3403 3404 3405 3406
    }

    if (libxlIsMultiFunctionDevice(vm->def, detach->info)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %.4x:%.2x:%.2x.%.1x"),
3407 3408
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3409
        goto error;
3410 3411 3412
    }


3413
    if (libxlMakePCI(detach, &pcidev) < 0)
C
Chunyan Liu 已提交
3414
        goto error;
3415

J
Jim Fehlig 已提交
3416
    if (libxl_device_pci_remove(cfg->ctx, vm->def->id, &pcidev, 0) < 0) {
3417 3418 3419
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to detach pci device\
                          %.4x:%.2x:%.2x.%.1x"),
3420 3421
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3422
        goto error;
3423 3424 3425 3426 3427 3428 3429 3430
    }


    virDomainHostdevRemove(vm->def, idx);

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

J
Jim Fehlig 已提交
3431
    ret = 0;
3432

3433
 error:
3434
    virDomainHostdevDefFree(detach);
J
Jim Fehlig 已提交
3435 3436 3437

 cleanup:
    virObjectUnref(cfg);
3438
    libxl_device_pci_dispose(&pcidev);
J
Jim Fehlig 已提交
3439
    return ret;
3440 3441 3442 3443 3444
}

static int
libxlDomainDetachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3445
                            virDomainHostdevDefPtr hostdev)
3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457
{
    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 已提交
3458
            return libxlDomainDetachHostPCIDevice(driver, vm, hostdev);
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468

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

    return -1;
}

3469 3470 3471 3472 3473
static int
libxlDomainDetachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3474
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3475 3476 3477 3478 3479 3480 3481
    int detachidx;
    virDomainNetDefPtr detach = NULL;
    libxl_device_nic nic;
    char mac[VIR_MAC_STRING_BUFLEN];
    int ret = -1;

    if ((detachidx = virDomainNetFindIdx(vm->def, net)) < 0)
J
Jim Fehlig 已提交
3482
        goto out;
3483 3484 3485 3486 3487 3488 3489

    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 已提交
3490
        ret = libxlDomainDetachHostDevice(driver, vm,
3491 3492 3493 3494 3495
                                          virDomainNetGetActualHostdev(detach));
        goto out;
    }

    libxl_device_nic_init(&nic);
J
Jim Fehlig 已提交
3496
    if (libxl_mac_to_device_nic(cfg->ctx, vm->def->id,
3497 3498 3499
                                virMacAddrFormat(&detach->mac, mac), &nic))
        goto cleanup;

J
Jim Fehlig 已提交
3500
    if (libxl_device_nic_remove(cfg->ctx, vm->def->id, &nic, 0)) {
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to detach network device"));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    libxl_device_nic_dispose(&nic);
 out:
    if (!ret)
        virDomainNetRemove(vm->def, detachidx);
J
Jim Fehlig 已提交
3513
    virObjectUnref(cfg);
3514 3515 3516
    return ret;
}

3517 3518 3519
static int
libxlDomainDetachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3520 3521 3522 3523 3524 3525
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

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

3529
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3530
            ret = libxlDomainDetachNetDevice(driver, vm,
3531 3532 3533
                                             dev->data.net);
            break;

3534
        case VIR_DOMAIN_DEVICE_HOSTDEV:
J
Jim Fehlig 已提交
3535
            ret = libxlDomainDetachHostDevice(driver, vm,
3536
                                              dev->data.hostdev);
3537 3538
            break;

3539
        default:
3540 3541 3542
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3543 3544 3545 3546 3547 3548
            break;
    }

    return ret;
}

3549

3550 3551 3552
static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3553
    virDomainDiskDefPtr disk, detach;
3554
    virDomainHostdevDefPtr hostdev, det_hostdev;
3555
    virDomainNetDefPtr net;
3556
    int idx;
3557 3558 3559 3560

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3561
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3562 3563
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3564
                return -1;
3565
            }
3566
            virDomainDiskDefFree(detach);
3567
            break;
3568

3569 3570 3571 3572 3573 3574 3575 3576 3577
        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;

3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
        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;
        }

3590
        default:
3591 3592
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3593
            return -1;
3594 3595
    }

3596
    return 0;
3597 3598 3599
}

static int
J
Jim Fehlig 已提交
3600
libxlDomainUpdateDeviceLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3601 3602 3603 3604 3605 3606 3607 3608 3609
{
    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 已提交
3610
                    ret = libxlDomainChangeEjectableMedia(vm, disk);
3611 3612 3613 3614
                    if (ret == 0)
                        dev->data.disk = NULL;
                    break;
                default:
3615 3616 3617
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3618 3619 3620 3621
                    break;
            }
            break;
        default:
3622 3623 3624
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
            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;
3641
            if (!(orig = virDomainDiskByName(vmdef, disk->dst, false))) {
3642 3643
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3644 3645 3646
                goto cleanup;
            }
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3647 3648
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3649 3650 3651
                goto cleanup;
            }

3652 3653 3654 3655 3656 3657
            if (virDomainDiskSetSource(orig, virDomainDiskGetSource(disk)) < 0)
                goto cleanup;
            virDomainDiskSetType(orig, virDomainDiskGetType(disk));
            virDomainDiskSetFormat(orig, virDomainDiskGetFormat(disk));
            if (virDomainDiskSetDriver(orig, virDomainDiskGetDriver(disk)) < 0)
                goto cleanup;
3658 3659
            break;
        default:
3660 3661
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3662 3663 3664 3665 3666
            goto cleanup;
    }

    ret = 0;

3667
 cleanup:
3668 3669 3670 3671 3672
    return ret;
}


static int
3673 3674
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3675 3676
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3677
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3678 3679 3680 3681 3682 3683 3684 3685
    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 已提交
3686
    if (!(vm = libxlDomObjFromDomain(dom)))
3687 3688
        goto cleanup;

3689 3690 3691
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3692 3693 3694
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

3695 3696 3697 3698 3699 3700 3701 3702
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
3703 3704
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3705
            goto endjob;
3706 3707 3708 3709
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
3710 3711
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3712
         goto endjob;
3713 3714 3715
    }

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3716
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3717
                                            cfg->caps, driver->xmlopt,
3718
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3719
            goto endjob;
3720 3721

        /* Make a copy for updated domain. */
3722
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3723
                                                    driver->xmlopt)))
3724
            goto endjob;
3725

3726
        if (libxlDomainAttachDeviceConfig(vmdef, dev) < 0)
3727
            goto endjob;
3728
    }
3729 3730 3731 3732

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

J
Jim Fehlig 已提交
3738
        if (libxlDomainAttachDeviceLive(driver, vm, dev) < 0)
3739
            goto endjob;
3740

3741 3742 3743 3744
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3745
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3746
            goto endjob;
3747 3748
    }

3749 3750
    ret = 0;

3751
    /* Finally, if no error until here, we can save config. */
3752
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3753
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
3754
        if (!ret) {
3755
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3756 3757 3758 3759
            vmdef = NULL;
        }
    }

3760
 endjob:
3761 3762 3763
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3764
 cleanup:
3765 3766 3767
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3768
        virObjectUnlock(vm);
3769
    virObjectUnref(cfg);
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783
    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)
{
3784
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3785
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3786 3787 3788 3789 3790 3791 3792 3793
    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 已提交
3794
    if (!(vm = libxlDomObjFromDomain(dom)))
3795 3796
        goto cleanup;

3797 3798 3799
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3800 3801 3802
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

3803 3804 3805 3806 3807 3808 3809 3810 3811 3812
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3813
            goto endjob;
3814 3815 3816 3817 3818 3819
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3820
         goto endjob;
3821 3822 3823 3824
    }

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3825
                                            cfg->caps, driver->xmlopt,
3826
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3827
            goto endjob;
3828 3829

        /* Make a copy for updated domain. */
3830
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3831
                                                    driver->xmlopt)))
3832
            goto endjob;
3833

3834
        if (libxlDomainDetachDeviceConfig(vmdef, dev) < 0)
3835
            goto endjob;
3836 3837 3838 3839 3840 3841
    }

    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,
3842
                                            cfg->caps, driver->xmlopt,
3843
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3844
            goto endjob;
3845

J
Jim Fehlig 已提交
3846
        if (libxlDomainDetachDeviceLive(driver, vm, dev) < 0)
3847
            goto endjob;
3848 3849 3850 3851 3852

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3853
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3854
            goto endjob;
3855 3856
    }

3857 3858
    ret = 0;

3859
    /* Finally, if no error until here, we can save config. */
3860
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3861
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
3862 3863 3864 3865 3866 3867
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3868
 endjob:
3869 3870 3871
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3872
 cleanup:
3873 3874 3875 3876
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3877
    virObjectUnref(cfg);
3878
    return ret;
3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
}

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)
{
3892
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3893
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3894 3895 3896 3897 3898 3899 3900 3901
    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 已提交
3902
    if (!(vm = libxlDomObjFromDomain(dom)))
3903 3904
        goto cleanup;

3905 3906 3907
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
            goto cleanup;
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
         goto cleanup;
    }

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3930
                                            cfg->caps, driver->xmlopt,
3931
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3932 3933 3934
            goto cleanup;

        /* Make a copy for updated domain. */
3935
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948
                                                    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,
3949
                                            cfg->caps, driver->xmlopt,
3950
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
3951 3952
            goto cleanup;

J
Jim Fehlig 已提交
3953
        if ((ret = libxlDomainUpdateDeviceLive(vm, dev)) < 0)
3954 3955 3956 3957 3958 3959
            goto cleanup;

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3960
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3961 3962 3963 3964 3965
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3966
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
3967 3968 3969 3970 3971 3972
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3973
 cleanup:
3974 3975 3976 3977
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3978
    virObjectUnref(cfg);
3979
    return ret;
3980 3981
}

3982 3983 3984 3985 3986
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
3987 3988
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
3989

3990
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
3991
        goto cleanup;
3992

3993
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
3994 3995
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3996
        goto cleanup;
3997 3998
    }

3999 4000
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

4001
 cleanup:
4002 4003
    virObjectUnref(cfg);
    return ret;
4004 4005
}

4006 4007 4008 4009 4010 4011 4012 4013 4014 4015
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;
4016
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4017 4018

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
4019
        goto cleanup;
4020

4021
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
4022
    if (numa_info == NULL || nr_nodes == 0) {
4023 4024 4025
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
4026 4027 4028
    }

    /* Check/sanitize the cell range */
4029
    if (startCell >= nr_nodes) {
4030 4031
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
4032
                       startCell, nr_nodes - 1);
4033 4034 4035
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
4036 4037
    if (lastCell >= nr_nodes)
        lastCell = nr_nodes - 1;
4038 4039 4040 4041 4042 4043 4044

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

4046 4047
    ret = numCells;

4048
 cleanup:
4049
    libxl_numainfo_list_free(numa_info, nr_nodes);
4050
    virObjectUnref(cfg);
4051 4052 4053
    return ret;
}

4054
static int
4055
libxlConnectDomainEventRegister(virConnectPtr conn,
4056 4057
                                virConnectDomainEventCallback callback,
                                void *opaque,
4058
                                virFreeCallback freecb)
4059 4060 4061
{
    libxlDriverPrivatePtr driver = conn->privateData;

4062 4063 4064
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

4065 4066 4067 4068
    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        return -1;
4069

4070
    return 0;
4071 4072 4073 4074
}


static int
4075 4076
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
4077 4078 4079
{
    libxlDriverPrivatePtr driver = conn->privateData;

4080 4081 4082
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

4083 4084 4085 4086
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
4087

4088
    return 0;
4089 4090
}

4091 4092 4093 4094 4095 4096
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

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

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

4103 4104 4105
    *autostart = vm->autostart;
    ret = 0;

4106
 cleanup:
4107
    if (vm)
4108
        virObjectUnlock(vm);
4109 4110 4111 4112 4113 4114 4115
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4116
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4117 4118 4119 4120
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
4121
    if (!(vm = libxlDomObjFromDomain(dom)))
4122 4123
        goto cleanup;

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

4126 4127 4128
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4129 4130 4131
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4132
    if (!vm->persistent) {
4133 4134
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
4135
        goto endjob;
4136 4137 4138 4139 4140
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
4141
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
4142
            goto endjob;
4143
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
4144
            goto endjob;
4145 4146

        if (autostart) {
4147
            if (virFileMakePath(cfg->autostartDir) < 0) {
4148
                virReportSystemError(errno,
4149
                                     _("cannot create autostart directory %s"),
4150
                                     cfg->autostartDir);
4151
                goto endjob;
4152 4153 4154 4155 4156 4157
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4158
                goto endjob;
4159 4160 4161 4162 4163 4164
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4165
                goto endjob;
4166 4167 4168 4169 4170 4171 4172
            }
        }

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

4173
 endjob:
4174 4175 4176
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

4177
 cleanup:
4178 4179 4180
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    if (vm)
4181
        virObjectUnlock(vm);
4182
    virObjectUnref(cfg);
4183 4184 4185
    return ret;
}

4186 4187 4188
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
J
Jim Fehlig 已提交
4189 4190
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4191 4192
    virDomainObjPtr vm;
    char * ret = NULL;
4193
    const char *name = NULL;
J
Jim Fehlig 已提交
4194
    libxl_scheduler sched_id;
4195

J
Jim Fehlig 已提交
4196
    if (!(vm = libxlDomObjFromDomain(dom)))
4197 4198
        goto cleanup;

4199 4200 4201
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

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

4209 4210
    if (nparams)
        *nparams = 0;
4211
    switch (sched_id) {
J
Jim Fehlig 已提交
4212
    case LIBXL_SCHEDULER_SEDF:
4213
        name = "sedf";
4214
        break;
J
Jim Fehlig 已提交
4215
    case LIBXL_SCHEDULER_CREDIT:
4216
        name = "credit";
4217 4218
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
4219
        break;
J
Jim Fehlig 已提交
4220
    case LIBXL_SCHEDULER_CREDIT2:
4221
        name = "credit2";
4222
        break;
J
Jim Fehlig 已提交
4223
    case LIBXL_SCHEDULER_ARINC653:
4224
        name = "arinc653";
4225 4226
        break;
    default:
J
Jim Fehlig 已提交
4227 4228
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
4229
                     " with libxenlight"), vm->def->id);
4230 4231 4232
        goto cleanup;
    }

4233
    ignore_value(VIR_STRDUP(ret, name));
4234

4235
 cleanup:
4236
    if (vm)
4237
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4238
    virObjectUnref(cfg);
4239 4240 4241
    return ret;
}

4242
static int
4243 4244 4245 4246
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
4247
{
J
Jim Fehlig 已提交
4248 4249
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4250
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4251 4252
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
4253 4254
    int ret = -1;

4255 4256 4257 4258
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

J
Jim Fehlig 已提交
4260
    if (!(vm = libxlDomObjFromDomain(dom)))
4261 4262
        goto cleanup;

4263 4264 4265
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4266
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
4267 4268
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
4269 4270 4271
        goto cleanup;
    }

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

J
Jim Fehlig 已提交
4274
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4275 4276
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4277 4278 4279
        goto cleanup;
    }

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

4287 4288
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
4289 4290
        goto cleanup;

4291
    if (*nparams > 1) {
4292 4293
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
4294
            goto cleanup;
4295 4296
    }

4297 4298
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
4299 4300
    ret = 0;

4301
 cleanup:
4302
    if (vm)
4303
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4304
    virObjectUnref(cfg);
4305 4306 4307 4308
    return ret;
}

static int
4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319
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)
4320
{
4321
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
4322
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4323
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4324
    libxl_domain_sched_params sc_info;
4325
    int sched_id;
4326
    size_t i;
4327 4328
    int ret = -1;

4329
    virCheckFlags(0, -1);
4330 4331 4332 4333 4334 4335
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
4336
        return -1;
4337

J
Jim Fehlig 已提交
4338
    if (!(vm = libxlDomObjFromDomain(dom)))
4339 4340
        goto cleanup;

4341 4342 4343
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4344 4345 4346
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4347
    if (!virDomainObjIsActive(vm)) {
4348
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4349
        goto endjob;
4350 4351
    }

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

J
Jim Fehlig 已提交
4354
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4355 4356
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4357
        goto endjob;
4358 4359
    }

J
Jim Fehlig 已提交
4360
    if (libxl_domain_sched_params_get(cfg->ctx, vm->def->id, &sc_info) != 0) {
4361 4362
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
4363
                         " with libxenlight"), vm->def->id);
4364
        goto endjob;
4365 4366 4367
    }

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

4370
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
4371
            sc_info.weight = params[i].value.ui;
4372
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
4373 4374 4375
            sc_info.cap = params[i].value.ui;
    }

J
Jim Fehlig 已提交
4376
    if (libxl_domain_sched_params_set(cfg->ctx, vm->def->id, &sc_info) != 0) {
4377 4378
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
4379
                         " with libxenlight"), vm->def->id);
4380
        goto endjob;
4381 4382 4383 4384
    }

    ret = 0;

4385
 endjob:
4386 4387 4388
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

4389
 cleanup:
4390
    if (vm)
4391
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4392
    virObjectUnref(cfg);
4393 4394 4395
    return ret;
}

B
Bamvor Jian Zhang 已提交
4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416

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

    virCheckFlags(VIR_DOMAIN_CONSOLE_FORCE, -1);

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

J
Jim Fehlig 已提交
4417
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
4418 4419
        goto cleanup;

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

B
Bamvor Jian Zhang 已提交
4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432
    if (virDomainOpenConsoleEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

    priv = vm->privateData;

I
Ian Campbell 已提交
4433 4434
    if (vm->def->nconsoles)
        chr = vm->def->consoles[0];
B
Bamvor Jian Zhang 已提交
4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445

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

    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("character device %s is not using a PTY"),
4446
                       dev_name ? dev_name : NULLSTR(chr->info.alias));
B
Bamvor Jian Zhang 已提交
4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461
        goto cleanup;
    }

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

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

4462
 cleanup:
B
Bamvor Jian Zhang 已提交
4463 4464 4465 4466 4467
    if (vm)
        virObjectUnlock(vm);
    return ret;
}

4468 4469 4470 4471 4472 4473 4474
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487
/* 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 已提交
4488 4489
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505
    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;

4506 4507
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
4508
    if (!(vm = libxlDomObjFromDomain(dom)))
4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527
        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];
4528
        int numnodes;
4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546

        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 已提交
4547
            numnodes = libxl_get_max_nodes(cfg->ctx);
4548 4549 4550
            if (numnodes <= 0)
                goto cleanup;

J
Jim Fehlig 已提交
4551
            if (libxl_node_bitmap_alloc(cfg->ctx, &nodemap, 0)) {
4552 4553 4554
                virReportOOMError();
                goto cleanup;
            }
J
Ján Tomko 已提交
4555 4556
            if (!(nodes = virBitmapNew(numnodes)))
                goto cleanup;
4557

J
Jim Fehlig 已提交
4558
            rc = libxl_domain_get_nodeaffinity(cfg->ctx,
4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577
                                               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;
                }
            }

4578
            if (!(nodeset = virBitmapFormat(nodes)))
4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594
                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;

4595
 cleanup:
4596 4597 4598 4599 4600
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
    if (vm)
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4601
    virObjectUnref(cfg);
4602 4603 4604 4605
    return ret;
}
#endif

J
Jim Fehlig 已提交
4606 4607 4608 4609 4610 4611
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4612
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4613
        goto cleanup;
4614 4615 4616 4617

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

J
Jim Fehlig 已提交
4618 4619
    ret = virDomainObjIsActive(obj);

4620
 cleanup:
J
Jim Fehlig 已提交
4621
    if (obj)
4622
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4623 4624 4625 4626 4627 4628 4629 4630 4631
    return ret;
}

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

J
Jim Fehlig 已提交
4632
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4633
        goto cleanup;
4634 4635 4636 4637

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

J
Jim Fehlig 已提交
4638 4639
    ret = obj->persistent;

4640
 cleanup:
J
Jim Fehlig 已提交
4641
    if (obj)
4642
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4643 4644 4645
    return ret;
}

4646 4647 4648 4649 4650 4651
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4652
    if (!(vm = libxlDomObjFromDomain(dom)))
4653
        goto cleanup;
4654 4655 4656 4657

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

4658 4659
    ret = vm->updated;

4660
 cleanup:
4661
    if (vm)
4662
        virObjectUnlock(vm);
4663 4664 4665
    return ret;
}

4666 4667 4668 4669 4670 4671
static int
libxlDomainGetTotalCPUStats(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
                            virTypedParameterPtr params,
                            unsigned int nparams)
{
J
Jim Fehlig 已提交
4672
    libxlDriverConfigPtr cfg;
4673 4674 4675 4676 4677 4678
    libxl_dominfo d_info;
    int ret = -1;

    if (nparams == 0)
        return LIBXL_NB_TOTAL_CPU_STAT_PARAM;

J
Jim Fehlig 已提交
4679 4680 4681
    libxl_dominfo_init(&d_info);
    cfg = libxlDriverConfigGet(driver);

4682 4683 4684 4685
    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 已提交
4686
        goto cleanup;
4687 4688 4689 4690 4691 4692 4693 4694 4695 4696
    }

    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 已提交
4697
    virObjectUnref(cfg);
4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711
    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 已提交
4712
    libxlDriverConfigPtr cfg;
4713 4714 4715 4716 4717
    int ret = -1;

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

J
Jim Fehlig 已提交
4720
    cfg = libxlDriverConfigGet(driver);
4721 4722 4723 4724 4725
    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 已提交
4726
        goto cleanup;
4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738
    }

    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 已提交
4739 4740 4741
    if (vcpuinfo)
        libxl_vcpuinfo_list_free(vcpuinfo, maxcpu);
    virObjectUnref(cfg);
4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782
    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;
}

4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796
#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 已提交
4797
    libxlDriverConfigPtr cfg;
4798 4799 4800 4801 4802 4803 4804 4805
    virDomainObjPtr vm;
    libxl_dominfo d_info;
    unsigned mem, maxmem;
    size_t i = 0;
    int ret = -1;

    virCheckFlags(0, -1);

4806
    libxl_dominfo_init(&d_info);
J
Jim Fehlig 已提交
4807 4808
    cfg = libxlDriverConfigGet(driver);

4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838
    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:
4839
    if (!libxlDomainObjEndJob(driver, vm))
4840 4841 4842
        vm = NULL;

 cleanup:
4843
    libxl_dominfo_dispose(&d_info);
4844 4845
    if (vm)
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
4846
    virObjectUnref(cfg);
4847 4848 4849 4850 4851
    return ret;
}

#undef LIBXL_SET_MEMSTAT

4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888
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;
}

4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939
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;
}
4940

4941
static int
4942 4943 4944
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4945 4946 4947 4948
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4949 4950 4951
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4952 4953 4954 4955
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4956
        ret = -1;
4957 4958 4959 4960 4961 4962

    return ret;
}


static int
4963
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4964 4965 4966
{
    libxlDriverPrivatePtr driver = conn->privateData;

4967 4968 4969
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4970 4971 4972 4973
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        return -1;
4974

4975
    return 0;
4976 4977
}

J
Jim Fehlig 已提交
4978

4979
static int
4980
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4981 4982 4983 4984
{
    return 1;
}

4985
static int
4986 4987 4988
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4989 4990 4991 4992
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4993
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4994

4995 4996 4997
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4998 4999
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
5000 5001 5002 5003

    return ret;
}

5004 5005 5006 5007 5008 5009 5010 5011 5012
/* Which features are supported by this driver? */
static int
libxlConnectSupportsFeature(virConnectPtr conn, int feature)
{
    if (virConnectSupportsFeatureEnsureACL(conn) < 0)
        return -1;

    switch (feature) {
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
J
Jim Fehlig 已提交
5013
    case VIR_DRV_FEATURE_MIGRATION_PARAMS:
5014 5015 5016 5017 5018
        return 1;
    default:
        return 0;
    }
}
5019

5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030
static int
libxlNodeDeviceGetPCIInfo(virNodeDeviceDefPtr def,
                          unsigned *domain,
                          unsigned *bus,
                          unsigned *slot,
                          unsigned *function)
{
    virNodeDevCapsDefPtr cap;

    cap = def->caps;
    while (cap) {
5031
        if (cap->data.type == VIR_NODE_DEV_CAP_PCI_DEV) {
5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044
            *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 已提交
5045
        return -1;
5046 5047
    }

C
Chunyan Liu 已提交
5048
    return 0;
5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084
}

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")) {
5085
        virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_XEN);
5086 5087 5088 5089 5090 5091 5092 5093 5094 5095
    } else {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported driver name '%s'"), driverName);
        goto cleanup;
    }

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

    ret = 0;
5096
 cleanup:
5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138
    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 已提交
5139
        goto cleanup;
5140 5141

    ret = 0;
C
Chunyan Liu 已提交
5142

5143
 cleanup:
C
Chunyan Liu 已提交
5144
    virPCIDeviceFree(pci);
5145 5146 5147 5148 5149 5150 5151 5152
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
C
Chunyan Liu 已提交
5153
    virPCIDevicePtr pci = NULL;
5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179
    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 已提交
5180
        goto cleanup;
5181 5182

    ret = 0;
C
Chunyan Liu 已提交
5183

5184
 cleanup:
C
Chunyan Liu 已提交
5185
    virPCIDeviceFree(pci);
5186 5187 5188 5189 5190
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

J
Jim Fehlig 已提交
5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201
static char *
libxlDomainMigrateBegin3Params(virDomainPtr domain,
                               virTypedParameterPtr params,
                               int nparams,
                               char **cookieout ATTRIBUTE_UNUSED,
                               int *cookieoutlen ATTRIBUTE_UNUSED,
                               unsigned int flags)
{
    const char *xmlin = NULL;
    virDomainObjPtr vm = NULL;

5202 5203 5204 5205 5206
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return NULL;
#endif

J
Jim Fehlig 已提交
5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218
    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 已提交
5219 5220 5221 5222 5223 5224
    if (STREQ_NULLABLE(vm->def->name, "Domain-0")) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Domain-0 cannot be migrated"));
            return NULL;
    }

J
Jim Fehlig 已提交
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
    if (virDomainMigrateBegin3ParamsEnsureACL(domain->conn, vm->def) < 0) {
        virObjectUnlock(vm);
        return NULL;
    }

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

    return libxlDomainMigrationBegin(domain->conn, vm, xmlin);
}

static int
libxlDomainMigratePrepare3Params(virConnectPtr dconn,
                                 virTypedParameterPtr params,
                                 int nparams,
                                 const char *cookiein ATTRIBUTE_UNUSED,
                                 int cookieinlen ATTRIBUTE_UNUSED,
                                 char **cookieout ATTRIBUTE_UNUSED,
                                 int *cookieoutlen ATTRIBUTE_UNUSED,
                                 char **uri_out,
                                 unsigned int flags)
{
    libxlDriverPrivatePtr driver = dconn->privateData;
    virDomainDefPtr def = NULL;
    const char *dom_xml = NULL;
    const char *dname = NULL;
    const char *uri_in = NULL;

5257 5258 5259 5260 5261
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283
    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;

5284
    if (libxlDomainMigrationPrepare(dconn, &def, uri_in, uri_out, flags) < 0)
J
Jim Fehlig 已提交
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
        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;

5312 5313 5314 5315 5316
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339
    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;

    if (libxlDomainMigrationPerform(driver, vm, dom_xml, dconnuri,
5340
                                    uri, dname, flags) < 0)
J
Jim Fehlig 已提交
5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364
        goto cleanup;

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

5367 5368 5369 5370 5371
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return NULL;
#endif

J
Jim Fehlig 已提交
5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391
    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) {
5392
        virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
5393 5394 5395
        return NULL;
    }

5396
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
5397
        virDomainObjEndAPI(&vm);
5398 5399 5400 5401 5402 5403 5404 5405
        return NULL;
    }

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

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

5406
    virDomainObjEndAPI(&vm);
5407 5408

    return ret;
J
Jim Fehlig 已提交
5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422
}

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;

5423 5424 5425 5426 5427
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442
    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);
}

5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459
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;
}
5460

5461
static virHypervisorDriver libxlHypervisorDriver = {
5462
    .name = LIBXL_DRIVER_NAME,
5463 5464 5465 5466
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
5467
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
5468
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
5469
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
5470
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
5471 5472 5473 5474
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
5475 5476 5477 5478 5479 5480 5481
    .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 */
5482
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
5483 5484
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
5485
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
5486 5487
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
5488
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
5489 5490 5491 5492
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
5493
    .domainSave = libxlDomainSave, /* 0.9.2 */
5494
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
5495
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
5496
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
5497
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
5498 5499 5500 5501
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
5502
    .domainPinVcpuFlags = libxlDomainPinVcpuFlags, /* 1.2.1 */
5503
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
5504
    .domainGetVcpuPinInfo = libxlDomainGetVcpuPinInfo, /* 1.2.1 */
5505
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
5506 5507 5508 5509
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
5510 5511 5512
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
5513
    .domainDefineXMLFlags = libxlDomainDefineXMLFlags, /* 1.2.12 */
5514
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
5515
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
5516 5517 5518 5519 5520
    .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 */
5521 5522 5523 5524
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
5525
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
5526
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
5527
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
5528 5529 5530
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
5531
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
5532
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
5533
    .domainGetJobInfo = libxlDomainGetJobInfo, /* 1.3.1 */
5534
    .domainGetJobStats = libxlDomainGetJobStats, /* 1.3.1 */
P
Pavel Hrdina 已提交
5535 5536
    .domainMemoryStats = libxlDomainMemoryStats, /* 1.3.0 */
    .domainGetCPUStats = libxlDomainGetCPUStats, /* 1.3.0 */
5537 5538
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
5539 5540 5541
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
5542
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
5543 5544 5545
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
5546 5547 5548
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
5549
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
5550 5551 5552 5553
    .nodeDeviceDettach = libxlNodeDeviceDettach, /* 1.2.3 */
    .nodeDeviceDetachFlags = libxlNodeDeviceDetachFlags, /* 1.2.3 */
    .nodeDeviceReAttach = libxlNodeDeviceReAttach, /* 1.2.3 */
    .nodeDeviceReset = libxlNodeDeviceReset, /* 1.2.3 */
5554 5555 5556 5557 5558
    .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 */
5559
    .nodeGetSecurityModel = libxlNodeGetSecurityModel, /* 1.2.16 */
J
Jim Fehlig 已提交
5560 5561
};

5562 5563 5564 5565
static virConnectDriver libxlConnectDriver = {
    .hypervisorDriver = &libxlHypervisorDriver,
};

J
Jim Fehlig 已提交
5566 5567
static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
5568
    .stateInitialize = libxlStateInitialize,
5569
    .stateAutoStart = libxlStateAutoStart,
5570 5571
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
5572 5573 5574 5575 5576 5577
};


int
libxlRegister(void)
{
5578 5579
    if (virRegisterConnectDriver(&libxlConnectDriver,
                                 true) < 0)
J
Jim Fehlig 已提交
5580 5581 5582 5583 5584 5585
        return -1;
    if (virRegisterStateDriver(&libxlStateDriver) < 0)
        return -1;

    return 0;
}