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

#include <config.h>

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

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

#define VIR_FROM_THIS VIR_FROM_LIBXL

60 61
VIR_LOG_INIT("libxl.libxl_driver");

J
Jim Fehlig 已提交
62 63 64 65 66 67
#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

68
#define LIBXL_CONFIG_FORMAT_XM "xen-xm"
69
#define LIBXL_CONFIG_FORMAT_SEXPR "xen-sxpr"
70

71 72
#define HYPERVISOR_CAPABILITIES "/proc/xen/capabilities"

73 74 75
/* Number of Xen scheduler parameters */
#define XEN_SCHED_CREDIT_NPARAM   2

76

J
Jim Fehlig 已提交
77 78 79
static libxlDriverPrivatePtr libxl_driver = NULL;

/* Function declarations */
80 81
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
82 83
                           void *opaque);

J
Jim Fehlig 已提交
84
static int
85 86
libxlVmStart(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
             bool start_paused, int restore_fd);
J
Jim Fehlig 已提交
87

J
Jim Fehlig 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

/* Function definitions */
static virDomainObjPtr
libxlDomObjFromDomain(virDomainPtr dom)
{
    virDomainObjPtr vm;
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

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

    return vm;
}

109 110
static int
libxlAutostartDomain(virDomainObjPtr vm,
111 112 113 114
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    virErrorPtr err;
115
    int ret = -1;
116

117
    virObjectLock(vm);
118 119 120
    virResetLastError();

    if (vm->autostart && !virDomainObjIsActive(vm) &&
121
        libxlVmStart(driver, vm, false, -1) < 0) {
122 123 124 125
        err = virGetLastError();
        VIR_ERROR(_("Failed to autostart VM '%s': %s"),
                  vm->def->name,
                  err ? err->message : _("unknown error"));
126
        goto cleanup;
127 128
    }

129 130
    ret = 0;
cleanup:
131
    virObjectUnlock(vm);
132
    return ret;
133 134
}

135 136 137 138
static int
libxlDoNodeGetInfo(libxlDriverPrivatePtr driver, virNodeInfoPtr info)
{
    libxl_physinfo phy_info;
139
    virArch hostarch = virArchFromHost();
140 141
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    int ret = -1;
142

143
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
144 145
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
146
        goto cleanup;
147 148
    }

149
    if (virStrcpyStatic(info->model, virArchToString(hostarch)) == NULL) {
150 151
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("machine type %s too big for destination"),
152
                       virArchToString(hostarch));
153
        goto cleanup;
154 155
    }

156
    info->memory = phy_info.total_pages * (cfg->verInfo->pagesize / 1024);
157 158 159 160 161 162
    info->cpus = phy_info.nr_cpus;
    info->nodes = phy_info.nr_nodes;
    info->cores = phy_info.cores_per_socket;
    info->threads = phy_info.threads_per_core;
    info->sockets = 1;
    info->mhz = phy_info.cpu_khz / 1000;
163 164 165 166 167 168

    ret = 0;

cleanup:
    virObjectUnref(cfg);
    return ret;
169 170
}

171

J
Jim Fehlig 已提交
172
/*
J
Jim Fehlig 已提交
173 174 175 176 177
 * Handle previously registered event notification from libxenlight.
 *
 * Note: Xen 4.3 removed the const from the event handler signature.
 * Detect which signature to use based on
 * LIBXL_HAVE_NONCONST_EVENT_OCCURS_EVENT_ARG.
J
Jim Fehlig 已提交
178
 */
J
Jim Fehlig 已提交
179 180 181 182 183 184 185

#ifdef LIBXL_HAVE_NONCONST_EVENT_OCCURS_EVENT_ARG
# define VIR_LIBXL_EVENT_CONST /* empty */
#else
# define VIR_LIBXL_EVENT_CONST const
#endif

186 187 188 189 190 191 192
struct libxlShutdownThreadInfo
{
    virDomainObjPtr vm;
    libxl_event *event;
};


193
static void
194
libxlDomainShutdownThread(void *opaque)
J
Jim Fehlig 已提交
195 196
{
    libxlDriverPrivatePtr driver = libxl_driver;
197 198 199 200 201
    struct libxlShutdownThreadInfo *shutdown_info = opaque;
    virDomainObjPtr vm = shutdown_info->vm;
    libxlDomainObjPrivatePtr priv = vm->privateData;
    libxl_event *ev = shutdown_info->event;
    libxl_ctx *ctx = priv->ctx;
202
    virObjectEventPtr dom_event = NULL;
203
    libxl_shutdown_reason xl_reason = ev->u.domain_shutdown.shutdown_reason;
204
    virDomainShutoffReason reason = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
J
Jim Fehlig 已提交
205

206
    virObjectLock(vm);
J
Jiri Denemark 已提交
207

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    if (xl_reason == LIBXL_SHUTDOWN_REASON_POWEROFF) {
        dom_event = virDomainEventLifecycleNewFromObj(vm,
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
        switch ((enum virDomainLifecycleAction) vm->def->onPoweroff) {
        case VIR_DOMAIN_LIFECYCLE_DESTROY:
            reason = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
            goto destroy;
        case VIR_DOMAIN_LIFECYCLE_RESTART:
        case VIR_DOMAIN_LIFECYCLE_RESTART_RENAME:
            goto restart;
        case VIR_DOMAIN_LIFECYCLE_PRESERVE:
        case VIR_DOMAIN_LIFECYCLE_LAST:
            goto cleanup;
        }
    } else if (xl_reason == LIBXL_SHUTDOWN_REASON_CRASH) {
        dom_event = virDomainEventLifecycleNewFromObj(vm,
225 226
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_CRASHED);
227 228 229 230 231 232 233 234 235 236
        switch ((enum virDomainLifecycleCrashAction) vm->def->onCrash) {
        case VIR_DOMAIN_LIFECYCLE_CRASH_DESTROY:
            reason = VIR_DOMAIN_SHUTOFF_CRASHED;
            goto destroy;
        case VIR_DOMAIN_LIFECYCLE_CRASH_RESTART:
        case VIR_DOMAIN_LIFECYCLE_CRASH_RESTART_RENAME:
            goto restart;
        case VIR_DOMAIN_LIFECYCLE_CRASH_PRESERVE:
        case VIR_DOMAIN_LIFECYCLE_CRASH_LAST:
            goto cleanup;
237 238 239 240 241 242
        case VIR_DOMAIN_LIFECYCLE_CRASH_COREDUMP_DESTROY:
            libxlDomainAutoCoreDump(driver, vm);
            goto destroy;
        case VIR_DOMAIN_LIFECYCLE_CRASH_COREDUMP_RESTART:
            libxlDomainAutoCoreDump(driver, vm);
            goto restart;
243 244 245
        }
    } else if (xl_reason == LIBXL_SHUTDOWN_REASON_REBOOT) {
        dom_event = virDomainEventLifecycleNewFromObj(vm,
246 247
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
248 249 250 251 252 253 254 255 256 257 258 259 260 261
        switch ((enum virDomainLifecycleAction) vm->def->onReboot) {
        case VIR_DOMAIN_LIFECYCLE_DESTROY:
            reason = VIR_DOMAIN_SHUTOFF_SHUTDOWN;
            goto destroy;
        case VIR_DOMAIN_LIFECYCLE_RESTART:
        case VIR_DOMAIN_LIFECYCLE_RESTART_RENAME:
            goto restart;
        case VIR_DOMAIN_LIFECYCLE_PRESERVE:
        case VIR_DOMAIN_LIFECYCLE_LAST:
            goto cleanup;
        }
    } else {
        VIR_INFO("Unhandled shutdown_reason %d", xl_reason);
        goto cleanup;
J
Jim Fehlig 已提交
262 263
    }

264
destroy:
265 266 267 268
    if (dom_event) {
        libxlDomainEventQueue(driver, dom_event);
        dom_event = NULL;
    }
269
    libxl_domain_destroy(ctx, vm->def->id, NULL);
270
    if (libxlDomainCleanupJob(driver, vm, reason)) {
271 272 273 274 275 276 277 278
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
    }
    goto cleanup;

restart:
279 280 281 282
    if (dom_event) {
        libxlDomainEventQueue(driver, dom_event);
        dom_event = NULL;
    }
283
    libxl_domain_destroy(ctx, vm->def->id, NULL);
284
    libxlDomainCleanupJob(driver, vm, VIR_DOMAIN_SHUTOFF_SHUTDOWN);
285 286 287
    libxlVmStart(driver, vm, 0, -1);

cleanup:
J
Jim Fehlig 已提交
288
    if (vm)
289
        virObjectUnlock(vm);
290
    if (dom_event)
291
        libxlDomainEventQueue(driver, dom_event);
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    libxl_event_free(ctx, ev);
    VIR_FREE(shutdown_info);
}

static void
libxlEventHandler(void *data, VIR_LIBXL_EVENT_CONST libxl_event *event)
{
    virDomainObjPtr vm = data;
    libxlDomainObjPrivatePtr priv = vm->privateData;
    libxl_shutdown_reason xl_reason = event->u.domain_shutdown.shutdown_reason;
    struct libxlShutdownThreadInfo *shutdown_info;
    virThread thread;

    if (event->type != LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN) {
        VIR_INFO("Unhandled event type %d", event->type);
        goto error;
    }

    /*
     * Similar to the xl implementation, ignore SUSPEND.  Any actions needed
     * after calling libxl_domain_suspend() are handled by it's callers.
     */
    if (xl_reason == LIBXL_SHUTDOWN_REASON_SUSPEND)
        goto error;

    /*
     * Start a thread to handle shutdown.  We don't want to be tying up
     * libxl's event machinery by doing a potentially lengthy shutdown.
     */
    if (VIR_ALLOC(shutdown_info) < 0)
        goto error;

    shutdown_info->vm = data;
    shutdown_info->event = (libxl_event *)event;
    if (virThreadCreate(&thread, false, libxlDomainShutdownThread,
                        shutdown_info) < 0) {
        /*
         * Not much we can do on error here except log it.
         */
        VIR_ERROR(_("Failed to create thread to handle domain shutdown"));
        goto error;
    }

    /*
     * libxl_event freed in shutdown thread
     */
    return;

error:
J
Jim Fehlig 已提交
341 342
    /* Cast away any const */
    libxl_event_free(priv->ctx, (libxl_event *)event);
J
Jim Fehlig 已提交
343 344
}

345
const struct libxl_event_hooks ev_hooks = {
J
Jim Fehlig 已提交
346 347 348 349 350
    .event_occurs_mask = LIBXL_EVENTMASK_ALL,
    .event_occurs = libxlEventHandler,
    .disaster = NULL,
};

351
static int
352
libxlDomainSetVcpuAffinities(libxlDriverPrivatePtr driver, virDomainObjPtr vm)
353 354 355
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
    virDomainDefPtr def = vm->def;
J
Jim Fehlig 已提交
356
    libxl_bitmap map;
357
    virBitmapPtr cpumask = NULL;
358 359 360
    uint8_t *cpumap = NULL;
    virNodeInfo nodeinfo;
    size_t cpumaplen;
361 362
    int vcpu;
    size_t i;
363 364 365 366 367 368 369 370 371 372 373
    int ret = -1;

    if (libxlDoNodeGetInfo(driver, &nodeinfo) < 0)
        goto cleanup;

    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));

    for (vcpu = 0; vcpu < def->cputune.nvcpupin; ++vcpu) {
        if (vcpu != def->cputune.vcpupin[vcpu]->vcpuid)
            continue;

374
        if (VIR_ALLOC_N(cpumap, cpumaplen) < 0)
375 376
            goto cleanup;

377
        cpumask = def->cputune.vcpupin[vcpu]->cpumask;
378

379 380 381 382
        for (i = 0; i < virBitmapSize(cpumask); ++i) {
            bool bit;
            ignore_value(virBitmapGetBit(cpumask, i, &bit));
            if (bit)
383
                VIR_USE_CPU(cpumap, i);
384 385 386 387 388
        }

        map.size = cpumaplen;
        map.map = cpumap;

J
Jim Fehlig 已提交
389
        if (libxl_set_vcpuaffinity(priv->ctx, def->id, vcpu, &map) != 0) {
390 391
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"), vcpu);
392 393 394 395 396 397 398 399 400 401 402 403 404
            goto cleanup;
        }

        VIR_FREE(cpumap);
    }

    ret = 0;

