libxl_domain.c 48.9 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
 *
 * 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/>.
 */

#include <config.h>

23 24
#include <fcntl.h>

J
Jim Fehlig 已提交
25
#include "libxl_domain.h"
26
#include "libxl_capabilities.h"
J
Jim Fehlig 已提交
27 28

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

#define VIR_FROM_THIS VIR_FROM_LIBXL

42
VIR_LOG_INIT("libxl.libxl_domain");
J
Jim Fehlig 已提交
43

44 45
VIR_ENUM_IMPL(libxlDomainJob,
              LIBXL_JOB_LAST,
46 47 48 49 50 51
              "none",
              "query",
              "destroy",
              "modify",
);

J
Jim Fehlig 已提交
52 53 54 55 56 57 58 59
static virClassPtr libxlDomainObjPrivateClass;

static void
libxlDomainObjPrivateDispose(void *obj);

static int
libxlDomainObjPrivateOnceInit(void)
{
60
    if (!VIR_CLASS_NEW(libxlDomainObjPrivate, virClassForObjectLockable()))
J
Jim Fehlig 已提交
61 62 63 64 65
        return -1;

    return 0;
}

66
VIR_ONCE_GLOBAL_INIT(libxlDomainObjPrivate);
J
Jim Fehlig 已提交
67

68 69 70 71 72 73 74 75
static int
libxlDomainObjInitJob(libxlDomainObjPrivatePtr priv)
{
    memset(&priv->job, 0, sizeof(priv->job));

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

76 77 78
    if (VIR_ALLOC(priv->job.current) < 0)
        return -1;

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    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));
95
    VIR_FREE(priv->job.current);
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
}

/* 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
J
Ján Tomko 已提交
111
libxlDomainObjBeginJob(libxlDriverPrivatePtr driver G_GNUC_UNUSED,
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
                       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();
135 136
    priv->job.started = now;
    priv->job.current->type = VIR_DOMAIN_JOB_UNBOUNDED;
137 138 139

    return 0;

140
 error:
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    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 已提交
168
void
J
Ján Tomko 已提交
169
libxlDomainObjEndJob(libxlDriverPrivatePtr driver G_GNUC_UNUSED,
170 171 172 173 174 175 176 177 178 179 180 181
                     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);
}

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
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 已提交
203
static void *
J
Ján Tomko 已提交
204
libxlDomainObjPrivateAlloc(void *opaque G_GNUC_UNUSED)
J
Jim Fehlig 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218
{
    libxlDomainObjPrivatePtr priv;

    if (libxlDomainObjPrivateInitialize() < 0)
        return NULL;

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

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

219 220 221 222 223 224
    if (libxlDomainObjInitJob(priv) < 0) {
        virChrdevFree(priv->devs);
        virObjectUnref(priv);
        return NULL;
    }

J
Jim Fehlig 已提交
225 226 227 228 229 230 231 232
    return priv;
}

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

233
    libxlDomainObjFreeJob(priv);
J
Jim Fehlig 已提交
234 235 236 237 238 239 240 241
    virChrdevFree(priv->devs);
}

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

242
    VIR_FREE(priv->lockState);
J
Jim Fehlig 已提交
243 244 245
    virObjectUnref(priv);
}

246
static int
247
libxlDomainObjPrivateXMLParse(xmlXPathContextPtr ctxt,
248
                              virDomainObjPtr vm,
J
Ján Tomko 已提交
249
                              virDomainDefParserConfigPtr config G_GNUC_UNUSED)
250
{
251
    libxlDomainObjPrivatePtr priv = vm->privateData;
252 253 254 255 256 257 258

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

    return 0;
}

static int
259 260
libxlDomainObjPrivateXMLFormat(virBufferPtr buf,
                               virDomainObjPtr vm)
261
{
262
    libxlDomainObjPrivatePtr priv = vm->privateData;
263 264 265 266 267 268 269

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

    return 0;
}

J
Jim Fehlig 已提交
270 271 272
virDomainXMLPrivateDataCallbacks libxlDomainXMLPrivateDataCallbacks = {
    .alloc = libxlDomainObjPrivateAlloc,
    .free = libxlDomainObjPrivateFree,
273 274
    .parse = libxlDomainObjPrivateXMLParse,
    .format = libxlDomainObjPrivateXMLFormat,
J
Jim Fehlig 已提交
275 276 277 278 279
};


static int
libxlDomainDeviceDefPostParse(virDomainDeviceDefPtr dev,
280
                              const virDomainDef *def,
J
Ján Tomko 已提交
281 282 283
                              unsigned int parseFlags G_GNUC_UNUSED,
                              void *opaque G_GNUC_UNUSED,
                              void *parseOpaque G_GNUC_UNUSED)
J
Jim Fehlig 已提交
284 285 286 287
{
    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 &&
288
        def->os.type != VIR_DOMAIN_OSTYPE_HVM)
J
Jim Fehlig 已提交
289 290
        dev->data.chr->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_XEN;

291 292 293 294 295
    if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV ||
        (dev->type == VIR_DOMAIN_DEVICE_NET &&
         dev->data.net->type == VIR_DOMAIN_NET_TYPE_HOSTDEV)) {

        virDomainHostdevDefPtr hostdev;
296
        virDomainHostdevSubsysPCIPtr pcisrc;
297 298

        if (dev->type == VIR_DOMAIN_DEVICE_NET)
299
            hostdev = &dev->data.net->data.hostdev.def;
300 301
        else
            hostdev = dev->data.hostdev;
302
        pcisrc = &hostdev->source.subsys.u.pci;
303

304 305 306 307 308 309 310 311 312
        /* 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;
        }

313 314
        if (hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
            hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI &&
315 316
            pcisrc->backend == VIR_DOMAIN_HOSTDEV_PCI_BACKEND_DEFAULT)
            pcisrc->backend = VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN;
317 318
    }

319
    if (dev->type == VIR_DOMAIN_DEVICE_VIDEO && def->os.type == VIR_DOMAIN_OSTYPE_HVM) {
320 321 322 323 324 325 326 327 328 329 330
        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;
                }
331
            break;
332 333 334 335 336 337 338
        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;
            }
339
            break;
J
Jim Fehlig 已提交
340 341 342 343
        case VIR_DOMAIN_VIDEO_TYPE_QXL:
            if (dev->data.video->vram == 0)
                dev->data.video->vram = 128 * 1024;
            break;
344 345 346
        }
    }

347 348 349
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        virDomainDiskDefPtr disk = dev->data.disk;
        int actual_type = virStorageSourceGetActualType(disk->src);
350
        int format = virDomainDiskGetFormat(disk);
351

352
        /* for network-based disks, set 'qemu' as the default driver */
