libxl_driver.c 198.6 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/>.
J
Jim Fehlig 已提交
21 22 23 24
 */

#include <config.h>

25
#include <math.h>
J
Jim Fehlig 已提交
26
#include <libxl.h>
27
#include <libxl_utils.h>
28
#include <xenstore.h>
29
#include <fcntl.h>
30
#include <regex.h>
J
Jim Fehlig 已提交
31 32

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

#define VIR_FROM_THIS VIR_FROM_LIBXL

63 64
VIR_LOG_INIT("libxl.libxl_driver");

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

71
#define LIBXL_NB_TOTAL_CPU_STAT_PARAM 1
72
#define LIBXL_NB_TOTAL_BLK_STAT_PARAM 6
73

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

77 78 79
/* Number of Xen scheduler parameters */
#define XEN_SCHED_CREDIT_NPARAM   2

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

89

90
static libxlDriverPrivatePtr libxl_driver;
J
Jim Fehlig 已提交
91

92 93 94 95 96 97 98 99 100
/* 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;
};

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
/* Object used to store disk statistics across multiple xen backends */
typedef struct _libxlBlockStats libxlBlockStats;
typedef libxlBlockStats *libxlBlockStatsPtr;
struct _libxlBlockStats {
    long long rd_req;
    long long rd_bytes;
    long long wr_req;
    long long wr_bytes;
    long long f_req;

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

J
Jim Fehlig 已提交
120
/* Function declarations */
121 122
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
123 124
                           void *opaque);

J
Jim Fehlig 已提交
125 126

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

311
    vm = virDomainObjListFindByUUID(driver->domains, dom->uuid);
J
Jim Fehlig 已提交
312 313 314 315 316 317 318 319 320 321 322
    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;
}

323 324
static int
libxlAutostartDomain(virDomainObjPtr vm,
325 326 327
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
328
    int ret = -1;
329

W
Wang Yufei 已提交
330
    virObjectRef(vm);
331
    virObjectLock(vm);
332 333
    virResetLastError();

W
Wang Yufei 已提交
334 335
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;
336

337
    if (vm->autostart && !virDomainObjIsActive(vm) &&
338
        libxlDomainStartNew(driver, vm, false) < 0) {
339 340 341
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to autostart VM '%s': %s"),
                       vm->def->name, virGetLastErrorMessage());
342
        goto endjob;
343 344
    }

345
    ret = 0;
346 347

 endjob:
W
Wang Yufei 已提交
348 349 350
    libxlDomainObjEndJob(driver, vm);
 cleanup:
    virDomainObjEndAPI(&vm);
351

352
    return ret;
353 354
}

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

static void
libxlReconnectNotifyNets(virDomainDefPtr def)
{
    size_t i;
    virConnectPtr conn = NULL;

    for (i = 0; i < def->nnets; i++) {
        virDomainNetDefPtr net = def->nets[i];
        /* keep others from trying to use the macvtap device name, but
         * don't return error if this happens, since that causes the
         * domain to be unceremoniously killed, which would be *very*
         * impolite.
         */
        if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_DIRECT)
           ignore_value(virNetDevMacVLanReserveName(net->ifname, false));

        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            if (!conn && !(conn = virGetConnectNetwork()))
                continue;
            virDomainNetNotifyActualDevice(conn, def, net);
        }
    }

    virObjectUnref(conn);
}


J
Jim Fehlig 已提交
383 384 385 386
/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
387 388
static int
libxlReconnectDomain(virDomainObjPtr vm,
J
Jim Fehlig 已提交
389 390 391
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
392
    libxlDomainObjPrivatePtr priv = vm->privateData;
J
Jim Fehlig 已提交
393
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
394 395 396 397
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;
398
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
399
    unsigned int hostdev_flags = VIR_HOSTDEV_SP_PCI;
400
    int ret = -1;
401 402 403 404

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

406
    virObjectRef(vm);
407
    virObjectLock(vm);
J
Jim Fehlig 已提交
408

409 410
    libxl_dominfo_init(&d_info);

J
Jim Fehlig 已提交
411
    /* Does domain still exist? */
J
Jim Fehlig 已提交
412
    rc = libxl_domain_info(cfg->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
413
    if (rc == ERROR_INVAL) {
414
        goto error;
J
Jim Fehlig 已提交
415 416 417
    } else if (rc != 0) {
        VIR_DEBUG("libxl_domain_info failed (code %d), ignoring domain %d",
                  rc, vm->def->id);
418
        goto error;
J
Jim Fehlig 已提交
419 420 421
    }

    /* Is this a domain that was under libvirt control? */
J
Jim Fehlig 已提交
422
    if (libxl_userdata_retrieve(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
423 424
                                "libvirt-xml", &data, &len)) {
        VIR_DEBUG("libxl_userdata_retrieve failed, ignoring domain %d", vm->def->id);
425
        goto error;
J
Jim Fehlig 已提交
426 427 428 429
    }

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

431 432
    libxlLoggerOpenFile(cfg->logger, vm->def->id, vm->def->name, NULL);

433
    /* Update hostdev state */
434
    if (virHostdevUpdateActiveDomainDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
435
                                            vm->def, hostdev_flags) < 0)
436
        goto error;
437

438 439 440 441 442 443 444 445 446 447 448
    if (d_info.shutdown &&
            d_info.shutdown_reason == LIBXL_SHUTDOWN_REASON_SUSPEND)
        virDomainObjSetState(vm, VIR_DOMAIN_PMSUSPENDED,
                             VIR_DOMAIN_PMSUSPENDED_UNKNOWN);
    else if (d_info.paused)
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED,
                             VIR_DOMAIN_PAUSED_UNKNOWN);
    else
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNKNOWN);

449
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
450 451
        driver->inhibitCallback(true, driver->inhibitOpaque);

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

455 456
    libxlReconnectNotifyNets(vm->def);

457 458 459
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
        VIR_WARN("Cannot update XML for running Xen guest %s", vm->def->name);

C
Cédric Bosdonnat 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
    /* now that we know it's reconnected call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL) &&
        STRNEQ("Domain-0", vm->def->name)) {
        char *xml = virDomainDefFormat(vm->def, cfg->caps, 0);
        int hookret;

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

481 482 483
    ret = 0;

 cleanup:
484
    libxl_dominfo_dispose(&d_info);
485
    virObjectUnlock(vm);
486
    virObjectUnref(vm);
J
Jim Fehlig 已提交
487
    virObjectUnref(cfg);
488
    return ret;
J
Jim Fehlig 已提交
489

490
 error:
491
    libxlDomainCleanup(driver, vm);
492
    if (!vm->persistent)
493
        virDomainObjListRemoveLocked(driver->domains, vm);
494
    goto cleanup;
J
Jim Fehlig 已提交
495 496 497 498 499
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
500
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
501 502 503
}

static int
504
libxlStateCleanup(void)
J
Jim Fehlig 已提交
505 506 507 508
{
    if (!libxl_driver)
        return -1;

509
    virObjectUnref(libxl_driver->hostdevMgr);
510
    virObjectUnref(libxl_driver->xmlopt);
511
    virObjectUnref(libxl_driver->domains);
512 513
    virPortAllocatorRangeFree(libxl_driver->reservedGraphicsPorts);
    virPortAllocatorRangeFree(libxl_driver->migrationPorts);
514
    virLockManagerPluginUnref(libxl_driver->lockManager);
J
Jim Fehlig 已提交
515

516
    virObjectUnref(libxl_driver->domainEventState);
517
    virSysinfoDefFree(libxl_driver->hostsysinfo);
518

519 520 521 522
    if (libxl_driver->lockFD != -1)
        virPidFileRelease(libxl_driver->config->stateDir, "driver", libxl_driver->lockFD);

    virObjectUnref(libxl_driver->config);
J
Jim Fehlig 已提交
523 524 525 526 527 528
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

529 530
static bool
libxlDriverShouldLoad(bool privileged)
531
{
532
    /* Don't load if non-root */
J
Jim Fehlig 已提交
533
    if (!privileged) {
534
        VIR_INFO("Not running privileged, disabling libxenlight driver");
535
        return false;
J
Jim Fehlig 已提交
536 537
    }

R
Roman Bogorodskiy 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    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");

554
            return false;
R
Roman Bogorodskiy 已提交
555 556 557 558
        }
    } else if (!virFileExists(HYPERVISOR_XENSTORED)) {
        VIR_INFO("Disabling driver as neither " HYPERVISOR_CAPABILITIES
                 " nor " HYPERVISOR_XENSTORED " exist");
559
        return false;
560 561
    }

562
    return true;
563 564
}

565 566 567 568 569 570 571 572 573 574
/* 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,
};

575 576 577 578 579 580 581 582
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
};

583 584 585 586 587 588
const struct libxl_event_hooks ev_hooks = {
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlDomainEventHandler,
    .disaster = NULL,
};

J
Jim Fehlig 已提交
589 590 591 592 593 594 595
static int
libxlAddDom0(libxlDriverPrivatePtr driver)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    libxl_dominfo d_info;
596
    unsigned long long maxmem;
J
Jim Fehlig 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    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,
624
                                   NULL)))
J
Jim Fehlig 已提交
625 626 627
        goto cleanup;
    def = NULL;

J
Jim Fehlig 已提交
628
    vm->persistent = 1;
J
Jim Fehlig 已提交
629
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
630
    if (virDomainDefSetVcpusMax(vm->def, d_info.vcpu_max_id + 1, driver->xmlopt))
631 632
        goto cleanup;

633 634
    if (virDomainDefSetVcpus(vm->def, d_info.vcpu_online) < 0)
        goto cleanup;
J
Jim Fehlig 已提交
635
    vm->def->mem.cur_balloon = d_info.current_memkb;
636 637 638
    if (libxlDriverGetDom0MaxmemConf(cfg, &maxmem) < 0)
        maxmem = d_info.current_memkb;
    virDomainDefSetMemoryTotal(vm->def, maxmem);
J
Jim Fehlig 已提交
639 640 641 642 643 644

    ret = 0;

 cleanup:
    libxl_dominfo_dispose(&d_info);
    virDomainDefFree(def);
645
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
646 647 648 649
    virObjectUnref(cfg);
    return ret;
}

650 651 652 653 654
static int
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
655
    libxlDriverConfigPtr cfg;
656
    char *driverConf = NULL;
657 658 659
    char ebuf[1024];

    if (!libxlDriverShouldLoad(privileged))
660
        return VIR_DRV_STATE_INIT_SKIPPED;
661

J
Jim Fehlig 已提交
662
    if (VIR_ALLOC(libxl_driver) < 0)
663
        return VIR_DRV_STATE_INIT_ERROR;
J
Jim Fehlig 已提交
664

665
    libxl_driver->lockFD = -1;
J
Jim Fehlig 已提交
666
    if (virMutexInit(&libxl_driver->lock) < 0) {
667 668
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
J
Jim Fehlig 已提交
669
        VIR_FREE(libxl_driver);
670
        return VIR_DRV_STATE_INIT_ERROR;
J
Jim Fehlig 已提交
671 672 673
    }

    /* Allocate bitmap for vnc port reservation */
674
    if (!(libxl_driver->reservedGraphicsPorts =
675 676
          virPortAllocatorRangeNew(_("VNC"),
                                   LIBXL_VNC_PORT_MIN,
677
                                   LIBXL_VNC_PORT_MAX)))
678
        goto error;
J
Jim Fehlig 已提交
679

J
Jim Fehlig 已提交
680 681
    /* Allocate bitmap for migration port reservation */
    if (!(libxl_driver->migrationPorts =
682 683
          virPortAllocatorRangeNew(_("migration"),
                                   LIBXL_MIGRATION_PORT_MIN,
684
                                   LIBXL_MIGRATION_PORT_MAX)))
J
Jim Fehlig 已提交
685 686
        goto error;

687 688
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
689

690 691 692
    if (!(libxl_driver->hostdevMgr = virHostdevManagerGetDefault()))
        goto error;

693
    if (!(cfg = libxlDriverConfigNew()))
694
        goto error;
J
Jim Fehlig 已提交
695

696 697 698 699 700 701 702
    if (virAsprintf(&driverConf, "%s/libxl.conf", cfg->configBaseDir) < 0)
        goto error;

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

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

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

709 710 711
    /* Register callback to handle domain events */
    libxl_event_register_callbacks(cfg->ctx, &ev_hooks, libxl_driver);

712 713
    libxl_driver->config = cfg;
    if (virFileMakePath(cfg->stateDir) < 0) {
714 715
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create state dir '%s': %s"),
716
                       cfg->stateDir,
717
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
718 719
        goto error;
    }
720
    if (virFileMakePath(cfg->libDir) < 0) {
721 722
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create lib dir '%s': %s"),
723
                       cfg->libDir,
724
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
725 726
        goto error;
    }
727
    if (virFileMakePath(cfg->saveDir) < 0) {
728 729
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create save dir '%s': %s"),
730
                       cfg->saveDir,
731
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
732 733
        goto error;
    }
734 735 736 737 738 739 740
    if (virFileMakePath(cfg->autoDumpDir) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create dump dir '%s': %s"),
                       cfg->autoDumpDir,
                       virStrerror(errno, ebuf, sizeof(ebuf)));
        goto error;
    }
J
Joao Martins 已提交
741 742 743 744 745 746 747
    if (virFileMakePath(cfg->channelDir) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create channel dir '%s': %s"),
                       cfg->channelDir,
                       virStrerror(errno, ebuf, sizeof(ebuf)));
        goto error;
    }
J
Jim Fehlig 已提交
748

749
    if ((libxl_driver->lockFD =
750
         virPidFileAcquire(cfg->stateDir, "driver", false, getpid())) < 0)
751 752
        goto error;

753 754 755 756 757 758 759 760
    if (!(libxl_driver->lockManager =
          virLockManagerPluginNew(cfg->lockManagerName ?
                                  cfg->lockManagerName : "nop",
                                  "libxl",
                                  cfg->configBaseDir,
                                  0)))
        goto error;

761
    /* read the host sysinfo */
762
    libxl_driver->hostsysinfo = virSysinfoRead();
763

764
    libxl_driver->domainEventState = virObjectEventStateNew();
E
Eric Blake 已提交
765
    if (!libxl_driver->domainEventState)
766 767
        goto error;

768
    if ((cfg->caps = libxlMakeCapabilities(cfg->ctx)) == NULL) {
769 770
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
771 772 773
        goto error;
    }

774
    if (!(libxl_driver->xmlopt = libxlCreateXMLConf()))
775
        goto error;
J
Jim Fehlig 已提交
776

J
Jim Fehlig 已提交
777 778 779 780
    /* Add Domain-0 */
    if (libxlAddDom0(libxl_driver) < 0)
        goto error;

J
Jim Fehlig 已提交
781
    /* Load running domains first. */
782
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
783 784
                                       cfg->stateDir,
                                       cfg->autostartDir,
785
                                       true,
786
                                       cfg->caps,
787
                                       libxl_driver->xmlopt,
788
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
789 790 791 792 793
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
794
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
795 796
                                       cfg->configDir,
                                       cfg->autostartDir,
797
                                       false,
798
                                       cfg->caps,
799
                                       libxl_driver->xmlopt,
800
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
801 802
        goto error;

803 804 805
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);

806 807
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
808

809
    return VIR_DRV_STATE_INIT_COMPLETE;
J
Jim Fehlig 已提交
810

811
 error:
812
    VIR_FREE(driverConf);
813
    libxlStateCleanup();
814
    return VIR_DRV_STATE_INIT_ERROR;
J
Jim Fehlig 已提交
815 816 817
}

static int
818
libxlStateReload(void)
J
Jim Fehlig 已提交
819
{
820 821
    libxlDriverConfigPtr cfg;

J
Jim Fehlig 已提交
822 823 824
    if (!libxl_driver)
        return 0;

825 826
    cfg = libxlDriverConfigGet(libxl_driver);

827
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
828 829
                                   cfg->configDir,
                                   cfg->autostartDir,
830
                                   true,
831
                                   cfg->caps,
832
                                   libxl_driver->xmlopt,
833 834
                                   NULL, libxl_driver);

835 836
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
837

838
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
839 840 841 842
    return 0;
}