cleanup:
    VIR_FREE(cpumap);
    return ret;
}

M
Markus Groß 已提交
405 406 407 408 409
static int
libxlFreeMem(libxlDomainObjPrivatePtr priv, libxl_domain_config *d_config)
{
    uint32_t needed_mem;
    uint32_t free_mem;
410
    size_t i;
M
Markus Groß 已提交
411 412 413 414
    int ret = -1;
    int tries = 3;
    int wait_secs = 10;

J
Jim Fehlig 已提交
415
    if ((ret = libxl_domain_need_memory(priv->ctx, &d_config->b_info,
M
Markus Groß 已提交
416 417
                                        &needed_mem)) >= 0) {
        for (i = 0; i < tries; ++i) {
J
Jim Fehlig 已提交
418
            if ((ret = libxl_get_free_memory(priv->ctx, &free_mem)) < 0)
M
Markus Groß 已提交
419 420 421 422 423 424 425
                break;

            if (free_mem >= needed_mem) {
                ret = 0;
                break;
            }

J
Jim Fehlig 已提交
426
            if ((ret = libxl_set_memory_target(priv->ctx, 0,
M
Markus Groß 已提交
427 428 429 430
                                               free_mem - needed_mem,
                                               /* relative */ 1, 0)) < 0)
                break;

J
Jim Fehlig 已提交
431
            ret = libxl_wait_for_free_memory(priv->ctx, 0, needed_mem,
M
Markus Groß 已提交
432 433 434 435
                                             wait_secs);
            if (ret == 0 || ret != ERROR_NOMEM)
                break;

J
Jim Fehlig 已提交
436
            if ((ret = libxl_wait_for_memory_target(priv->ctx, 0, 1)) < 0)
M
Markus Groß 已提交
437 438 439 440 441 442 443
                break;
        }
    }

    return ret;
}

J
Jim Fehlig 已提交
444 445 446 447 448 449
/*
 * Start a domain through libxenlight.
 *
 * virDomainObjPtr should be locked on invocation
 */
static int
450 451
libxlVmStart(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
             bool start_paused, int restore_fd)
J
Jim Fehlig 已提交
452 453
{
    libxl_domain_config d_config;
454
    virDomainDefPtr def = NULL;
455
    virObjectEventPtr event = NULL;
456
    libxlSavefileHeader hdr;
457
    int ret = -1;
J
Jim Fehlig 已提交
458 459
    uint32_t domid = 0;
    char *dom_xml = NULL;
460 461
    char *managed_save_path = NULL;
    int managed_save_fd = -1;
J
Jim Fehlig 已提交
462
    libxlDomainObjPrivatePtr priv = vm->privateData;
463
    libxlDriverConfigPtr cfg;
B
Bamvor Jian Zhang 已提交
464 465 466
#ifdef LIBXL_HAVE_DOMAIN_CREATE_RESTORE_PARAMS
    libxl_domain_restore_params params;
#endif
467
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
J
Jim Fehlig 已提交
468

J
Jim Fehlig 已提交
469
    if (libxlDomainObjPrivateInitCtx(vm) < 0)
470 471 472 473
        return ret;

    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        return ret;
J
Jim Fehlig 已提交
474

475
    cfg = libxlDriverConfigGet(driver);
476 477 478
    /* If there is a managed saved state restore it instead of starting
     * from scratch. The old state is removed once the restoring succeeded. */
    if (restore_fd < 0) {
479 480
        managed_save_path = libxlDomainManagedSavePath(driver, vm);
        if (managed_save_path == NULL)
481
            goto endjob;
482

483
        if (virFileExists(managed_save_path)) {
484

485 486 487
            managed_save_fd = libxlDomainSaveImageOpen(driver, cfg,
                                                       managed_save_path,
                                                       &def, &hdr);
488
            if (managed_save_fd < 0)
489
                goto endjob;
490

491 492
            restore_fd = managed_save_fd;

493 494 495 496 497 498
            if (STRNEQ(vm->def->name, def->name) ||
                memcmp(vm->def->uuid, def->uuid, VIR_UUID_BUFLEN)) {
                char vm_uuidstr[VIR_UUID_STRING_BUFLEN];
                char def_uuidstr[VIR_UUID_STRING_BUFLEN];
                virUUIDFormat(vm->def->uuid, vm_uuidstr);
                virUUIDFormat(def->uuid, def_uuidstr);
499 500 501 502
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("cannot restore domain '%s' uuid %s from a file"
                                 " which belongs to domain '%s' uuid %s"),
                               vm->def->name, vm_uuidstr, def->name, def_uuidstr);
503
                goto endjob;
504 505
            }

506
            virDomainObjAssignDef(vm, def, true, NULL);
507 508
            def = NULL;

509
            if (unlink(managed_save_path) < 0)
510 511
                VIR_WARN("Failed to remove the managed state %s",
                         managed_save_path);
512

513
            vm->hasManagedSave = false;
514
        }
515
        VIR_FREE(managed_save_path);
516 517
    }

J
Jim Fehlig 已提交
518
    libxl_domain_config_init(&d_config);
J
Jim Fehlig 已提交
519

520
    if (libxlBuildDomainConfig(driver, vm, &d_config) < 0)
521
        goto endjob;
J
Jim Fehlig 已提交
522

523
    if (cfg->autoballoon && libxlFreeMem(priv, &d_config) < 0) {
524 525 526
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to get free memory for domain '%s'"),
                       d_config.c_info.name);
527
        goto endjob;
M
Markus Groß 已提交
528
    }
J
Jim Fehlig 已提交
529

530 531 532 533
    if (virHostdevPrepareDomainDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                       vm->def, VIR_HOSTDEV_SP_PCI) < 0)
        goto endjob;

534 535
    /* Unlock virDomainObj while creating the domain */
    virObjectUnlock(vm);
536
    if (restore_fd < 0) {
J
Jim Fehlig 已提交
537 538
        ret = libxl_domain_create_new(priv->ctx, &d_config,
                                      &domid, NULL, NULL);
539
    } else {
B
Bamvor Jian Zhang 已提交
540 541 542 543 544
#ifdef LIBXL_HAVE_DOMAIN_CREATE_RESTORE_PARAMS
        params.checkpointed_stream = 0;
        ret = libxl_domain_create_restore(priv->ctx, &d_config, &domid,
                                          restore_fd, &params, NULL, NULL);
#else
J
Jim Fehlig 已提交
545 546
        ret = libxl_domain_create_restore(priv->ctx, &d_config, &domid,
                                          restore_fd, NULL, NULL);
B
Bamvor Jian Zhang 已提交
547
#endif
548
    }
549
    virObjectLock(vm);
550

J
Jim Fehlig 已提交
551
    if (ret) {
552
        if (restore_fd < 0)
553 554 555
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to create new domain '%s'"),
                           d_config.c_info.name);
556
        else
557 558 559
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to restore domain '%s'"),
                           d_config.c_info.name);
560
        goto endjob;
J
Jim Fehlig 已提交
561 562
    }

563 564 565 566
    /*
     * The domain has been successfully created with libxl, so it should
     * be cleaned up if there are any subsequent failures.
     */
567
    vm->def->id = domid;
568
    if (libxlDomainEventsRegister(vm) < 0)
569
        goto cleanup_dom;
570

571
    if ((dom_xml = virDomainDefFormat(vm->def, 0)) == NULL)
572
        goto cleanup_dom;
J
Jim Fehlig 已提交
573

J
Jim Fehlig 已提交
574
    if (libxl_userdata_store(priv->ctx, domid, "libvirt-xml",
J
Jim Fehlig 已提交
575
                             (uint8_t *)dom_xml, strlen(dom_xml) + 1)) {
576 577
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to store userdata"));
578
        goto cleanup_dom;
J
Jim Fehlig 已提交
579 580
    }

581
    if (libxlDomainSetVcpuAffinities(driver, vm) < 0)
582
        goto cleanup_dom;
583

J
Jim Fehlig 已提交
584
    if (!start_paused) {
J
Jim Fehlig 已提交
585
        libxl_domain_unpause(priv->ctx, domid);
J
Jiri Denemark 已提交
586
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
J
Jim Fehlig 已提交
587
    } else {
J
Jiri Denemark 已提交
588
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
J
Jim Fehlig 已提交
589 590
    }

591
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
592
        goto cleanup_dom;
J
Jim Fehlig 已提交
593

594
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
595 596
        driver->inhibitCallback(true, driver->inhibitOpaque);

597
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STARTED,
598 599 600
                                     restore_fd < 0 ?
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED :
                                         VIR_DOMAIN_EVENT_STARTED_RESTORED);
601 602
    if (event)
        libxlDomainEventQueue(driver, event);
603

604 605 606 607 608 609 610 611 612 613 614
    ret = 0;
    goto endjob;

cleanup_dom:
    libxl_domain_destroy(priv->ctx, domid, NULL);
    vm->def->id = -1;
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);

endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;
J
Jim Fehlig 已提交
615

J
Jim Fehlig 已提交
616
    libxl_domain_config_dispose(&d_config);
J
Jim Fehlig 已提交
617
    VIR_FREE(dom_xml);
618
    VIR_FREE(managed_save_path);
619
    virDomainDefFree(def);
620
    VIR_FORCE_CLOSE(managed_save_fd);
621
    virObjectUnref(cfg);
622
    return ret;
J
Jim Fehlig 已提交
623 624 625 626 627 628 629
}


/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
630 631
static int
libxlReconnectDomain(virDomainObjPtr vm,
J
Jim Fehlig 已提交
632 633 634
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
635
    libxlDomainObjPrivatePtr priv = vm->privateData;
J
Jim Fehlig 已提交
636 637 638 639
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;
640
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
J
Jim Fehlig 已提交
641

642
    virObjectLock(vm);
J
Jim Fehlig 已提交
643

644
    libxlDomainObjPrivateInitCtx(vm);
J
Jim Fehlig 已提交
645
    /* Does domain still exist? */
646
    rc = libxl_domain_info(priv->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
647 648 649 650 651 652 653 654 655
    if (rc == ERROR_INVAL) {
        goto out;
    } else if (rc != 0) {
        VIR_DEBUG("libxl_domain_info failed (code %d), ignoring domain %d",
                  rc, vm->def->id);
        goto out;
    }

    /* Is this a domain that was under libvirt control? */
656
    if (libxl_userdata_retrieve(priv->ctx, vm->def->id,
J
Jim Fehlig 已提交
657 658 659 660 661 662 663
                                "libvirt-xml", &data, &len)) {
        VIR_DEBUG("libxl_userdata_retrieve failed, ignoring domain %d", vm->def->id);
        goto out;
    }

    /* Update domid in case it changed (e.g. reboot) while we were gone? */
    vm->def->id = d_info.domid;
664 665 666 667 668 669

    /* Update hostdev state */
    if (virHostdevUpdateDomainActiveDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                            vm->def, VIR_HOSTDEV_SP_PCI) < 0)
        goto out;

J
Jiri Denemark 已提交
670
    virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_UNKNOWN);
J
Jim Fehlig 已提交
671