353 354 355 356 357
        if (actual_type == VIR_STORAGE_TYPE_NETWORK) {
            if (!virDomainDiskGetDriver(disk) &&
                virDomainDiskSetDriver(disk, "qemu") < 0)
                return -1;
        }
358 359 360 361

        /* xl.cfg default format is raw. See xl-disk-configuration(5) */
        if (format == VIR_STORAGE_FILE_NONE)
            virDomainDiskSetFormat(disk, VIR_STORAGE_FILE_RAW);
362 363
    }

J
Jim Fehlig 已提交
364 365 366
    return 0;
}

367 368
static int
libxlDomainDefPostParse(virDomainDefPtr def,
J
Ján Tomko 已提交
369
                        unsigned int parseFlags G_GNUC_UNUSED,
370
                        void *opaque,
J
Ján Tomko 已提交
371
                        void *parseOpaque G_GNUC_UNUSED)
372
{
373 374 375 376
    libxlDriverPrivatePtr driver = opaque;
    g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);

    if (!virCapabilitiesDomainSupported(cfg->caps, def->os.type,
377 378 379 380
                                        def->os.arch,
                                        def->virtType))
        return -1;

381 382
    /* 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. */
383
    if (def->os.type != VIR_DOMAIN_OSTYPE_HVM && def->nconsoles == 0) {
384 385
        virDomainChrDefPtr chrdef;

386
        if (!(chrdef = virDomainChrDefNew(NULL)))
387 388
            return -1;

389
        chrdef->source->type = VIR_DOMAIN_CHR_TYPE_PTY;
390 391 392 393
        chrdef->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_CONSOLE;
        chrdef->target.port = 0;
        chrdef->targetType = VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_XEN;

394 395
        if (VIR_ALLOC_N(def->consoles, 1) < 0) {
            virDomainChrDefFree(chrdef);
396
            return -1;
397
        }
398 399 400 401

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

P
Pavel Hrdina 已提交
403 404 405 406
    /* add implicit input devices */
    if (xenDomainDefAddImplicitInputDevice(def) < 0)
        return -1;

W
Wim ten Have 已提交
407
    /* For x86_64 HVM */
408 409
    if (def->os.type == VIR_DOMAIN_OSTYPE_HVM &&
        def->os.arch == VIR_ARCH_X86_64) {
W
Wim ten Have 已提交
410
        /* always enable pae */
411
        def->features[VIR_DOMAIN_FEATURE_PAE] = VIR_TRISTATE_SWITCH_ON;
W
Wim ten Have 已提交
412 413 414 415

        /* if vnuma is effective enable acpi */
        if (virDomainNumaGetNodeCount(def->numa) > 0)
            def->features[VIR_DOMAIN_FEATURE_ACPI] = VIR_TRISTATE_SWITCH_ON;
416 417
    }

418 419 420 421 422 423 424 425 426 427
    /* add implicit balloon device */
    if (def->memballoon == NULL) {
        virDomainMemballoonDefPtr memballoon;
        if (VIR_ALLOC(memballoon) < 0)
            return -1;

        memballoon->model = VIR_DOMAIN_MEMBALLOON_MODEL_XEN;
        def->memballoon = memballoon;
    }

428 429 430 431 432
    /* add implicit xenbus device */
    if (virDomainControllerFindByType(def, VIR_DOMAIN_CONTROLLER_TYPE_XENBUS) == -1)
        if (virDomainDefAddController(def, VIR_DOMAIN_CONTROLLER_TYPE_XENBUS, -1, -1) == NULL)
            return -1;

433 434 435
    return 0;
}

J
Jim Fehlig 已提交
436 437
virDomainDefParserConfig libxlDomainDefParserConfig = {
    .macPrefix = { 0x00, 0x16, 0x3e },
438
    .netPrefix = LIBXL_GENERATED_PREFIX_XEN,
J
Jim Fehlig 已提交
439
    .devicesPostParseCallback = libxlDomainDeviceDefPostParse,
440
    .domainPostParseCallback = libxlDomainDefPostParse,
441
    .features = VIR_DOMAIN_DEF_FEATURE_NET_MODEL_STRING,
J
Jim Fehlig 已提交
442 443
};

444

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
static void
libxlDomainShutdownHandleDestroy(libxlDriverPrivatePtr driver,
                                 virDomainObjPtr vm)
{
    libxlDomainDestroyInternal(driver, vm);
    libxlDomainCleanup(driver, vm);
    if (!vm->persistent)
        virDomainObjListRemove(driver->domains, vm);
}