843 844 845 846 847 848 849 850 851 852
static int
libxlConnectURIProbe(char **uri)
{
    if (libxl_driver == NULL)
        return 0;

    return VIR_STRDUP(*uri, "xen:///system");
}


J
Jim Fehlig 已提交
853
static virDrvOpenStatus
854 855
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
856
                 virConfPtr conf ATTRIBUTE_UNUSED,
857
                 unsigned int flags)
J
Jim Fehlig 已提交
858
{
E
Eric Blake 已提交
859 860
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

861 862 863 864 865 866
    /* Error if xen or libxl scheme specified but driver not started. */
    if (libxl_driver == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight state driver is not active"));
        return VIR_DRV_OPEN_ERROR;
    }
J
Jim Fehlig 已提交
867

868
    /* /session isn't supported in libxenlight */
869
    if (STRNEQ(conn->uri->path, "") &&
870 871 872 873
        STRNEQ(conn->uri->path, "/") &&
        STRNEQ(conn->uri->path, "/system")) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected Xen URI path '%s', try xen:///system"),
874
                       conn->uri->path);
875
        return VIR_DRV_OPEN_ERROR;
J
Jim Fehlig 已提交
876 877
    }

878 879 880
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
881 882 883 884 885 886
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
887
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
888 889 890 891 892 893
{
    conn->privateData = NULL;
    return 0;
}

static const char *
894
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
895
{
896 897 898
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
899
    return "Xen";
J
Jim Fehlig 已提交
900 901 902
}

static int
903
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
904 905
{
    libxlDriverPrivatePtr driver = conn->privateData;
906
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
907

908 909 910
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

911 912 913
    cfg = libxlDriverConfigGet(driver);
    *version = cfg->version;
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
914 915 916
    return 0;
}

917

918
static char *libxlConnectGetHostname(virConnectPtr conn)
919
{
920 921 922
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

923 924 925
    return virGetHostname();
}

926 927 928 929 930 931 932 933
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

934 935 936
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

937 938 939 940 941 942 943 944
    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;
945
    if (virBufferCheckError(&buf) < 0)
946 947 948
        return NULL;
    return virBufferContentAndReset(&buf);
}
949

J
Jim Fehlig 已提交
950
static int
951
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
952 953 954
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;
955
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
956

957 958 959
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

960 961
    cfg = libxlDriverConfigGet(driver);
    ret = libxl_get_max_cpus(cfg->ctx);
962 963 964 965 966
    /* 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)
967
        ret = -1;
J
Jim Fehlig 已提交
968

969
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
970 971 972 973 974 975
    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
976 977 978
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

979
    return libxlDriverNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
980 981 982
}

static char *
983
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
984 985 986
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;
987
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
988

989 990 991
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

992
    cfg = libxlDriverConfigGet(driver);
993
    xml = virCapabilitiesFormatXML(cfg->caps);
J
Jim Fehlig 已提交
994

995
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
996 997 998 999
    return xml;
}

static int
1000
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
1001 1002 1003 1004
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1005 1006 1007
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

1008 1009
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1010 1011 1012 1013 1014

    return n;
}

static int
1015
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
1016 1017 1018 1019
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1020 1021 1022
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

1023 1024
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036

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

1040 1041 1042 1043
    virCheckFlags(VIR_DOMAIN_START_PAUSED |
                  VIR_DOMAIN_START_VALIDATE, NULL);

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

1046
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
1047
                                        NULL, parse_flags)))
J
Jim Fehlig 已提交
1048 1049
        goto cleanup;

1050 1051 1052
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

1053
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1054
                                   driver->xmlopt,
1055
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
1056 1057
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
1058 1059 1060
        goto cleanup;
    def = NULL;

1061
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
1062
        if (!vm->persistent)
1063 1064 1065 1066
            virDomainObjListRemove(driver->domains, vm);
        goto cleanup;
    }

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

1074
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid, vm->def->id);
J
Jim Fehlig 已提交
1075

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

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

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

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

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

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

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

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

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

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

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

1127
 cleanup:
1128
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    return dom;
}

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

1139
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
1140
    if (!vm) {
1141
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1142 1143 1144
        goto cleanup;
    }

1145 1146 1147
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

1148
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid, vm->def->id);
J
Jim Fehlig 已提交
1149

1150
 cleanup:
1151
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
1152 1153 1154
    return dom;
}

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

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

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

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

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

1175
    if (virDomainObjCheckActive(vm) < 0)
1176
        goto endjob;
1177

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

J
Jiri Denemark 已提交
1186
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1187

1188
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
1189 1190 1191
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

1192
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
1193
        goto endjob;
1194 1195 1196

    ret = 0;

1197
 endjob:
W
Wang Yufei 已提交
1198
    libxlDomainObjEndJob(driver, vm);
1199

1200
 cleanup:
W
Wang Yufei 已提交
1201
    virDomainObjEndAPI(&vm);
1202
    virObjectEventStateQueue(driver->domainEventState, event);
1203
    virObjectUnref(cfg);
1204 1205 1206 1207 1208 1209 1210 1211
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1212
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1213
    virDomainObjPtr vm;
1214
    virObjectEventPtr event = NULL;
1215 1216
    int ret = -1;

J
Jim Fehlig 已提交
1217
    if (!(vm = libxlDomObjFromDomain(dom)))
1218 1219
        goto cleanup;

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

1222 1223 1224
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1225 1226 1227
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1228
    if (virDomainObjCheckActive(vm) < 0)
1229
        goto endjob;
1230

J
Jiri Denemark 已提交
1231
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1232
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
1233 1234
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
1235
                           vm->def->id);
1236
            goto endjob;
1237 1238
        }

J
Jiri Denemark 已提交
1239 1240
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1241

1242
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_RESUMED,
1243 1244 1245
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

1246
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
1247
        goto endjob;
1248 1249 1250

    ret = 0;

1251
 endjob:
W
Wang Yufei 已提交
1252
    libxlDomainObjEndJob(driver, vm);
1253

1254
 cleanup:
W
Wang Yufei 已提交
1255
    virDomainObjEndAPI(&vm);
1256
    virObjectEventStateQueue(driver->domainEventState, event);
1257
    virObjectUnref(cfg);
1258 1259 1260
    return ret;
}

J
Jim Fehlig 已提交
1261
static int
1262
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1263
{
J
Jim Fehlig 已提交
1264 1265
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1266 1267 1268
    virDomainObjPtr vm;
    int ret = -1;

1269 1270 1271 1272 1273
    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;
1274

J
Jim Fehlig 已提交
1275
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1276 1277
        goto cleanup;

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

1280
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1281 1282
        goto cleanup;

1283
    if (virDomainObjCheckActive(vm) < 0)
J
Jim Fehlig 已提交
1284 1285
        goto cleanup;

1286
    if (flags & VIR_DOMAIN_SHUTDOWN_PARAVIRT) {
J
Jim Fehlig 已提交
1287
        ret = libxl_domain_shutdown(cfg->ctx, vm->def->id);
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
        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 已提交
1302
        ret = libxl_send_trigger(cfg->ctx, vm->def->id,
1303 1304 1305 1306
                                 LIBXL_TRIGGER_POWER, 0);
        if (ret == 0)
            goto cleanup;

1307 1308
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
1309
                       vm->def->id);
1310
        ret = -1;
J
Jim Fehlig 已提交
1311 1312
    }

1313
 cleanup:
1314
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
1315
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1316 1317 1318
    return ret;
}

1319 1320 1321 1322 1323 1324 1325
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


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

J
Jim Fehlig 已提交
1334 1335 1336
    virCheckFlags(VIR_DOMAIN_REBOOT_PARAVIRT, -1);
    if (flags == 0)
        flags = VIR_DOMAIN_REBOOT_PARAVIRT;
E
Eric Blake 已提交
1337

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

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

1343
    if (virDomainRebootEnsureACL(dom->conn, vm->def, flags) < 0)
1344 1345
        goto cleanup;

1346
    if (virDomainObjCheckActive(vm) < 0)
J
Jim Fehlig 已提交
1347 1348
        goto cleanup;

J
Jim Fehlig 已提交
1349
    if (flags & VIR_DOMAIN_REBOOT_PARAVIRT) {
J
Jim Fehlig 已提交
1350
        ret = libxl_domain_reboot(cfg->ctx, vm->def->id);
J
Jim Fehlig 已提交
1351 1352 1353
        if (ret == 0)
            goto cleanup;

1354 1355
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
1356
                       vm->def->id);
J
Jim Fehlig 已提交
1357
        ret = -1;
J
Jim Fehlig 已提交
1358 1359
    }

1360
 cleanup:
1361
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
1362
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1363 1364 1365 1366
    return ret;
}

static int
1367 1368
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1369 1370
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
1371
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1372 1373
    virDomainObjPtr vm;
    int ret = -1;
1374
    virObjectEventPtr event = NULL;
J
Jim Fehlig 已提交
1375

1376 1377
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1378
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1379 1380
        goto cleanup;

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

1383 1384 1385
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1386 1387 1388
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1389
    if (virDomainObjCheckActive(vm) < 0)
1390
        goto endjob;
J
Jim Fehlig 已提交
1391

1392
    if (libxlDomainDestroyInternal(driver, vm) < 0) {
1393
        virReportError(VIR_ERR_INTERNAL_ERROR,
1394
                       _("Failed to destroy domain '%d'"), vm->def->id);
1395
        goto endjob;
J
Jim Fehlig 已提交
1396 1397
    }

1398 1399 1400 1401 1402 1403 1404
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_DESTROYED);

    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

    libxlDomainCleanup(driver, vm);
1405
    if (!vm->persistent)
1406
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1407 1408 1409

    ret = 0;

1410
 endjob:
W
Wang Yufei 已提交
1411
    libxlDomainObjEndJob(driver, vm);
1412

1413
 cleanup:
W
Wang Yufei 已提交
1414
    virDomainObjEndAPI(&vm);
1415
    virObjectEventStateQueue(driver->domainEventState, event);
J
Jim Fehlig 已提交
1416
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1417 1418 1419
    return ret;
}

1420 1421 1422 1423 1424 1425
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
#ifdef LIBXL_HAVE_DOMAIN_SUSPEND_ONLY
static int
libxlDomainPMSuspendForDuration(virDomainPtr dom,
                                unsigned int target,
                                unsigned long long duration,
                                unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1437
    virObjectEventPtr event = NULL;
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477

    virCheckFlags(0, -1);
    if (target != VIR_NODE_SUSPEND_TARGET_MEM) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED,
                _("PMSuspend type %d not supported by libxenlight driver"),
                target);
        return -1;
    }

    if (duration != 0) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                _("Duration not supported. Use 0 for now"));
        return -1;
    }

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

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

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

    if (!virDomainObjCheckActive(vm))
        goto endjob;

    /* Unlock virDomainObjPtr to not deadlock with even handler, which will try
     * to send lifecycle event
     */
    virObjectUnlock(vm);
    ret = libxl_domain_suspend_only(cfg->ctx, vm->def->id, NULL);
    virObjectLock(vm);

    if (ret < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to suspend domain '%d'"), vm->def->id);
        goto endjob;
    }

1478 1479 1480 1481
    virDomainObjSetState(vm, VIR_DOMAIN_PMSUSPENDED, VIR_DOMAIN_PMSUSPENDED_UNKNOWN);
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_PMSUSPENDED,
                                              VIR_DOMAIN_EVENT_PMSUSPENDED_MEMORY);

1482 1483 1484 1485 1486 1487 1488
    ret = 0;

 endjob:
    libxlDomainObjEndJob(driver, vm);

 cleanup:
    virDomainObjEndAPI(&vm);
1489
    virObjectEventStateQueue(driver->domainEventState, event);
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
    return ret;
}
#endif

static int
libxlDomainPMWakeup(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    virObjectEventPtr event = NULL;
    libxlDomainObjPrivatePtr priv;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);

    virCheckFlags(0, -1);

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

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

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

    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PMSUSPENDED) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not suspended"));
        goto endjob;
    }


    priv = vm->privateData;
    if (libxl_domain_resume(cfg->ctx, vm->def->id, 1, NULL) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to resume domain '%d'"), vm->def->id);
        goto endjob;
    }
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_WAKEUP);
    /* reenable death event - libxl reports it only once */
    if (priv->deathW)
        libxl_evdisable_domain_death(cfg->ctx, priv->deathW);
    if (libxl_evenable_domain_death(cfg->ctx, vm->def->id, 0, &priv->deathW))
        goto destroy_dom;

    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_WAKEUP);

    ret = 0;
    goto endjob;

 destroy_dom:
    libxlDomainDestroyInternal(driver, vm);
    vm->def->id = -1;
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);
1545 1546 1547
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                              VIR_DOMAIN_EVENT_STOPPED_FAILED);
    libxlDomainCleanup(driver, vm);
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557

 endjob:
    libxlDomainObjEndJob(driver, vm);

 cleanup:
    virDomainObjEndAPI(&vm);
    virObjectEventStateQueue(driver->domainEventState, event);
    return ret;
}

1558 1559 1560 1561 1562 1563
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *type = NULL;

J
Jim Fehlig 已提交
1564
    if (!(vm = libxlDomObjFromDomain(dom)))
1565 1566
        goto cleanup;

1567 1568 1569
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1570
    if (VIR_STRDUP(type, virDomainOSTypeToString(vm->def->os.type)) < 0)
1571
        goto cleanup;
1572

1573
 cleanup:
1574
    virDomainObjEndAPI(&vm);
1575 1576 1577
    return type;
}

1578
static unsigned long long
1579 1580 1581
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    virDomainObjPtr vm;
1582
    unsigned long long ret = 0;
1583

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

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

1590
    ret = virDomainDefGetMemoryTotal(vm->def);
1591

1592
 cleanup:
1593
    virDomainObjEndAPI(&vm);
1594 1595 1596
    return ret;
}

1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615

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

    if (*flags & VIR_DOMAIN_AFFECT_CONFIG) {
1616
        if (!(*persistentDef = virDomainObjGetPersistentDef(caps, xmlopt, dom, NULL))) {
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Get persistent config failed"));
            return -1;
        }
    }

    return 0;
}


1627
static int
1628
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1629 1630 1631
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1632
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1633
    virDomainObjPtr vm;
1634
    virDomainDefPtr persistentDef = NULL;
1635 1636 1637
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1638 1639
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1640

J
Jim Fehlig 已提交
1641
    if (!(vm = libxlDomObjFromDomain(dom)))
1642 1643
        goto cleanup;

1644 1645 1646
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

1647 1648 1649
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1650 1651
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm, &flags,
                                        &persistentDef) < 0)
1652
        goto endjob;
1653

1654 1655
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1656

1657
        if (flags & VIR_DOMAIN_MEM_LIVE) {
J
Jim Fehlig 已提交
1658
            if (libxl_domain_setmaxmem(cfg->ctx, vm->def->id, newmem) < 0) {
1659 1660
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
1661
                                 " with libxenlight"), vm->def->id);
1662
                goto endjob;
1663 1664 1665 1666 1667 1668
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
1669
            virDomainDefSetMemoryTotal(persistentDef, newmem);
1670 1671
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
1672
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1673
            goto endjob;
1674 1675
        }

1676 1677
    } else {
        /* resize the current memory */
1678

1679
        if (newmem > virDomainDefGetMemoryTotal(vm->def)) {
1680 1681
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1682
            goto endjob;
1683 1684 1685
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
1686 1687 1688 1689
            int res;

            /* Unlock virDomainObj while ballooning memory */
            virObjectUnlock(vm);
J
Jim Fehlig 已提交
1690
            res = libxl_set_memory_target(cfg->ctx, vm->def->id, newmem, 0,
1691 1692 1693
                                          /* force */ 1);
            virObjectLock(vm);
            if (res < 0) {
1694 1695
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
1696
                                 " with libxenlight"), vm->def->id);
1697
                goto endjob;
1698
            }
1699
            vm->def->mem.cur_balloon = newmem;
1700 1701 1702 1703 1704
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1705
            ret = virDomainSaveConfig(cfg->configDir, cfg->caps, persistentDef);
1706
            goto endjob;
1707
        }
1708 1709
    }

