libxl_domain.c 42.2 KB
Newer Older
J
Jim Fehlig 已提交
1 2 3
/*
 * libxl_domain.c: libxl domain object private state
 *
4
 * Copyright (C) 2011-2015 SUSE LINUX Products GmbH, Nuernberg, Germany.
J
Jim Fehlig 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * 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
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *     Jim Fehlig <jfehlig@suse.com>
 */

#include <config.h>

26 27
#include <fcntl.h>

J
Jim Fehlig 已提交
28
#include "libxl_domain.h"
29
#include "libxl_capabilities.h"
J
Jim Fehlig 已提交
30 31

#include "viralloc.h"
32
#include "viratomic.h"
J
Jim Fehlig 已提交
33 34
#include "virfile.h"
#include "virerror.h"
C
Cédric Bosdonnat 已提交
35
#include "virhook.h"
J
Jim Fehlig 已提交
36 37
#include "virlog.h"
#include "virstring.h"
38
#include "virtime.h"
39
#include "locking/domain_lock.h"
P
Pavel Hrdina 已提交
40
#include "xen_common.h"
41
#include "network/bridge_driver.h"
J
Jim Fehlig 已提交
42 43 44

#define VIR_FROM_THIS VIR_FROM_LIBXL

45
VIR_LOG_INIT("libxl.libxl_domain");
J
Jim Fehlig 已提交
46

47 48 49 50 51 52 53
VIR_ENUM_IMPL(libxlDomainJob, LIBXL_JOB_LAST,
              "none",
              "query",
              "destroy",
              "modify",
);

J
Jim Fehlig 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
static virClassPtr libxlDomainObjPrivateClass;

static void
libxlDomainObjPrivateDispose(void *obj);