672
    if (virAtomicIntInc(&driver->nactive) == 1 && driver->inhibitCallback)
673 674
        driver->inhibitCallback(true, driver->inhibitOpaque);

675
    /* Re-register domain death et. al. events */
676
    libxlDomainEventsRegister(vm);
677
    virObjectUnlock(vm);
678
    return 0;
J
Jim Fehlig 已提交
679 680

out:
681
    libxlDomainCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_UNKNOWN);
J
Jim Fehlig 已提交
682
    if (!vm->persistent)
683
        virDomainObjListRemoveLocked(driver->domains, vm);
J
Jim Fehlig 已提交
684
    else
685
        virObjectUnlock(vm);
686 687

    return -1;
J
Jim Fehlig 已提交
688 689 690 691 692
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
693
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
694 695 696
}

static int
697
libxlStateCleanup(void)
J
Jim Fehlig 已提交
698 699 700 701
{
    if (!libxl_driver)
        return -1;

702
    virObjectUnref(libxl_driver->hostdevMgr);
703
    virObjectUnref(libxl_driver->config);
704
    virObjectUnref(libxl_driver->xmlopt);
705
    virObjectUnref(libxl_driver->domains);
706
    virObjectUnref(libxl_driver->reservedVNCPorts);
J
Jim Fehlig 已提交
707

708
    virObjectEventStateFree(libxl_driver->domainEventState);
709
    virSysinfoDefFree(libxl_driver->hostsysinfo);
710

J
Jim Fehlig 已提交
711 712 713 714 715 716
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

717 718
static bool
libxlDriverShouldLoad(bool privileged)
719
{
720
    bool ret = false;
J
Jim Fehlig 已提交
721
    virCommandPtr cmd;
722
    int status;
723
    char *output = NULL;
J
Jim Fehlig 已提交
724

725
    /* Don't load if non-root */
J
Jim Fehlig 已提交
726
    if (!privileged) {
727
        VIR_INFO("Not running privileged, disabling libxenlight driver");
728
        return ret;
J
Jim Fehlig 已提交
729 730
    }

731 732 733 734 735
    if (!virFileExists(HYPERVISOR_CAPABILITIES)) {
        VIR_INFO("Disabling driver as " HYPERVISOR_CAPABILITIES
                 " does not exist");
        return false;
    }
736 737 738 739 740
    /*
     * 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.
     */
741
    status = virFileReadAll(HYPERVISOR_CAPABILITIES, 10, &output);
742 743 744 745 746
    if (status >= 0) {
        status = strncmp(output, "control_d", 9);
    }
    VIR_FREE(output);
    if (status) {
747 748 749 750 751 752 753
        VIR_INFO("No Xen capabilities detected, probably not running "
                 "in a Xen Dom0.  Disabling libxenlight driver");

        return ret;
    }

    /* Don't load if legacy xen toolstack (xend) is in use */
J
Jim Fehlig 已提交
754 755
    cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL);
    if (virCommandRun(cmd, &status) == 0 && status == 0) {
756
        VIR_INFO("Legacy xen tool stack seems to be in use, disabling "
J
Jim Fehlig 已提交
757
                  "libxenlight driver.");
758 759
    } else {
        ret = true;
J
Jim Fehlig 已提交
760 761 762
    }
    virCommandFree(cmd);

763 764 765 766 767 768 769 770
    return ret;
}

static int
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
771
    libxlDriverConfigPtr cfg;
772 773 774 775 776
    char ebuf[1024];

    if (!libxlDriverShouldLoad(privileged))
        return 0;

J
Jim Fehlig 已提交
777 778 779 780
    if (VIR_ALLOC(libxl_driver) < 0)
        return -1;

    if (virMutexInit(&libxl_driver->lock) < 0) {
781 782
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
J
Jim Fehlig 已提交
783 784 785 786 787
        VIR_FREE(libxl_driver);
        return -1;
    }

    /* Allocate bitmap for vnc port reservation */
788
    if (!(libxl_driver->reservedVNCPorts =
J
Ján Tomko 已提交
789 790
          virPortAllocatorNew(_("VNC"),
                              LIBXL_VNC_PORT_MIN,
791 792
                              LIBXL_VNC_PORT_MAX)))
        goto error;
J
Jim Fehlig 已提交
793

794 795
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
796

797 798 799
    if (!(libxl_driver->hostdevMgr = virHostdevManagerGetDefault()))
        goto error;

800
    if (!(cfg = libxlDriverConfigNew()))
801
        goto error;
J
Jim Fehlig 已提交
802

803 804
    libxl_driver->config = cfg;
    if (virFileMakePath(cfg->logDir) < 0) {
805 806
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create log dir '%s': %s"),
807
                       cfg->logDir,
808
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
809 810
        goto error;
    }
811
    if (virFileMakePath(cfg->stateDir) < 0) {
812 813
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create state dir '%s': %s"),
814
                       cfg->stateDir,
815
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
816 817
        goto error;
    }
818
    if (virFileMakePath(cfg->libDir) < 0) {
819 820
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create lib dir '%s': %s"),
821
                       cfg->libDir,
822
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
823 824
        goto error;
    }
825
    if (virFileMakePath(cfg->saveDir) < 0) {
826 827
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create save dir '%s': %s"),
828
                       cfg->saveDir,
829
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
830 831
        goto error;
    }
832 833 834 835 836 837 838
    if (virFileMakePath(cfg->autoDumpDir) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create dump dir '%s': %s"),
                       cfg->autoDumpDir,
                       virStrerror(errno, ebuf, sizeof(ebuf)));
        goto error;
    }
J
Jim Fehlig 已提交
839

840
    /* read the host sysinfo */
841
    libxl_driver->hostsysinfo = virSysinfoRead();
842

843
    libxl_driver->domainEventState = virObjectEventStateNew();
E
Eric Blake 已提交
844
    if (!libxl_driver->domainEventState)
845 846
        goto error;

847
    if ((cfg->caps = libxlMakeCapabilities(cfg->ctx)) == NULL) {
848 849
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
850 851 852
        goto error;
    }

853
    if (!(libxl_driver->xmlopt = virDomainXMLOptionNew(&libxlDomainDefParserConfig,
854 855
                                                       &libxlDomainXMLPrivateDataCallbacks,
                                                       NULL)))
856
        goto error;
J
Jim Fehlig 已提交
857 858

    /* Load running domains first. */
859
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
860 861
                                       cfg->stateDir,
                                       cfg->autostartDir,
862
                                       1,
863
                                       cfg->caps,
864 865
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
866
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
867 868 869 870 871
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
872
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
873 874
                                       cfg->configDir,
                                       cfg->autostartDir,
875
                                       0,
876
                                       cfg->caps,
877 878
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
879
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
880 881
        goto error;

882 883
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
884

J
Jim Fehlig 已提交
885 886 887
    return 0;

error:
888
    libxlStateCleanup();
889
    return -1;
J
Jim Fehlig 已提交
890 891
}

892 893 894 895 896 897 898 899 900 901
static void
libxlStateAutoStart(void)
{
    if (!libxl_driver)
        return;

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

J
Jim Fehlig 已提交
902
static int
903
libxlStateReload(void)
J
Jim Fehlig 已提交
904
{
905 906
    libxlDriverConfigPtr cfg;

J
Jim Fehlig 已提交
907 908 909
    if (!libxl_driver)
        return 0;

910 911
    cfg = libxlDriverConfigGet(libxl_driver);

912
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
913 914
                                   cfg->configDir,
                                   cfg->autostartDir,
915
                                   1,
916
                                   cfg->caps,
917 918
                                   libxl_driver->xmlopt,
                                   1 << VIR_DOMAIN_VIRT_XEN,
919 920
                                   NULL, libxl_driver);

921 922
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
923

924
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
925 926 927 928 929
    return 0;
}


static virDrvOpenStatus
930 931 932
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 unsigned int flags)
J
Jim Fehlig 已提交
933
{
E
Eric Blake 已提交
934 935
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
936 937 938 939
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

940
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
941 942 943 944 945 946 947 948 949 950 951 952
            return VIR_DRV_OPEN_ERROR;
    } else {
        /* Only xen scheme */
        if (conn->uri->scheme == NULL || STRNEQ(conn->uri->scheme, "xen"))
            return VIR_DRV_OPEN_DECLINED;

        /* If server name is given, its for remote driver */
        if (conn->uri->server != NULL)
            return VIR_DRV_OPEN_DECLINED;

        /* Error if xen or libxl scheme specified but driver not started. */
        if (libxl_driver == NULL) {
953 954
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
955 956 957 958 959 960 961 962
            return VIR_DRV_OPEN_ERROR;
        }

        /* /session isn't supported in libxenlight */
        if (conn->uri->path &&
            STRNEQ(conn->uri->path, "") &&
            STRNEQ(conn->uri->path, "/") &&
            STRNEQ(conn->uri->path, "/system")) {
963 964 965
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
966 967 968 969
            return VIR_DRV_OPEN_ERROR;
        }
    }

970 971 972
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
973 974 975 976 977 978
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
979
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
980 981 982 983 984 985
{
    conn->privateData = NULL;
    return 0;
}

static const char *
986
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
987
{
988 989 990
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
991
    return "Xen";
J
Jim Fehlig 已提交
992 993 994
}

static int
995
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
996 997
{
    libxlDriverPrivatePtr driver = conn->privateData;
998
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
999

1000 1001 1002
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

1003 1004 1005
    cfg = libxlDriverConfigGet(driver);
    *version = cfg->version;
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1006 1007 1008
    return 0;
}

1009

1010
static char *libxlConnectGetHostname(virConnectPtr conn)
1011
{
1012 1013 1014
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

1015 1016 1017
    return virGetHostname();
}

1018 1019 1020 1021 1022 1023 1024 1025
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

1026 1027 1028
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    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;
    if (virBufferError(&buf)) {
        virReportOOMError();
        return NULL;
    }
    return virBufferContentAndReset(&buf);
}
1043

J
Jim Fehlig 已提交
1044
static int
1045
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
1046 1047 1048
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;
1049
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
1050

1051 1052 1053
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

1054 1055
    cfg = libxlDriverConfigGet(driver);
    ret = libxl_get_max_cpus(cfg->ctx);