1710 1711
    ret = 0;

1712
 endjob:
W
Wang Yufei 已提交
1713
    libxlDomainObjEndJob(driver, vm);
1714

1715
 cleanup:
W
Wang Yufei 已提交
1716
    virDomainObjEndAPI(&vm);
1717
    virObjectUnref(cfg);
1718 1719 1720 1721 1722 1723 1724 1725 1726
    return ret;
}

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

1727 1728 1729 1730 1731 1732
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1733 1734 1735
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
J
Jim Fehlig 已提交
1736 1737
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1738
    virDomainObjPtr vm;
1739
    libxl_dominfo d_info;
J
Jim Fehlig 已提交
1740 1741
    int ret = -1;

J
Jim Fehlig 已提交
1742
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1743 1744
        goto cleanup;

1745 1746 1747
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1748
    info->maxMem = virDomainDefGetMemoryTotal(vm->def);
1749 1750 1751 1752
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
    } else {
1753 1754
        libxl_dominfo_init(&d_info);

J
Jim Fehlig 已提交
1755
        if (libxl_domain_info(cfg->ctx, &d_info, vm->def->id) != 0) {
1756
            virReportError(VIR_ERR_INTERNAL_ERROR,
1757 1758
                           _("libxl_domain_info failed for domain '%d'"),
                           vm->def->id);
1759 1760 1761 1762
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1763 1764

        libxl_dominfo_dispose(&d_info);
1765 1766
    }

J
Jiri Denemark 已提交
1767
    info->state = virDomainObjGetState(vm, NULL);
1768
    info->nrVirtCpu = virDomainDefGetVcpus(vm->def);
J
Jim Fehlig 已提交
1769 1770
    ret = 0;

1771
 cleanup:
1772
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
1773
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1774 1775 1776
    return ret;
}

1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1788
    if (!(vm = libxlDomObjFromDomain(dom)))
1789 1790
        goto cleanup;

1791 1792 1793
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1794
    *state = virDomainObjGetState(vm, reason);
1795 1796
    ret = 0;

1797
 cleanup:
1798
    virDomainObjEndAPI(&vm);
1799 1800 1801
    return ret;
}

1802 1803 1804
/*
 * virDomainObjPtr must be locked on invocation
 */
1805
static int
1806 1807 1808 1809
libxlDoDomainSave(libxlDriverPrivatePtr driver,
                  virDomainObjPtr vm,
                  const char *to,
                  bool managed)
1810
{
J
Jim Fehlig 已提交
1811
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1812
    libxlSavefileHeader hdr;
1813
    virObjectEventPtr event = NULL;
1814 1815
    char *xml = NULL;
    uint32_t xml_len;
1816
    int fd = -1;
1817 1818 1819
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1820 1821 1822
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1823 1824 1825 1826
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1827
                            -1, -1, 0)) < 0) {
1828 1829 1830 1831 1832
        virReportSystemError(-fd,
                             _("Failed to create domain save file '%s'"), to);
        goto cleanup;
    }

1833
    if ((xml = virDomainDefFormat(vm->def, cfg->caps, 0)) == NULL)
1834 1835 1836 1837 1838 1839 1840 1841 1842
        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)) {
1843 1844
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1845 1846 1847 1848
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1849 1850
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1851 1852 1853
        goto cleanup;
    }

1854 1855
    /* Unlock virDomainObj while saving domain */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
1856
    ret = libxl_domain_suspend(cfg->ctx, vm->def->id, fd, 0, NULL);
1857 1858 1859
    virObjectLock(vm);

    if (ret != 0) {
1860 1861 1862
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1863
        ret = -1;
1864 1865 1866
        goto cleanup;
    }

1867 1868 1869
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_SAVED);

1870
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1871 1872
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

1873
    if (libxlDomainDestroyInternal(driver, vm) < 0) {
1874 1875
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1876 1877 1878
        goto cleanup;
    }

1879
    libxlDomainCleanup(driver, vm);
1880
    vm->hasManagedSave = managed;
1881 1882
    ret = 0;

1883
 cleanup:
1884 1885 1886
    VIR_FREE(xml);
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1887
    virObjectEventStateQueue(driver->domainEventState, event);
J
Jim Fehlig 已提交
1888
    virObjectUnref(cfg);
1889 1890 1891 1892
    return ret;
}

static int
1893 1894
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1895
{
1896 1897
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1898 1899
    int ret = -1;

1900 1901 1902 1903 1904
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1905 1906
    virCheckFlags(0, -1);
    if (dxml) {
1907 1908
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1909 1910 1911
        return -1;
    }

J
Jim Fehlig 已提交
1912
    if (!(vm = libxlDomObjFromDomain(dom)))
1913 1914
        goto cleanup;

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

1917 1918 1919
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1920 1921 1922
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

1923
    if (virDomainObjCheckActive(vm) < 0)
1924
        goto endjob;
1925

1926
    if (libxlDoDomainSave(driver, vm, to, false) < 0)
1927
        goto endjob;
1928

1929
    if (!vm->persistent)
1930
        virDomainObjListRemove(driver->domains, vm);
1931 1932

    ret = 0;
1933

1934
 endjob:
W
Wang Yufei 已提交
1935
    libxlDomainObjEndJob(driver, vm);
1936

1937
 cleanup:
W
Wang Yufei 已提交
1938
    virDomainObjEndAPI(&vm);
1939 1940
    return ret;
}
1941

1942
static int
1943 1944 1945 1946 1947 1948 1949 1950
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)
1951 1952
{
    libxlDriverPrivatePtr driver = conn->privateData;
1953
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1954 1955 1956 1957 1958
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1959

1960 1961 1962 1963 1964
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

1965
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1966
    if (dxml) {
1967 1968
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1969 1970 1971
        return -1;
    }

1972
    fd = libxlDomainSaveImageOpen(driver, cfg, from, &def, &hdr);
1973
    if (fd < 0)
1974
        goto cleanup;
1975

1976
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1977
        goto cleanup;
1978

1979
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1980
                                   driver->xmlopt,
1981 1982 1983
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1984
        goto cleanup;
1985 1986
    def = NULL;

1987
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0) {
1988
        if (!vm->persistent)
1989 1990 1991 1992
            virDomainObjListRemove(driver->domains, vm);
        goto cleanup;
    }

1993 1994 1995
    ret = libxlDomainStartRestore(driver, vm,
                                  (flags & VIR_DOMAIN_SAVE_PAUSED) != 0,
                                  fd, hdr.version);
1996
    if (ret < 0 && !vm->persistent)
1997
        virDomainObjListRemove(driver->domains, vm);
1998

W
Wang Yufei 已提交
1999
    libxlDomainObjEndJob(driver, vm);
2000

2001
 cleanup:
2002 2003
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
2004
    virDomainDefFree(def);
W
Wang Yufei 已提交
2005
    virDomainObjEndAPI(&vm);
2006
    virObjectUnref(cfg);
2007 2008 2009
    return ret;
}

2010 2011 2012 2013 2014 2015
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

2016
static int
2017
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
2018 2019
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
2020
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2021
    virDomainObjPtr vm;
2022
    virObjectEventPtr event = NULL;
2023 2024 2025 2026 2027
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

J
Jim Fehlig 已提交
2028
    if (!(vm = libxlDomObjFromDomain(dom)))
2029 2030
        goto cleanup;

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

2033 2034 2035
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2036 2037 2038
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2039
    if (virDomainObjCheckActive(vm) < 0)
2040
        goto endjob;
2041 2042 2043

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
2044
        if (libxl_domain_pause(cfg->ctx, vm->def->id) != 0) {
2045 2046 2047
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
2048
                           vm->def->id);
2049
            goto endjob;
2050 2051 2052 2053 2054
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

2055 2056
    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
2057
    ret = libxl_domain_core_dump(cfg->ctx, vm->def->id, to, NULL);
2058 2059
    virObjectLock(vm);
    if (ret != 0) {
2060 2061
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
2062
                       vm->def->id);
2063 2064
        ret = -1;
        goto unpause;
2065 2066 2067
    }

    if (flags & VIR_DUMP_CRASH) {
2068
        if (libxlDomainDestroyInternal(driver, vm) < 0) {
2069
            virReportError(VIR_ERR_INTERNAL_ERROR,
2070
                           _("Failed to destroy domain '%d'"), vm->def->id);
2071
            goto unpause;
2072 2073
        }

2074 2075 2076
        libxlDomainCleanup(driver, vm);
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_CRASHED);
2077
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
2078
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
2079
        if (!vm->persistent)
2080
            virDomainObjListRemove(driver->domains, vm);
2081 2082 2083 2084
    }

    ret = 0;

2085
 unpause:
2086
    if (virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
2087
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
2088 2089
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
2090
                             " libxenlight"), vm->def->id);
2091 2092 2093 2094 2095
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
2096

2097
 endjob:
W
Wang Yufei 已提交
2098
    libxlDomainObjEndJob(driver, vm);
2099

2100
 cleanup:
W
Wang Yufei 已提交
2101
    virDomainObjEndAPI(&vm);
2102
    virObjectEventStateQueue(driver->domainEventState, event);
J
Jim Fehlig 已提交
2103
    virObjectUnref(cfg);
2104 2105 2106
    return ret;
}

2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
static int
libxlDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

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

2122 2123 2124
    if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2125 2126 2127
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2128
    if (virDomainObjCheckActive(vm) < 0)
2129
        goto endjob;
2130
    if (!vm->persistent) {
2131 2132
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
2133
        goto endjob;
2134
    }
2135 2136 2137

    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
2138
        goto endjob;
2139 2140 2141

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

2142
    if (libxlDoDomainSave(driver, vm, name, true) < 0)
2143
        goto endjob;
2144

2145
    if (!vm->persistent)
2146
        virDomainObjListRemove(driver->domains, vm);
2147 2148

    ret = 0;
2149

2150
 endjob:
W
Wang Yufei 已提交
2151
    libxlDomainObjEndJob(driver, vm);
2152

2153
 cleanup:
W
Wang Yufei 已提交
2154
    virDomainObjEndAPI(&vm);
2155 2156 2157 2158
    VIR_FREE(name);
    return ret;
}

2159 2160
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
2161 2162 2163 2164
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
2165
    int ret = -1;
2166

2167
    virObjectLock(vm);
2168 2169 2170 2171 2172 2173

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

    vm->hasManagedSave = virFileExists(name);

2174
    ret = 0;
2175
 cleanup:
2176
    virObjectUnlock(vm);
2177
    VIR_FREE(name);
2178
    return ret;
2179 2180
}

2181 2182 2183 2184 2185 2186 2187 2188
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

2192 2193 2194
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2195
    ret = vm->hasManagedSave;
2196

2197
 cleanup:
2198
    virDomainObjEndAPI(&vm);
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
    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 已提交
2212
    if (!(vm = libxlDomObjFromDomain(dom)))
2213 2214
        goto cleanup;

2215 2216 2217
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2218 2219 2220 2221 2222
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
2223
    vm->hasManagedSave = false;
2224

2225
 cleanup:
2226
    VIR_FREE(name);
2227
    virDomainObjEndAPI(&vm);
2228 2229 2230
    return ret;
}

2231 2232 2233 2234 2235
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2236
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2237 2238
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
2239
    libxl_bitmap map;
2240 2241
    uint8_t *bitmask = NULL;
    unsigned int maplen;
2242 2243
    size_t i;
    unsigned int pos;
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
    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)) {
2256 2257
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2258 2259 2260 2261
        return -1;
    }

    if (!nvcpus) {
2262
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2263 2264 2265
        return -1;
    }

J
Jim Fehlig 已提交
2266
    if (!(vm = libxlDomObjFromDomain(dom)))
2267 2268
        goto cleanup;

2269 2270 2271
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

2272 2273 2274
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2275
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2276 2277
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2278
        goto endjob;
2279 2280 2281
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2282 2283
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2284
        goto endjob;
2285 2286
    }

2287
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2288 2289
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2290
        goto endjob;
2291 2292
    }

2293 2294
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && virDomainDefGetVcpusMax(vm->def) < max)
        max = virDomainDefGetVcpusMax(vm->def);
2295 2296

    if (nvcpus > max) {
2297 2298 2299
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2300
        goto endjob;
2301 2302
    }

2303
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm, NULL)))
2304
        goto endjob;
2305

E
Eric Blake 已提交
2306
    maplen = VIR_CPU_MAPLEN(nvcpus);
2307
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
2308
        goto endjob;
2309 2310

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2311
        pos = i / 8;
2312 2313 2314 2315 2316 2317 2318 2319
        bitmask[pos] |= 1 << (i % 8);
    }

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

    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
2320
        if (virDomainDefSetVcpusMax(def, nvcpus, driver->xmlopt) < 0)
2321
            goto cleanup;
2322 2323 2324
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
2325 2326
        if (virDomainDefSetVcpus(def, nvcpus) < 0)
            goto cleanup;
2327 2328 2329
        break;

    case VIR_DOMAIN_VCPU_LIVE:
J
Jim Fehlig 已提交
2330
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2331 2332
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2333
                             " with libxenlight"), vm->def->id);
2334
            goto endjob;
2335
        }
2336 2337
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0)
            goto endjob;
2338 2339 2340
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2341
        if (libxl_set_vcpuonline(cfg->ctx, vm->def->id, &map) != 0) {
2342 2343
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
2344
                             " with libxenlight"), vm->def->id);
2345
            goto endjob;
2346
        }
2347 2348 2349
        if (virDomainDefSetVcpus(vm->def, nvcpus) < 0 ||
            virDomainDefSetVcpus(def, nvcpus) < 0)
            goto endjob;
2350 2351 2352 2353 2354
        break;
    }

    ret = 0;

2355
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2356
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0) {
2357 2358 2359 2360 2361
            VIR_WARN("Unable to save status on vm %s after changing vcpus",
                     vm->def->name);
        }
    }
    if (flags & VIR_DOMAIN_VCPU_CONFIG) {
2362
        if (virDomainSaveConfig(cfg->configDir, cfg->caps, def) < 0) {
2363 2364 2365 2366
            VIR_WARN("Unable to save configuration of vm %s after changing vcpus",
                     vm->def->name);
        }
    }
2367

2368
 endjob:
W
Wang Yufei 已提交
2369
    libxlDomainObjEndJob(driver, vm);
2370

2371
 cleanup:
2372
    VIR_FREE(bitmask);
W
Wang Yufei 已提交
2373 2374
    virDomainObjEndAPI(&vm);
    virObjectUnref(cfg);
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
    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;
2390
    bool active;
2391 2392 2393 2394 2395

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

J
Jim Fehlig 已提交
2396
    if (!(vm = libxlDomObjFromDomain(dom)))
2397 2398
        goto cleanup;

2399
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2400 2401
        goto cleanup;

2402 2403 2404 2405 2406 2407 2408 2409 2410
    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)) {
2411 2412
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2413 2414 2415
        return -1;
    }

2416
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2417
        if (!active) {
2418 2419
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2420 2421 2422 2423
            goto cleanup;
        }
        def = vm->def;
    } else {
2424
        if (!vm->persistent) {
2425 2426
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2427 2428
            goto cleanup;
        }
2429 2430 2431
        def = vm->newDef ? vm->newDef : vm->def;
    }

2432 2433 2434
    if (flags & VIR_DOMAIN_VCPU_MAXIMUM)
        ret = virDomainDefGetVcpusMax(def);
    else
2435
        ret = virDomainDefGetVcpus(def);
2436

2437
 cleanup:
2438
    virDomainObjEndAPI(&vm);
2439 2440 2441
    return ret;
}