static int
libxlDomainObjPrivateOnceInit(void)
{
    if (!(libxlDomainObjPrivateClass = virClassNew(virClassForObjectLockable(),
                                                   "libxlDomainObjPrivate",
                                                   sizeof(libxlDomainObjPrivate),
                                                   libxlDomainObjPrivateDispose)))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(libxlDomainObjPrivate)

73 74 75 76 77 78 79 80
static int
libxlDomainObjInitJob(libxlDomainObjPrivatePtr priv)
{
    memset(&priv->job, 0, sizeof(priv->job));

    if (virCondInit(&priv->job.cond) < 0)
        return -1;

81 82 83
    if (VIR_ALLOC(priv->job.current) < 0)
        return -1;

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    return 0;
}

static void
libxlDomainObjResetJob(libxlDomainObjPrivatePtr priv)
{
    struct libxlDomainJobObj *job = &priv->job;

    job->active = LIBXL_JOB_NONE;
    job->owner = 0;
}

static void
libxlDomainObjFreeJob(libxlDomainObjPrivatePtr priv)
{
    ignore_value(virCondDestroy(&priv->job.cond));
100
    VIR_FREE(priv->job.current);
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
}

/* Give up waiting for mutex after 30 seconds */
#define LIBXL_JOB_WAIT_TIME (1000ull * 30)

/*
 * obj must be locked before calling, libxlDriverPrivatePtr must NOT be locked
 *
 * This must be called by anything that will change the VM state
 * in any way
 *
 * Upon successful return, the object will have its ref count increased,
 * successful calls must be followed by EndJob eventually
 */
int
libxlDomainObjBeginJob(libxlDriverPrivatePtr driver ATTRIBUTE_UNUSED,
                       virDomainObjPtr obj,
                       enum libxlDomainJob job)
{
    libxlDomainObjPrivatePtr priv = obj->privateData;
    unsigned long long now;
    unsigned long long then;

    if (virTimeMillisNow(&now) < 0)
        return -1;
    then = now + LIBXL_JOB_WAIT_TIME;

    while (priv->job.active) {
        VIR_DEBUG("Wait normal job condition for starting job: %s",
                  libxlDomainJobTypeToString(job));
        if (virCondWaitUntil(&priv->job.cond, &obj->parent.lock, then) < 0)
            goto error;
    }

    libxlDomainObjResetJob(priv);

    VIR_DEBUG("Starting job: %s", libxlDomainJobTypeToString(job));
    priv->job.active = job;
    priv->job.owner = virThreadSelfID();
140 141
    priv->job.started = now;
    priv->job.current->type = VIR_DOMAIN_JOB_UNBOUNDED;
142 143 144

    return 0;

145
 error:
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    VIR_WARN("Cannot start job (%s) for domain %s;"
             " current job is (%s) owned by (%d)",
             libxlDomainJobTypeToString(job),
             obj->def->name,
             libxlDomainJobTypeToString(priv->job.active),
             priv->job.owner);

    if (errno == ETIMEDOUT)
        virReportError(VIR_ERR_OPERATION_TIMEOUT,
                       "%s", _("cannot acquire state change lock"));
    else
        virReportSystemError(errno,
                             "%s", _("cannot acquire job mutex"));

    return -1;
}

/*
 * obj must be locked before calling
 *
 * To be called after completing the work associated with the
 * earlier libxlDomainBeginJob() call
 *
 * Returns true if the remaining reference count on obj is
 * non-zero, false if the reference count has dropped to zero
 * and obj is disposed.
 */
W
Wang Yufei 已提交
173
void
174 175 176 177 178 179 180 181 182 183 184 185 186
libxlDomainObjEndJob(libxlDriverPrivatePtr driver ATTRIBUTE_UNUSED,
                     virDomainObjPtr obj)
{
    libxlDomainObjPrivatePtr priv = obj->privateData;
    enum libxlDomainJob job = priv->job.active;

    VIR_DEBUG("Stopping job: %s",
              libxlDomainJobTypeToString(job));

    libxlDomainObjResetJob(priv);
    virCondSignal(&priv->job.cond);
}

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
int
libxlDomainJobUpdateTime(struct libxlDomainJobObj *job)
{
    virDomainJobInfoPtr jobInfo = job->current;
    unsigned long long now;

    if (!job->started)
        return 0;

    if (virTimeMillisNow(&now) < 0)
        return -1;

    if (now < job->started) {
        job->started = 0;
        return 0;
    }

    jobInfo->timeElapsed = now - job->started;
    return 0;
}

J
Jim Fehlig 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
static void *
libxlDomainObjPrivateAlloc(void)
{
    libxlDomainObjPrivatePtr priv;

    if (libxlDomainObjPrivateInitialize() < 0)
        return NULL;

    if (!(priv = virObjectLockableNew(libxlDomainObjPrivateClass)))
        return NULL;

    if (!(priv->devs = virChrdevAlloc())) {
        virObjectUnref(priv);
        return NULL;
    }

224 225 226 227 228 229
    if (libxlDomainObjInitJob(priv) < 0) {
        virChrdevFree(priv->devs);
        virObjectUnref(priv);
        return NULL;
    }

J
Jim Fehlig 已提交
230 231 232 233 234 235 236 237
    return priv;
}

static void
libxlDomainObjPrivateDispose(void *obj)
{
    libxlDomainObjPrivatePtr priv = obj;

238
    libxlDomainObjFreeJob(priv);
J
Jim Fehlig 已提交
239 240 241 242 243 244 245 246
    virChrdevFree(priv->devs);
}

static void
libxlDomainObjPrivateFree(void *data)
{
    libxlDomainObjPrivatePtr priv = data;

247
    VIR_FREE(priv->lockState);
J
Jim Fehlig 已提交
248 249 250
    virObjectUnref(priv);
}

251
static int
252
libxlDomainObjPrivateXMLParse(xmlXPathContextPtr ctxt,
253 254
                              virDomainObjPtr vm,
                              virDomainDefParserConfigPtr config ATTRIBUTE_UNUSED)
255
{
256
    libxlDomainObjPrivatePtr priv = vm->privateData;
257 258 259 260 261 262 263

    priv->lockState = virXPathString("string(./lockstate)", ctxt);

    return 0;
}

static int
264 265
libxlDomainObjPrivateXMLFormat(virBufferPtr buf,
                               virDomainObjPtr vm)
266
{
267
    libxlDomainObjPrivatePtr priv = vm->privateData;
268 269 270 271 272 273 274

    if (priv->lockState)
        virBufferAsprintf(buf, "<lockstate>%s</lockstate>\n", priv->lockState);

    return 0;
}

J
Jim Fehlig 已提交
275 276 277
virDomainXMLPrivateDataCallbacks libxlDomainXMLPrivateDataCallbacks = {
    .alloc = libxlDomainObjPrivateAlloc,
    .free = libxlDomainObjPrivateFree,
278 279
    .parse = libxlDomainObjPrivateXMLParse,
    .format = libxlDomainObjPrivateXMLFormat,
J
Jim Fehlig 已提交
280 281 282 283 284
};


static int
libxlDomainDeviceDefPostParse(virDomainDeviceDefPtr dev,
285
                              const virDomainDef *def,
J
Jim Fehlig 已提交
286
                              virCapsPtr caps ATTRIBUTE_UNUSED,
287
                              unsigned int parseFlags ATTRIBUTE_UNUSED,
J
Jim Fehlig 已提交
288 289 290 291 292
                              void *opaque ATTRIBUTE_UNUSED)
{
    if (dev->type == VIR_DOMAIN_DEVICE_CHR &&
        dev->data.chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE &&
        dev->data.chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_NONE &&
293
        def->os.type != VIR_DOMAIN_OSTYPE_HVM)
J
Jim Fehlig 已提交
294 295
        dev->data.chr->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_XEN;

296 297 298 299
    if (dev->type == VIR_DOMAIN_DEVICE_NET &&
            (dev->data.net->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
             dev->data.net->type == VIR_DOMAIN_NET_TYPE_ETHERNET ||
             dev->data.net->type == VIR_DOMAIN_NET_TYPE_NETWORK)) {
300
        if (dev->data.net->guestIP.nips > 1) {
301 302 303 304 305 306 307
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                    _("multiple IP addresses not supported on device type %s"),
                    virDomainNetTypeToString(dev->data.net->type));
            return -1;
        }
    }

308 309 310 311 312
    if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV ||
        (dev->type == VIR_DOMAIN_DEVICE_NET &&
         dev->data.net->type == VIR_DOMAIN_NET_TYPE_HOSTDEV)) {

        virDomainHostdevDefPtr hostdev;
313
        virDomainHostdevSubsysPCIPtr pcisrc;
314 315

        if (dev->type == VIR_DOMAIN_DEVICE_NET)
316
            hostdev = &dev->data.net->data.hostdev.def;
317 318
        else
            hostdev = dev->data.hostdev;
319
        pcisrc = &hostdev->source.subsys.u.pci;
320

321 322 323 324 325 326 327 328 329
        /* forbid capabilities mode hostdev in this kind of hypervisor */
        if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_CAPABILITIES) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("hostdev mode 'capabilities' is not "
                             "supported in %s"),
                           virDomainVirtTypeToString(def->virtType));
            return -1;
        }

330 331
        if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
            hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
332 333
            pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT)
            pcisrc->backend = VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN;
334 335
    }