1056 1057 1058 1059 1060
    /* 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)
1061
        ret = -1;
J
Jim Fehlig 已提交
1062

1063
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1064 1065 1066 1067 1068 1069
    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
1070 1071 1072
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

1073
    return libxlDoNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
1074 1075 1076
}

static char *
1077
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
1078 1079 1080
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;
1081
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
1082

1083 1084 1085
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

1086 1087
    cfg = libxlDriverConfigGet(driver);
    if ((xml = virCapabilitiesFormatXML(cfg->caps)) == NULL)
J
Jim Fehlig 已提交
1088 1089
        virReportOOMError();

1090
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1091 1092 1093 1094
    return xml;
}

static int
1095
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
1096 1097 1098 1099
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1100 1101 1102
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

1103 1104
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1105 1106 1107 1108 1109

    return n;
}

static int
1110
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
1111 1112 1113 1114
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

1115 1116 1117
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

1118 1119
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

    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;
1132
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
1133 1134 1135

    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);

1136
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
1137
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
1138 1139 1140
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

1141 1142 1143
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

1144
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1145
                                   driver->xmlopt,
1146 1147
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
1148 1149 1150
        goto cleanup;
    def = NULL;

1151 1152
    if (libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0,
                     -1) < 0) {
1153
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
        vm = NULL;
        goto cleanup;
    }

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

cleanup:
    virDomainDefFree(def);
    if (vm)
1165
        virObjectUnlock(vm);
1166
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
    return dom;
}

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

1177
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
1178
    if (!vm) {
1179
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1180 1181 1182
        goto cleanup;
    }

1183 1184 1185
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1186 1187 1188 1189 1190 1191
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1192
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
    return dom;
}

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

1203
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
1204
    if (!vm) {
1205
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1206 1207 1208
        goto cleanup;
    }

1209 1210 1211
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1212 1213 1214 1215 1216 1217
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1218
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    return dom;
}

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

1229
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
1230
    if (!vm) {
1231
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
1232 1233 1234
        goto cleanup;
    }

1235 1236 1237
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1238 1239 1240 1241 1242 1243
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

  cleanup:
    if (vm)
1244
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1245 1246 1247
    return dom;
}

1248 1249 1250 1251
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1252
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1253 1254
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
1255
    virObjectEventPtr event = NULL;
1256 1257
    int ret = -1;

J
Jim Fehlig 已提交
1258
    if (!(vm = libxlDomObjFromDomain(dom)))
1259
        goto cleanup;
1260 1261 1262 1263

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

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

1267
    if (!virDomainObjIsActive(vm)) {
1268
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1269
        goto endjob;
1270 1271 1272 1273
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1274
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1275
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
1276 1277 1278
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to suspend domain '%d' with libxenlight"),
                           dom->id);
1279
            goto endjob;
1280 1281
        }

J
Jiri Denemark 已提交
1282
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
1283

1284
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
1285 1286 1287
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

1288
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1289
        goto endjob;
1290 1291 1292

    ret = 0;

1293 1294 1295 1296
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1297 1298
cleanup:
    if (vm)
1299
        virObjectUnlock(vm);
1300
    if (event)
1301
        libxlDomainEventQueue(driver, event);
1302
    virObjectUnref(cfg);
1303 1304 1305 1306 1307 1308 1309 1310
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1311
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1312 1313
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
1314
    virObjectEventPtr event = NULL;
1315 1316
    int ret = -1;

J
Jim Fehlig 已提交
1317
    if (!(vm = libxlDomObjFromDomain(dom)))
1318 1319
        goto cleanup;

1320 1321 1322
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1326
    if (!virDomainObjIsActive(vm)) {
1327
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1328
        goto endjob;
1329 1330 1331 1332
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
1333
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
J
Jim Fehlig 已提交
1334
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
1335 1336 1337
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
                           dom->id);
1338
            goto endjob;
1339 1340
        }

J
Jiri Denemark 已提交
1341 1342
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
1343

1344
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_RESUMED,
1345 1346 1347
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

1348
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
1349
        goto endjob;
1350 1351 1352

    ret = 0;

1353 1354 1355 1356
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1357 1358
cleanup:
    if (vm)
1359
        virObjectUnlock(vm);
1360
    if (event)
1361
        libxlDomainEventQueue(driver, event);
1362
    virObjectUnref(cfg);
1363 1364 1365
    return ret;
}

J
Jim Fehlig 已提交
1366
static int
1367
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1368 1369 1370 1371 1372
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

1373 1374
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1375
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1376 1377
        goto cleanup;

1378
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1379 1380
        goto cleanup;

J
Jim Fehlig 已提交
1381
    if (!virDomainObjIsActive(vm)) {
1382 1383
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1384 1385 1386 1387
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1388
    if (libxl_domain_shutdown(priv->ctx, dom->id) != 0) {
1389 1390 1391
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
        goto cleanup;
    }

    /* vm is marked shutoff (or removed from domains list if not persistent)
     * in shutdown event handler.
     */
    ret = 0;

cleanup:
    if (vm)
1402
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1403 1404 1405
    return ret;
}

1406 1407 1408 1409 1410 1411 1412
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
1413
static int
E
Eric Blake 已提交
1414
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
1415 1416 1417 1418 1419
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

E
Eric Blake 已提交
1420 1421
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1422
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1423 1424
        goto cleanup;

1425
    if (virDomainRebootEnsureACL(dom->conn, vm->def, flags) < 0)
1426 1427
        goto cleanup;

J
Jim Fehlig 已提交
1428
    if (!virDomainObjIsActive(vm)) {
1429 1430
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1431 1432 1433 1434
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
1435
    if (libxl_domain_reboot(priv->ctx, dom->id) != 0) {
1436 1437 1438
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
                       dom->id);
J
Jim Fehlig 已提交
1439 1440 1441 1442 1443 1444
        goto cleanup;
    }
    ret = 0;

cleanup:
    if (vm)
1445
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1446 1447 1448 1449
    return ret;
}

static int
1450 1451
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
1452 1453 1454 1455
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1456
    virObjectEventPtr event = NULL;
J
Jim Fehlig 已提交
1457
    libxlDomainObjPrivatePtr priv;
J
Jim Fehlig 已提交
1458

1459 1460
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1461
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1462 1463
        goto cleanup;

1464 1465 1466
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
1467
    if (!virDomainObjIsActive(vm)) {
1468 1469
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
1470 1471 1472
        goto cleanup;
    }

1473
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1474 1475
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

J
Jim Fehlig 已提交
1476 1477
    priv = vm->privateData;
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
1478 1479
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), dom->id);
J
Jim Fehlig 已提交
1480 1481 1482
        goto cleanup;
    }

1483
    if (libxlDomainCleanupJob(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED)) {
1484 1485 1486 1487
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
J
Jim Fehlig 已提交
1488 1489 1490 1491 1492 1493
    }

    ret = 0;

cleanup:
    if (vm)
1494
        virObjectUnlock(vm);
1495 1496
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1497 1498 1499
    return ret;
}

1500 1501 1502 1503 1504 1505
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1506 1507 1508 1509 1510 1511
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *type = NULL;

J
Jim Fehlig 已提交
1512
    if (!(vm = libxlDomObjFromDomain(dom)))
1513 1514
        goto cleanup;

1515 1516 1517 1518 1519
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

    if (VIR_STRDUP(type, vm->def->os.type) < 0)
        goto cleanup;
1520 1521 1522

cleanup:
    if (vm)
1523
        virObjectUnlock(vm);
1524 1525 1526
    return type;
}

1527
static unsigned long long
1528 1529 1530
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    virDomainObjPtr vm;
1531
    unsigned long long ret = 0;
1532

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

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

1539 1540 1541 1542
    ret = vm->def->mem.max_balloon;

cleanup:
    if (vm)
1543
        virObjectUnlock(vm);
1544 1545 1546 1547
    return ret;
}

static int
1548
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1549 1550 1551
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1552
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1553 1554
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1555 1556
    virDomainDefPtr persistentDef = NULL;
    bool isActive;
1557 1558 1559
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1560 1561
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1562

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

1566 1567 1568
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
    isActive = virDomainObjIsActive(vm);

    if (flags == VIR_DOMAIN_MEM_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE;
        else
            flags = VIR_DOMAIN_MEM_CONFIG;
    }
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
        else
            flags = VIR_DOMAIN_MEM_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1585 1586
    }

1587
    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
1588 1589
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set memory on an inactive domain"));
1590
        goto endjob;
1591 1592 1593 1594
    }

    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
1595 1596
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a transient domain"));
1597
            goto endjob;
1598
        }
1599
        if (!(persistentDef = virDomainObjGetPersistentDef(cfg->caps,
1600
                                                           driver->xmlopt,
1601
                                                           vm)))
1602
            goto endjob;
1603 1604
    }

1605 1606
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1607

1608 1609
        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
J
Jim Fehlig 已提交
1610
            if (libxl_domain_setmaxmem(priv->ctx, dom->id, newmem) < 0) {
1611 1612 1613
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
                                 " with libxenlight"), dom->id);
1614
                goto endjob;
1615 1616 1617 1618 1619 1620 1621 1622 1623
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            /* Help clang 2.8 decipher the logic flow.  */
            sa_assert(persistentDef);
            persistentDef->mem.max_balloon = newmem;
            if (persistentDef->mem.cur_balloon > newmem)
                persistentDef->mem.cur_balloon = newmem;
1624
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
1625
            goto endjob;
1626 1627
        }

1628 1629
    } else {
        /* resize the current memory */
1630

1631
        if (newmem > vm->def->mem.max_balloon) {
1632 1633
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1634
            goto endjob;
1635 1636 1637
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
1638 1639
            int res;

1640
            priv = vm->privateData;
1641 1642 1643 1644 1645 1646
            /* Unlock virDomainObj while ballooning memory */
            virObjectUnlock(vm);
            res = libxl_set_memory_target(priv->ctx, dom->id, newmem, 0,
                                          /* force */ 1);
            virObjectLock(vm);
            if (res < 0) {
1647 1648 1649
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
                                 " with libxenlight"), dom->id);
1650
                goto endjob;
1651 1652 1653 1654 1655 1656
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1657
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
1658
            goto endjob;
1659
        }
1660 1661
    }

1662 1663
    ret = 0;

1664 1665 1666 1667
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1668 1669
cleanup:
    if (vm)
1670
        virObjectUnlock(vm);
1671
    virObjectUnref(cfg);
1672 1673 1674 1675 1676 1677 1678 1679 1680
    return ret;
}

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

1681 1682 1683 1684 1685 1686
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1687 1688 1689 1690
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
    virDomainObjPtr vm;
1691
    libxl_dominfo d_info;
1692
    libxlDomainObjPrivatePtr priv;
J
Jim Fehlig 已提交
1693 1694
    int ret = -1;

J
Jim Fehlig 已提交
1695
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1696 1697
        goto cleanup;

1698 1699 1700
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1701
    priv = vm->privateData;
1702 1703 1704
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1705
        info->maxMem = vm->def->mem.max_balloon;
1706
    } else {
1707
        if (libxl_domain_info(priv->ctx, &d_info, dom->id) != 0) {
1708 1709
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxl_domain_info failed for domain '%d'"), dom->id);
1710 1711 1712 1713
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1714
        info->maxMem = d_info.max_memkb;
1715 1716
    }

J
Jiri Denemark 已提交
1717
    info->state = virDomainObjGetState(vm, NULL);
J
Jim Fehlig 已提交
1718 1719 1720 1721 1722
    info->nrVirtCpu = vm->def->vcpus;
    ret = 0;

  cleanup:
    if (vm)
1723
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1724 1725 1726
    return ret;
}

1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1738
    if (!(vm = libxlDomObjFromDomain(dom)))
1739 1740
        goto cleanup;

1741 1742 1743
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1744
    *state = virDomainObjGetState(vm, reason);
1745 1746 1747 1748
    ret = 0;

  cleanup:
    if (vm)
1749
        virObjectUnlock(vm);
1750 1751 1752
    return ret;
}

1753 1754 1755
/*
 * virDomainObjPtr must be locked on invocation
 */
1756
static int
1757 1758
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1759
{
1760
    libxlDomainObjPrivatePtr priv = vm->privateData;
1761
    libxlSavefileHeader hdr;
1762
    virObjectEventPtr event = NULL;
1763 1764
    char *xml = NULL;
    uint32_t xml_len;
1765
    int fd = -1;
1766 1767 1768
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1769 1770 1771
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1772 1773 1774 1775
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1776
                            -1, -1, 0)) < 0) {
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
        virReportSystemError(-fd,
                             _("Failed to create domain save file '%s'"), to);
        goto cleanup;
    }

    if ((xml = virDomainDefFormat(vm->def, 0)) == NULL)
        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)) {
1792 1793
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1794 1795 1796 1797
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1798 1799
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1800 1801 1802
        goto cleanup;
    }

1803 1804 1805 1806 1807 1808
    /* Unlock virDomainObj while saving domain */
    virObjectUnlock(vm);
    ret = libxl_domain_suspend(priv->ctx, vm->def->id, fd, 0, NULL);
    virObjectLock(vm);

    if (ret != 0) {
1809 1810 1811
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1812
        ret = -1;
1813 1814 1815
        goto cleanup;
    }