2442 2443 2444 2445 2446 2447 2448
static int
libxlDomainGetMaxVcpus(virDomainPtr dom)
{
    return libxlDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

2449
static int
2450 2451 2452
libxlDomainPinVcpuFlags(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen,
                        unsigned int flags)
2453 2454
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2455
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2456
    virDomainDefPtr targetDef = NULL;
2457
    virBitmapPtr pcpumap = NULL;
2458
    virDomainVcpuDefPtr vcpuinfo;
2459 2460
    virDomainObjPtr vm;
    int ret = -1;
2461 2462 2463

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
2464

J
Jim Fehlig 已提交
2465
    if (!(vm = libxlDomObjFromDomain(dom)))
2466 2467
        goto cleanup;

2468
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2469 2470
        goto cleanup;

2471 2472 2473
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

2474 2475
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
2476
        goto endjob;
2477

2478
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2479 2480 2481 2482 2483
        targetDef = vm->def;

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

2484 2485
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
2486
        goto endjob;
2487

2488 2489 2490 2491 2492 2493 2494
    if (!(vcpuinfo = virDomainDefGetVcpu(targetDef, vcpu)) ||
        !vcpuinfo->online) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("vcpu '%u' is not active"), vcpu);
        goto endjob;
    }

2495 2496
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        libxl_bitmap map = { .size = maplen, .map = cpumap };
J
Jim Fehlig 已提交
2497
        if (libxl_set_vcpuaffinity(cfg->ctx, vm->def->id, vcpu, &map, NULL) != 0) {
2498 2499 2500
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"),
                           vcpu);
2501
            goto endjob;
2502
        }
2503
    }
2504

2505 2506 2507
    virBitmapFree(vcpuinfo->cpumask);
    vcpuinfo->cpumask = pcpumap;
    pcpumap = NULL;
2508

2509 2510
    ret = 0;

2511
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
2512
        ret = virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps);
2513
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
2514
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, targetDef);
2515 2516
    }

2517
 endjob:
W
Wang Yufei 已提交
2518
    libxlDomainObjEndJob(driver, vm);
2519

2520
 cleanup:
W
Wang Yufei 已提交
2521
    virDomainObjEndAPI(&vm);
2522
    virBitmapFree(pcpumap);
2523
    virObjectUnref(cfg);
2524 2525 2526
    return ret;
}

2527 2528 2529 2530 2531 2532 2533 2534
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

2535 2536 2537 2538 2539 2540 2541 2542 2543
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;
2544
    int ret = -1;
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558

    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;

2559
    if (flags & VIR_DOMAIN_AFFECT_LIVE)
2560 2561 2562 2563 2564
        targetDef = vm->def;

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

2565 2566
    ret = virDomainDefGetVcpuPinInfoHelper(targetDef, maplen, ncpumaps, cpumaps,
                                           libxl_get_max_cpus(cfg->ctx), NULL);
2567

2568
 cleanup:
2569
    virDomainObjEndAPI(&vm);
2570 2571 2572
    virObjectUnref(cfg);
    return ret;
}
2573 2574 2575 2576 2577

static int
libxlDomainGetVcpus(virDomainPtr dom, virVcpuInfoPtr info, int maxinfo,
                    unsigned char *cpumaps, int maplen)
{
J
Jim Fehlig 已提交
2578 2579
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2580 2581 2582 2583
    virDomainObjPtr vm;
    int ret = -1;
    libxl_vcpuinfo *vcpuinfo;
    int maxcpu, hostcpus;
2584
    size_t i;
2585 2586
    unsigned char *cpumap;

J
Jim Fehlig 已提交
2587
    if (!(vm = libxlDomObjFromDomain(dom)))
2588 2589
        goto cleanup;

2590 2591 2592
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2593
    if (virDomainObjCheckActive(vm) < 0)
2594 2595
        goto cleanup;

J
Jim Fehlig 已提交
2596
    if ((vcpuinfo = libxl_list_vcpu(cfg->ctx, vm->def->id, &maxcpu,
2597
                                    &hostcpus)) == NULL) {
2598 2599
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
2600
                       vm->def->id);
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622
        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 已提交
2623
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2624 2625 2626 2627 2628
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

2629
 cleanup:
2630
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
2631
    virObjectUnref(cfg);
2632 2633 2634
    return ret;
}

J
Jim Fehlig 已提交
2635
static char *
2636
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2637
{
2638 2639
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2640
    virDomainObjPtr vm;
2641
    virDomainDefPtr def;
J
Jim Fehlig 已提交
2642 2643
    char *ret = NULL;

2644
    virCheckFlags(VIR_DOMAIN_XML_COMMON_FLAGS, NULL);
2645

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

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

2652 2653 2654 2655 2656
    if ((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef)
        def = vm->newDef;
    else
        def = vm->def;

2657
    ret = virDomainDefFormat(def, cfg->caps,
2658
                             virDomainDefFormatConvertXMLFlags(flags));
J
Jim Fehlig 已提交
2659

2660
 cleanup:
2661
    virDomainObjEndAPI(&vm);
2662
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2663 2664 2665
    return ret;
}

2666
static char *
2667 2668 2669
libxlConnectDomainXMLFromNative(virConnectPtr conn,
                                const char *nativeFormat,
                                const char *nativeConfig,
2670
                                unsigned int flags)
2671 2672
{
    libxlDriverPrivatePtr driver = conn->privateData;
2673
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2674 2675 2676 2677
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2678 2679
    virCheckFlags(0, NULL);

2680 2681 2682
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

2683
    if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XL)) {
J
Ján Tomko 已提交
2684
        if (!(conf = virConfReadString(nativeConfig, 0)))
2685 2686 2687
            goto cleanup;
        if (!(def = xenParseXL(conf,
                               cfg->caps,
2688
                               driver->xmlopt)))
2689
            goto cleanup;
2690
    } else if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XM)) {
J
Ján Tomko 已提交
2691
        if (!(conf = virConfReadString(nativeConfig, 0)))
2692 2693 2694
            goto cleanup;

        if (!(def = xenParseXM(conf,
2695 2696
                               cfg->caps,
                               driver->xmlopt)))
2697
            goto cleanup;
2698
    } else if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_SEXPR)) {
2699 2700 2701
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("conversion from 'xen-sxpr' format is no longer supported"));
        goto cleanup;
2702
    } else {
2703 2704
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2705 2706 2707
        goto cleanup;
    }

2708
    xml = virDomainDefFormat(def, cfg->caps, VIR_DOMAIN_DEF_FORMAT_INACTIVE);
2709

2710
 cleanup:
2711 2712 2713
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2714
    virObjectUnref(cfg);
2715 2716 2717 2718 2719
    return xml;
}

#define MAX_CONFIG_SIZE (1024 * 65)
static char *
2720 2721 2722
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
2723 2724
{
    libxlDriverPrivatePtr driver = conn->privateData;
2725
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2726 2727 2728 2729 2730
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    int len = MAX_CONFIG_SIZE;
    char *ret = NULL;

E
Eric Blake 已提交
2731 2732
    virCheckFlags(0, NULL);

2733 2734 2735
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

2736
    if (!(def = virDomainDefParseString(domainXml,
2737
                                        cfg->caps, driver->xmlopt, NULL,
2738
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE)))
2739 2740
        goto cleanup;

2741
    if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XL)) {
2742
        if (!(conf = xenFormatXL(def, conn)))
2743
            goto cleanup;
2744
    } else if (STREQ(nativeFormat, XEN_CONFIG_FORMAT_XM)) {
2745
        if (!(conf = xenFormatXM(conn, def)))
2746 2747 2748 2749 2750
            goto cleanup;
    } else {

        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2751
        goto cleanup;
2752
    }
2753

2754
    if (VIR_ALLOC_N(ret, len) < 0)
2755 2756 2757 2758 2759 2760 2761
        goto cleanup;

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

2762
 cleanup:
2763 2764 2765
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2766
    virObjectUnref(cfg);
2767 2768 2769
    return ret;
}

J
Jim Fehlig 已提交
2770
static int
2771 2772
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
2773 2774 2775 2776
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2777 2778 2779
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2780 2781
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
2782 2783 2784 2785
    return n;
}

static int
2786
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
2787 2788 2789 2790
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2791 2792 2793
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2794
    n = virDomainObjListNumOfDomains(driver->domains, false,
2795 2796
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
2797 2798 2799 2800 2801
    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
2802
                           unsigned int flags)
J
Jim Fehlig 已提交
2803 2804 2805 2806 2807 2808 2809
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

J
Jim Fehlig 已提交
2810
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2811 2812
        goto cleanup;

2813 2814 2815
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2816 2817 2818
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2819
    if (virDomainObjIsActive(vm)) {
2820 2821
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
2822
        goto endjob;
J
Jim Fehlig 已提交
2823 2824
    }

2825 2826
    ret = libxlDomainStartNew(driver, vm,
                              (flags & VIR_DOMAIN_START_PAUSED) != 0);
2827
    if (ret < 0)
2828
        goto endjob;
2829
    dom->id = vm->def->id;
J
Jim Fehlig 已提交
2830

2831
 endjob:
W
Wang Yufei 已提交
2832
    libxlDomainObjEndJob(driver, vm);
2833

2834
 cleanup:
W
Wang Yufei 已提交
2835
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
    return ret;
}

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

static virDomainPtr
2846
libxlDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags)
J
Jim Fehlig 已提交
2847 2848
{
    libxlDriverPrivatePtr driver = conn->privateData;
2849
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2850 2851 2852
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
2853
    virObjectEventPtr event = NULL;
2854
    virDomainDefPtr oldDef = NULL;
2855
    unsigned int parse_flags = VIR_DOMAIN_DEF_PARSE_INACTIVE;
J
Jim Fehlig 已提交
2856

2857 2858 2859
    virCheckFlags(VIR_DOMAIN_DEFINE_VALIDATE, NULL);

    if (flags & VIR_DOMAIN_DEFINE_VALIDATE)
2860
        parse_flags |= VIR_DOMAIN_DEF_PARSE_VALIDATE_SCHEMA;
2861

2862
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
2863
                                        NULL, parse_flags)))
2864
        goto cleanup;
J
Jim Fehlig 已提交
2865

2866 2867 2868
    if (virXMLCheckIllegalChars("name", def->name, "\n") < 0)
        goto cleanup;

2869
    if (virDomainDefineXMLFlagsEnsureACL(conn, def) < 0)
2870
        goto cleanup;
2871

2872
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2873
                                   driver->xmlopt,
2874 2875
                                   0,
                                   &oldDef)))
2876
        goto cleanup;
J
Jim Fehlig 已提交
2877
    def = NULL;
2878

J
Jim Fehlig 已提交
2879 2880
    vm->persistent = 1;

2881
    if (virDomainSaveConfig(cfg->configDir,
2882
                            cfg->caps,
J
Jim Fehlig 已提交
2883
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2884
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
2885 2886 2887
        goto cleanup;
    }

2888
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid, vm->def->id);
J
Jim Fehlig 已提交
2889

2890
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2891
                                     !oldDef ?
2892 2893 2894
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

2895
 cleanup:
J
Jim Fehlig 已提交
2896
    virDomainDefFree(def);
2897
    virDomainDefFree(oldDef);
2898
    virDomainObjEndAPI(&vm);
2899
    virObjectEventStateQueue(driver->domainEventState, event);
2900
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2901 2902 2903
    return dom;
}

2904 2905 2906 2907 2908 2909
static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    return libxlDomainDefineXMLFlags(conn, xml, 0);
}

J
Jim Fehlig 已提交
2910
static int
2911 2912
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2913 2914
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2915
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2916
    virDomainObjPtr vm;
2917
    virObjectEventPtr event = NULL;
2918
    char *name = NULL;
J
Jim Fehlig 已提交
2919 2920
    int ret = -1;

2921 2922
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2923
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2924 2925
        goto cleanup;

2926 2927 2928
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2929
    if (!vm->persistent) {
2930 2931
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2932 2933 2934
        goto cleanup;
    }

2935 2936 2937 2938 2939 2940 2941
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2942 2943
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2944 2945 2946
                goto cleanup;
            }
        } else {
2947 2948 2949
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2950 2951 2952 2953
            goto cleanup;
        }
    }

2954
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2955 2956
        goto cleanup;

2957
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2958 2959
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2960
    if (virDomainObjIsActive(vm))
2961
        vm->persistent = 0;
2962
    else
2963
        virDomainObjListRemove(driver->domains, vm);
2964

J
Jim Fehlig 已提交
2965 2966
    ret = 0;

2967
 cleanup:
2968
    VIR_FREE(name);
2969
    virDomainObjEndAPI(&vm);
2970
    virObjectEventStateQueue(driver->domainEventState, event);
2971
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2972 2973 2974
    return ret;
}

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

2981
static int
J
Jim Fehlig 已提交
2982
libxlDomainChangeEjectableMedia(virDomainObjPtr vm, virDomainDiskDefPtr disk)
2983
{
J
Jim Fehlig 已提交
2984
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
2985 2986
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2987
    size_t i;
2988 2989
    int ret = -1;

2990
    for (i = 0; i < vm->def->ndisks; i++) {
2991 2992 2993 2994 2995 2996 2997 2998
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
2999 3000 3001
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
3002 3003 3004 3005
        goto cleanup;
    }

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

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

J
Jim Fehlig 已提交
3015
    if ((ret = libxl_cdrom_insert(cfg->ctx, vm->def->id, &x_disk, NULL)) < 0) {
3016 3017 3018
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
3019 3020 3021
        goto cleanup;
    }

3022 3023 3024
    if (virDomainDiskSetSource(origdisk, virDomainDiskGetSource(disk)) < 0)
        goto cleanup;
    virDomainDiskSetType(origdisk, virDomainDiskGetType(disk));
3025 3026 3027 3028 3029

    virDomainDiskDefFree(disk);

    ret = 0;

3030
 cleanup:
J
Jim Fehlig 已提交
3031
    virObjectUnref(cfg);
3032 3033 3034 3035
    return ret;
}

static int
J
Jim Fehlig 已提交
3036
libxlDomainAttachDeviceDiskLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3037
{
J
Jim Fehlig 已提交
3038
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
3039 3040 3041 3042 3043 3044
    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 已提交
3045
            ret = libxlDomainChangeEjectableMedia(vm, l_disk);
3046 3047 3048
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (l_disk->bus == VIR_DOMAIN_DISK_BUS_XEN) {
3049
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
3050 3051
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
3052 3053 3054
                    goto cleanup;
                }

3055
                if (!virDomainDiskGetSource(l_disk)) {
3056 3057
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
3058 3059 3060
                    goto cleanup;
                }

3061
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
3062 3063
                    goto cleanup;

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

3067 3068 3069
                if (virDomainLockImageAttach(libxl_driver->lockManager,
                                             "xen:///system",
                                             vm, l_disk->src) < 0)
3070 3071
                    goto cleanup;

J
Jim Fehlig 已提交
3072
                if ((ret = libxl_device_disk_add(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
3073
                                                &x_disk, NULL)) < 0) {
3074 3075 3076
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
3077 3078
                    if (virDomainLockImageDetach(libxl_driver->lockManager,
                                                 vm, l_disk->src) < 0) {
3079 3080 3081
                        VIR_WARN("Unable to release lock on %s",
                                 virDomainDiskGetSource(l_disk));
                    }
3082 3083 3084
                    goto cleanup;
                }

3085
                libxlUpdateDiskDef(l_disk, &x_disk);
3086 3087 3088
                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
3089 3090 3091
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
3092 3093 3094
            }
            break;
        default:
3095 3096 3097
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
3098 3099 3100
            break;
    }

3101
 cleanup:
J
Jim Fehlig 已提交
3102
    virObjectUnref(cfg);
3103 3104 3105
    return ret;
}

3106 3107 3108 3109 3110
static int
libxlDomainAttachHostPCIDevice(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
J
Jim Fehlig 已提交
3111
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3112
    libxl_device_pci pcidev;
3113 3114
    virDomainHostdevDefPtr found;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
3115
    virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
J
Jim Fehlig 已提交
3116
    int ret = -1;
3117

3118 3119
    libxl_device_pci_init(&pcidev);

3120 3121
    if (virDomainHostdevFind(vm->def, hostdev, &found) >= 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
3122 3123
                       _("target pci device " VIR_PCI_DEVICE_ADDRESS_FMT
                         " already exists"),
3124 3125
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
J
Jim Fehlig 已提交
3126
        goto cleanup;
3127 3128 3129
    }

    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs + 1) < 0)
J
Jim Fehlig 已提交
3130
        goto cleanup;
3131 3132 3133 3134

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

3137
    if (libxlMakePCI(hostdev, &pcidev) < 0)
C
Chunyan Liu 已提交
3138
        goto error;
3139