336
    if (dev->type == VIR_DOMAIN_DEVICE_VIDEO && def->os.type == VIR_DOMAIN_OSTYPE_HVM) {
337 338 339 340 341 342 343 344 345 346 347
        int dm_type = libxlDomainGetEmulatorType(def);

        switch (dev->data.video->type) {
        case VIR_DOMAIN_VIDEO_TYPE_VGA:
        case VIR_DOMAIN_VIDEO_TYPE_XEN:
            if (dev->data.video->vram == 0) {
                if (dm_type == LIBXL_DEVICE_MODEL_VERSION_QEMU_XEN)
                    dev->data.video->vram = 16 * 1024;
                else
                    dev->data.video->vram = 8 * 1024;
                }
348
            break;
349 350 351 352 353 354 355
        case VIR_DOMAIN_VIDEO_TYPE_CIRRUS:
            if (dev->data.video->vram == 0) {
                if (dm_type == LIBXL_DEVICE_MODEL_VERSION_QEMU_XEN)
                    dev->data.video->vram = 8 * 1024;
                else
                    dev->data.video->vram = 4 * 1024;
            }
356
            break;
J
Jim Fehlig 已提交
357 358 359 360
        case VIR_DOMAIN_VIDEO_TYPE_QXL:
            if (dev->data.video->vram == 0)
                dev->data.video->vram = 128 * 1024;
            break;
361 362 363
        }
    }

364 365 366 367 368 369 370 371 372 373 374 375
    /* for network-based disks, set 'qemu' as the default driver */
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        virDomainDiskDefPtr disk = dev->data.disk;
        int actual_type = virStorageSourceGetActualType(disk->src);

        if (actual_type == VIR_STORAGE_TYPE_NETWORK) {
            if (!virDomainDiskGetDriver(disk) &&
                virDomainDiskSetDriver(disk, "qemu") < 0)
                return -1;
        }
    }

J
Jim Fehlig 已提交
376 377 378
    return 0;
}

379 380 381
static int
libxlDomainDefPostParse(virDomainDefPtr def,
                        virCapsPtr caps ATTRIBUTE_UNUSED,
382
                        unsigned int parseFlags ATTRIBUTE_UNUSED,
383 384
                        void *opaque ATTRIBUTE_UNUSED)
{
385 386
    /* Xen PV domains always have a PV console, so add one to the domain config
     * via post-parse callback if not explicitly specified in the XML. */
387
    if (def->os.type != VIR_DOMAIN_OSTYPE_HVM && def->nconsoles == 0) {
388 389 390 391 392 393 394 395 396 397
        virDomainChrDefPtr chrdef;

        if (!(chrdef = virDomainChrDefNew()))
            return -1;

        chrdef->source.type = VIR_DOMAIN_CHR_TYPE_PTY;
        chrdef->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
        chrdef->target.port = 0;
        chrdef->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_XEN;

398 399
        if (VIR_ALLOC_N(def->consoles, 1) < 0) {
            virDomainChrDefFree(chrdef);
400
            return -1;
401
        }
402 403 404 405

        def->nconsoles = 1;
        def->consoles[0] = chrdef;
    }
406

P
Pavel Hrdina 已提交
407 408 409 410
    /* add implicit input devices */
    if (xenDomainDefAddImplicitInputDevice(def) < 0)
        return -1;

411 412 413
    return 0;
}

J
Jim Fehlig 已提交
414 415 416
virDomainDefParserConfig libxlDomainDefParserConfig = {
    .macPrefix = { 0x00, 0x16, 0x3e },
    .devicesPostParseCallback = libxlDomainDeviceDefPostParse,
417
    .domainPostParseCallback = libxlDomainDefPostParse,
J
Jim Fehlig 已提交
418 419
};

420 421 422

struct libxlShutdownThreadInfo
{
423
    libxlDriverPrivatePtr driver;
424 425 426 427 428 429 430 431 432 433 434
    virDomainObjPtr vm;
    libxl_event *event;
};


static void
libxlDomainShutdownThread(void *opaque)
{
    struct libxlShutdownThreadInfo *shutdown_info = opaque;
    virDomainObjPtr vm = shutdown_info->vm;
    libxl_event *ev = shutdown_info->event;
435
    libxlDriverPrivatePtr driver = shutdown_info->driver;
436 437
    virObjectEventPtr dom_event = NULL;
    libxl_shutdown_reason xl_reason = ev->u.domain_shutdown.shutdown_reason;
438
    libxlDriverConfigPtr cfg;
439

440
    cfg = libxlDriverConfigGet(driver);
441

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

445
    if (xl_reason == LIBXL_SHUTDOWN_REASON_POWEROFF) {
446 447 448
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_SHUTDOWN);

449 450 451
        dom_event = virDomainEventLifecycleNewFromObj(vm,
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
452
        switch ((virDomainLifecycleAction) vm->def->onPoweroff) {
453 454 455 456 457 458 459
        case VIR_DOMAIN_LIFECYCLE_DESTROY:
            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:
460
            goto endjob;
461 462
        }
    } else if (xl_reason == LIBXL_SHUTDOWN_REASON_CRASH) {
463 464 465
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_CRASHED);

466 467 468
        dom_event = virDomainEventLifecycleNewFromObj(vm,
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_CRASHED);
469
        switch ((virDomainLifecycleCrashAction) vm->def->onCrash) {
470 471 472 473 474 475 476
        case VIR_DOMAIN_LIFECYCLE_CRASH_DESTROY:
            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:
477
            goto endjob;
478 479 480 481 482 483 484 485
        case VIR_DOMAIN_LIFECYCLE_CRASH_COREDUMP_DESTROY:
            libxlDomainAutoCoreDump(driver, vm);
            goto destroy;
        case VIR_DOMAIN_LIFECYCLE_CRASH_COREDUMP_RESTART:
            libxlDomainAutoCoreDump(driver, vm);
            goto restart;
        }
    } else if (xl_reason == LIBXL_SHUTDOWN_REASON_REBOOT) {
486 487 488
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_SHUTDOWN);