1816
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1817 1818
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

J
Jim Fehlig 已提交
1819
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
1820 1821
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1822 1823 1824
        goto cleanup;
    }

1825
    libxlDomainCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED);
1826
    vm->hasManagedSave = true;
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
    ret = 0;

cleanup:
    VIR_FREE(xml);
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
    if (event)
        libxlDomainEventQueue(driver, event);
    return ret;
}

static int
1839 1840
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1841
{
1842 1843
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1844
    int ret = -1;
1845
    bool remove_dom = false;
1846

1847 1848
    virCheckFlags(0, -1);
    if (dxml) {
1849 1850
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1851 1852 1853
        return -1;
    }

J
Jim Fehlig 已提交
1854
    if (!(vm = libxlDomObjFromDomain(dom)))
1855 1856
        goto cleanup;

1857 1858 1859
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1863
    if (!virDomainObjIsActive(vm)) {
1864
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1865
        goto endjob;
1866 1867
    }

1868
    if (libxlDoDomainSave(driver, vm, to) < 0)
1869
        goto endjob;
1870

1871 1872
    if (!vm->persistent)
        remove_dom = true;
1873 1874

    ret = 0;
1875

1876 1877 1878 1879
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1880
cleanup:
1881 1882 1883 1884
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1885
    if (vm)
1886
        virObjectUnlock(vm);
1887 1888
    return ret;
}
1889

1890
static int
1891 1892 1893 1894 1895 1896 1897 1898
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)
1899 1900
{
    libxlDriverPrivatePtr driver = conn->privateData;
1901
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1902 1903 1904 1905 1906
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1907

1908
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1909
    if (dxml) {
1910 1911
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1912 1913 1914
        return -1;
    }

1915
    fd = libxlDomainSaveImageOpen(driver, cfg, from, &def, &hdr);
1916
    if (fd < 0)
1917
        goto cleanup_unlock;
1918

1919
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1920
        goto cleanup_unlock;
1921

1922
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1923
                                   driver->xmlopt,
1924 1925 1926
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1927
        goto cleanup_unlock;
1928 1929 1930

    def = NULL;

1931 1932
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_SAVE_PAUSED) != 0, fd);
    if (ret < 0 && !vm->persistent) {
1933
        virDomainObjListRemove(driver->domains, vm);
1934 1935 1936 1937
        vm = NULL;
    }

cleanup:
1938 1939
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1940 1941
    virDomainDefFree(def);
    if (vm)
1942
        virObjectUnlock(vm);
1943
    virObjectUnref(cfg);
1944
    return ret;
1945 1946 1947 1948

cleanup_unlock:
    libxlDriverUnlock(driver);
    goto cleanup;
1949 1950
}

1951 1952 1953 1954 1955 1956
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

1957
static int
1958
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1959 1960 1961 1962
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1963
    virObjectEventPtr event = NULL;
1964
    bool remove_dom = false;
1965 1966 1967 1968 1969
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

J
Jim Fehlig 已提交
1970
    if (!(vm = libxlDomObjFromDomain(dom)))
1971 1972
        goto cleanup;

1973 1974 1975
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1979
    if (!virDomainObjIsActive(vm)) {
1980
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1981
        goto endjob;
1982 1983 1984 1985 1986 1987
    }

    priv = vm->privateData;

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
J
Jim Fehlig 已提交
1988
        if (libxl_domain_pause(priv->ctx, dom->id) != 0) {
1989 1990 1991 1992
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
                           dom->id);
1993
            goto endjob;
1994 1995 1996 1997 1998
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

1999 2000 2001 2002 2003
    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
    ret = libxl_domain_core_dump(priv->ctx, dom->id, to, NULL);
    virObjectLock(vm);
    if (ret != 0) {
2004 2005 2006
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
                       dom->id);
2007 2008
        ret = -1;
        goto unpause;
2009 2010 2011
    }

    if (flags & VIR_DUMP_CRASH) {
J
Jim Fehlig 已提交
2012
        if (libxl_domain_destroy(priv->ctx, dom->id, NULL) < 0) {
2013 2014
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to destroy domain '%d'"), dom->id);
2015
            goto unpause;
2016 2017
        }

2018
        libxlDomainCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED);
2019
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
2020
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
2021 2022
        if (!vm->persistent)
            remove_dom = true;
2023 2024 2025 2026
    }

    ret = 0;

2027 2028
unpause:
    if (virDomainObjIsActive(vm) && paused) {
J
Jim Fehlig 已提交
2029
        if (libxl_domain_unpause(priv->ctx, dom->id) != 0) {
2030 2031 2032
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
                             " libxenlight"), dom->id);
2033 2034 2035 2036 2037
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
2038 2039 2040 2041 2042

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

2043
cleanup:
2044 2045 2046 2047
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
2048
    if (vm)
2049
        virObjectUnlock(vm);
2050
    if (event)
2051 2052 2053 2054
        libxlDomainEventQueue(driver, event);
    return ret;
}

2055 2056 2057 2058 2059 2060 2061
static int
libxlDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;
2062
    bool remove_dom = false;
2063 2064 2065

    virCheckFlags(0, -1);

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

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

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

2075
    if (!virDomainObjIsActive(vm)) {
2076
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2077
        goto endjob;
2078
    }
2079
    if (!vm->persistent) {
2080 2081
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
2082
        goto endjob;
2083
    }
2084 2085 2086

    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
2087
        goto endjob;
2088 2089 2090

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

2091
    if (libxlDoDomainSave(driver, vm, name) < 0)
2092
        goto endjob;
2093

2094 2095
    if (!vm->persistent)
        remove_dom = true;
2096 2097

    ret = 0;
2098

2099 2100 2101 2102
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2103
cleanup:
2104 2105 2106 2107
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
2108
    if (vm)
2109
        virObjectUnlock(vm);
2110 2111 2112 2113
    VIR_FREE(name);
    return ret;
}

2114 2115
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
2116 2117 2118 2119
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
2120
    int ret = -1;
2121

2122
    virObjectLock(vm);
2123 2124 2125 2126 2127 2128

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

    vm->hasManagedSave = virFileExists(name);

2129
    ret = 0;
2130
cleanup:
2131
    virObjectUnlock(vm);
2132
    VIR_FREE(name);
2133
    return ret;
2134 2135
}

2136 2137 2138 2139 2140 2141 2142 2143
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

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

2150
    ret = vm->hasManagedSave;
2151 2152 2153

cleanup:
    if (vm)
2154
        virObjectUnlock(vm);
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
    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 已提交
2168
    if (!(vm = libxlDomObjFromDomain(dom)))
2169 2170
        goto cleanup;

2171 2172 2173
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2174 2175 2176 2177 2178
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
2179
    vm->hasManagedSave = false;
2180 2181 2182 2183

cleanup:
    VIR_FREE(name);
    if (vm)
2184
        virObjectUnlock(vm);
2185 2186 2187
    return ret;
}

2188 2189 2190 2191 2192
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2193
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2194 2195 2196
    libxlDomainObjPrivatePtr priv;
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
2197
    libxl_bitmap map;
2198 2199
    uint8_t *bitmask = NULL;
    unsigned int maplen;
2200 2201
    size_t i;
    unsigned int pos;
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
    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)) {
2214 2215
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2216 2217 2218 2219
        return -1;
    }

    if (!nvcpus) {
2220
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
2221 2222 2223
        return -1;
    }

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

2227 2228 2229
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

2233
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
2234 2235
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
2236
        goto endjob;
2237 2238 2239
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
2240 2241
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
2242
        goto endjob;
2243 2244
    }

2245
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
2246 2247
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
2248
        goto endjob;
2249 2250 2251 2252 2253 2254 2255
    }

    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && vm->def->maxvcpus < max) {
        max = vm->def->maxvcpus;
    }

    if (nvcpus > max) {
2256 2257 2258
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
2259
        goto endjob;
2260 2261 2262 2263
    }

    priv = vm->privateData;

2264
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm)))
2265
        goto endjob;
2266

E
Eric Blake 已提交
2267
    maplen = VIR_CPU_MAPLEN(nvcpus);
2268
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
2269
        goto endjob;
2270 2271

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
2272
        pos = i / 8;
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
        bitmask[pos] |= 1 << (i % 8);
    }

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

    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
        def->maxvcpus = nvcpus;
        if (nvcpus < def->vcpus)
            def->vcpus = nvcpus;
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
        def->vcpus = nvcpus;
        break;

    case VIR_DOMAIN_VCPU_LIVE:
J
Jim Fehlig 已提交
2291
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2292 2293 2294
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2295
            goto endjob;
2296 2297 2298 2299
        }
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
J
Jim Fehlig 已提交
2300
        if (libxl_set_vcpuonline(priv->ctx, dom->id, &map) != 0) {
2301 2302 2303
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
                             " with libxenlight"), dom->id);
2304
            goto endjob;
2305 2306 2307 2308 2309 2310 2311 2312
        }
        def->vcpus = nvcpus;
        break;
    }

    ret = 0;

    if (flags & VIR_DOMAIN_VCPU_CONFIG)
2313
        ret = virDomainSaveConfig(cfg->configDir, def);
2314

2315 2316 2317 2318
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2319 2320 2321
cleanup:
    VIR_FREE(bitmask);
     if (vm)
2322
        virObjectUnlock(vm);
2323
     virObjectUnref(cfg);
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
    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;
2339
    bool active;
2340 2341 2342 2343 2344

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

J
Jim Fehlig 已提交
2345
    if (!(vm = libxlDomObjFromDomain(dom)))
2346 2347
        goto cleanup;

2348
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2349 2350
        goto cleanup;

2351 2352 2353 2354 2355 2356 2357 2358 2359
    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)) {
2360 2361
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
2362 2363 2364
        return -1;
    }

2365
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
2366
        if (!active) {
2367 2368
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
2369 2370 2371 2372
            goto cleanup;
        }
        def = vm->def;
    } else {
2373
        if (!vm->persistent) {
2374 2375
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
2376 2377
            goto cleanup;
        }
2378 2379 2380 2381 2382 2383 2384
        def = vm->newDef ? vm->newDef : vm->def;
    }

    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;

cleanup:
    if (vm)
2385
        virObjectUnlock(vm);
2386 2387 2388 2389
    return ret;
}

static int
2390 2391 2392
libxlDomainPinVcpuFlags(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen,
                        unsigned int flags)
2393 2394
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2395
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2396
    virDomainDefPtr targetDef = NULL;
2397
    virBitmapPtr pcpumap = NULL;
2398 2399
    virDomainObjPtr vm;
    int ret = -1;
2400 2401 2402

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
2403

J
Jim Fehlig 已提交
2404
    if (!(vm = libxlDomObjFromDomain(dom)))
2405 2406
        goto cleanup;

2407
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
2408 2409
        goto cleanup;

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

2413
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) && !virDomainObjIsActive(vm)) {
2414
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2415
                       _("domain is inactive"));
2416
        goto endjob;
2417 2418
    }

2419 2420
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
2421
        goto endjob;
2422 2423 2424 2425 2426 2427 2428 2429

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        targetDef = vm->def;
    }

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

2430 2431
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
2432
        goto endjob;
2433

2434 2435 2436 2437 2438 2439 2440 2441 2442
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        libxl_bitmap map = { .size = maplen, .map = cpumap };
        libxlDomainObjPrivatePtr priv;

        priv = vm->privateData;
        if (libxl_set_vcpuaffinity(priv->ctx, dom->id, vcpu, &map) != 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"),
                           vcpu);
2443
            goto endjob;
2444
        }
2445
    }
2446