static void
libxlDomainShutdownHandleRestart(libxlDriverPrivatePtr driver,
                                 virDomainObjPtr vm)
{
    libxlDomainDestroyInternal(driver, vm);
    libxlDomainCleanup(driver, vm);
    if (libxlDomainStartNew(driver, vm, false) < 0) {
        VIR_ERROR(_("Failed to restart VM '%s': %s"),
                  vm->def->name, virGetLastErrorMessage());
    }
}


469 470
struct libxlShutdownThreadInfo
{
471
    libxlDriverPrivatePtr driver;
472 473 474 475 476 477 478 479
    libxl_event *event;
};


static void
libxlDomainShutdownThread(void *opaque)
{
    struct libxlShutdownThreadInfo *shutdown_info = opaque;
480
    virDomainObjPtr vm = NULL;
481
    libxl_event *ev = shutdown_info->event;
482
    libxlDriverPrivatePtr driver = shutdown_info->driver;
483 484
    virObjectEventPtr dom_event = NULL;
    libxl_shutdown_reason xl_reason = ev->u.domain_shutdown.shutdown_reason;
485
    g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
486
    libxl_domain_config d_config;
487

J
Jim Fehlig 已提交
488
    libxl_domain_config_init(&d_config);
489

490
    vm = virDomainObjListFindByID(driver->domains, ev->domid);
491 492 493 494 495
    if (!vm) {
        VIR_INFO("Received event for unknown domain ID %d", ev->domid);
        goto cleanup;
    }

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

499
    if (xl_reason == LIBXL_SHUTDOWN_REASON_POWEROFF) {
500 501 502
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_SHUTDOWN);

503 504 505
        dom_event = virDomainEventLifecycleNewFromObj(vm,
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
506
        switch ((virDomainLifecycleAction) vm->def->onPoweroff) {
507
        case VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY:
508 509
            libxlDomainShutdownHandleDestroy(driver, vm);
            goto endjob;
510 511
        case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART:
        case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART_RENAME:
512 513
            libxlDomainShutdownHandleRestart(driver, vm);
            goto endjob;
514
        case VIR_DOMAIN_LIFECYCLE_ACTION_PRESERVE:
515 516
        case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_DESTROY:
        case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_RESTART:
517
        case VIR_DOMAIN_LIFECYCLE_ACTION_LAST:
518
            goto endjob;
519 520
        }
    } else if (xl_reason == LIBXL_SHUTDOWN_REASON_CRASH) {
521 522 523
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_CRASHED);

524 525 526
        dom_event = virDomainEventLifecycleNewFromObj(vm,
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_CRASHED);
527 528
        switch ((virDomainLifecycleAction) vm->def->onCrash) {
        case VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY:
529 530
            libxlDomainShutdownHandleDestroy(driver, vm);
            goto endjob;
531 532
        case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART:
        case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART_RENAME:
533 534
            libxlDomainShutdownHandleRestart(driver, vm);
            goto endjob;
535 536
        case VIR_DOMAIN_LIFECYCLE_ACTION_PRESERVE:
        case VIR_DOMAIN_LIFECYCLE_ACTION_LAST:
537
            goto endjob;
538
        case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_DESTROY:
539
            libxlDomainAutoCoreDump(driver, vm);
540 541
            libxlDomainShutdownHandleDestroy(driver, vm);
            goto endjob;
542
        case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_RESTART:
543
            libxlDomainAutoCoreDump(driver, vm);
544 545
            libxlDomainShutdownHandleRestart(driver, vm);
            goto endjob;
546 547
        }
    } else if (xl_reason == LIBXL_SHUTDOWN_REASON_REBOOT) {
548 549 550
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_SHUTDOWN);

551 552 553
        dom_event = virDomainEventLifecycleNewFromObj(vm,
                                           VIR_DOMAIN_EVENT_STOPPED,
                                           VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
554
        switch ((virDomainLifecycleAction) vm->def->onReboot) {
555
        case VIR_DOMAIN_LIFECYCLE_ACTION_DESTROY:
556 557
            libxlDomainShutdownHandleDestroy(driver, vm);
            goto endjob;
558 559
        case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART:
        case VIR_DOMAIN_LIFECYCLE_ACTION_RESTART_RENAME:
560 561
            libxlDomainShutdownHandleRestart(driver, vm);
            goto endjob;
562
        case VIR_DOMAIN_LIFECYCLE_ACTION_PRESERVE:
563 564
        case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_DESTROY:
        case VIR_DOMAIN_LIFECYCLE_ACTION_COREDUMP_RESTART:
565
        case VIR_DOMAIN_LIFECYCLE_ACTION_LAST:
566
            goto endjob;
567
        }
J
Jim Fehlig 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
#ifdef LIBXL_HAVE_SOFT_RESET
    } else if (xl_reason == LIBXL_SHUTDOWN_REASON_SOFT_RESET) {
        libxlDomainObjPrivatePtr priv = vm->privateData;

        if (libxl_retrieve_domain_configuration(cfg->ctx, vm->def->id,
                                                &d_config) != 0) {
            VIR_ERROR(_("Failed to retrieve config for VM '%s'. "
                        "Unable to perform soft reset. Destroying VM"),
                      vm->def->name);
            libxlDomainShutdownHandleDestroy(driver, vm);
            goto endjob;
        }

        if (priv->deathW) {
            libxl_evdisable_domain_death(cfg->ctx, priv->deathW);
            priv->deathW = NULL;
        }

        if (libxl_domain_soft_reset(cfg->ctx, &d_config, vm->def->id,
                                    NULL, NULL) != 0) {
            VIR_ERROR(_("Failed to soft reset VM '%s'. Destroying VM"),
                      vm->def->name);
            libxlDomainShutdownHandleDestroy(driver, vm);
            goto endjob;
        }
        libxl_evenable_domain_death(cfg->ctx, vm->def->id, 0, &priv->deathW);
        libxl_domain_unpause(cfg->ctx, vm->def->id);
#endif
596 597
    } else {
        VIR_INFO("Unhandled shutdown_reason %d", xl_reason);
598
    }