489 490 491
        dom_event = virDomainEventLifecycleNewFromObj(vm,
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
492
        switch ((virDomainLifecycleAction) vm->def->onReboot) {
493 494 495 496 497 498 499
        case VIR_DOMAIN_LIFECYCLE_DESTROY:
            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:
500
            goto endjob;
501 502 503
        }
    } else {
        VIR_INFO("Unhandled shutdown_reason %d", xl_reason);
504
        goto endjob;
505 506
    }

507
 destroy:
508 509 510 511
    if (dom_event) {
        libxlDomainEventQueue(driver, dom_event);
        dom_event = NULL;
    }
512
    libxlDomainDestroyInternal(driver, vm);
513
    libxlDomainCleanup(driver, vm);
514 515 516 517
    if (!vm->persistent)
        virDomainObjListRemove(driver->domains, vm);

    goto endjob;
518

519
 restart:
520 521 522 523
    if (dom_event) {
        libxlDomainEventQueue(driver, dom_event);
        dom_event = NULL;
    }
524
    libxlDomainDestroyInternal(driver, vm);
525
    libxlDomainCleanup(driver, vm);
526
    if (libxlDomainStartNew(driver, vm, false) < 0) {
527
        VIR_ERROR(_("Failed to restart VM '%s': %s"),
528
                  vm->def->name, virGetLastErrorMessage());
529
    }
530

531
 endjob:
W
Wang Yufei 已提交
532
    libxlDomainObjEndJob(driver, vm);
533

534
 cleanup:
W
Wang Yufei 已提交
535
    virDomainObjEndAPI(&vm);
536 537
    if (dom_event)
        libxlDomainEventQueue(driver, dom_event);
538
    libxl_event_free(cfg->ctx, ev);
539
    VIR_FREE(shutdown_info);
540
    virObjectUnref(cfg);
541 542 543 544 545
}

/*
 * Handle previously registered domain event notification from libxenlight.
 */
546 547
void
libxlDomainEventHandler(void *data, VIR_LIBXL_EVENT_CONST libxl_event *event)
548
{
549 550
    libxlDriverPrivatePtr driver = data;
    virDomainObjPtr vm = NULL;
551
    libxl_shutdown_reason xl_reason = event->u.domain_shutdown.shutdown_reason;
552
    struct libxlShutdownThreadInfo *shutdown_info = NULL;
553
    virThread thread;
554
    libxlDriverConfigPtr cfg;
555 556 557 558 559 560 561 562

    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
563
     * after calling libxl_domain_suspend() are handled by its callers.
564 565 566 567
     */
    if (xl_reason == LIBXL_SHUTDOWN_REASON_SUSPEND)
        goto error;

W
Wang Yufei 已提交
568
    vm = virDomainObjListFindByIDRef(driver->domains, event->domid);
569 570 571 572 573
    if (!vm) {
        VIR_INFO("Received event for unknown domain ID %d", event->domid);
        goto error;
    }

574 575 576 577 578 579 580
    /*
     * 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;

581 582
    shutdown_info->driver = driver;
    shutdown_info->vm = vm;
583 584 585 586 587 588 589 590 591 592 593
    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;
    }

    /*
594
     * VM is unlocked and libxl_event freed in shutdown thread
595 596 597
     */
    return;

598
 error:
599
    cfg = libxlDriverConfigGet(driver);
600
    /* Cast away any const */
601 602
    libxl_event_free(cfg->ctx, (libxl_event *)event);
    virObjectUnref(cfg);
W
Wang Yufei 已提交
603
    virDomainObjEndAPI(&vm);
604
    VIR_FREE(shutdown_info);
605 606
}

607 608 609 610 611
void
libxlDomainEventQueue(libxlDriverPrivatePtr driver, virObjectEventPtr event)
{
    virObjectEventStateQueue(driver->domainEventState, event);
}
612 613

char *
614 615
libxlDomainManagedSavePath(libxlDriverPrivatePtr driver, virDomainObjPtr vm)
{
616 617 618 619 620 621 622
    char *ret;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);

    ignore_value(virAsprintf(&ret, "%s/%s.save", cfg->saveDir, vm->def->name));
    virObjectUnref(cfg);
    return ret;
}
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679

/*
 * Open a saved image file and initialize domain definition from the header.
 *
 * Returns the opened fd on success, -1 on failure.
 */
int
libxlDomainSaveImageOpen(libxlDriverPrivatePtr driver,
                         libxlDriverConfigPtr cfg,
                         const char *from,
                         virDomainDefPtr *ret_def,
                         libxlSavefileHeaderPtr ret_hdr)
{
    int fd;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    char *xml = NULL;

    if ((fd = virFileOpenAs(from, O_RDONLY, 0, -1, -1, 0)) < 0) {
        virReportSystemError(-fd,
                             _("Failed to open domain image file '%s'"), from);
        goto error;
    }

    if (saferead(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("failed to read libxl header"));
        goto error;
    }

    if (memcmp(hdr.magic, LIBXL_SAVE_MAGIC, sizeof(hdr.magic))) {
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("image magic is incorrect"));
        goto error;
    }

    if (hdr.version > LIBXL_SAVE_VERSION) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("image version is not supported (%d > %d)"),
                       hdr.version, LIBXL_SAVE_VERSION);
        goto error;
    }

    if (hdr.xmlLen <= 0) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("invalid XML length: %d"), hdr.xmlLen);
        goto error;
    }

    if (VIR_ALLOC_N(xml, hdr.xmlLen) < 0)
        goto error;

    if (saferead(fd, xml, hdr.xmlLen) != hdr.xmlLen) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s", _("failed to read XML"));
        goto error;
    }

    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
680 681
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                        VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
682 683 684 685 686 687 688 689 690
        goto error;

    VIR_FREE(xml);

    *ret_def = def;
    *ret_hdr = hdr;

    return fd;

691
 error:
692 693 694 695 696
    VIR_FREE(xml);
    virDomainDefFree(def);
    VIR_FORCE_CLOSE(fd);
    return -1;
}
697

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
/*
 * Internal domain destroy function.
 *
 * virDomainObjPtr must be locked on invocation
 */
int
libxlDomainDestroyInternal(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    int ret = -1;

    /* Unlock virDomainObj during destroy, which can take considerable
     * time on large memory domains.
     */
    virObjectUnlock(vm);
    ret = libxl_domain_destroy(cfg->ctx, vm->def->id, NULL);
    virObjectLock(vm);

    virObjectUnref(cfg);
    return ret;
}

721 722 723 724 725 726 727
/*
 * Cleanup function for domain that has reached shutoff state.
 *
 * virDomainObjPtr must be locked on invocation
 */
void
libxlDomainCleanup(libxlDriverPrivatePtr driver,
728
                   virDomainObjPtr vm)
729 730 731 732 733 734
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    int vnc_port;
    char *file;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
735 736 737 738 739
    unsigned int hostdev_flags = VIR_HOSTDEV_SP_PCI;

#ifdef LIBXL_HAVE_PVUSB
    hostdev_flags |= VIR_HOSTDEV_SP_USB;
#endif
740

C
Cédric Bosdonnat 已提交
741 742 743 744 745 746 747 748 749 750 751
    /* now that we know it's stopped call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
        char *xml = virDomainDefFormat(vm->def, cfg->caps, 0);

        /* we can't stop the operation even if the script raised an error */
        ignore_value(virHookCall(VIR_HOOK_DRIVER_LIBXL, vm->def->name,
                                 VIR_HOOK_LIBXL_OP_STOPPED, VIR_HOOK_SUBOP_END,
                                 NULL, xml, NULL));
        VIR_FREE(xml);
    }

752
    virHostdevReAttachDomainDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
753
                                    vm->def, hostdev_flags, NULL);
754

755 756 757 758 759
    VIR_FREE(priv->lockState);
    if (virDomainLockProcessPause(driver->lockManager, vm, &priv->lockState) < 0)
        VIR_WARN("Unable to release lease on %s", vm->def->name);
    VIR_DEBUG("Preserving lock state '%s'", NULLSTR(priv->lockState));

760 761 762
    vm->def->id = -1;

    if (priv->deathW) {
J
Jim Fehlig 已提交
763
        libxl_evdisable_domain_death(cfg->ctx, priv->deathW);
764 765 766 767 768 769 770 771 772 773 774
        priv->deathW = NULL;
    }

    if (virAtomicIntDecAndTest(&driver->nactive) && driver->inhibitCallback)
        driver->inhibitCallback(false, driver->inhibitOpaque);

    if ((vm->def->ngraphics == 1) &&
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics[0]->data.vnc.autoport) {
        vnc_port = vm->def->graphics[0]->data.vnc.port;
        if (vnc_port >= LIBXL_VNC_PORT_MIN) {
775
            if (virPortAllocatorRelease(driver->reservedGraphicsPorts,
776 777 778 779 780
                                        vnc_port) < 0)
                VIR_DEBUG("Could not mark port %d as unused", vnc_port);
        }
    }

781 782 783 784 785 786 787 788 789
    if ((vm->def->nnets)) {
        size_t i;

        for (i = 0; i < vm->def->nnets; i++) {
            virDomainNetDefPtr net = vm->def->nets[i];

            if (net->ifname &&
                STRPREFIX(net->ifname, LIBXL_GENERATED_PREFIX_XEN))
                VIR_FREE(net->ifname);
790 791 792 793

            /* cleanup actual device */
            virDomainNetRemoveHostdev(vm->def, net);
            networkReleaseActualDevice(vm->def, net);
794 795 796
        }
    }

797 798 799 800 801 802
    if (virAsprintf(&file, "%s/%s.xml", cfg->stateDir, vm->def->name) > 0) {
        if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR)
            VIR_DEBUG("Failed to remove domain XML for %s", vm->def->name);
        VIR_FREE(file);
    }

C
Cédric Bosdonnat 已提交
803 804 805 806 807 808 809
    /* The "release" hook cleans up additional resources */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
        char *xml = virDomainDefFormat(vm->def, cfg->caps, 0);

        /* we can't stop the operation even if the script raised an error */
        ignore_value(virHookCall(VIR_HOOK_DRIVER_LIBXL, vm->def->name,
                                 VIR_HOOK_LIBXL_OP_RELEASE, VIR_HOOK_SUBOP_END,
810
                                 NULL, xml, NULL));
C
Cédric Bosdonnat 已提交
811 812 813
        VIR_FREE(xml);
    }

814
    virDomainObjRemoveTransientDef(vm);
815 816 817
    virObjectUnref(cfg);
}

818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
/*
 * Core dump domain to default dump path.
 *
 * virDomainObjPtr must be locked on invocation
 */
int
libxlDomainAutoCoreDump(libxlDriverPrivatePtr driver,
                        virDomainObjPtr vm)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    time_t curtime = time(NULL);
    char timestr[100];
    struct tm time_info;
    char *dumpfile = NULL;
    int ret = -1;

    localtime_r(&curtime, &time_info);
    strftime(timestr, sizeof(timestr), "%Y-%m-%d-%H:%M:%S", &time_info);

    if (virAsprintf(&dumpfile, "%s/%s-%s",
                    cfg->autoDumpDir,
                    vm->def->name,
                    timestr) < 0)
        goto cleanup;

    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
845
    libxl_domain_core_dump(cfg->ctx, vm->def->id, dumpfile, NULL);
846 847 848 849
    virObjectLock(vm);

    ret = 0;

850
 cleanup:
851 852 853 854 855
    VIR_FREE(dumpfile);
    virObjectUnref(cfg);

    return ret;
}
856 857 858 859