2447 2448 2449 2450 2451 2452
    /* full bitmap means reset the settings (if any). */
    if (virBitmapIsAllSet(pcpumap)) {
        if (virDomainVcpuPinDel(targetDef, vcpu) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to delete vcpupin xml for vcpu '%d'"),
                           vcpu);
2453
            goto endjob;
2454
        }
2455
        goto done;
2456 2457
    }

2458 2459
    if (!targetDef->cputune.vcpupin) {
        if (VIR_ALLOC(targetDef->cputune.vcpupin) < 0)
2460
            goto endjob;
2461
        targetDef->cputune.nvcpupin = 0;
H
Hu Tao 已提交
2462
    }
2463 2464
    if (virDomainVcpuPinAdd(&targetDef->cputune.vcpupin,
                            &targetDef->cputune.nvcpupin,
H
Hu Tao 已提交
2465 2466 2467
                            cpumap,
                            maplen,
                            vcpu) < 0) {
2468 2469
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to update or add vcpupin xml"));
2470
        goto endjob;
2471 2472
    }

2473
done:
2474 2475
    ret = 0;

2476 2477 2478 2479 2480 2481
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        ret = virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm);
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        ret = virDomainSaveConfig(cfg->configDir, targetDef);
    }

2482 2483 2484 2485
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

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

2494 2495 2496 2497 2498 2499 2500 2501
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
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;
    virDomainVcpuPinDefPtr *vcpupin_list;
    virBitmapPtr cpumask = NULL;
    int maxcpu, hostcpus, vcpu, pcpu, n, ret = -1;
    unsigned char *cpumap;
    bool pinned;

    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;

    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        targetDef = vm->def;
    }

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

    /* Clamp to actual number of vcpus */
    if (ncpumaps > targetDef->vcpus)
        ncpumaps = targetDef->vcpus;

    /* we use cfg->ctx, as vm->privateData->ctx may be NULL if VM is down. */
    if ((hostcpus = libxl_get_max_cpus(cfg->ctx)) < 0)
        goto cleanup;

    maxcpu = maplen * 8;
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;

    /* initialize cpumaps */
    memset(cpumaps, 0xff, maplen * ncpumaps);
    if (maxcpu % 8) {
        for (vcpu = 0; vcpu < ncpumaps; vcpu++) {
            cpumap = VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
            cpumap[maplen - 1] &= (1 << maxcpu % 8) - 1;
        }
    }

    /* if vcpupin setting exists, there may be unused pcpus */
    for (n = 0; n < targetDef->cputune.nvcpupin; n++) {
        vcpupin_list = targetDef->cputune.vcpupin;
        vcpu = vcpupin_list[n]->vcpuid;
        cpumask = vcpupin_list[n]->cpumask;
        cpumap = VIR_GET_CPUMAP(cpumaps, maplen, vcpu);
        for (pcpu = 0; pcpu < maxcpu; pcpu++) {
            if (virBitmapGetBit(cpumask, pcpu, &pinned) < 0)
                goto cleanup;
            if (!pinned)
                VIR_UNUSE_CPU(cpumap, pcpu);
        }
    }
    ret = ncpumaps;

cleanup:
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(cfg);
    return ret;
}
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588

static int
libxlDomainGetVcpus(virDomainPtr dom, virVcpuInfoPtr info, int maxinfo,
                    unsigned char *cpumaps, int maplen)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    int ret = -1;
    libxl_vcpuinfo *vcpuinfo;
    int maxcpu, hostcpus;
2589
    size_t i;
2590 2591
    unsigned char *cpumap;

J
Jim Fehlig 已提交
2592
    if (!(vm = libxlDomObjFromDomain(dom)))
2593 2594
        goto cleanup;

2595 2596 2597
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2598
    if (!virDomainObjIsActive(vm)) {
2599
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2600 2601 2602 2603
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
2604
    if ((vcpuinfo = libxl_list_vcpu(priv->ctx, dom->id, &maxcpu,
2605
                                    &hostcpus)) == NULL) {
2606 2607 2608
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
                       dom->id);
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
        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 已提交
2631
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2632 2633 2634 2635 2636 2637 2638
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

cleanup:
    if (vm)
2639
        virObjectUnlock(vm);
2640 2641 2642
    return ret;
}

J
Jim Fehlig 已提交
2643
static char *
2644
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2645 2646 2647 2648
{
    virDomainObjPtr vm;
    char *ret = NULL;

2649 2650
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2651
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2652 2653
        goto cleanup;

2654 2655 2656
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

  cleanup:
    if (vm)
2661
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2662 2663 2664
    return ret;
}

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

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

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

2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
    if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
        if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
            goto cleanup;

        if (!(def = xenParseXM(conf,
                               cfg->verInfo->xen_version_major,
                               cfg->caps))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("parsing xm config failed"));
            goto cleanup;
        }
    } else if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_SEXPR)) {
        /* only support latest xend config format */
        if (!(def = xenParseSxprString(nativeConfig,
                                       XEND_CONFIG_VERSION_3_1_0,
                                       NULL,
                                       -1))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("parsing sxpr config failed"));
            goto cleanup;
        }
    } else {
2704 2705
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2706 2707 2708 2709 2710 2711 2712 2713 2714
        goto cleanup;
    }

    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);

cleanup:
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2715
    virObjectUnref(cfg);
2716 2717 2718 2719 2720
    return xml;
}

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

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

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

2737
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2738 2739
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2740 2741 2742
        goto cleanup;
    }

2743
    if (!(def = virDomainDefParseString(domainXml,
2744
                                        cfg->caps, driver->xmlopt,
2745 2746
                                        1 << VIR_DOMAIN_VIRT_XEN,
                                        VIR_DOMAIN_XML_INACTIVE)))
2747 2748
        goto cleanup;

2749
    if (!(conf = xenFormatXM(conn, def, cfg->verInfo->xen_version_major)))
2750 2751
        goto cleanup;

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

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

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

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

2775 2776 2777
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

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

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

2789 2790 2791
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

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

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

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

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

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

J
Jim Fehlig 已提交
2814
    if (virDomainObjIsActive(vm)) {
2815 2816
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
J
Jim Fehlig 已提交
2817 2818 2819
        goto cleanup;
    }

2820
    ret = libxlVmStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0, -1);
J
Jim Fehlig 已提交
2821 2822 2823

cleanup:
    if (vm)
2824
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837
    return ret;
}

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

static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    libxlDriverPrivatePtr driver = conn->privateData;
2838
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2839 2840 2841
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
2842
    virObjectEventPtr event = NULL;
2843
    virDomainDefPtr oldDef = NULL;
J
Jim Fehlig 已提交
2844

2845
    /* Lock the driver until the virDomainObj is created and locked */
J
Jim Fehlig 已提交
2846
    libxlDriverLock(driver);
2847
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
M
Matthias Bolte 已提交
2848
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
2849
                                        VIR_DOMAIN_XML_INACTIVE)))
2850
        goto cleanup_unlock;
J
Jim Fehlig 已提交
2851

2852
    if (virDomainDefineXMLEnsureACL(conn, def) < 0)
2853
        goto cleanup_unlock;
2854

2855
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2856
                                   driver->xmlopt,
2857 2858
                                   0,
                                   &oldDef)))
2859 2860
        goto cleanup_unlock;

J
Jim Fehlig 已提交
2861 2862
    def = NULL;
    vm->persistent = 1;
2863
    libxlDriverUnlock(driver);
J
Jim Fehlig 已提交
2864

2865
    if (virDomainSaveConfig(cfg->configDir,
J
Jim Fehlig 已提交
2866
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2867
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
2868 2869 2870 2871 2872 2873 2874 2875
        vm = NULL;
        goto cleanup;
    }

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

2876
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2877
                                     !oldDef ?
2878 2879 2880
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

J
Jim Fehlig 已提交
2881 2882
cleanup:
    virDomainDefFree(def);
2883
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
2884
    if (vm)
2885
        virObjectUnlock(vm);
2886 2887
    if (event)
        libxlDomainEventQueue(driver, event);
2888
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2889
    return dom;
2890 2891 2892 2893

cleanup_unlock:
    libxlDriverUnlock(driver);
    goto cleanup;
J
Jim Fehlig 已提交
2894 2895 2896
}

static int
2897 2898
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2899 2900
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2901
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2902
    virDomainObjPtr vm;
2903
    virObjectEventPtr event = NULL;
2904
    char *name = NULL;
J
Jim Fehlig 已提交
2905 2906
    int ret = -1;

2907 2908
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2909
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2910 2911
        goto cleanup;

2912 2913 2914
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2915
    if (!vm->persistent) {
2916 2917
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2918 2919 2920
        goto cleanup;
    }

2921 2922 2923 2924 2925 2926 2927
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2928 2929
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2930 2931 2932
                goto cleanup;
            }
        } else {
2933 2934 2935
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2936 2937 2938 2939
            goto cleanup;
        }
    }

2940
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2941 2942
        goto cleanup;

2943
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2944 2945
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2946 2947 2948
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
2949
        virDomainObjListRemove(driver->domains, vm);
2950 2951 2952
        vm = NULL;
    }

J
Jim Fehlig 已提交
2953 2954 2955
    ret = 0;

  cleanup:
2956
    VIR_FREE(name);
J
Jim Fehlig 已提交
2957
    if (vm)
2958
        virObjectUnlock(vm);
2959 2960
    if (event)
        libxlDomainEventQueue(driver, event);
2961
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2962 2963 2964
    return ret;
}

2965 2966 2967 2968 2969 2970
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2971 2972 2973 2974 2975 2976
static int
libxlDomainChangeEjectableMedia(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDiskDefPtr disk)
{
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2977
    size_t i;
2978 2979
    int ret = -1;

2980
    for (i = 0; i < vm->def->ndisks; i++) {
2981 2982 2983 2984 2985 2986 2987 2988
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
2989 2990 2991
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
2992 2993 2994 2995
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2996 2997 2998
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
2999 3000 3001
        return -1;
    }

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

J
Jim Fehlig 已提交
3005
    if ((ret = libxl_cdrom_insert(priv->ctx, vm->def->id, &x_disk, NULL)) < 0) {
3006 3007 3008
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
        goto cleanup;
    }

    VIR_FREE(origdisk->src);
    origdisk->src = disk->src;
    disk->src = NULL;
    origdisk->type = disk->type;


    virDomainDiskDefFree(disk);

    ret = 0;

cleanup:
    return ret;
}

static int
libxlDomainAttachDeviceDiskLive(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr l_disk = dev->data.disk;
    libxl_device_disk x_disk;
    int ret = -1;

    switch (l_disk->device)  {
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
            ret = libxlDomainChangeEjectableMedia(priv, vm, l_disk);
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (l_disk->bus == VIR_DOMAIN_DISK_BUS_XEN) {
3040
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
3041 3042
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
3043 3044 3045 3046
                    goto cleanup;
                }

                if (!l_disk->src) {
3047 3048
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
3049 3050 3051
                    goto cleanup;
                }

3052
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
3053 3054
                    goto cleanup;

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

J
Jim Fehlig 已提交
3058 3059
                if ((ret = libxl_device_disk_add(priv->ctx, vm->def->id,
                                                &x_disk, NULL)) < 0) {
3060 3061 3062
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
3063 3064 3065 3066 3067 3068
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

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

cleanup:
    return ret;
}

3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173
static int
libxlDomainAttachHostPCIDevice(libxlDriverPrivatePtr driver,
                               libxlDomainObjPrivatePtr priv,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    libxl_device_pci pcidev;
    virDomainHostdevDefPtr found;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

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

    if (virDomainHostdevFind(vm->def, hostdev, &found) >= 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("target pci device %.4x:%.2x:%.2x.%.1x already exists"),
                       hostdev->source.subsys.u.pci.addr.domain,
                       hostdev->source.subsys.u.pci.addr.bus,
                       hostdev->source.subsys.u.pci.addr.slot,
                       hostdev->source.subsys.u.pci.addr.function);
        return -1;
    }

    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs + 1) < 0)
        return -1;

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

    if (libxlMakePci(hostdev, &pcidev) < 0)
        goto reattach_hostdev;

    if (libxl_device_pci_add(priv->ctx, vm->def->id, &pcidev, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to attach pci device %.4x:%.2x:%.2x.%.1x"),
                       hostdev->source.subsys.u.pci.addr.domain,
                       hostdev->source.subsys.u.pci.addr.bus,
                       hostdev->source.subsys.u.pci.addr.slot,
                       hostdev->source.subsys.u.pci.addr.function);
        goto reattach_hostdev;
    }

    vm->def->hostdevs[vm->def->nhostdevs++] = hostdev;
    return 0;

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