J
Jim Fehlig 已提交
3140
    if (libxl_device_pci_add(cfg->ctx, vm->def->id, &pcidev, 0) < 0) {
3141
        virReportError(VIR_ERR_INTERNAL_ERROR,
3142 3143
                       _("libxenlight failed to attach pci device "
                         VIR_PCI_DEVICE_ADDRESS_FMT),
3144 3145
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3146
        goto error;
3147 3148 3149
    }

    vm->def->hostdevs[vm->def->nhostdevs++] = hostdev;
J
Jim Fehlig 已提交
3150 3151
    ret = 0;
    goto cleanup;
3152

3153
 error:
3154 3155
    virHostdevReAttachPCIDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                 vm->def->name, &hostdev, 1, NULL);
J
Jim Fehlig 已提交
3156 3157 3158

 cleanup:
    virObjectUnref(cfg);
3159
    libxl_device_pci_dispose(&pcidev);
J
Jim Fehlig 已提交
3160
    return ret;
3161 3162
}

3163
#ifdef LIBXL_HAVE_PVUSB
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217
static int
libxlDomainAttachControllerDevice(libxlDriverPrivatePtr driver,
                                  virDomainObjPtr vm,
                                  virDomainControllerDefPtr controller)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    const char *type = virDomainControllerTypeToString(controller->type);
    libxl_device_usbctrl usbctrl;
    int ret = -1;

    libxl_device_usbctrl_init(&usbctrl);

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

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

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

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

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

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

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

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

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

3218 3219 3220 3221 3222 3223 3224 3225 3226
static int
libxlDomainAttachHostUSBDevice(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    libxl_device_usbdev usbdev;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
    int ret = -1;
3227 3228
    size_t i;
    int ports = 0, usbdevs = 0;
3229 3230 3231 3232 3233 3234 3235

    libxl_device_usbdev_init(&usbdev);

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

3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
    /* search for available controller:port */
    for (i = 0; i < vm->def->ncontrollers; i++)
        ports += vm->def->controllers[i]->opts.usbopts.ports;

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

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

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

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

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

3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs + 1) < 0)
        goto cleanup;

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

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

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

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

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

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

3299 3300 3301
static int
libxlDomainAttachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3302
                            virDomainHostdevDefPtr hostdev)
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312
{
    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 已提交
3313
        if (libxlDomainAttachHostPCIDevice(driver, vm, hostdev) < 0)
C
Chunyan Liu 已提交
3314
            return -1;
3315 3316
        break;

3317 3318 3319 3320 3321 3322 3323
#ifdef LIBXL_HAVE_PVUSB
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
        if (libxlDomainAttachHostUSBDevice(driver, vm, hostdev) < 0)
            return -1;
        break;
#endif

3324 3325 3326 3327
    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
C
Chunyan Liu 已提交
3328
        return -1;
3329 3330 3331 3332 3333
    }

    return 0;
}

3334
static int
J
Jim Fehlig 已提交
3335
libxlDomainDetachDeviceDiskLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3336
{
J
Jim Fehlig 已提交
3337
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(libxl_driver);
3338 3339
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
3340
    int idx;
3341 3342 3343 3344 3345 3346
    int ret = -1;

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

3347 3348 3349
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
3350 3351
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3352 3353 3354
                    goto cleanup;
                }

3355
                l_disk = vm->def->disks[idx];
3356

J
Jim Fehlig 已提交
3357
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3358 3359
                    goto cleanup;

J
Jim Fehlig 已提交
3360
                if ((ret = libxl_device_disk_remove(cfg->ctx, vm->def->id,
J
Jim Fehlig 已提交
3361
                                                    &x_disk, NULL)) < 0) {
3362 3363 3364
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3365 3366 3367
                    goto cleanup;
                }

3368 3369
                if (virDomainLockImageDetach(libxl_driver->lockManager,
                                             vm, l_disk->src) < 0)
3370 3371 3372
                    VIR_WARN("Unable to release lock on %s",
                             virDomainDiskGetSource(l_disk));

3373
                virDomainDiskRemove(vm->def, idx);
3374 3375 3376
                virDomainDiskDefFree(l_disk);

            } else {
3377 3378 3379
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3380 3381 3382
            }
            break;
        default:
3383 3384 3385
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3386 3387 3388
            break;
    }

3389
 cleanup:
J
Jim Fehlig 已提交
3390
    virObjectUnref(cfg);
3391 3392 3393
    return ret;
}

3394 3395 3396 3397 3398
static int
libxlDomainAttachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3399
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3400
    virDomainNetType actualType;
3401 3402
    libxl_device_nic nic;
    int ret = -1;
3403
    char mac[VIR_MAC_STRING_BUFLEN];
3404
    virConnectPtr conn = NULL;
3405
    virErrorPtr save_err = NULL;
3406

3407 3408
    libxl_device_nic_init(&nic);

3409 3410
    /* preallocate new slot for device */
    if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets + 1) < 0)
3411
        goto cleanup;
3412 3413 3414 3415 3416

    /* 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.
     */
3417 3418 3419 3420 3421 3422
    if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
        if (!(conn = virGetConnectNetwork()))
            goto cleanup;
        if (virDomainNetAllocateActualDevice(conn, vm->def, net) < 0)
            goto cleanup;
    }
3423 3424 3425

    actualType = virDomainNetGetActualType(net);

3426 3427 3428 3429
    if (virDomainHasNet(vm->def, net)) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("network device with mac %s already exists"),
                       virMacAddrFormat(&net->mac, mac));
3430
        goto cleanup;
3431 3432
    }

3433
    if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV) {
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444
        virDomainHostdevDefPtr hostdev = virDomainNetGetActualHostdev(net);
        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;

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

3445 3446 3447
        /* 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
3448
         * the nets list if successful.
3449
         */
3450
        ret = libxlDomainAttachHostDevice(driver, vm, hostdev);
3451
        goto cleanup;
3452 3453
    }

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

J
Jim Fehlig 已提交
3457
    if (libxl_device_nic_add(cfg->ctx, vm->def->id, &nic, 0)) {
3458 3459 3460 3461 3462 3463 3464 3465
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to attach network device"));
        goto cleanup;
    }

    ret = 0;

 cleanup:
3466
    virErrorPreserveLast(&save_err);
3467
    libxl_device_nic_dispose(&nic);
3468 3469 3470
    if (!ret) {
        vm->def->nets[vm->def->nnets++] = net;
    } else {
3471
        virDomainNetRemoveHostdev(vm->def, net);
3472 3473
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK && conn)
            virDomainNetReleaseActualDevice(conn, vm->def, net);
3474
    }
3475
    virObjectUnref(conn);
J
Jim Fehlig 已提交
3476
    virObjectUnref(cfg);
3477
    virErrorRestore(&save_err);
3478 3479 3480
    return ret;
}

3481
static int
3482 3483
libxlDomainAttachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3484 3485 3486 3487 3488 3489
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
J
Jim Fehlig 已提交
3490
            ret = libxlDomainAttachDeviceDiskLive(vm, dev);
3491 3492 3493 3494
            if (!ret)
                dev->data.disk = NULL;
            break;

3495
#ifdef LIBXL_HAVE_PVUSB
3496 3497 3498 3499 3500
        case VIR_DOMAIN_DEVICE_CONTROLLER:
            ret = libxlDomainAttachControllerDevice(driver, vm, dev->data.controller);
            if (!ret)
                dev->data.controller = NULL;
            break;
3501
#endif
3502

3503
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3504
            ret = libxlDomainAttachNetDevice(driver, vm,
3505 3506 3507 3508 3509
                                             dev->data.net);
            if (!ret)
                dev->data.net = NULL;
            break;

3510
        case VIR_DOMAIN_DEVICE_HOSTDEV:
J
Jim Fehlig 已提交
3511
            ret = libxlDomainAttachHostDevice(driver, vm,
3512
                                              dev->data.hostdev);
3513 3514 3515 3516
            if (!ret)
                dev->data.hostdev = NULL;
            break;

3517
        default:
3518 3519 3520
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3521 3522 3523 3524 3525 3526 3527 3528 3529 3530
            break;
    }

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
3531
    virDomainNetDefPtr net;
3532
    virDomainHostdevDefPtr hostdev;
3533
    virDomainControllerDefPtr controller;
3534
    virDomainHostdevDefPtr found;
3535
    char mac[VIR_MAC_STRING_BUFLEN];
3536 3537 3538 3539

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3540
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3541 3542
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3543 3544
                return -1;
            }
3545
            if (virDomainDiskInsert(vmdef, disk) < 0)
3546 3547 3548 3549
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;
3550

3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565
        case VIR_DOMAIN_DEVICE_CONTROLLER:
            controller = dev->data.controller;
            if (controller->idx != -1 &&
                virDomainControllerFind(vmdef, controller->type,
                                        controller->idx) >= 0) {
                virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                               _("Target already exists"));
                return -1;
            }

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

3566 3567
        case VIR_DOMAIN_DEVICE_NET:
            net = dev->data.net;
3568 3569 3570 3571 3572 3573
            if (virDomainHasNet(vmdef, net)) {
                virReportError(VIR_ERR_INVALID_ARG,
                               _("network device with mac %s already exists"),
                               virMacAddrFormat(&net->mac, mac));
                return -1;
            }
3574 3575 3576 3577 3578
            if (virDomainNetInsert(vmdef, net))
                return -1;
            dev->data.net = NULL;
            break;

3579 3580 3581
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            hostdev = dev->data.hostdev;

3582 3583 3584 3585 3586 3587
            switch (hostdev->source.subsys.type) {
            case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_SCSI:
#ifndef LIBXL_HAVE_PVUSB
            case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
#endif
            case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_LAST:
3588
                return -1;
3589
            }
3590 3591

            if (virDomainHostdevFind(vmdef, hostdev, &found) >= 0) {
3592 3593
                virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                               _("device is already in the domain configuration"));
3594 3595 3596
                return -1;
            }

3597 3598
            if (virDomainHostdevInsert(vmdef, hostdev) < 0)
                return -1;
3599
            dev->data.hostdev = NULL;
3600
            break;
3601 3602

        default:
3603 3604
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3605 3606 3607 3608 3609 3610
            return -1;
    }
    return 0;
}

static int
3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643
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 已提交
3644
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3645
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
3646
    virDomainHostdevSubsysPCIPtr pcisrc = &subsys->u.pci;
3647 3648 3649 3650
    libxl_device_pci pcidev;
    virDomainHostdevDefPtr detach;
    int idx;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
J
Jim Fehlig 已提交
3651
    int ret = -1;
3652

3653 3654
    libxl_device_pci_init(&pcidev);

3655 3656 3657
    idx = virDomainHostdevFind(vm->def, hostdev, &detach);
    if (idx < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
3658 3659
                       _("host pci device " VIR_PCI_DEVICE_ADDRESS_FMT
                         " not found"),
3660 3661
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
J
Jim Fehlig 已提交
3662
        goto cleanup;
3663 3664 3665 3666
    }

    if (libxlIsMultiFunctionDevice(vm->def, detach->info)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
3667 3668
                       _("cannot hot unplug multifunction PCI device: "
                         VIR_PCI_DEVICE_ADDRESS_FMT),
3669 3670
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3671
        goto error;
3672 3673 3674
    }


3675
    if (libxlMakePCI(detach, &pcidev) < 0)
C
Chunyan Liu 已提交
3676
        goto error;
3677

J
Jim Fehlig 已提交
3678
    if (libxl_device_pci_remove(cfg->ctx, vm->def->id, &pcidev, 0) < 0) {
3679
        virReportError(VIR_ERR_INTERNAL_ERROR,
3680
                       _("libxenlight failed to detach pci device "
3681
                         VIR_PCI_DEVICE_ADDRESS_FMT),
3682 3683
                       pcisrc->addr.domain, pcisrc->addr.bus,
                       pcisrc->addr.slot, pcisrc->addr.function);
C
Chunyan Liu 已提交
3684
        goto error;
3685 3686 3687 3688 3689 3690 3691 3692
    }


    virDomainHostdevRemove(vm->def, idx);

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

J
Jim Fehlig 已提交
3693
    ret = 0;
3694

3695
 error:
3696
    virDomainHostdevDefFree(detach);
J
Jim Fehlig 已提交
3697 3698 3699

 cleanup:
    virObjectUnref(cfg);
3700
    libxl_device_pci_dispose(&pcidev);
J
Jim Fehlig 已提交
3701
    return ret;
3702 3703
}

3704
#ifdef LIBXL_HAVE_PVUSB
3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
static int
libxlDomainDetachControllerDevice(libxlDriverPrivatePtr driver,
                                  virDomainObjPtr vm,
                                  virDomainDeviceDefPtr dev)
{
    int idx, ret = -1;
    virDomainControllerDefPtr detach = NULL;
    virDomainControllerDefPtr controller = dev->data.controller;
    const char *type = virDomainControllerTypeToString(controller->type);
    libxl_device_usbctrl usbctrl;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);

    libxl_device_usbctrl_init(&usbctrl);

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

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

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

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

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

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

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

3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803
static int
libxlDomainDetachHostUSBDevice(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
    virDomainHostdevSubsysUSBPtr usbsrc = &subsys->u.usb;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
    libxl_device_usbdev usbdev;
    libxl_device_usbdev *usbdevs = NULL;
    int num = 0;
    virDomainHostdevDefPtr detach;
    int idx;
    size_t i;
    bool found = false;
    int ret = -1;

    libxl_device_usbdev_init(&usbdev);

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

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

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

    if (libxl_device_usbdev_remove(cfg->ctx, vm->def->id, &usbdev, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
3804 3805
                       _("libxenlight failed to detach USB device "
                         "Busnum: %3x, Devnum: %3x"),
3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824
                       usbsrc->bus, usbsrc->device);
        goto cleanup;
    }

    virDomainHostdevRemove(vm->def, idx);

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

    ret = 0;

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

3825 3826 3827
static int
libxlDomainDetachHostDevice(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3828
                            virDomainHostdevDefPtr hostdev)
3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840
{
    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 已提交
3841
            return libxlDomainDetachHostPCIDevice(driver, vm, hostdev);
3842

3843 3844 3845 3846 3847
#ifdef LIBXL_HAVE_PVUSB
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
            return libxlDomainDetachHostUSBDevice(driver, vm, hostdev);
#endif

3848 3849 3850 3851 3852 3853 3854 3855 3856
        default:
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected hostdev type %d"), subsys->type);
            break;
    }

    return -1;
}

3857 3858 3859 3860 3861
static int
libxlDomainDetachNetDevice(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm,
                           virDomainNetDefPtr net)
{
J
Jim Fehlig 已提交
3862
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3863 3864 3865 3866 3867
    int detachidx;
    virDomainNetDefPtr detach = NULL;
    libxl_device_nic nic;
    char mac[VIR_MAC_STRING_BUFLEN];
    int ret = -1;
3868
    virErrorPtr save_err = NULL;
3869

3870 3871
    libxl_device_nic_init(&nic);

3872
    if ((detachidx = virDomainNetFindIdx(vm->def, net)) < 0)
3873
        goto cleanup;
3874 3875 3876 3877 3878 3879 3880

    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 已提交
3881
        ret = libxlDomainDetachHostDevice(driver, vm,
3882
                                          virDomainNetGetActualHostdev(detach));
3883
        goto cleanup;
3884 3885
    }

J
Jim Fehlig 已提交
3886
    if (libxl_mac_to_device_nic(cfg->ctx, vm->def->id,
3887 3888 3889
                                virMacAddrFormat(&detach->mac, mac), &nic))
        goto cleanup;

J
Jim Fehlig 已提交
3890
    if (libxl_device_nic_remove(cfg->ctx, vm->def->id, &nic, 0)) {
3891 3892 3893 3894 3895 3896 3897 3898
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to detach network device"));
        goto cleanup;
    }

    ret = 0;

 cleanup:
3899
    virErrorPreserveLast(&save_err);
3900
    libxl_device_nic_dispose(&nic);