599

600
 endjob:
W
Wang Yufei 已提交
601
    libxlDomainObjEndJob(driver, vm);
602

603
 cleanup:
W
Wang Yufei 已提交
604
    virDomainObjEndAPI(&vm);
605
    virObjectEventStateQueue(driver->domainEventState, dom_event);
606
    libxl_event_free(cfg->ctx, ev);
607
    VIR_FREE(shutdown_info);
608
    libxl_domain_config_dispose(&d_config);
609 610
}

611 612 613 614 615 616 617 618
static void
libxlDomainDeathThread(void *opaque)
{
    struct libxlShutdownThreadInfo *shutdown_info = opaque;
    virDomainObjPtr vm = NULL;
    libxl_event *ev = shutdown_info->event;
    libxlDriverPrivatePtr driver = shutdown_info->driver;
    virObjectEventPtr dom_event = NULL;
619
    g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);
620 621 622 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
    libxlDomainObjPrivatePtr priv;

    vm = virDomainObjListFindByID(driver->domains, ev->domid);
    if (!vm) {
        /* vm->def->id already cleared, means the death was handled by the
         * driver already */
        goto cleanup;
    }

    priv = vm->privateData;

    if (priv->ignoreDeathEvent) {
        priv->ignoreDeathEvent = false;
        goto cleanup;
    }

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

    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_DESTROYED);
    dom_event = virDomainEventLifecycleNewFromObj(vm,
                                                  VIR_DOMAIN_EVENT_STOPPED,
                                                  VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
    libxlDomainCleanup(driver, vm);
    if (!vm->persistent)
        virDomainObjListRemove(driver->domains, vm);
    libxlDomainObjEndJob(driver, vm);

 cleanup:
    virDomainObjEndAPI(&vm);
    virObjectEventStateQueue(driver->domainEventState, dom_event);
    libxl_event_free(cfg->ctx, ev);
    VIR_FREE(shutdown_info);
}


656 657 658
/*
 * Handle previously registered domain event notification from libxenlight.
 */
659 660
void
libxlDomainEventHandler(void *data, VIR_LIBXL_EVENT_CONST libxl_event *event)
661
{
662
    libxlDriverPrivatePtr driver = data;
663
    libxl_shutdown_reason xl_reason = event->u.domain_shutdown.shutdown_reason;
664
    struct libxlShutdownThreadInfo *shutdown_info = NULL;
665
    virThread thread;
666
    g_autoptr(libxlDriverConfig) cfg = NULL;
667
    int ret = -1;
668

669 670
    if (event->type != LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN &&
            event->type != LIBXL_EVENT_TYPE_DOMAIN_DEATH) {
671 672 673 674
        VIR_INFO("Unhandled event type %d", event->type);
        goto error;
    }

675 676 677 678 679 680 681
    /*
     * Similar to the xl implementation, ignore SUSPEND.  Any actions needed
     * after calling libxl_domain_suspend() are handled by its callers.
     */
    if (xl_reason == LIBXL_SHUTDOWN_REASON_SUSPEND)
        goto error;

682 683 684 685 686 687 688
    /*
     * 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;

689
    shutdown_info->driver = driver;
690
    shutdown_info->event = (libxl_event *)event;
691 692 693 694 695 696 697 698
    if (event->type == LIBXL_EVENT_TYPE_DOMAIN_SHUTDOWN)
        ret = virThreadCreate(&thread, false, libxlDomainShutdownThread,
                              shutdown_info);
    else if (event->type == LIBXL_EVENT_TYPE_DOMAIN_DEATH)
        ret = virThreadCreate(&thread, false, libxlDomainDeathThread,
                              shutdown_info);

    if (ret < 0) {
699 700 701 702 703 704 705 706
        /*
         * Not much we can do on error here except log it.
         */
        VIR_ERROR(_("Failed to create thread to handle domain shutdown"));
        goto error;
    }

    /*
707
     * libxlShutdownThreadInfo and libxl_event are freed in shutdown thread
708 709 710
     */
    return;

711
 error:
712
    cfg = libxlDriverConfigGet(driver);
713
    /* Cast away any const */
714
    libxl_event_free(cfg->ctx, (libxl_event *)event);
715
    VIR_FREE(shutdown_info);
716 717
}

718
char *
719 720
libxlDomainManagedSavePath(libxlDriverPrivatePtr driver, virDomainObjPtr vm)
{
721
    char *ret;
722
    g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);
723

724
    ret = g_strdup_printf("%s/%s.save", cfg->saveDir, vm->def->name);
725 726
    return ret;
}
727 728 729 730 731 732 733 734

/*
 * 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,
735
                         libxlDriverConfigPtr cfg G_GNUC_UNUSED,
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
                         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;
    }

783
    if (!(def = virDomainDefParseString(xml, driver->xmlopt, NULL,
784 785
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                        VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
786 787 788 789 790 791 792 793 794
        goto error;

    VIR_FREE(xml);

    *ret_def = def;
    *ret_hdr = hdr;

    return fd;

795
 error:
796 797 798 799 800
    VIR_FREE(xml);
    virDomainDefFree(def);
    VIR_FORCE_CLOSE(fd);
    return -1;
}
801

802 803 804 805 806 807 808 809 810
/*
 * Internal domain destroy function.
 *
 * virDomainObjPtr must be locked on invocation
 */