cleanup:
    return -1;
}

static int
libxlDomainAttachHostDevice(libxlDriverPrivatePtr driver,
                            libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm,
                            virDomainDeviceDefPtr dev)
{
    virDomainHostdevDefPtr hostdev = dev->data.hostdev;

    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:
        if (libxlDomainAttachHostPCIDevice(driver, priv, vm, hostdev) < 0)
            goto error;
        break;

    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
        goto error;
    }

    return 0;

error:
    return -1;
}

3174 3175 3176 3177 3178 3179
static int
libxlDomainDetachDeviceDiskLive(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
3180
    int idx;
3181 3182 3183 3184 3185 3186
    int ret = -1;

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

3187 3188 3189
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
3190 3191
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
3192 3193 3194
                    goto cleanup;
                }

3195
                l_disk = vm->def->disks[idx];
3196

J
Jim Fehlig 已提交
3197
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
3198 3199
                    goto cleanup;

J
Jim Fehlig 已提交
3200 3201
                if ((ret = libxl_device_disk_remove(priv->ctx, vm->def->id,
                                                    &x_disk, NULL)) < 0) {
3202 3203 3204
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
3205 3206 3207
                    goto cleanup;
                }

3208
                virDomainDiskRemove(vm->def, idx);
3209 3210 3211
                virDomainDiskDefFree(l_disk);

            } else {
3212 3213 3214
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
3215 3216 3217
            }
            break;
        default:
3218 3219 3220
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
3221 3222 3223 3224 3225 3226 3227 3228
            break;
    }

cleanup:
    return ret;
}

static int
3229 3230 3231
libxlDomainAttachDeviceLive(libxlDriverPrivatePtr driver,
                            libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm,
3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            ret = libxlDomainAttachDeviceDiskLive(priv, vm, dev);
            if (!ret)
                dev->data.disk = NULL;
            break;

3243 3244 3245 3246 3247 3248
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            ret = libxlDomainAttachHostDevice(driver, priv, vm, dev);
            if (!ret)
                dev->data.hostdev = NULL;
            break;

3249
        default:
3250 3251 3252
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
            break;
    }

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
3263 3264
    virDomainHostdevDefPtr hostdev;
    virDomainHostdevDefPtr found;
3265 3266 3267 3268

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3269
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
3270 3271
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
3272 3273
                return -1;
            }
3274
            if (virDomainDiskInsert(vmdef, disk))
3275 3276 3277 3278
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;
3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            hostdev = dev->data.hostdev;

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

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

            virDomainHostdevInsert(vmdef, hostdev);
            break;
3298 3299

        default:
3300 3301
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
3302 3303 3304 3305 3306 3307
            return -1;
    }
    return 0;
}

static int
3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429
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,
                               libxlDomainObjPrivatePtr priv,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
    libxl_device_pci pcidev;
    virDomainHostdevDefPtr detach;
    int idx;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

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

    idx = virDomainHostdevFind(vm->def, hostdev, &detach);
    if (idx < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("host pci device %.4x:%.2x:%.2x.%.1x not found"),
                       subsys->u.pci.addr.domain, subsys->u.pci.addr.bus,
                       subsys->u.pci.addr.slot, subsys->u.pci.addr.function);
        return -1;
    }

    if (libxlIsMultiFunctionDevice(vm->def, detach->info)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %.4x:%.2x:%.2x.%.1x"),
                       subsys->u.pci.addr.domain, subsys->u.pci.addr.bus,
                       subsys->u.pci.addr.slot, subsys->u.pci.addr.function);
        goto cleanup;
    }


    libxl_device_pci_init(&pcidev);

    if (libxlMakePci(detach, &pcidev) < 0)
        goto cleanup;

    if (libxl_device_pci_remove(priv->ctx, vm->def->id, &pcidev, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to detach pci device\
                          %.4x:%.2x:%.2x.%.1x"),
                       subsys->u.pci.addr.domain, subsys->u.pci.addr.bus,
                       subsys->u.pci.addr.slot, subsys->u.pci.addr.function);
        goto cleanup;
    }

    libxl_device_pci_dispose(&pcidev);

    virDomainHostdevRemove(vm->def, idx);

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

    return 0;

cleanup:
    virDomainHostdevDefFree(detach);
    return -1;
}

static int
libxlDomainDetachHostDevice(libxlDriverPrivatePtr driver,
                            libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm,
                            virDomainDeviceDefPtr dev)
{
    virDomainHostdevDefPtr hostdev = dev->data.hostdev;
    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:
            return libxlDomainDetachHostPCIDevice(driver, priv, vm, hostdev);

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

    return -1;
}

static int
libxlDomainDetachDeviceLive(libxlDriverPrivatePtr driver,
                            libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm,
3430 3431 3432 3433 3434 3435 3436 3437 3438
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            ret = libxlDomainDetachDeviceDiskLive(priv, vm, dev);
            break;

3439 3440 3441 3442
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            ret = libxlDomainDetachHostDevice(driver, priv, vm, dev);
            break;

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

    return ret;
}

3453

3454 3455 3456
static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
3457
    virDomainDiskDefPtr disk, detach;
3458 3459 3460 3461 3462
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3463
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
3464 3465
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
3466 3467
                break;
            }
3468
            virDomainDiskDefFree(detach);
3469 3470 3471
            ret = 0;
            break;
        default:
3472 3473
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceLive(libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    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:
                    ret = libxlDomainChangeEjectableMedia(priv, vm, disk);
                    if (ret == 0)
                        dev->data.disk = NULL;
                    break;
                default:
3497 3498 3499
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3500 3501 3502 3503
                    break;
            }
            break;
        default:
3504 3505 3506
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr orig;
    virDomainDiskDefPtr disk;
3518
    int idx;
3519 3520 3521 3522 3523
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3524
            if ((idx = virDomainDiskIndexByName(vmdef, disk->dst, false)) < 0) {
3525 3526
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3527 3528
                goto cleanup;
            }
3529
            orig = vmdef->disks[idx];
3530
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3531 3532
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
                goto cleanup;
            }

            VIR_FREE(orig->src);
            orig->src = disk->src;
            orig->type = disk->type;
            if (disk->driverName) {
                VIR_FREE(orig->driverName);
                orig->driverName = disk->driverName;
                disk->driverName = NULL;
            }
3544
            orig->format = disk->format;
3545 3546 3547
            disk->src = NULL;
            break;
        default:
3548 3549
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560
            goto cleanup;
    }

    ret = 0;

cleanup:
    return ret;
}


static int
3561 3562
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3563 3564
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3565
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3566 3567 3568 3569 3570 3571 3572 3573 3574
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    libxlDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3575
    if (!(vm = libxlDomObjFromDomain(dom)))
3576 3577
        goto cleanup;

3578 3579 3580
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3584 3585 3586 3587 3588 3589 3590 3591
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
3592 3593
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3594
            goto endjob;
3595 3596 3597 3598
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
3599 3600
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3601
         goto endjob;
3602 3603 3604 3605 3606
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3607
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3608
                                            cfg->caps, driver->xmlopt,
3609
                                            VIR_DOMAIN_XML_INACTIVE)))
3610
            goto endjob;
3611 3612

        /* Make a copy for updated domain. */
3613
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3614
                                                    driver->xmlopt)))
3615
            goto endjob;
3616

3617
        if ((ret = libxlDomainAttachDeviceConfig(vmdef, dev)) < 0)
3618
            goto endjob;
3619
    } else {
3620
        ret = 0;
3621
    }
3622 3623 3624 3625

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
3626
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3627
                                            cfg->caps, driver->xmlopt,
3628
                                            VIR_DOMAIN_XML_INACTIVE)))
3629
            goto endjob;
3630

3631
        if ((ret = libxlDomainAttachDeviceLive(driver, priv, vm, dev)) < 0)
3632
            goto endjob;
3633

3634 3635 3636 3637
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3638
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3639 3640 3641 3642 3643
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3644
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3645
        if (!ret) {
3646
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3647 3648 3649 3650
            vmdef = NULL;
        }
    }

3651 3652 3653 3654
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3655 3656 3657 3658
cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3659
        virObjectUnlock(vm);
3660
    virObjectUnref(cfg);
3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674
    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)
{
3675
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3676
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3677 3678 3679 3680 3681 3682 3683 3684 3685
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    libxlDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3686
    if (!(vm = libxlDomObjFromDomain(dom)))
3687 3688
        goto cleanup;

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

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

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

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

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3719
                                            cfg->caps, driver->xmlopt,
3720
                                            VIR_DOMAIN_XML_INACTIVE)))
3721
            goto endjob;
3722 3723

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

        if ((ret = libxlDomainDetachDeviceConfig(vmdef, dev)) < 0)
3729
            goto endjob;
3730 3731 3732 3733 3734 3735 3736 3737
    } 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,
3738
                                            cfg->caps, driver->xmlopt,
3739
                                            VIR_DOMAIN_XML_INACTIVE)))
3740
            goto endjob;
3741

3742
        if ((ret = libxlDomainDetachDeviceLive(driver, priv, vm, dev)) < 0)
3743
            goto endjob;
3744 3745 3746 3747 3748

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

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

3762 3763 3764 3765
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3766 3767 3768 3769 3770
cleanup:
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3771
    virObjectUnref(cfg);
3772
    return ret;
3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785
}

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)
{
3786
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3787
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3788 3789 3790 3791 3792 3793 3794 3795 3796
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    libxlDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3797
    if (!(vm = libxlDomObjFromDomain(dom)))
3798 3799
        goto cleanup;

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

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

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

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3827
                                            cfg->caps, driver->xmlopt,
3828 3829 3830 3831
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3832
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845
                                                    driver->xmlopt)))
            goto cleanup;

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

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

        if ((ret = libxlDomainUpdateDeviceLive(priv, vm, dev)) < 0)
            goto cleanup;

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3857
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3858 3859 3860 3861 3862
            ret = -1;
    }

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

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

3879 3880 3881 3882 3883
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
3884 3885
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
3886

3887
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
3888
        goto cleanup;
3889

3890
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
3891 3892
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3893
        goto cleanup;
3894 3895
    }

3896 3897 3898 3899 3900
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

cleanup:
    virObjectUnref(cfg);
    return ret;
3901 3902
}

3903 3904 3905 3906 3907 3908 3909 3910 3911 3912
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;
3913
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3914 3915

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
3916
        goto cleanup;
3917

3918
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
3919
    if (numa_info == NULL || nr_nodes == 0) {
3920 3921 3922
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
3923 3924 3925
    }

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

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

3943 3944 3945 3946
    ret = numCells;

cleanup:
    libxl_numainfo_list_free(numa_info, nr_nodes);
3947
    virObjectUnref(cfg);
3948 3949 3950
    return ret;
}