J
Jim Fehlig 已提交
3901
    if (!ret) {
3902 3903 3904 3905 3906 3907 3908 3909 3910
        if (detach->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            virConnectPtr conn = virGetConnectNetwork();
            if (conn) {
                virDomainNetReleaseActualDevice(conn, vm->def, detach);
                virObjectUnref(conn);
            } else {
                VIR_WARN("Unable to release network device '%s'", NULLSTR(detach->ifname));
            }
        }
J
Jim Fehlig 已提交
3911 3912
        virDomainNetRemove(vm->def, detachidx);
    }
J
Jim Fehlig 已提交
3913
    virObjectUnref(cfg);
3914
    virErrorRestore(&save_err);
3915 3916 3917
    return ret;
}

3918 3919 3920
static int
libxlDomainDetachDeviceLive(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
3921 3922
                            virDomainDeviceDefPtr dev)
{
3923
    virDomainHostdevDefPtr hostdev;
3924 3925 3926 3927
    int ret = -1;

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

3931
#ifdef LIBXL_HAVE_PVUSB
3932 3933 3934
        case VIR_DOMAIN_DEVICE_CONTROLLER:
            ret = libxlDomainDetachControllerDevice(driver, vm, dev);
            break;
3935
#endif
3936

3937
        case VIR_DOMAIN_DEVICE_NET:
J
Jim Fehlig 已提交
3938
            ret = libxlDomainDetachNetDevice(driver, vm,
3939 3940 3941
                                             dev->data.net);
            break;

3942
        case VIR_DOMAIN_DEVICE_HOSTDEV:
3943 3944 3945 3946 3947
            hostdev = dev->data.hostdev;

            /* If this is a network hostdev, we need to use the higher-level
             * detach function so that mac address / virtualport are reset
             */
3948
            if (hostdev->parentnet)
3949
                ret = libxlDomainDetachNetDevice(driver, vm,
3950
                                                 hostdev->parentnet);
3951 3952
            else
                ret = libxlDomainDetachHostDevice(driver, vm, hostdev);
3953 3954
            break;

3955
        default:
3956 3957 3958
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
3959 3960 3961 3962 3963 3964
            break;
    }

    return ret;
}

3965

3966 3967 3968
static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3969
    virDomainDiskDefPtr disk, detach;
3970
    virDomainHostdevDefPtr hostdev, det_hostdev;
3971
    virDomainControllerDefPtr cont, det_cont;
3972
    virDomainNetDefPtr net;
3973
    int idx;
3974 3975 3976 3977

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3978
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3979 3980
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3981
                return -1;
3982
            }
3983
            virDomainDiskDefFree(detach);
3984
            break;
3985

3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997
        case VIR_DOMAIN_DEVICE_CONTROLLER:
            cont = dev->data.controller;
            if ((idx = virDomainControllerFind(vmdef, cont->type,
                                               cont->idx)) < 0) {
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("device not present in domain configuration"));
                return -1;
            }
            det_cont = virDomainControllerRemove(vmdef, idx);
            virDomainControllerDefFree(det_cont);
            break;

3998 3999 4000 4001 4002 4003 4004 4005 4006
        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;

4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018
        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;
        }

4019
        default:
4020 4021
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
4022
            return -1;
4023 4024
    }

4025
    return 0;
4026 4027 4028
}

static int
J
Jim Fehlig 已提交
4029
libxlDomainUpdateDeviceLive(virDomainObjPtr vm, virDomainDeviceDefPtr dev)
4030 4031 4032 4033 4034 4035 4036 4037 4038
{
    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 已提交
4039
                    ret = libxlDomainChangeEjectableMedia(vm, disk);
4040 4041 4042 4043
                    if (ret == 0)
                        dev->data.disk = NULL;
                    break;
                default:
4044 4045 4046
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
4047 4048 4049 4050
                    break;
            }
            break;
        default:
4051 4052 4053
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069
            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;
4070
            if (!(orig = virDomainDiskByName(vmdef, disk->dst, false))) {
4071 4072
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
4073 4074 4075
                goto cleanup;
            }
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
4076 4077
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
4078 4079 4080
                goto cleanup;
            }

4081 4082 4083 4084 4085 4086
            if (virDomainDiskSetSource(orig, virDomainDiskGetSource(disk)) < 0)
                goto cleanup;
            virDomainDiskSetType(orig, virDomainDiskGetType(disk));
            virDomainDiskSetFormat(orig, virDomainDiskGetFormat(disk));
            if (virDomainDiskSetDriver(orig, virDomainDiskGetDriver(disk)) < 0)
                goto cleanup;
4087 4088
            break;
        default:
4089 4090
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
4091 4092 4093 4094 4095
            goto cleanup;
    }

    ret = 0;

4096
 cleanup:
4097 4098 4099 4100 4101
    return ret;
}


static int
4102 4103
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
4104 4105
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4106
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4107 4108 4109 4110 4111 4112 4113 4114
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
4115
    if (!(vm = libxlDomObjFromDomain(dom)))
4116 4117
        goto cleanup;

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

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

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

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

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

4138
        if (libxlDomainAttachDeviceConfig(vmdef, dev) < 0)
4139
            goto endjob;
4140
    }
4141 4142 4143 4144

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

J
Jim Fehlig 已提交
4150
        if (libxlDomainAttachDeviceLive(driver, vm, dev) < 0)
4151
            goto endjob;
4152

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

4161 4162
    ret = 0;

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

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

4175
 cleanup:
4176 4177
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
W
Wang Yufei 已提交
4178
    virDomainObjEndAPI(&vm);
4179
    virObjectUnref(cfg);
4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
    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)
{
4194
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4195
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4196 4197 4198 4199 4200 4201 4202 4203
    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 已提交
4204
    if (!(vm = libxlDomObjFromDomain(dom)))
4205 4206
        goto cleanup;

4207 4208 4209
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4210 4211 4212
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

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

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
4218
                                            cfg->caps, driver->xmlopt, NULL,
4219 4220
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                            VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
4221
            goto endjob;
4222 4223

        /* Make a copy for updated domain. */
4224
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
4225
                                                    driver->xmlopt, NULL)))
4226
            goto endjob;
4227

4228
        if (libxlDomainDetachDeviceConfig(vmdef, dev) < 0)
4229
            goto endjob;
4230 4231 4232 4233 4234 4235
    }

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
4236
                                            cfg->caps, driver->xmlopt, NULL,
4237 4238
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                            VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
4239
            goto endjob;
4240

J
Jim Fehlig 已提交
4241
        if (libxlDomainDetachDeviceLive(driver, vm, dev) < 0)
4242
            goto endjob;
4243 4244 4245 4246 4247

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

4252 4253
    ret = 0;

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

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

4266
 cleanup:
4267 4268
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
W
Wang Yufei 已提交
4269
    virDomainObjEndAPI(&vm);
4270
    virObjectUnref(cfg);
4271
    return ret;
4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284
}

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)
{
4285
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4286
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4287 4288 4289 4290 4291 4292 4293 4294
    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 已提交
4295
    if (!(vm = libxlDomObjFromDomain(dom)))
4296 4297
        goto cleanup;

4298 4299 4300
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4301 4302
    if (virDomainObjUpdateModificationImpact(vm, &flags) < 0)
        goto cleanup;
4303 4304 4305

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
4306
                                            cfg->caps, driver->xmlopt, NULL,
4307
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
4308 4309 4310
            goto cleanup;

        /* Make a copy for updated domain. */
4311
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
4312
                                                    driver->xmlopt, NULL)))
4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324
            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,
4325
                                            cfg->caps, driver->xmlopt, NULL,
4326
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE)))
4327 4328
            goto cleanup;

J
Jim Fehlig 已提交
4329
        if ((ret = libxlDomainUpdateDeviceLive(vm, dev)) < 0)
4330 4331 4332 4333 4334 4335
            goto cleanup;

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
4336
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
4337 4338 4339 4340 4341
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
4342
        ret = virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef);
4343 4344 4345 4346 4347 4348
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

4349
 cleanup:
4350 4351
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
4352
    virDomainObjEndAPI(&vm);
4353
    virObjectUnref(cfg);
4354
    return ret;
4355 4356
}

4357 4358 4359 4360 4361
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
4362 4363
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
4364

4365
    libxl_physinfo_init(&phy_info);
4366
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
4367
        goto cleanup;
4368

4369
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
4370 4371
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
4372
        goto cleanup;
4373 4374
    }

4375 4376
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

4377
 cleanup:
4378
    libxl_physinfo_dispose(&phy_info);
4379 4380
    virObjectUnref(cfg);
    return ret;
4381 4382
}

4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
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;
4393
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4394 4395

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
4396
        goto cleanup;
4397

4398
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
4399
    if (numa_info == NULL || nr_nodes == 0) {
4400 4401 4402
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
4403 4404 4405
    }

    /* Check/sanitize the cell range */
4406
    if (startCell >= nr_nodes) {
4407 4408
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
4409
                       startCell, nr_nodes - 1);
4410 4411 4412
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
4413 4414
    if (lastCell >= nr_nodes)
        lastCell = nr_nodes - 1;
4415 4416 4417 4418 4419 4420 4421

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

4423 4424
    ret = numCells;

4425
 cleanup:
4426
    libxl_numainfo_list_free(numa_info, nr_nodes);
4427
    virObjectUnref(cfg);
4428 4429 4430
    return ret;
}

4431
static int
4432
libxlConnectDomainEventRegister(virConnectPtr conn,
4433 4434
                                virConnectDomainEventCallback callback,
                                void *opaque,
4435
                                virFreeCallback freecb)
4436 4437 4438
{
    libxlDriverPrivatePtr driver = conn->privateData;

4439 4440 4441
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

4442 4443 4444 4445
    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        return -1;
4446

4447
    return 0;
4448 4449 4450 4451
}


static int
4452 4453
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
4454 4455 4456
{
    libxlDriverPrivatePtr driver = conn->privateData;

4457 4458 4459
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

4460 4461 4462 4463
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
4464

4465
    return 0;
4466 4467
}

4468 4469 4470 4471 4472 4473
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4474
    if (!(vm = libxlDomObjFromDomain(dom)))
4475 4476
        goto cleanup;

4477 4478 4479
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4480 4481 4482
    *autostart = vm->autostart;
    ret = 0;

4483
 cleanup:
4484
    virDomainObjEndAPI(&vm);
4485 4486 4487 4488 4489 4490 4491
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4492
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4493 4494 4495 4496
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
4497
    if (!(vm = libxlDomObjFromDomain(dom)))
4498 4499
        goto cleanup;

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

4502 4503 4504
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4505 4506 4507
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4508
    if (!vm->persistent) {
4509 4510
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
4511
        goto endjob;
4512 4513 4514 4515 4516
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
4517
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
4518
            goto endjob;
4519
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
4520
            goto endjob;
4521 4522

        if (autostart) {
4523
            if (virFileMakePath(cfg->autostartDir) < 0) {
4524
                virReportSystemError(errno,
4525
                                     _("cannot create autostart directory %s"),
4526
                                     cfg->autostartDir);
4527
                goto endjob;
4528 4529 4530 4531 4532 4533
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4534
                goto endjob;
4535 4536 4537 4538 4539 4540
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4541
                goto endjob;
4542 4543 4544 4545 4546 4547 4548
            }
        }

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

4549
 endjob:
W
Wang Yufei 已提交
4550
    libxlDomainObjEndJob(driver, vm);
4551

4552
 cleanup:
4553 4554
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
W
Wang Yufei 已提交
4555
    virDomainObjEndAPI(&vm);
4556
    virObjectUnref(cfg);
4557 4558 4559
    return ret;
}

4560 4561 4562
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
J
Jim Fehlig 已提交
4563 4564
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4565 4566
    virDomainObjPtr vm;
    char * ret = NULL;
4567
    const char *name = NULL;
J
Jim Fehlig 已提交
4568
    libxl_scheduler sched_id;
4569

J
Jim Fehlig 已提交
4570
    if (!(vm = libxlDomObjFromDomain(dom)))
4571 4572
        goto cleanup;

4573 4574 4575
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4576
    if (virDomainObjCheckActive(vm) < 0)
4577 4578
        goto cleanup;

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

4581 4582
    if (nparams)
        *nparams = 0;
4583
    switch ((int)sched_id) {
J
Jim Fehlig 已提交
4584
    case LIBXL_SCHEDULER_SEDF:
4585
        name = "sedf";
4586
        break;
J
Jim Fehlig 已提交
4587
    case LIBXL_SCHEDULER_CREDIT:
4588
        name = "credit";
4589 4590
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
4591
        break;
J
Jim Fehlig 已提交
4592
    case LIBXL_SCHEDULER_CREDIT2:
4593
        name = "credit2";
4594
        break;
J
Jim Fehlig 已提交
4595
    case LIBXL_SCHEDULER_ARINC653:
4596
        name = "arinc653";
4597 4598
        break;
    default:
J
Jim Fehlig 已提交
4599 4600
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
4601
                     " with libxenlight"), vm->def->id);
4602 4603 4604
        goto cleanup;
    }

4605
    ignore_value(VIR_STRDUP(ret, name));
4606

4607
 cleanup:
4608
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
4609
    virObjectUnref(cfg);
4610 4611 4612
    return ret;
}

4613
static int
4614 4615 4616 4617
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
4618
{
J
Jim Fehlig 已提交
4619 4620
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4621
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4622 4623
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
4624 4625
    int ret = -1;

4626 4627 4628 4629
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

J
Jim Fehlig 已提交
4631
    if (!(vm = libxlDomObjFromDomain(dom)))
4632 4633
        goto cleanup;

4634 4635 4636
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4637
    if (virDomainObjCheckActive(vm) < 0)
4638 4639
        goto cleanup;

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

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

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

4655 4656
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
4657 4658
        goto cleanup;

4659
    if (*nparams > 1) {
4660
        if (virTypedParameterAssign(&params[1], VIR_DOMAIN_SCHEDULER_CAP,
4661
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
4662
            goto cleanup;
4663 4664
    }

4665 4666
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
4667 4668
    ret = 0;

4669
 cleanup:
4670
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
4671
    virObjectUnref(cfg);
4672 4673 4674 4675
    return ret;
}

static int
4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686
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)
4687
{
4688
    libxlDriverPrivatePtr driver = dom->conn->privateData;
J
Jim Fehlig 已提交
4689
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4690
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4691
    libxl_domain_sched_params sc_info;
4692
    int sched_id;
4693
    size_t i;
4694 4695
    int ret = -1;

4696
    virCheckFlags(0, -1);
4697 4698 4699 4700 4701 4702
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
4703
        return -1;
4704

J
Jim Fehlig 已提交
4705
    if (!(vm = libxlDomObjFromDomain(dom)))
4706 4707
        goto cleanup;

4708 4709 4710
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

4711 4712 4713
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

4714
    if (virDomainObjCheckActive(vm) < 0)
4715
        goto endjob;
4716

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

J
Jim Fehlig 已提交
4719
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4720 4721
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4722
        goto endjob;
4723 4724
    }

J
Jim Fehlig 已提交
4725
    if (libxl_domain_sched_params_get(cfg->ctx, vm->def->id, &sc_info) != 0) {
4726 4727
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
4728
                         " with libxenlight"), vm->def->id);
4729
        goto endjob;
4730 4731 4732
    }

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

4735
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
4736
            sc_info.weight = params[i].value.ui;
4737
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
4738 4739 4740
            sc_info.cap = params[i].value.ui;
    }

J
Jim Fehlig 已提交
4741
    if (libxl_domain_sched_params_set(cfg->ctx, vm->def->id, &sc_info) != 0) {
4742 4743
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
4744
                         " with libxenlight"), vm->def->id);
4745
        goto endjob;
4746 4747 4748 4749
    }

    ret = 0;

4750
 endjob:
W
Wang Yufei 已提交
4751
    libxlDomainObjEndJob(driver, vm);
4752

4753
 cleanup:
W
Wang Yufei 已提交
4754
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
4755
    virObjectUnref(cfg);
4756 4757 4758
    return ret;
}

B
Bamvor Jian Zhang 已提交
4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772

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

    virCheckFlags(VIR_DOMAIN_CONSOLE_FORCE, -1);

J
Jim Fehlig 已提交
4773
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
4774 4775
        goto cleanup;

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