int
libxlDomainSetVcpuAffinities(libxlDriverPrivatePtr driver, virDomainObjPtr vm)
{
J
Jim Fehlig 已提交
860
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
861
    virDomainVcpuDefPtr vcpu;
862 863
    libxl_bitmap map;
    virBitmapPtr cpumask = NULL;
P
Peter Krempa 已提交
864
    size_t i;
865 866
    int ret = -1;

867 868
    libxl_bitmap_init(&map);

869
    for (i = 0; i < virDomainDefGetVcpus(vm->def); ++i) {
870
        vcpu = virDomainDefGetVcpu(vm->def, i);
871

872 873 874 875
        if (!vcpu->online)
            continue;

        if (!(cpumask = vcpu->cpumask))
876 877 878 879
            cpumask = vm->def->cpumask;

        if (!cpumask)
            continue;
880

881 882
        if (virBitmapToData(cpumask, &map.map, (int *)&map.size) < 0)
            goto cleanup;
883

884
        if (libxl_set_vcpuaffinity(cfg->ctx, vm->def->id, i, &map) != 0) {
885
            virReportError(VIR_ERR_INTERNAL_ERROR,
886
                           _("Failed to pin vcpu '%zu' with libxenlight"), i);
887 888 889
            goto cleanup;
        }

890
        libxl_bitmap_dispose(&map); /* Also returns to freshly-init'd state */
891 892 893 894
    }

    ret = 0;

895
 cleanup:
896
    libxl_bitmap_dispose(&map);
J
Jim Fehlig 已提交
897
    virObjectUnref(cfg);
898 899
    return ret;
}
900

901 902
static int
libxlDomainFreeMem(libxl_ctx *ctx, libxl_domain_config *d_config)
903 904 905 906 907 908
{
    uint32_t needed_mem;
    uint32_t free_mem;
    int tries = 3;
    int wait_secs = 10;

J
Jim Fehlig 已提交
909 910
    if (libxl_domain_need_memory(ctx, &d_config->b_info, &needed_mem) < 0)
        goto error;
911

J
Jim Fehlig 已提交
912 913 914
    do {
        if (libxl_get_free_memory(ctx, &free_mem) < 0)
            goto error;
915

J
Jim Fehlig 已提交
916 917
        if (free_mem >= needed_mem)
            return 0;
918

J
Jim Fehlig 已提交
919 920 921
        if (libxl_set_memory_target(ctx, 0, free_mem - needed_mem,
                                    /* relative */ 1, 0) < 0)
            goto error;
922

J
Jim Fehlig 已提交
923 924
        if (libxl_wait_for_memory_target(ctx, 0, wait_secs) < 0)
            goto error;
925

J
Jim Fehlig 已提交
926 927 928 929 930 931 932
        tries--;
    } while (tries > 0);

 error:
    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                   _("Failed to balloon domain0 memory"));
    return -1;
933
}
934

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
static int
libxlNetworkPrepareDevices(virDomainDefPtr def)
{
    size_t i;

    for (i = 0; i < def->nnets; i++) {
        virDomainNetDefPtr net = def->nets[i];
        int actualType;

        /* If appropriate, grab a physical device from the configured
         * network's pool of devices, or resolve bridge device name
         * to the one defined in the network definition.
         */
        if (networkAllocateActualDevice(def, net) < 0)
            return -1;

        actualType = virDomainNetGetActualType(net);
        if (actualType == VIR_DOMAIN_NET_TYPE_HOSTDEV &&
            net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            /* Each type='hostdev' network device must also have a
             * corresponding entry in the hostdevs array. For netdevs
             * that are hardcoded as type='hostdev', this is already
             * done by the parser, but for those allocated from a
             * network / determined at runtime, we need to do it
             * separately.
             */
            virDomainHostdevDefPtr hostdev = virDomainNetGetActualHostdev(net);
            virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;

            if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
                hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
                pcisrc->backend = VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN;

            if (virDomainHostdevInsert(def, hostdev) < 0)
                return -1;
        }
    }
    return 0;
}

975
static void
976
libxlConsoleCallback(libxl_ctx *ctx, libxl_event *ev, void *for_callback)
977 978 979
{
    virDomainObjPtr vm = for_callback;
    size_t i;
B
Bob Liu 已提交
980 981 982
    virDomainChrDefPtr chr;
    char *console = NULL;
    int ret;
983 984 985

    virObjectLock(vm);
    for (i = 0; i < vm->def->nconsoles; i++) {
B
Bob Liu 已提交
986 987
        chr = vm->def->consoles[i];

988 989 990 991 992
        if (i == 0 &&
            chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL)
            chr = vm->def->serials[0];

        if (chr->source.type == VIR_DOMAIN_CHR_TYPE_PTY) {
993 994 995
            libxl_console_type console_type;

            console_type =
996
                (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL ?
997
                 LIBXL_CONSOLE_TYPE_SERIAL : LIBXL_CONSOLE_TYPE_PV);
998
            ret = libxl_console_get_tty(ctx, ev->domid,
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
                                        chr->target.port, console_type,
                                        &console);
            if (!ret) {
                VIR_FREE(chr->source.data.file.path);
                if (console && console[0] != '\0') {
                    ignore_value(VIR_STRDUP(chr->source.data.file.path,
                                            console));
                }
            }
            VIR_FREE(console);
        }
    }
B
Bob Liu 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
    for (i = 0; i < vm->def->nserials; i++) {
        chr = vm->def->serials[i];

        ignore_value(virAsprintf(&chr->info.alias, "serial%zd", i));
        if (chr->source.type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if (chr->source.data.file.path)
                continue;
            ret = libxl_console_get_tty(ctx, ev->domid,
                                        chr->target.port,
                                        LIBXL_CONSOLE_TYPE_SERIAL,
                                        &console);
            if (!ret) {
                VIR_FREE(chr->source.data.file.path);
                if (console && console[0] != '\0') {
                    ignore_value(VIR_STRDUP(chr->source.data.file.path,
                                            console));
                }
            }
            VIR_FREE(console);
        }
    }
1032 1033 1034 1035
    virObjectUnlock(vm);
    libxl_event_free(ctx, ev);
}

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
/*
 * Create interface names for the network devices in parameter def.
 * Names are created with the pattern 'vif<domid>.<devid><suffix>'.
 * devid is extracted from the network devices in the d_config
 * parameter. User-provided interface names are skipped.
 */