3951
static int
3952
libxlConnectDomainEventRegister(virConnectPtr conn,
3953 3954
                                virConnectDomainEventCallback callback,
                                void *opaque,
3955
                                virFreeCallback freecb)
3956 3957 3958
{
    libxlDriverPrivatePtr driver = conn->privateData;

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

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

3967
    return 0;
3968 3969 3970 3971
}


static int
3972 3973
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
3974 3975 3976
{
    libxlDriverPrivatePtr driver = conn->privateData;

3977 3978 3979
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

3980 3981 3982 3983
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
3984

3985
    return 0;
3986 3987
}

3988 3989 3990 3991 3992 3993
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
3994
    if (!(vm = libxlDomObjFromDomain(dom)))
3995 3996
        goto cleanup;

3997 3998 3999
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4000 4001 4002 4003 4004
    *autostart = vm->autostart;
    ret = 0;

cleanup:
    if (vm)
4005
        virObjectUnlock(vm);
4006 4007 4008 4009 4010 4011 4012
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4013
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
4014 4015 4016 4017
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
4018
    if (!(vm = libxlDomObjFromDomain(dom)))
4019 4020
        goto cleanup;

4021 4022 4023
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

4027
    if (!vm->persistent) {
4028 4029
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
4030
        goto endjob;
4031 4032 4033 4034 4035
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
4036
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
4037
            goto endjob;
4038
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
4039
            goto endjob;
4040 4041

        if (autostart) {
4042
            if (virFileMakePath(cfg->autostartDir) < 0) {
4043
                virReportSystemError(errno,
4044
                                     _("cannot create autostart directory %s"),
4045
                                     cfg->autostartDir);
4046
                goto endjob;
4047 4048 4049 4050 4051 4052
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4053
                goto endjob;
4054 4055 4056 4057 4058 4059
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4060
                goto endjob;
4061 4062 4063 4064 4065 4066 4067
            }
        }

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

4068 4069 4070 4071
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

4072 4073 4074 4075
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    if (vm)
4076
        virObjectUnlock(vm);
4077
    virObjectUnref(cfg);
4078 4079 4080
    return ret;
}

4081 4082 4083 4084 4085 4086
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    char * ret = NULL;
4087
    const char *name = NULL;
J
Jim Fehlig 已提交
4088
    libxl_scheduler sched_id;
4089

J
Jim Fehlig 已提交
4090
    if (!(vm = libxlDomObjFromDomain(dom)))
4091 4092
        goto cleanup;

4093 4094 4095
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4096
    if (!virDomainObjIsActive(vm)) {
4097
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4098 4099 4100 4101
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
4102
    sched_id = libxl_get_scheduler(priv->ctx);
4103

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

4128
    ignore_value(VIR_STRDUP(ret, name));
4129 4130 4131

cleanup:
    if (vm)
4132
        virObjectUnlock(vm);
4133 4134 4135
    return ret;
}

4136
static int
4137 4138 4139 4140
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
4141 4142 4143
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4144 4145
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
4146 4147
    int ret = -1;

4148 4149 4150 4151
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

J
Jim Fehlig 已提交
4153
    if (!(vm = libxlDomObjFromDomain(dom)))
4154 4155
        goto cleanup;

4156 4157 4158
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

4159
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
4160 4161
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
4162 4163 4164 4165 4166
        goto cleanup;
    }

    priv = vm->privateData;

J
Jim Fehlig 已提交
4167
    sched_id = libxl_get_scheduler(priv->ctx);
4168

J
Jim Fehlig 已提交
4169
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4170 4171
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4172 4173 4174
        goto cleanup;
    }

J
Jim Fehlig 已提交
4175
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
4176 4177 4178
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
4179 4180 4181
        goto cleanup;
    }

4182 4183
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
4184 4185
        goto cleanup;

4186
    if (*nparams > 1) {
4187 4188
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
4189
            goto cleanup;
4190 4191
    }

4192 4193
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
4194 4195 4196 4197
    ret = 0;

cleanup:
    if (vm)
4198
        virObjectUnlock(vm);
4199 4200 4201 4202
    return ret;
}

static int
4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213
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)
4214
{
4215
    libxlDriverPrivatePtr driver = dom->conn->privateData;
4216 4217
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
4218
    libxl_domain_sched_params sc_info;
4219
    int sched_id;
4220
    size_t i;
4221 4222
    int ret = -1;

4223
    virCheckFlags(0, -1);
4224 4225 4226 4227 4228 4229
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
4230
        return -1;
4231

J
Jim Fehlig 已提交
4232
    if (!(vm = libxlDomObjFromDomain(dom)))
4233 4234
        goto cleanup;

4235 4236 4237
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

4241
    if (!virDomainObjIsActive(vm)) {
4242
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
4243
        goto endjob;
4244 4245 4246 4247
    }

    priv = vm->privateData;

J
Jim Fehlig 已提交
4248
    sched_id = libxl_get_scheduler(priv->ctx);
4249

J
Jim Fehlig 已提交
4250
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
4251 4252
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
4253
        goto endjob;
4254 4255
    }

J
Jim Fehlig 已提交
4256
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
4257 4258 4259
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
4260
        goto endjob;
4261 4262 4263
    }

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

4266
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
4267
            sc_info.weight = params[i].value.ui;
4268
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
4269 4270 4271
            sc_info.cap = params[i].value.ui;
    }

J
Jim Fehlig 已提交
4272
    if (libxl_domain_sched_params_set(priv->ctx, dom->id, &sc_info) != 0) {
4273 4274 4275
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
4276
        goto endjob;
4277 4278 4279 4280
    }

    ret = 0;

4281 4282 4283 4284
endjob:
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

4285 4286
cleanup:
    if (vm)
4287
        virObjectUnlock(vm);
4288 4289 4290
    return ret;
}

B
Bamvor Jian Zhang 已提交
4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312

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;
    char *console = NULL;

    virCheckFlags(VIR_DOMAIN_CONSOLE_FORCE, -1);

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

J
Jim Fehlig 已提交
4313
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369
        goto cleanup;

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

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

    priv = vm->privateData;

    if (vm->def->nserials)
        chr = vm->def->serials[0];

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

    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("character device %s is not using a PTY"),
                       NULLSTR(dev_name));
        goto cleanup;
    }

    ret = libxl_primary_console_get_tty(priv->ctx, vm->def->id, &console);
    if (ret)
        goto cleanup;

    if (VIR_STRDUP(chr->source.data.file.path, console) < 0)
        goto cleanup;

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

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

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

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

4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406
/* 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)
{
    libxlDomainObjPrivatePtr priv;
    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;

4407 4408
    libxl_bitmap_init(&nodemap);

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

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

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

    priv = vm->privateData;

    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];
4431
        int numnodes;
4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449

        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 */
4450 4451 4452 4453
            numnodes = libxl_get_max_nodes(priv->ctx);
            if (numnodes <= 0)
                goto cleanup;

4454
            if (libxl_node_bitmap_alloc(priv->ctx, &nodemap, 0) ||
4455
                !(nodes = virBitmapNew(numnodes))) {
4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507
                virReportOOMError();
                goto cleanup;
            }

            rc = libxl_domain_get_nodeaffinity(priv->ctx,
                                               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;
                }
            }

            nodeset = virBitmapFormat(nodes);
            if (!nodeset && VIR_STRDUP(nodeset, "") < 0)
                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;

cleanup:
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
    if (vm)
        virObjectUnlock(vm);
    return ret;
}
#endif

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

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

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

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

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

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

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

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

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

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

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

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

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

4560 4561 4562 4563
    ret = vm->updated;

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

4568
static int
4569 4570 4571
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4572 4573 4574 4575
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4576 4577 4578
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4579 4580 4581 4582
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4583
        ret = -1;
4584 4585 4586 4587 4588 4589

    return ret;
}


static int
4590
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4591 4592 4593
{
    libxlDriverPrivatePtr driver = conn->privateData;

4594 4595 4596
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4597 4598 4599 4600
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        return -1;
4601

4602
    return 0;
4603 4604
}

J
Jim Fehlig 已提交
4605

4606
static int
4607
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4608 4609 4610 4611
{
    return 1;
}

4612
static int
4613 4614 4615
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4616 4617 4618 4619
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4620
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4621

4622 4623 4624
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4625 4626
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
4627 4628 4629 4630

    return ret;
}

4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644
/* Which features are supported by this driver? */
static int
libxlConnectSupportsFeature(virConnectPtr conn, int feature)
{
    if (virConnectSupportsFeatureEnsureACL(conn) < 0)
        return -1;

    switch (feature) {
    case VIR_DRV_FEATURE_TYPED_PARAM_STRING:
        return 1;
    default:
        return 0;
    }
}
4645

4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820
static int
libxlNodeDeviceGetPCIInfo(virNodeDeviceDefPtr def,
                          unsigned *domain,
                          unsigned *bus,
                          unsigned *slot,
                          unsigned *function)
{
    virNodeDevCapsDefPtr cap;
    int ret = -1;

    cap = def->caps;
    while (cap) {
        if (cap->type == VIR_NODE_DEV_CAP_PCI_DEV) {
            *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);
        goto out;
    }

    ret = 0;
out:
    return ret;
}

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")) {
        if (virPCIDeviceSetStubDriver(pci, "pciback") < 0)
            goto cleanup;
    } else {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported driver name '%s'"), driverName);
        goto cleanup;
    }

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

    ret = 0;
cleanup:
    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)
        goto out;

    ret = 0;
out:
    virPCIDeviceFree(pci);
cleanup:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
    virPCIDevicePtr pci;
    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)
        goto out;

    ret = 0;
out:
    virPCIDeviceFree(pci);
cleanup:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

4821

J
Jim Fehlig 已提交
4822
static virDriver libxlDriver = {
4823
    .no = VIR_DRV_LIBXL,
4824
    .name = LIBXL_DRIVER_NAME,
4825 4826 4827 4828
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
4829
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
4830
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
4831
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
4832
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
4833 4834 4835 4836
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
4837 4838 4839 4840 4841 4842 4843
    .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 */
4844
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
4845 4846
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
4847
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
4848 4849
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
4850
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
4851 4852 4853 4854
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
4855
    .domainSave = libxlDomainSave, /* 0.9.2 */
4856
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
4857
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
4858
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
4859
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
4860 4861 4862 4863
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
4864
    .domainPinVcpuFlags = libxlDomainPinVcpuFlags, /* 1.2.1 */
4865
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
4866
    .domainGetVcpuPinInfo = libxlDomainGetVcpuPinInfo, /* 1.2.1 */
4867
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
4868 4869 4870 4871
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
4872 4873 4874 4875
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
4876
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
4877 4878 4879 4880 4881
    .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 */
4882 4883 4884 4885
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
4886
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
4887
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
4888
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
4889 4890 4891
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
4892
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
4893
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
4894 4895
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
4896 4897 4898
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
4899
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
4900 4901 4902
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
4903 4904 4905
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
4906
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
4907 4908 4909 4910
    .nodeDeviceDettach = libxlNodeDeviceDettach, /* 1.2.3 */
    .nodeDeviceDetachFlags = libxlNodeDeviceDetachFlags, /* 1.2.3 */
    .nodeDeviceReAttach = libxlNodeDeviceReAttach, /* 1.2.3 */
    .nodeDeviceReset = libxlNodeDeviceReset, /* 1.2.3 */
J
Jim Fehlig 已提交
4911 4912 4913 4914
};

static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
4915
    .stateInitialize = libxlStateInitialize,
4916
    .stateAutoStart = libxlStateAutoStart,
4917 4918
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931
};


int
libxlRegister(void)
{
    if (virRegisterDriver(&libxlDriver) < 0)
        return -1;
    if (virRegisterStateDriver(&libxlStateDriver) < 0)
        return -1;

    return 0;
}