int
libxlDomainDestroyInternal(libxlDriverPrivatePtr driver,
                           virDomainObjPtr vm)
{
811
    g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);
812
    libxlDomainObjPrivatePtr priv = vm->privateData;
813 814
    int ret = -1;

815 816 817 818
    /* Ignore next LIBXL_EVENT_TYPE_DOMAIN_DEATH as the caller will handle
     * domain death appropriately already (having more info, like the reason).
     */
    priv->ignoreDeathEvent = true;
819 820 821 822 823 824
    /* 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);
825 826
    if (ret)
        priv->ignoreDeathEvent = false;
827 828 829 830

    return ret;
}

831 832 833 834 835 836 837
/*
 * Cleanup function for domain that has reached shutoff state.
 *
 * virDomainObjPtr must be locked on invocation
 */
void
libxlDomainCleanup(libxlDriverPrivatePtr driver,
838
                   virDomainObjPtr vm)
839 840
{
    libxlDomainObjPrivatePtr priv = vm->privateData;
841
    g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);
842 843 844
    int vnc_port;
    char *file;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
845
    unsigned int hostdev_flags = VIR_HOSTDEV_SP_PCI;
846
    virConnectPtr conn = NULL;
847 848 849 850

#ifdef LIBXL_HAVE_PVUSB
    hostdev_flags |= VIR_HOSTDEV_SP_USB;
#endif
851

C
Cédric Bosdonnat 已提交
852 853
    /* now that we know it's stopped call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
854
        char *xml = virDomainDefFormat(vm->def, driver->xmlopt, 0);
C
Cédric Bosdonnat 已提交
855 856 857 858 859 860 861 862

        /* 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);
    }

863
    virHostdevReAttachDomainDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
864
                                    vm->def, hostdev_flags, NULL);
865

866 867 868 869 870
    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));

J
Jim Fehlig 已提交
871
    libxlLoggerCloseFile(cfg->logger, vm->def->id);
872 873 874
    vm->def->id = -1;

    if (priv->deathW) {
J
Jim Fehlig 已提交
875
        libxl_evdisable_domain_death(cfg->ctx, priv->deathW);
876 877 878
        priv->deathW = NULL;
    }

879 880
    priv->ignoreDeathEvent = false;

881 882 883 884 885 886 887 888
    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) {
889
            if (virPortAllocatorRelease(vnc_port) < 0)
890 891 892 893
                VIR_DEBUG("Could not mark port %d as unused", vnc_port);
        }
    }

894 895 896 897 898 899 900 901 902
    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);
903 904 905

            /* cleanup actual device */
            virDomainNetRemoveHostdev(vm->def, net);
906 907 908 909 910 911
            if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
                if (conn || (conn = virGetConnectNetwork()))
                    virDomainNetReleaseActualDevice(conn, vm->def, net);
                else
                    VIR_WARN("Unable to release network device '%s'", NULLSTR(net->ifname));
            }
912 913 914
        }
    }

915 916 917 918 919
    file = g_strdup_printf("%s/%s.xml", cfg->stateDir, vm->def->name);

    if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR)
        VIR_DEBUG("Failed to remove domain XML for %s", vm->def->name);
    VIR_FREE(file);
920

C
Cédric Bosdonnat 已提交
921 922
    /* The "release" hook cleans up additional resources */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
923
        char *xml = virDomainDefFormat(vm->def, driver->xmlopt, 0);
C
Cédric Bosdonnat 已提交
924 925 926 927

        /* 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,
928
                                 NULL, xml, NULL));
C
Cédric Bosdonnat 已提交
929 930 931
        VIR_FREE(xml);
    }

932
    virDomainObjRemoveTransientDef(vm);
933
    virObjectUnref(conn);
934 935
}

936 937 938 939 940 941 942 943 944
/*
 * Core dump domain to default dump path.
 *
 * virDomainObjPtr must be locked on invocation
 */
int
libxlDomainAutoCoreDump(libxlDriverPrivatePtr driver,
                        virDomainObjPtr vm)
{
945
    g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);
946 947
    g_autoptr(GDateTime) now = g_date_time_new_now_local();
    g_autofree char *nowstr = NULL;
948 949
    char *dumpfile = NULL;

950
    nowstr = g_date_time_format(now, "%Y-%m-%d-%H:%M:%S");
951

952
    dumpfile = g_strdup_printf("%s/%s-%s", cfg->autoDumpDir, vm->def->name,
953
                               nowstr);
954 955 956

    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
J
Jim Fehlig 已提交
957
    libxl_domain_core_dump(cfg->ctx, vm->def->id, dumpfile, NULL);
958 959 960
    virObjectLock(vm);

    VIR_FREE(dumpfile);
961
    return 0;
962
}
963 964 965 966

int
libxlDomainSetVcpuAffinities(libxlDriverPrivatePtr driver, virDomainObjPtr vm)
{
967
    g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);
968
    virDomainVcpuDefPtr vcpu;
969 970
    libxl_bitmap map;
    virBitmapPtr cpumask = NULL;
P
Peter Krempa 已提交
971
    size_t i;
972 973
    int ret = -1;

974 975
    libxl_bitmap_init(&map);