B
Bamvor Jian Zhang 已提交
4778 4779 4780
    if (virDomainOpenConsoleEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4781
    if (virDomainObjCheckActive(vm) < 0)
B
Bamvor Jian Zhang 已提交
4782 4783 4784
        goto cleanup;

    priv = vm->privateData;
B
Bob Liu 已提交
4785 4786
    if (dev_name) {
        size_t i;
B
Bamvor Jian Zhang 已提交
4787

B
Bob Liu 已提交
4788 4789 4790 4791 4792 4793 4794
        for (i = 0; !chr && i < vm->def->nserials; i++) {
            if (STREQ(dev_name, vm->def->serials[i]->info.alias)) {
                chr = vm->def->serials[i];
                break;
            }
        }
    } else if (vm->def->nconsoles) {
I
Ian Campbell 已提交
4795
        chr = vm->def->consoles[0];
4796 4797 4798
        if (chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL)
            chr = vm->def->serials[0];
    }
B
Bamvor Jian Zhang 已提交
4799 4800 4801 4802 4803 4804 4805 4806

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

4807
    if (chr->source->type != VIR_DOMAIN_CHR_TYPE_PTY) {
B
Bamvor Jian Zhang 已提交
4808 4809
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("character device %s is not using a PTY"),
4810
                       dev_name ? dev_name : NULLSTR(chr->info.alias));
B
Bamvor Jian Zhang 已提交
4811 4812 4813 4814 4815
        goto cleanup;
    }

    /* handle mutually exclusive access to console devices */
    ret = virChrdevOpen(priv->devs,
4816
                        chr->source,
B
Bamvor Jian Zhang 已提交
4817 4818 4819 4820 4821 4822 4823 4824 4825
                        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;
    }

4826
 cleanup:
4827
    virDomainObjEndAPI(&vm);
B
Bamvor Jian Zhang 已提交
4828 4829 4830
    return ret;
}

4831 4832 4833 4834 4835 4836 4837
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850
/* 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 已提交
4851 4852
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868
    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;

4869 4870
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
4871
    if (!(vm = libxlDomObjFromDomain(dom)))
4872 4873 4874 4875 4876
        goto cleanup;

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

4877
    if (virDomainObjCheckActive(vm) < 0)
4878 4879 4880 4881 4882 4883 4884 4885 4886 4887
        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];
4888
        int numnodes;
4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906

        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 已提交
4907
            numnodes = libxl_get_max_nodes(cfg->ctx);
4908 4909 4910
            if (numnodes <= 0)
                goto cleanup;

J
Jim Fehlig 已提交
4911
            if (libxl_node_bitmap_alloc(cfg->ctx, &nodemap, 0)) {
4912 4913 4914
                virReportOOMError();
                goto cleanup;
            }
J
Ján Tomko 已提交
4915 4916
            if (!(nodes = virBitmapNew(numnodes)))
                goto cleanup;
4917

J
Jim Fehlig 已提交
4918
            rc = libxl_domain_get_nodeaffinity(cfg->ctx,
4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937
                                               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;
                }
            }

4938
            if (!(nodeset = virBitmapFormat(nodes)))
4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954
                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;

4955
 cleanup:
4956 4957 4958
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
4959
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
4960
    virObjectUnref(cfg);
4961 4962 4963 4964
    return ret;
}
#endif

J
Jim Fehlig 已提交
4965 4966 4967 4968 4969 4970
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4971
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4972
        goto cleanup;
4973 4974 4975 4976

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

J
Jim Fehlig 已提交
4977 4978
    ret = virDomainObjIsActive(obj);

4979
 cleanup:
4980
    virDomainObjEndAPI(&obj);
J
Jim Fehlig 已提交
4981 4982 4983 4984 4985 4986 4987 4988 4989
    return ret;
}

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

J
Jim Fehlig 已提交
4990
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4991
        goto cleanup;
4992 4993 4994 4995

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

J
Jim Fehlig 已提交
4996 4997
    ret = obj->persistent;

4998
 cleanup:
4999
    virDomainObjEndAPI(&obj);
J
Jim Fehlig 已提交
5000 5001 5002
    return ret;
}

5003 5004 5005 5006 5007 5008
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
5009
    if (!(vm = libxlDomObjFromDomain(dom)))
5010
        goto cleanup;
5011 5012 5013 5014

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

5015 5016
    ret = vm->updated;

5017
 cleanup:
5018
    virDomainObjEndAPI(&vm);
5019 5020 5021
    return ret;
}

5022 5023
static int
libxlDomainInterfaceStats(virDomainPtr dom,
5024
                          const char *device,
5025 5026 5027 5028
                          virDomainInterfaceStatsPtr stats)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
M
Michal Privoznik 已提交
5029
    virDomainNetDefPtr net = NULL;
5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040
    int ret = -1;

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

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

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

5041
    if (virDomainObjCheckActive(vm) < 0)
5042 5043
        goto endjob;

5044
    if (!(net = virDomainNetFind(vm->def, device)))
M
Michal Privoznik 已提交
5045 5046
        goto endjob;

5047
    if (virNetDevTapInterfaceStats(net->ifname, stats,
5048
                                   !virDomainNetTypeSharesHostView(net)) < 0)
M
Michal Privoznik 已提交
5049 5050 5051
        goto endjob;

    ret = 0;
5052 5053

 endjob:
W
Wang Yufei 已提交
5054
    libxlDomainObjEndJob(driver, vm);
5055 5056

 cleanup:
W
Wang Yufei 已提交
5057
    virDomainObjEndAPI(&vm);
5058 5059 5060
    return ret;
}

5061 5062 5063 5064 5065 5066
static int
libxlDomainGetTotalCPUStats(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
                            virTypedParameterPtr params,
                            unsigned int nparams)
{
J
Jim Fehlig 已提交
5067
    libxlDriverConfigPtr cfg;
5068 5069 5070 5071 5072 5073
    libxl_dominfo d_info;
    int ret = -1;

    if (nparams == 0)
        return LIBXL_NB_TOTAL_CPU_STAT_PARAM;

J
Jim Fehlig 已提交
5074 5075 5076
    libxl_dominfo_init(&d_info);
    cfg = libxlDriverConfigGet(driver);

5077 5078 5079 5080
    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 已提交
5081
        goto cleanup;
5082 5083 5084 5085 5086 5087 5088 5089 5090 5091
    }

    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 已提交
5092
    virObjectUnref(cfg);
5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106
    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 已提交
5107
    libxlDriverConfigPtr cfg;
5108 5109 5110 5111 5112
    int ret = -1;

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

J
Jim Fehlig 已提交
5115
    cfg = libxlDriverConfigGet(driver);
5116 5117 5118 5119 5120
    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 已提交
5121
        goto cleanup;
5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133
    }

    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 已提交
5134 5135 5136
    if (vcpuinfo)
        libxl_vcpuinfo_list_free(vcpuinfo, maxcpu);
    virObjectUnref(cfg);
5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159
    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;

5160
    if (virDomainObjCheckActive(vm) < 0)
5161 5162 5163 5164 5165 5166 5167 5168 5169
        goto cleanup;

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

 cleanup:
5170
    virDomainObjEndAPI(&vm);
5171 5172 5173
    return ret;
}

5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187
#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 已提交
5188
    libxlDriverConfigPtr cfg;
5189 5190 5191 5192 5193 5194 5195 5196
    virDomainObjPtr vm;
    libxl_dominfo d_info;
    unsigned mem, maxmem;
    size_t i = 0;
    int ret = -1;

    virCheckFlags(0, -1);

5197
    libxl_dominfo_init(&d_info);
J
Jim Fehlig 已提交
5198 5199
    cfg = libxlDriverConfigGet(driver);

5200 5201 5202 5203 5204 5205 5206 5207 5208
    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;

5209
    if (virDomainObjCheckActive(vm) < 0)
5210 5211 5212 5213 5214 5215 5216 5217 5218
        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;
5219
    maxmem = virDomainDefGetMemoryTotal(vm->def);
5220 5221 5222 5223 5224 5225 5226

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

    ret = i;

 endjob:
W
Wang Yufei 已提交
5227
    libxlDomainObjEndJob(driver, vm);
5228 5229

 cleanup:
5230
    libxl_dominfo_dispose(&d_info);
W
Wang Yufei 已提交
5231
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
5232
    virObjectUnref(cfg);
5233 5234 5235 5236 5237
    return ret;
}

#undef LIBXL_SET_MEMSTAT

5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269
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:
5270
    virDomainObjEndAPI(&vm);
5271 5272 5273
    return ret;
}

5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320
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:
5321
    virDomainObjEndAPI(&vm);
5322 5323
    return ret;
}
5324

R
Roman Bogorodskiy 已提交
5325
#ifdef __linux__
5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372
static int
libxlDiskPathToID(const char *virtpath)
{
    static char const* drive_prefix[] = {"xvd", "hd", "sd"};
    int disk, partition, chrused;
    int fmt, id;
    size_t i;

    fmt = id = -1;

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

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

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

5373
# define LIBXL_VBD_SECTOR_SIZE 512
5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423

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

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

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

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

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

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

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

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

static int
libxlDomainBlockStatsVBD(virDomainObjPtr vm,
                         const char *dev,
                         libxlBlockStatsPtr stats)
{
    int ret = -1;
    int devno = libxlDiskPathToID(dev);
    int size;
    char *path, *name, *val;
5424
    unsigned long long status;
5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447

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

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

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

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

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

5448
# define LIBXL_SET_VBDSTAT(FIELD, VAR, MUL) \
5449
    if ((virAsprintf(&name, "%s/"FIELD, path) < 0) || \
5450 5451 5452 5453 5454 5455 5456 5457
        (virFileReadAll(name, 256, &val) < 0) || \
        (sscanf(val, "%llu", &status) != 1)) { \
        virReportError(VIR_ERR_OPERATION_FAILED, \
                       _("cannot read %s"), name); \
        goto cleanup; \
    } \
    VAR += (status * MUL); \
    VIR_FREE(name); \
5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510
    VIR_FREE(val);

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

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

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

# undef LIBXL_SET_VBDSTAT

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

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

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

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

    if (STREQ(disk_drv, "phy")) {
5511
        if (disk_fmt != VIR_STORAGE_FILE_RAW) {
5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                           _("unsupported format %s"),
                           virStorageFileFormatTypeToString(disk_fmt));
            return ret;
        }

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

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

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

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

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

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

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

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

5568
    if (virDomainObjCheckActive(vm) < 0)
5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617
        goto endjob;

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

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

 endjob:
    libxlDomainObjEndJob(driver, vm);

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

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

    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

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

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

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

5618
    if (virDomainObjCheckActive(vm) < 0)
5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633
        goto endjob;

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

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

    nstats = 0;

5634 5635 5636
#define LIBXL_BLKSTAT_ASSIGN_PARAM(VAR, NAME) \
    if (nstats < *nparams && (blkstats.VAR) != -1) { \
        if (virTypedParameterAssign(params + nstats, NAME, \
5637
                                    VIR_TYPED_PARAM_LLONG, (blkstats.VAR)) < 0) \
5638 5639
            goto endjob; \
        nstats++; \
5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664
    }

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

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

    LIBXL_BLKSTAT_ASSIGN_PARAM(f_req, VIR_DOMAIN_BLOCK_STATS_FLUSH_REQ);

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

    *nparams = nstats;

#undef LIBXL_BLKSTAT_ASSIGN_PARAM

 endjob:
    libxlDomainObjEndJob(driver, vm);

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

5665
static int
5666 5667 5668
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
5669 5670 5671 5672
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

5673 5674 5675
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

5676 5677 5678 5679
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
5680
        ret = -1;
5681 5682 5683 5684 5685 5686

    return ret;
}


static int
5687
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
5688 5689 5690
{
    libxlDriverPrivatePtr driver = conn->privateData;

5691 5692 5693
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

5694 5695
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
5696
                                        callbackID, true) < 0)
5697
        return -1;
5698

5699
    return 0;
5700 5701
}

J
Jim Fehlig 已提交
5702

5703
static int
5704
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
5705 5706 5707 5708
{
    return 1;
}

5709
static int
5710 5711 5712
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
5713 5714 5715 5716
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
5717
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
5718

5719 5720 5721
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

5722 5723
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
5724 5725 5726 5727

    return ret;
}

5728 5729 5730 5731 5732 5733 5734
/* Which features are supported by this driver? */
static int
libxlConnectSupportsFeature(virConnectPtr conn, int feature)
{
    if (virConnectSupportsFeatureEnsureACL(conn) < 0)
        return -1;

5735
    switch ((virDrvFeature) feature) {
5736
    case VIR_DRV_FEATURE_MIGRATION_V3:
5737
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
J
Jim Fehlig 已提交
5738
    case VIR_DRV_FEATURE_MIGRATION_PARAMS:
J
Joao Martins 已提交
5739
    case VIR_DRV_FEATURE_MIGRATION_P2P:
5740
        return 1;
5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751
    case VIR_DRV_FEATURE_FD_PASSING:
    case VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION:
    case VIR_DRV_FEATURE_MIGRATION_DIRECT:
    case VIR_DRV_FEATURE_MIGRATION_OFFLINE:
    case VIR_DRV_FEATURE_MIGRATION_V1:
    case VIR_DRV_FEATURE_MIGRATION_V2:
    case VIR_DRV_FEATURE_PROGRAM_KEEPALIVE:
    case VIR_DRV_FEATURE_REMOTE:
    case VIR_DRV_FEATURE_REMOTE_CLOSE_CALLBACK:
    case VIR_DRV_FEATURE_REMOTE_EVENT_CALLBACK:
    case VIR_DRV_FEATURE_XML_MIGRATABLE:
5752 5753 5754 5755
    default:
        return 0;
    }
}
5756

5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767
static int
libxlNodeDeviceGetPCIInfo(virNodeDeviceDefPtr def,
                          unsigned *domain,
                          unsigned *bus,
                          unsigned *slot,
                          unsigned *function)
{
    virNodeDevCapsDefPtr cap;

    cap = def->caps;
    while (cap) {
5768
        if (cap->data.type == VIR_NODE_DEV_CAP_PCI_DEV) {
5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781
            *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 已提交
5782
        return -1;
5783 5784
    }

C
Chunyan Liu 已提交
5785
    return 0;
5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821
}

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")) {
5822
        virPCIDeviceSetStubDriver(pci, VIR_PCI_STUB_DRIVER_XEN);
5823 5824 5825 5826 5827 5828 5829 5830 5831 5832
    } else {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported driver name '%s'"), driverName);
        goto cleanup;
    }

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

    ret = 0;
5833
 cleanup:
5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875
    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 已提交
5876
        goto cleanup;
5877 5878

    ret = 0;
C
Chunyan Liu 已提交
5879

5880
 cleanup:
C
Chunyan Liu 已提交
5881
    virPCIDeviceFree(pci);
5882 5883 5884 5885 5886 5887 5888 5889
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
C
Chunyan Liu 已提交
5890
    virPCIDevicePtr pci = NULL;
5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916
    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 已提交
5917
        goto cleanup;
5918 5919

    ret = 0;
C
Chunyan Liu 已提交
5920

5921
 cleanup:
C
Chunyan Liu 已提交
5922
    virPCIDeviceFree(pci);
5923 5924 5925 5926 5927
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