static void
libxlDomainCreateIfaceNames(virDomainDefPtr def, libxl_domain_config *d_config)
{
    size_t i;

    for (i = 0; i < def->nnets && i < d_config->num_nics; i++) {
        virDomainNetDefPtr net = def->nets[i];
        libxl_device_nic *x_nic = &d_config->nics[i];
        const char *suffix =
            x_nic->nictype != LIBXL_NIC_TYPE_VIF ? "-emu" : "";

        if (net->ifname)
            continue;

        ignore_value(virAsprintf(&net->ifname,
                                 LIBXL_GENERATED_PREFIX_XEN "%d.%d%s",
                                 def->id, x_nic->devid, suffix));
    }
}

1062

1063 1064 1065 1066 1067 1068
#ifdef LIBXL_HAVE_SRM_V2
# define LIBXL_DOMSTART_RESTORE_VER_ATTR /* empty */
#else
# define LIBXL_DOMSTART_RESTORE_VER_ATTR ATTRIBUTE_UNUSED
#endif

1069 1070 1071
/*
 * Start a domain through libxenlight.
 *
1072
 * virDomainObjPtr must be locked and a job acquired on invocation
1073
 */
1074 1075 1076 1077 1078 1079
static int
libxlDomainStart(libxlDriverPrivatePtr driver,
                 virDomainObjPtr vm,
                 bool start_paused,
                 int restore_fd,
                 uint32_t restore_ver LIBXL_DOMSTART_RESTORE_VER_ATTR)
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
{
    libxl_domain_config d_config;
    virDomainDefPtr def = NULL;
    virObjectEventPtr event = NULL;
    libxlSavefileHeader hdr;
    int ret = -1;
    uint32_t domid = 0;
    char *dom_xml = NULL;
    char *managed_save_path = NULL;
    int managed_save_fd = -1;
    libxlDomainObjPrivatePtr priv = vm->privateData;
    libxlDriverConfigPtr cfg;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
1093
    libxl_asyncprogress_how aop_console_how;
1094
    libxl_domain_restore_params params;
1095 1096 1097 1098 1099
    unsigned int hostdev_flags = VIR_HOSTDEV_SP_PCI;

#ifdef LIBXL_HAVE_PVUSB
    hostdev_flags |= VIR_HOSTDEV_SP_USB;
#endif
1100

1101 1102
    libxl_domain_config_init(&d_config);

1103 1104 1105 1106 1107 1108
    cfg = libxlDriverConfigGet(driver);
    /* 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) {
        managed_save_path = libxlDomainManagedSavePath(driver, vm);
        if (managed_save_path == NULL)
1109
            goto cleanup;
1110 1111 1112 1113 1114 1115 1116

        if (virFileExists(managed_save_path)) {

            managed_save_fd = libxlDomainSaveImageOpen(driver, cfg,
                                                       managed_save_path,
                                                       &def, &hdr);
            if (managed_save_fd < 0)
1117
                goto cleanup;
1118 1119

            restore_fd = managed_save_fd;
1120
            restore_ver = hdr.version;
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

            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);
                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);
1132
                goto cleanup;
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
            }

            virDomainObjAssignDef(vm, def, true, NULL);
            def = NULL;

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

            vm->hasManagedSave = false;
        }
        VIR_FREE(managed_save_path);
    }

1147
    if (virDomainObjSetDefTransient(cfg->caps, driver->xmlopt, vm) < 0)
1148 1149
        goto cleanup;

C
Cédric Bosdonnat 已提交
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    /* Run an early hook to set-up missing devices */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
        char *xml = virDomainDefFormat(vm->def, cfg->caps, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_LIBXL, vm->def->name,
                              VIR_HOOK_LIBXL_OP_PREPARE, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto cleanup_dom;
    }

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    if (virDomainLockProcessStart(driver->lockManager,
                                  "xen:///system",
                                  vm,
                                  true,
                                  NULL) < 0)
        goto cleanup;

    if (virDomainLockProcessResume(driver->lockManager,
                                  "xen:///system",
                                  vm,
                                  priv->lockState) < 0)
        goto cleanup;
    VIR_FREE(priv->lockState);

1181 1182 1183
    if (libxlNetworkPrepareDevices(vm->def) < 0)
        goto cleanup_dom;

1184 1185 1186 1187 1188 1189 1190 1191
    if (libxlBuildDomainConfig(driver->reservedGraphicsPorts, vm->def,
                               cfg->ctx, &d_config) < 0)
        goto cleanup_dom;

    if (cfg->autoballoon && libxlDomainFreeMem(cfg->ctx, &d_config) < 0)
        goto cleanup_dom;

    if (virHostdevPrepareDomainDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
1192
                                       vm->def, hostdev_flags) < 0)
1193 1194
        goto cleanup_dom;