976
    for (i = 0; i < virDomainDefGetVcpus(vm->def); ++i) {
977
        vcpu = virDomainDefGetVcpu(vm->def, i);
978

979 980 981 982
        if (!vcpu->online)
            continue;

        if (!(cpumask = vcpu->cpumask))
983 984 985 986
            cpumask = vm->def->cpumask;

        if (!cpumask)
            continue;
987

988 989
        if (virBitmapToData(cpumask, &map.map, (int *)&map.size) < 0)
            goto cleanup;
990

J
Jim Fehlig 已提交
991
        if (libxl_set_vcpuaffinity(cfg->ctx, vm->def->id, i, &map, NULL) != 0) {
992
            virReportError(VIR_ERR_INTERNAL_ERROR,
993
                           _("Failed to pin vcpu '%zu' with libxenlight"), i);
994 995 996
            goto cleanup;
        }

997
        libxl_bitmap_dispose(&map); /* Also returns to freshly-init'd state */
998 999 1000 1001
    }

    ret = 0;

1002
 cleanup:
1003
    libxl_bitmap_dispose(&map);
1004 1005
    return ret;
}
1006

1007 1008
static int
libxlDomainFreeMem(libxl_ctx *ctx, libxl_domain_config *d_config)
1009 1010 1011
{
    uint32_t needed_mem;
    uint32_t free_mem;
1012
    int32_t target_mem;
1013 1014 1015
    int tries = 3;
    int wait_secs = 10;

J
Jim Fehlig 已提交
1016 1017
    if (libxl_domain_need_memory(ctx, &d_config->b_info, &needed_mem) < 0)
        goto error;
1018

J
Jim Fehlig 已提交
1019 1020 1021
    do {
        if (libxl_get_free_memory(ctx, &free_mem) < 0)
            goto error;
1022

J
Jim Fehlig 已提交
1023 1024
        if (free_mem >= needed_mem)
            return 0;
1025

1026 1027
        target_mem = free_mem - needed_mem;
        if (libxl_set_memory_target(ctx, 0, target_mem,
J
Jim Fehlig 已提交
1028 1029
                                    /* relative */ 1, 0) < 0)
            goto error;
1030

J
Jim Fehlig 已提交
1031 1032
        if (libxl_wait_for_memory_target(ctx, 0, wait_secs) < 0)
            goto error;
1033

J
Jim Fehlig 已提交
1034 1035 1036 1037 1038 1039 1040
        tries--;
    } while (tries > 0);

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

1043 1044 1045 1046
static int
libxlNetworkPrepareDevices(virDomainDefPtr def)
{
    size_t i;
1047 1048
    virConnectPtr conn = NULL;
    int ret = -1;
1049 1050 1051

    for (i = 0; i < def->nnets; i++) {
        virDomainNetDefPtr net = def->nets[i];
1052
        virDomainNetType actualType;
1053 1054 1055 1056 1057

        /* 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.
         */
1058 1059 1060 1061 1062 1063
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            if (!conn && !(conn = virGetConnectNetwork()))
                goto cleanup;
            if (virDomainNetAllocateActualDevice(conn, def, net) < 0)
                goto cleanup;
        }
1064

1065 1066 1067 1068
        /* final validation now that actual type is known */
        if (virDomainActualNetDefValidate(net) < 0)
            return -1;

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
        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)
1087
                goto cleanup;
1088 1089
        }
    }
1090 1091 1092 1093 1094

    ret = 0;
 cleanup:
    virObjectUnref(conn);
    return ret;
1095 1096
}

1097
static void
1098
libxlConsoleCallback(libxl_ctx *ctx, libxl_event *ev, void *for_callback)
1099 1100 1101
{
    virDomainObjPtr vm = for_callback;
    size_t i;
B
Bob Liu 已提交
1102 1103 1104
    virDomainChrDefPtr chr;
    char *console = NULL;
    int ret;
1105 1106 1107

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

1110 1111 1112 1113
        if (i == 0 &&
            chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL)
            chr = vm->def->serials[0];

1114
        if (chr->source->type == VIR_DOMAIN_CHR_TYPE_PTY) {
1115 1116 1117
            libxl_console_type console_type;

            console_type =
1118
                (chr->deviceType == VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL ?
1119
                 LIBXL_CONSOLE_TYPE_SERIAL : LIBXL_CONSOLE_TYPE_PV);
1120
            ret = libxl_console_get_tty(ctx, ev->domid,
1121 1122 1123
                                        chr->target.port, console_type,
                                        &console);
            if (!ret) {
1124
                VIR_FREE(chr->source->data.file.path);
1125 1126
                if (console && console[0] != '\0')
                    chr->source->data.file.path = g_strdup(console);
1127 1128 1129 1130
            }
            VIR_FREE(console);
        }
    }
B
Bob Liu 已提交
1131 1132 1133
    for (i = 0; i < vm->def->nserials; i++) {
        chr = vm->def->serials[i];

1134
        chr->info.alias = g_strdup_printf("serial%zd", i);
1135 1136
        if (chr->source->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if (chr->source->data.file.path)
B
Bob Liu 已提交
1137 1138 1139 1140 1141 1142
                continue;
            ret = libxl_console_get_tty(ctx, ev->domid,
                                        chr->target.port,
                                        LIBXL_CONSOLE_TYPE_SERIAL,
                                        &console);
            if (!ret) {
1143
                VIR_FREE(chr->source->data.file.path);
1144 1145
                if (console && console[0] != '\0')
                    chr->source->data.file.path = g_strdup(console);
B
Bob Liu 已提交
1146 1147 1148 1149
            }
            VIR_FREE(console);
        }
    }