J
Jim Fehlig 已提交
5928 5929 5930 5931
static char *
libxlDomainMigrateBegin3Params(virDomainPtr domain,
                               virTypedParameterPtr params,
                               int nparams,
5932 5933
                               char **cookieout,
                               int *cookieoutlen,
J
Jim Fehlig 已提交
5934 5935 5936 5937
                               unsigned int flags)
{
    const char *xmlin = NULL;
    virDomainObjPtr vm = NULL;
5938
    char *xmlout = NULL;
J
Jim Fehlig 已提交
5939

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

J
Jim Fehlig 已提交
5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956
    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 已提交
5957
    if (STREQ_NULLABLE(vm->def->name, "Domain-0")) {
5958 5959 5960
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain-0 cannot be migrated"));
        goto cleanup;
J
Jim Fehlig 已提交
5961 5962
    }

5963 5964
    if (virDomainMigrateBegin3ParamsEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;
J
Jim Fehlig 已提交
5965

5966
    if (virDomainObjCheckActive(vm) < 0)
5967
        goto cleanup;
J
Jim Fehlig 已提交
5968

5969 5970
    xmlout = libxlDomainMigrationSrcBegin(domain->conn, vm, xmlin,
                                          cookieout, cookieoutlen);
5971 5972 5973 5974

 cleanup:
    virDomainObjEndAPI(&vm);
    return xmlout;
J
Jim Fehlig 已提交
5975 5976
}

B
Bob Liu 已提交
5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014
static int
libxlDomainMigratePrepareTunnel3Params(virConnectPtr dconn,
                                       virStreamPtr st,
                                       virTypedParameterPtr params,
                                       int nparams,
                                       const char *cookiein,
                                       int cookieinlen,
                                       char **cookieout ATTRIBUTE_UNUSED,
                                       int *cookieoutlen ATTRIBUTE_UNUSED,
                                       unsigned int flags)
{
    libxlDriverPrivatePtr driver = dconn->privateData;
    virDomainDefPtr def = NULL;
    const char *dom_xml = NULL;
    const char *dname = NULL;
    const char *uri_in = NULL;

#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

    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;

6015
    if (!(def = libxlDomainMigrationDstPrepareDef(driver, dom_xml, dname)))
B
Bob Liu 已提交
6016 6017 6018 6019 6020
        goto error;

    if (virDomainMigratePrepareTunnel3ParamsEnsureACL(dconn, def) < 0)
        goto error;

6021 6022
    if (libxlDomainMigrationDstPrepareTunnel3(dconn, st, &def, cookiein,
                                              cookieinlen, flags) < 0)
B
Bob Liu 已提交
6023 6024 6025 6026 6027 6028 6029 6030 6031
        goto error;

    return 0;

 error:
    virDomainDefFree(def);
    return -1;
}

J
Jim Fehlig 已提交
6032 6033 6034 6035
static int
libxlDomainMigratePrepare3Params(virConnectPtr dconn,
                                 virTypedParameterPtr params,
                                 int nparams,
6036 6037
                                 const char *cookiein,
                                 int cookieinlen,
J
Jim Fehlig 已提交
6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048
                                 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;

6049 6050 6051 6052 6053
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069
    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;

6070
    if (!(def = libxlDomainMigrationDstPrepareDef(driver, dom_xml, dname)))
J
Jim Fehlig 已提交
6071 6072 6073 6074 6075
        goto error;

    if (virDomainMigratePrepare3ParamsEnsureACL(dconn, def) < 0)
        goto error;

6076 6077
    if (libxlDomainMigrationDstPrepare(dconn, &def, uri_in, uri_out,
                                       cookiein, cookieinlen, flags) < 0)
J
Jim Fehlig 已提交
6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104
        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;

6105 6106 6107 6108 6109
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131
    virCheckFlags(LIBXL_MIGRATION_FLAGS, -1);
    if (virTypedParamsValidate(params, nparams, LIBXL_MIGRATION_PARAMETERS) < 0)
        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;

B
Bob Liu 已提交
6132
    if ((flags & (VIR_MIGRATE_TUNNELLED | VIR_MIGRATE_PEER2PEER))) {
6133 6134
        if (libxlDomainMigrationSrcPerformP2P(driver, vm, dom->conn, dom_xml,
                                              dconnuri, uri, dname, flags) < 0)
J
Joao Martins 已提交
6135 6136
            goto cleanup;
    } else {
6137 6138
        if (libxlDomainMigrationSrcPerform(driver, vm, dom_xml, dconnuri,
                                           uri, dname, flags) < 0)
J
Joao Martins 已提交
6139 6140
            goto cleanup;
    }
J
Jim Fehlig 已提交
6141 6142 6143 6144

    ret = 0;

 cleanup:
6145
    virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162
    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;
6163
    virDomainPtr ret = NULL;
J
Jim Fehlig 已提交
6164

6165 6166 6167 6168 6169
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return NULL;
#endif

J
Jim Fehlig 已提交
6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189
    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) {
6190
        virDomainObjEndAPI(&vm);
J
Jim Fehlig 已提交
6191 6192 6193
        return NULL;
    }

6194
    ret = libxlDomainMigrationDstFinish(dconn, vm, flags, cancelled);
6195

6196
    virDomainObjEndAPI(&vm);
6197 6198

    return ret;
J
Jim Fehlig 已提交
6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211
}

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;
6212
    int ret = -1;
J
Jim Fehlig 已提交
6213

6214 6215 6216 6217 6218
#ifdef LIBXL_HAVE_NO_SUSPEND_RESUME
    virReportUnsupportedError();
    return -1;
#endif

J
Jim Fehlig 已提交
6219 6220 6221 6222 6223 6224 6225
    virCheckFlags(LIBXL_MIGRATION_FLAGS, -1);
    if (virTypedParamsValidate(params, nparams, LIBXL_MIGRATION_PARAMETERS) < 0)
        return -1;

    if (!(vm = libxlDomObjFromDomain(domain)))
        return -1;

6226 6227
    if (virDomainMigrateConfirm3ParamsEnsureACL(domain->conn, vm->def) < 0)
        goto cleanup;
J
Jim Fehlig 已提交
6228

6229
    ret = libxlDomainMigrationSrcConfirm(driver, vm, flags, cancelled);
6230 6231 6232 6233

 cleanup:
    virDomainObjEndAPI(&vm);
    return ret;
J
Jim Fehlig 已提交
6234 6235
}

6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252
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;
}
6253

6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368
static int
libxlGetDHCPInterfaces(virDomainPtr dom,
                       virDomainObjPtr vm,
                       virDomainInterfacePtr **ifaces)
{
    int rv = -1;
    int n_leases = 0;
    size_t i, j;
    size_t ifaces_count = 0;
    virNetworkPtr network = NULL;
    char macaddr[VIR_MAC_STRING_BUFLEN];
    virDomainInterfacePtr iface = NULL;
    virNetworkDHCPLeasePtr *leases = NULL;
    virDomainInterfacePtr *ifaces_ret = NULL;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        VIR_FREE(leases);
    }

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

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

    return rv;

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

    goto cleanup;
}


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

    virCheckFlags(0, -1);

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

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

6369
    if (virDomainObjCheckActive(vm) < 0)
6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389
        goto cleanup;

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

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

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


6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437
static char *
libxlConnectGetDomainCapabilities(virConnectPtr conn,
                                  const char *emulatorbin,
                                  const char *arch_str,
                                  const char *machine,
                                  const char *virttype_str,
                                  unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    libxlDriverConfigPtr cfg;
    char *ret = NULL;
    int virttype = VIR_DOMAIN_VIRT_XEN;
    virDomainCapsPtr domCaps = NULL;
    int arch = virArchFromHost(); /* virArch */

    virCheckFlags(0, ret);

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

    cfg = libxlDriverConfigGet(driver);

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

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

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

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

    if (machine) {
6438 6439 6440
        if (STRNEQ(machine, "xenpv") &&
            STRNEQ(machine, "xenpvh") &&
            STRNEQ(machine, "xenfv")) {
6441
            virReportError(VIR_ERR_INVALID_ARG, "%s",
6442
                           _("Xen only supports 'xenpv', 'xenpvh' and 'xenfv' machines"));
6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464
            goto cleanup;
        }
    } else {
        machine = "xenpv";
    }

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

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

    ret = virDomainCapsFormat(domCaps);

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


6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484
static int
libxlConnectCompareCPU(virConnectPtr conn,
                       const char *xmlDesc,
                       unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    libxlDriverConfigPtr cfg;
    int ret = VIR_CPU_COMPARE_ERROR;
    bool failIncompatible;

    virCheckFlags(VIR_CONNECT_COMPARE_CPU_FAIL_INCOMPATIBLE,
                  VIR_CPU_COMPARE_ERROR);

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

    failIncompatible = !!(flags & VIR_CONNECT_COMPARE_CPU_FAIL_INCOMPATIBLE);

    cfg = libxlDriverConfigGet(driver);

J
Jiri Denemark 已提交
6485 6486
    ret = virCPUCompareXML(cfg->caps->host.arch, cfg->caps->host.cpu,
                           xmlDesc, failIncompatible);
6487 6488 6489 6490 6491

    virObjectUnref(cfg);
    return ret;
}

6492 6493 6494 6495 6496 6497
static char *
libxlConnectBaselineCPU(virConnectPtr conn,
                        const char **xmlCPUs,
                        unsigned int ncpus,
                        unsigned int flags)
{
J
Jiri Denemark 已提交
6498 6499 6500
    virCPUDefPtr *cpus = NULL;
    virCPUDefPtr cpu = NULL;
    char *cpustr = NULL;
6501 6502 6503 6504 6505 6506 6507

    virCheckFlags(VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES |
                  VIR_CONNECT_BASELINE_CPU_MIGRATABLE, NULL);

    if (virConnectBaselineCPUEnsureACL(conn) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
6508 6509 6510
    if (!(cpus = virCPUDefListParse(xmlCPUs, ncpus, VIR_CPU_TYPE_HOST)))
        goto cleanup;

6511
    if (!(cpu = virCPUBaseline(VIR_ARCH_NONE, cpus, ncpus, NULL, NULL,
6512
                               !!(flags & VIR_CONNECT_BASELINE_CPU_MIGRATABLE))))
J
Jiri Denemark 已提交
6513 6514 6515 6516 6517 6518
        goto cleanup;

    if ((flags & VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES) &&
        virCPUExpandFeatures(cpus[0]->arch, cpu) < 0)
        goto cleanup;

6519
    cpustr = virCPUDefFormat(cpu, NULL);
6520 6521

 cleanup:
J
Jiri Denemark 已提交
6522 6523 6524 6525
    virCPUDefListFree(cpus);
    virCPUDefFree(cpu);

    return cpustr;
6526 6527
}

6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591
static int
libxlDomainSetMetadata(virDomainPtr dom,
                       int type,
                       const char *metadata,
                       const char *key,
                       const char *uri,
                       unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    VIR_AUTOUNREF(libxlDriverConfigPtr) cfg = libxlDriverConfigGet(driver);
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

    if (!(vm = libxlDomObjFromDomain(dom)))
        return -1;

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

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

    ret = virDomainObjSetMetadata(vm, type, metadata, key, uri, cfg->caps,
                                  driver->xmlopt, cfg->stateDir,
                                  cfg->configDir, flags);

    if (ret == 0) {
        virObjectEventPtr ev = NULL;
        ev = virDomainEventMetadataChangeNewFromObj(vm, type, uri);
        virObjectEventStateQueue(driver->domainEventState, ev);
    }

    libxlDomainObjEndJob(driver, vm);

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

static char *
libxlDomainGetMetadata(virDomainPtr dom,
                       int type,
                       const char *uri,
                       unsigned int flags)
{
    virDomainObjPtr vm;
    char *ret = NULL;

    if (!(vm = libxlDomObjFromDomain(dom)))
        return NULL;

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

    ret = virDomainObjGetMetadata(vm, type, uri, flags);

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

6592
static virHypervisorDriver libxlHypervisorDriver = {
6593
    .name = LIBXL_DRIVER_NAME,
6594
    .connectURIProbe = libxlConnectURIProbe,
6595 6596 6597 6598
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
6599
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
6600
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
6601
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
6602
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
6603 6604 6605 6606
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
6607 6608 6609 6610 6611 6612 6613
    .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 */
6614
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
6615 6616
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
6617
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
6618 6619 6620 6621
#ifdef LIBXL_HAVE_DOMAIN_SUSPEND_ONLY
    .domainPMSuspendForDuration = libxlDomainPMSuspendForDuration, /* 4.8.0 */
#endif
    .domainPMWakeup = libxlDomainPMWakeup, /* 4.8.0 */
6622 6623
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
6624
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
6625 6626 6627 6628
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
6629
    .domainSave = libxlDomainSave, /* 0.9.2 */
6630
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
6631
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
6632
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
6633
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
6634 6635 6636
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
6637
    .domainGetMaxVcpus = libxlDomainGetMaxVcpus, /* 3.0.0 */
6638
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
6639
    .domainPinVcpuFlags = libxlDomainPinVcpuFlags, /* 1.2.1 */
6640
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
6641
    .domainGetVcpuPinInfo = libxlDomainGetVcpuPinInfo, /* 1.2.1 */
6642
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
6643 6644 6645 6646
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
6647 6648 6649
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
6650
    .domainDefineXMLFlags = libxlDomainDefineXMLFlags, /* 1.2.12 */
6651
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
6652
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
6653 6654 6655 6656 6657
    .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 */
6658 6659 6660 6661
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
6662
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
6663
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
6664
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
6665 6666 6667
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
6668
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
6669
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
6670
    .domainGetJobInfo = libxlDomainGetJobInfo, /* 1.3.1 */
6671
    .domainGetJobStats = libxlDomainGetJobStats, /* 1.3.1 */
P
Pavel Hrdina 已提交
6672 6673
    .domainMemoryStats = libxlDomainMemoryStats, /* 1.3.0 */
    .domainGetCPUStats = libxlDomainGetCPUStats, /* 1.3.0 */
6674
    .domainInterfaceStats = libxlDomainInterfaceStats, /* 1.3.2 */
6675 6676
    .domainBlockStats = libxlDomainBlockStats, /* 2.1.0 */
    .domainBlockStatsFlags = libxlDomainBlockStatsFlags, /* 2.1.0 */
6677 6678
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
6679 6680 6681
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
6682
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
6683 6684 6685
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
6686 6687 6688
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
6689
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
6690 6691 6692 6693
    .nodeDeviceDettach = libxlNodeDeviceDettach, /* 1.2.3 */
    .nodeDeviceDetachFlags = libxlNodeDeviceDetachFlags, /* 1.2.3 */
    .nodeDeviceReAttach = libxlNodeDeviceReAttach, /* 1.2.3 */
    .nodeDeviceReset = libxlNodeDeviceReset, /* 1.2.3 */
6694 6695
    .domainMigrateBegin3Params = libxlDomainMigrateBegin3Params, /* 1.2.6 */
    .domainMigratePrepare3Params = libxlDomainMigratePrepare3Params, /* 1.2.6 */
B
Bob Liu 已提交
6696
    .domainMigratePrepareTunnel3Params = libxlDomainMigratePrepareTunnel3Params, /* 3.1.0 */
6697 6698 6699
    .domainMigratePerform3Params = libxlDomainMigratePerform3Params, /* 1.2.6 */
    .domainMigrateFinish3Params = libxlDomainMigrateFinish3Params, /* 1.2.6 */
    .domainMigrateConfirm3Params = libxlDomainMigrateConfirm3Params, /* 1.2.6 */
6700
    .nodeGetSecurityModel = libxlNodeGetSecurityModel, /* 1.2.16 */
6701
    .domainInterfaceAddresses = libxlDomainInterfaceAddresses, /* 1.3.5 */
6702
    .connectGetDomainCapabilities = libxlConnectGetDomainCapabilities, /* 2.0.0 */
6703
    .connectCompareCPU = libxlConnectCompareCPU, /* 2.3.0 */
6704
    .connectBaselineCPU = libxlConnectBaselineCPU, /* 2.3.0 */
6705 6706 6707
    .domainSetMetadata = libxlDomainSetMetadata, /* 5.7.0 */
    .domainGetMetadata = libxlDomainGetMetadata, /* 5.7.0 */

J
Jim Fehlig 已提交
6708 6709
};

6710
static virConnectDriver libxlConnectDriver = {
6711
    .localOnly = true,
6712
    .uriSchemes = (const char *[]){ "xen", NULL },
6713 6714 6715
    .hypervisorDriver = &libxlHypervisorDriver,
};

J
Jim Fehlig 已提交
6716 6717
static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
6718 6719 6720
    .stateInitialize = libxlStateInitialize,
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
6721 6722 6723 6724 6725 6726
};


int
libxlRegister(void)
{
6727 6728
    if (virRegisterConnectDriver(&libxlConnectDriver,
                                 true) < 0)
J
Jim Fehlig 已提交
6729 6730 6731 6732 6733 6734
        return -1;
    if (virRegisterStateDriver(&libxlStateDriver) < 0)
        return -1;

    return 0;
}