C
Cédric Bosdonnat 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
    /* now that we know it is about to start call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
        char *xml = virDomainDefFormat(vm->def, cfg->caps, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_LIBXL, vm->def->name,
                              VIR_HOOK_LIBXL_OP_START, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto cleanup_dom;
    }

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    if (priv->hookRun) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(vm->def->uuid, uuidstr);

        VIR_WARN("Domain id='%d' name='%s' uuid='%s' is tainted: hook",
                 vm->def->id,
                 vm->def->name,
                 uuidstr);
    }

1222 1223
    /* Unlock virDomainObj while creating the domain */
    virObjectUnlock(vm);
1224 1225 1226

    aop_console_how.for_callback = vm;
    aop_console_how.callback = libxlConsoleCallback;
1227
    if (restore_fd < 0) {
J
Jim Fehlig 已提交
1228
        ret = libxl_domain_create_new(cfg->ctx, &d_config,
1229
                                      &domid, NULL, &aop_console_how);
1230
    } else {
1231
        libxl_domain_restore_params_init(&params);
1232 1233 1234
#ifdef LIBXL_HAVE_SRM_V2
        params.stream_version = restore_ver;
#endif
J
Jim Fehlig 已提交
1235
        ret = libxl_domain_create_restore(cfg->ctx, &d_config, &domid,
1236 1237 1238
                                          restore_fd, &params, NULL,
                                          &aop_console_how);
        libxl_domain_restore_params_dispose(&params);
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
    }
    virObjectLock(vm);

    if (ret) {
        if (restore_fd < 0)
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to create new domain '%s'"),
                           d_config.c_info.name);
        else
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("libxenlight failed to restore domain '%s'"),
                           d_config.c_info.name);
1251
        goto cleanup_dom;
1252 1253 1254 1255 1256 1257 1258
    }

    /*
     * The domain has been successfully created with libxl, so it should
     * be cleaned up if there are any subsequent failures.
     */
    vm->def->id = domid;
1259 1260

    /* Always enable domain death events */
J
Jim Fehlig 已提交
1261
    if (libxl_evenable_domain_death(cfg->ctx, vm->def->id, 0, &priv->deathW))
J
Jim Fehlig 已提交
1262
        goto destroy_dom;
1263

1264
    libxlDomainCreateIfaceNames(vm->def, &d_config);
1265

1266
    if ((dom_xml = virDomainDefFormat(vm->def, cfg->caps, 0)) == NULL)
J
Jim Fehlig 已提交
1267
        goto destroy_dom;
1268

J
Jim Fehlig 已提交
1269
    if (libxl_userdata_store(cfg->ctx, domid, "libvirt-xml",
1270 1271 1272
                             (uint8_t *)dom_xml, strlen(dom_xml) + 1)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to store userdata"));
J
Jim Fehlig 已提交
1273
        goto destroy_dom;
1274 1275 1276
    }

    if (libxlDomainSetVcpuAffinities(driver, vm) < 0)
J
Jim Fehlig 已提交
1277
        goto destroy_dom;
1278 1279

    if (!start_paused) {
J
Jim Fehlig 已提交
1280
        libxl_domain_unpause(cfg->ctx, domid);
1281 1282 1283 1284 1285
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
    } else {
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
    }

1286
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
J
Jim Fehlig 已提交
1287
        goto destroy_dom;
1288 1289 1290 1291

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

C
Cédric Bosdonnat 已提交
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    /* finally we can call the 'started' hook script if any */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
        char *xml = virDomainDefFormat(vm->def, cfg->caps, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_LIBXL, vm->def->name,
                              VIR_HOOK_LIBXL_OP_STARTED, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, NULL);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto cleanup_dom;
    }

1309 1310 1311 1312 1313 1314 1315 1316
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STARTED,
                                     restore_fd < 0 ?
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED :
                                         VIR_DOMAIN_EVENT_STARTED_RESTORED);
    if (event)
        libxlDomainEventQueue(driver, event);

    ret = 0;
1317
    goto cleanup;
1318

J
Jim Fehlig 已提交
1319
 destroy_dom:
1320
    ret = -1;
1321
    libxlDomainDestroyInternal(driver, vm);
1322 1323 1324
    vm->def->id = -1;
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);

1325 1326
 cleanup_dom:
    libxlDomainCleanup(driver, vm);
1327

1328
 cleanup:
1329 1330 1331 1332 1333 1334 1335 1336
    libxl_domain_config_dispose(&d_config);
    VIR_FREE(dom_xml);
    VIR_FREE(managed_save_path);
    virDomainDefFree(def);
    VIR_FORCE_CLOSE(managed_save_fd);
    virObjectUnref(cfg);
    return ret;
}
1337

1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
int
libxlDomainStartNew(libxlDriverPrivatePtr driver,
            virDomainObjPtr vm,
            bool start_paused)
{
    return libxlDomainStart(driver, vm, start_paused, -1, LIBXL_SAVE_VERSION);
}

int
libxlDomainStartRestore(libxlDriverPrivatePtr driver,
                        virDomainObjPtr vm,
                        bool start_paused,
                        int restore_fd,
                        uint32_t restore_ver)
{
    return libxlDomainStart(driver, vm, start_paused,
                            restore_fd, restore_ver);
}

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
bool
libxlDomainDefCheckABIStability(libxlDriverPrivatePtr driver,
                                virDomainDefPtr src,
                                virDomainDefPtr dst)
{
    virDomainDefPtr migratableDefSrc = NULL;
    virDomainDefPtr migratableDefDst = NULL;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    bool ret = false;

    if (!(migratableDefSrc = virDomainDefCopy(src, cfg->caps, driver->xmlopt, true)) ||
        !(migratableDefDst = virDomainDefCopy(dst, cfg->caps, driver->xmlopt, true)))
        goto cleanup;

    ret = virDomainDefCheckABIStability(migratableDefSrc, migratableDefDst);

 cleanup:
    virDomainDefFree(migratableDefSrc);
    virDomainDefFree(migratableDefDst);
    virObjectUnref(cfg);
    return ret;
}