1150 1151 1152 1153
    virObjectUnlock(vm);
    libxl_event_free(ctx, ev);
}

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
/*
 * 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;

1174 1175
        net->ifname = g_strdup_printf(LIBXL_GENERATED_PREFIX_XEN "%d.%d%s",
                                      def->id, x_nic->devid, suffix);
1176 1177 1178
    }
}

1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
static void
libxlDomainUpdateDiskParams(virDomainDefPtr def, libxl_ctx *ctx)
{
    libxl_device_disk *disks;
    int num_disks = 0;
    size_t i;
    int idx;

    disks = libxl_device_disk_list(ctx, def->id, &num_disks);
    if (!disks)
        return;

    for (i = 0; i < num_disks; i++) {
        if ((idx = virDomainDiskIndexByName(def, disks[i].vdev, false)) < 0)
            continue;

        libxlUpdateDiskDef(def->disks[idx], &disks[i]);
    }

    for (i = 0; i < num_disks; i++)
        libxl_device_disk_dispose(&disks[i]);
    VIR_FREE(disks);
}

J
Joao Martins 已提交
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
#ifdef LIBXL_HAVE_DEVICE_CHANNEL
static void
libxlDomainCreateChannelPTY(virDomainDefPtr def, libxl_ctx *ctx)
{
    libxl_device_channel *x_channels;
    virDomainChrDefPtr chr;
    size_t i;
    int nchannels;

    x_channels = libxl_device_channel_list(ctx, def->id, &nchannels);
    if (!x_channels)
        return;

    for (i = 0; i < def->nchannels; i++) {
        libxl_channelinfo channelinfo;
        int ret;

        chr = def->channels[i];
1221
        if (chr->source->type != VIR_DOMAIN_CHR_TYPE_PTY)
J
Joao Martins 已提交
1222 1223 1224 1225 1226 1227
            continue;

        ret = libxl_device_channel_getinfo(ctx, def->id, &x_channels[i],
                                           &channelinfo);

        if (!ret && channelinfo.u.pty.path &&
1228
            *channelinfo.u.pty.path != '\0') {
1229
                VIR_FREE(chr->source->data.file.path);
1230
                chr->source->data.file.path = g_strdup(channelinfo.u.pty.path);
J
Joao Martins 已提交
1231 1232 1233 1234 1235 1236 1237
            }
    }

    for (i = 0; i < nchannels; i++)
        libxl_device_channel_dispose(&x_channels[i]);
}
#endif
1238

1239 1240 1241
#ifdef LIBXL_HAVE_SRM_V2
# define LIBXL_DOMSTART_RESTORE_VER_ATTR /* empty */
#else
J
Ján Tomko 已提交
1242
# define LIBXL_DOMSTART_RESTORE_VER_ATTR G_GNUC_UNUSED
1243 1244
#endif

1245 1246 1247
/*
 * Start a domain through libxenlight.
 *
1248
 * virDomainObjPtr must be locked and a job acquired on invocation
1249
 */
1250 1251 1252 1253 1254 1255
static int
libxlDomainStart(libxlDriverPrivatePtr driver,
                 virDomainObjPtr vm,
                 bool start_paused,
                 int restore_fd,
                 uint32_t restore_ver LIBXL_DOMSTART_RESTORE_VER_ATTR)
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
{
    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;
1267
    g_autoptr(libxlDriverConfig) cfg = libxlDriverConfigGet(driver);
1268
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
1269
    libxl_asyncprogress_how aop_console_how;
1270
    libxl_domain_restore_params params;
1271
    unsigned int hostdev_flags = VIR_HOSTDEV_SP_PCI;
1272
    char *config_json = NULL;
1273 1274 1275 1276

#ifdef LIBXL_HAVE_PVUSB
    hostdev_flags |= VIR_HOSTDEV_SP_USB;
#endif
1277

1278 1279
    libxl_domain_config_init(&d_config);

1280 1281 1282 1283 1284
    /* 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)
1285
            goto cleanup;
1286 1287 1288 1289 1290 1291 1292

        if (virFileExists(managed_save_path)) {

            managed_save_fd = libxlDomainSaveImageOpen(driver, cfg,
                                                       managed_save_path,
                                                       &def, &hdr);
            if (managed_save_fd < 0)
1293
                goto cleanup;
1294 1295

            restore_fd = managed_save_fd;
1296
            restore_ver = hdr.version;
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307

            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);
1308
                goto cleanup;
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
            }

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

1323
    if (virDomainObjSetDefTransient(driver->xmlopt, vm, NULL) < 0)
1324 1325
        goto cleanup;

C
Cédric Bosdonnat 已提交
1326 1327
    /* Run an early hook to set-up missing devices */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
1328
        char *xml = virDomainDefFormat(vm->def, driver->xmlopt, 0);
C
Cédric Bosdonnat 已提交
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
        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;
    }

1343 1344 1345 1346 1347 1348 1349
    if (virDomainLockProcessStart(driver->lockManager,
                                  "xen:///system",
                                  vm,
                                  true,
                                  NULL) < 0)
        goto cleanup;

1350 1351 1352
    if (libxlNetworkPrepareDevices(vm->def) < 0)
        goto cleanup_dom;

1353
    if (libxlBuildDomainConfig(driver->reservedGraphicsPorts, vm->def,
1354
                               cfg, &d_config) < 0)
1355 1356 1357 1358 1359 1360
        goto cleanup_dom;

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

    if (virHostdevPrepareDomainDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
1361
                                       vm->def, hostdev_flags) < 0)
1362 1363
        goto cleanup_dom;

C
Cédric Bosdonnat 已提交
1364 1365
    /* now that we know it is about to start call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
1366
        char *xml = virDomainDefFormat(vm->def, driver->xmlopt, 0);
C
Cédric Bosdonnat 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
        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;
    }

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
    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);
    }

1391 1392
    /* Unlock virDomainObj while creating the domain */
    virObjectUnlock(vm);
1393 1394 1395

    aop_console_how.for_callback = vm;
    aop_console_how.callback = libxlConsoleCallback;
1396
    if (restore_fd < 0) {
J
Jim Fehlig 已提交
1397
        ret = libxl_domain_create_new(cfg->ctx, &d_config,
1398
                                      &domid, NULL, &aop_console_how);
1399
    } else {
1400
        libxl_domain_restore_params_init(&params);
1401 1402 1403
#ifdef LIBXL_HAVE_SRM_V2
        params.stream_version = restore_ver;
#endif
J
Jim Fehlig 已提交
1404
        ret = libxl_domain_create_restore(cfg->ctx, &d_config, &domid,
1405 1406 1407
                                          restore_fd, &params, NULL,
                                          &aop_console_how);
        libxl_domain_restore_params_dispose(&params);
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
    }
    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);
1420
        goto cleanup_dom;
1421 1422 1423 1424 1425 1426 1427
    }

    /*
     * The domain has been successfully created with libxl, so it should
     * be cleaned up if there are any subsequent failures.
     */
    vm->def->id = domid;
1428 1429 1430
    config_json = libxl_domain_config_to_json(cfg->ctx, &d_config);

    libxlLoggerOpenFile(cfg->logger, domid, vm->def->name, config_json);
1431

J
Jim Fehlig 已提交
1432 1433 1434 1435 1436 1437 1438
    if (virDomainLockProcessResume(driver->lockManager,
                                  "xen:///system",
                                  vm,
                                  priv->lockState) < 0)
        goto destroy_dom;
    VIR_FREE(priv->lockState);

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

1443
    libxlDomainCreateIfaceNames(vm->def, &d_config);
1444
    libxlDomainUpdateDiskParams(vm->def, cfg->ctx);
1445

J
Joao Martins 已提交
1446 1447 1448 1449 1450
#ifdef LIBXL_HAVE_DEVICE_CHANNEL
    if (vm->def->nchannels > 0)
        libxlDomainCreateChannelPTY(vm->def, cfg->ctx);
#endif

1451
    if ((dom_xml = virDomainDefFormat(vm->def, driver->xmlopt, 0)) == NULL)
J
Jim Fehlig 已提交
1452
        goto destroy_dom;
1453

J
Jim Fehlig 已提交
1454
    if (libxl_userdata_store(cfg->ctx, domid, "libvirt-xml",
1455 1456 1457
                             (uint8_t *)dom_xml, strlen(dom_xml) + 1)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxenlight failed to store userdata"));
J
Jim Fehlig 已提交
1458
        goto destroy_dom;
1459 1460 1461
    }

    if (libxlDomainSetVcpuAffinities(driver, vm) < 0)
J
Jim Fehlig 已提交
1462
        goto destroy_dom;
1463 1464

    if (!start_paused) {
J
Jim Fehlig 已提交
1465
        libxl_domain_unpause(cfg->ctx, domid);
1466 1467 1468 1469 1470
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING, VIR_DOMAIN_RUNNING_BOOTED);
    } else {
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
    }

1471
    if (virDomainObjSave(vm, driver->xmlopt, cfg->stateDir) < 0)
J
Jim Fehlig 已提交
1472
        goto destroy_dom;
1473

1474
    if (virAtomicIntInc(&driver->nactive) == 0 && driver->inhibitCallback)
1475 1476
        driver->inhibitCallback(true, driver->inhibitOpaque);

C
Cédric Bosdonnat 已提交
1477 1478
    /* finally we can call the 'started' hook script if any */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
1479
        char *xml = virDomainDefFormat(vm->def, driver->xmlopt, 0);
C
Cédric Bosdonnat 已提交
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
        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;
    }

1494 1495 1496 1497
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STARTED,
                                     restore_fd < 0 ?
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED :
                                         VIR_DOMAIN_EVENT_STARTED_RESTORED);
1498
    virObjectEventStateQueue(driver->domainEventState, event);
1499 1500

    ret = 0;
1501
    goto cleanup;
1502

J
Jim Fehlig 已提交
1503
 destroy_dom:
1504
    ret = -1;
1505
    libxlDomainDestroyInternal(driver, vm);
1506 1507 1508
    vm->def->id = -1;
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF, VIR_DOMAIN_SHUTOFF_FAILED);

1509 1510
 cleanup_dom:
    libxlDomainCleanup(driver, vm);
1511

1512
 cleanup:
1513
    libxl_domain_config_dispose(&d_config);
1514
    VIR_FREE(config_json);
1515 1516 1517 1518 1519 1520
    VIR_FREE(dom_xml);
    VIR_FREE(managed_save_path);
    virDomainDefFree(def);
    VIR_FORCE_CLOSE(managed_save_fd);
    return ret;
}
1521

1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
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);
}

1541 1542 1543 1544 1545 1546 1547 1548 1549
bool
libxlDomainDefCheckABIStability(libxlDriverPrivatePtr driver,
                                virDomainDefPtr src,
                                virDomainDefPtr dst)
{
    virDomainDefPtr migratableDefSrc = NULL;
    virDomainDefPtr migratableDefDst = NULL;
    bool ret = false;

1550 1551
    if (!(migratableDefSrc = virDomainDefCopy(src, driver->xmlopt, NULL, true)) ||
        !(migratableDefDst = virDomainDefCopy(dst, driver->xmlopt, NULL, true)))
1552 1553
        goto cleanup;

1554 1555 1556
    ret = virDomainDefCheckABIStability(migratableDefSrc,
                                        migratableDefDst,
                                        driver->xmlopt);
1557 1558 1559 1560 1561 1562

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