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

#include <config.h>

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

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

#define VIR_FROM_THIS VIR_FROM_LIBXL

60 61
VIR_LOG_INIT("libxl.libxl_driver");

J
Jim Fehlig 已提交
62 63 64 65 66 67
#define LIBXL_DOM_REQ_POWEROFF 0
#define LIBXL_DOM_REQ_REBOOT   1
#define LIBXL_DOM_REQ_SUSPEND  2
#define LIBXL_DOM_REQ_CRASH    3
#define LIBXL_DOM_REQ_HALT     4

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

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

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

76

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

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

J
Jim Fehlig 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

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

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

    return vm;
}

105 106
static int
libxlAutostartDomain(virDomainObjPtr vm,
107 108 109 110
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    virErrorPtr err;
111
    int ret = -1;
112

113
    virObjectLock(vm);
114 115 116
    virResetLastError();

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

125
    ret = 0;
126
 cleanup:
127
    virObjectUnlock(vm);
128
    return ret;
129 130
}

J
Jim Fehlig 已提交
131 132 133 134
/*
 * Reconnect to running domains that were previously started/created
 * with libxenlight driver.
 */
135 136
static int
libxlReconnectDomain(virDomainObjPtr vm,
J
Jim Fehlig 已提交
137 138 139
                     void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
140
    libxlDomainObjPrivatePtr priv = vm->privateData;
J
Jim Fehlig 已提交
141 142 143 144
    int rc;
    libxl_dominfo d_info;
    int len;
    uint8_t *data = NULL;
145
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;
J
Jim Fehlig 已提交
146

147
    virObjectLock(vm);
J
Jim Fehlig 已提交
148

149
    libxlDomainObjPrivateInitCtx(vm);
J
Jim Fehlig 已提交
150
    /* Does domain still exist? */
151
    rc = libxl_domain_info(priv->ctx, &d_info, vm->def->id);
J
Jim Fehlig 已提交
152 153 154 155 156 157 158 159 160
    if (rc == ERROR_INVAL) {
        goto out;
    } else if (rc != 0) {
        VIR_DEBUG("libxl_domain_info failed (code %d), ignoring domain %d",
                  rc, vm->def->id);
        goto out;
    }

    /* Is this a domain that was under libvirt control? */
161
    if (libxl_userdata_retrieve(priv->ctx, vm->def->id,
J
Jim Fehlig 已提交
162 163 164 165 166 167 168
                                "libvirt-xml", &data, &len)) {
        VIR_DEBUG("libxl_userdata_retrieve failed, ignoring domain %d", vm->def->id);
        goto out;
    }

    /* Update domid in case it changed (e.g. reboot) while we were gone? */
    vm->def->id = d_info.domid;
169 170 171 172 173 174

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

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

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

180
    /* Re-register domain death et. al. events */
181
    libxlDomainEventsRegister(driver, vm);
182
    virObjectUnlock(vm);
183
    return 0;
J
Jim Fehlig 已提交
184

185
 out:
186
    libxlDomainCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_UNKNOWN);
J
Jim Fehlig 已提交
187
    if (!vm->persistent)
188
        virDomainObjListRemoveLocked(driver->domains, vm);
J
Jim Fehlig 已提交
189
    else
190
        virObjectUnlock(vm);
191 192

    return -1;
J
Jim Fehlig 已提交
193 194 195 196 197
}

static void
libxlReconnectDomains(libxlDriverPrivatePtr driver)
{
198
    virDomainObjListForEach(driver->domains, libxlReconnectDomain, driver);
J
Jim Fehlig 已提交
199 200 201
}

static int
202
libxlStateCleanup(void)
J
Jim Fehlig 已提交
203 204 205 206
{
    if (!libxl_driver)
        return -1;

207
    virObjectUnref(libxl_driver->hostdevMgr);
208
    virObjectUnref(libxl_driver->config);
209
    virObjectUnref(libxl_driver->xmlopt);
210
    virObjectUnref(libxl_driver->domains);
211
    virObjectUnref(libxl_driver->reservedVNCPorts);
J
Jim Fehlig 已提交
212

213
    virObjectEventStateFree(libxl_driver->domainEventState);
214
    virSysinfoDefFree(libxl_driver->hostsysinfo);
215

J
Jim Fehlig 已提交
216 217 218 219 220 221
    virMutexDestroy(&libxl_driver->lock);
    VIR_FREE(libxl_driver);

    return 0;
}

222 223
static bool
libxlDriverShouldLoad(bool privileged)
224
{
225
    bool ret = false;
J
Jim Fehlig 已提交
226
    virCommandPtr cmd;
227
    int status;
228
    char *output = NULL;
J
Jim Fehlig 已提交
229

230
    /* Don't load if non-root */
J
Jim Fehlig 已提交
231
    if (!privileged) {
232
        VIR_INFO("Not running privileged, disabling libxenlight driver");
233
        return ret;
J
Jim Fehlig 已提交
234 235
    }

236 237 238 239 240
    if (!virFileExists(HYPERVISOR_CAPABILITIES)) {
        VIR_INFO("Disabling driver as " HYPERVISOR_CAPABILITIES
                 " does not exist");
        return false;
    }
241 242 243 244 245
    /*
     * Don't load if not running on a Xen control domain (dom0). It is not
     * sufficient to check for the file to exist as any guest can mount
     * xenfs to /proc/xen.
     */
246
    status = virFileReadAll(HYPERVISOR_CAPABILITIES, 10, &output);
247 248 249 250 251
    if (status >= 0) {
        status = strncmp(output, "control_d", 9);
    }
    VIR_FREE(output);
    if (status) {
252 253 254 255 256 257 258
        VIR_INFO("No Xen capabilities detected, probably not running "
                 "in a Xen Dom0.  Disabling libxenlight driver");

        return ret;
    }

    /* Don't load if legacy xen toolstack (xend) is in use */
J
Jim Fehlig 已提交
259 260
    cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL);
    if (virCommandRun(cmd, &status) == 0 && status == 0) {
261
        VIR_INFO("Legacy xen tool stack seems to be in use, disabling "
J
Jim Fehlig 已提交
262
                  "libxenlight driver.");
263 264
    } else {
        ret = true;
J
Jim Fehlig 已提交
265 266 267
    }
    virCommandFree(cmd);

268 269 270 271 272 273 274 275
    return ret;
}

static int
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
276
    libxlDriverConfigPtr cfg;
277 278 279 280 281
    char ebuf[1024];

    if (!libxlDriverShouldLoad(privileged))
        return 0;

J
Jim Fehlig 已提交
282 283 284 285
    if (VIR_ALLOC(libxl_driver) < 0)
        return -1;

    if (virMutexInit(&libxl_driver->lock) < 0) {
286 287
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
J
Jim Fehlig 已提交
288 289 290 291 292
        VIR_FREE(libxl_driver);
        return -1;
    }

    /* Allocate bitmap for vnc port reservation */
293
    if (!(libxl_driver->reservedVNCPorts =
J
Ján Tomko 已提交
294 295
          virPortAllocatorNew(_("VNC"),
                              LIBXL_VNC_PORT_MIN,
296 297
                              LIBXL_VNC_PORT_MAX)))
        goto error;
J
Jim Fehlig 已提交
298

299 300
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
301

302 303 304
    if (!(libxl_driver->hostdevMgr = virHostdevManagerGetDefault()))
        goto error;

305
    if (!(cfg = libxlDriverConfigNew()))
306
        goto error;
J
Jim Fehlig 已提交
307

308 309
    libxl_driver->config = cfg;
    if (virFileMakePath(cfg->stateDir) < 0) {
310 311
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create state dir '%s': %s"),
312
                       cfg->stateDir,
313
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
314 315
        goto error;
    }
316
    if (virFileMakePath(cfg->libDir) < 0) {
317 318
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create lib dir '%s': %s"),
319
                       cfg->libDir,
320
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
321 322
        goto error;
    }
323
    if (virFileMakePath(cfg->saveDir) < 0) {
324 325
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create save dir '%s': %s"),
326
                       cfg->saveDir,
327
                       virStrerror(errno, ebuf, sizeof(ebuf)));
J
Jim Fehlig 已提交
328 329
        goto error;
    }
330 331 332 333 334 335 336
    if (virFileMakePath(cfg->autoDumpDir) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to create dump dir '%s': %s"),
                       cfg->autoDumpDir,
                       virStrerror(errno, ebuf, sizeof(ebuf)));
        goto error;
    }
J
Jim Fehlig 已提交
337

338
    /* read the host sysinfo */
339
    libxl_driver->hostsysinfo = virSysinfoRead();
340

341
    libxl_driver->domainEventState = virObjectEventStateNew();
E
Eric Blake 已提交
342
    if (!libxl_driver->domainEventState)
343 344
        goto error;

345
    if ((cfg->caps = libxlMakeCapabilities(cfg->ctx)) == NULL) {
346 347
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
348 349 350
        goto error;
    }

351
    if (!(libxl_driver->xmlopt = virDomainXMLOptionNew(&libxlDomainDefParserConfig,
352 353
                                                       &libxlDomainXMLPrivateDataCallbacks,
                                                       NULL)))
354
        goto error;
J
Jim Fehlig 已提交
355 356

    /* Load running domains first. */
357
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
358 359
                                       cfg->stateDir,
                                       cfg->autostartDir,
360
                                       1,
361
                                       cfg->caps,
362 363
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
364
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
365 366 367 368 369
        goto error;

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
370
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
371 372
                                       cfg->configDir,
                                       cfg->autostartDir,
373
                                       0,
374
                                       cfg->caps,
375 376
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
377
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
378 379
        goto error;

380 381
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
382

J
Jim Fehlig 已提交
383 384
    return 0;

385
 error:
386
    libxlStateCleanup();
387
    return -1;
J
Jim Fehlig 已提交
388 389
}

390 391 392 393 394 395 396 397 398 399
static void
libxlStateAutoStart(void)
{
    if (!libxl_driver)
        return;

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

J
Jim Fehlig 已提交
400
static int
401
libxlStateReload(void)
J
Jim Fehlig 已提交
402
{
403 404
    libxlDriverConfigPtr cfg;

J
Jim Fehlig 已提交
405 406 407
    if (!libxl_driver)
        return 0;

408 409
    cfg = libxlDriverConfigGet(libxl_driver);

410
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
411 412
                                   cfg->configDir,
                                   cfg->autostartDir,
413
                                   1,
414
                                   cfg->caps,
415 416
                                   libxl_driver->xmlopt,
                                   1 << VIR_DOMAIN_VIRT_XEN,
417 418
                                   NULL, libxl_driver);

419 420
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
421

422
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
423 424 425 426 427
    return 0;
}


static virDrvOpenStatus
428 429 430
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 unsigned int flags)
J
Jim Fehlig 已提交
431
{
E
Eric Blake 已提交
432 433
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
434 435 436 437
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

438
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
439 440 441 442 443 444 445 446 447 448 449 450
            return VIR_DRV_OPEN_ERROR;
    } else {
        /* Only xen scheme */
        if (conn->uri->scheme == NULL || STRNEQ(conn->uri->scheme, "xen"))
            return VIR_DRV_OPEN_DECLINED;

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

        /* Error if xen or libxl scheme specified but driver not started. */
        if (libxl_driver == NULL) {
451 452
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
453 454 455 456 457 458 459 460
            return VIR_DRV_OPEN_ERROR;
        }

        /* /session isn't supported in libxenlight */
        if (conn->uri->path &&
            STRNEQ(conn->uri->path, "") &&
            STRNEQ(conn->uri->path, "/") &&
            STRNEQ(conn->uri->path, "/system")) {
461 462 463
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
464 465 466 467
            return VIR_DRV_OPEN_ERROR;
        }
    }

468 469 470
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
471 472 473 474 475 476
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
477
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
478 479 480 481 482 483
{
    conn->privateData = NULL;
    return 0;
}

static const char *
484
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
485
{
486 487 488
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
489
    return "Xen";
J
Jim Fehlig 已提交
490 491 492
}

static int
493
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
494 495
{
    libxlDriverPrivatePtr driver = conn->privateData;
496
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
497

498 499 500
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

501 502 503
    cfg = libxlDriverConfigGet(driver);
    *version = cfg->version;
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
504 505 506
    return 0;
}

507

508
static char *libxlConnectGetHostname(virConnectPtr conn)
509
{
510 511 512
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

513 514 515
    return virGetHostname();
}

516 517 518 519 520 521 522 523
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

524 525 526
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

527 528 529 530 531 532 533 534 535 536 537 538 539 540
    if (!driver->hostsysinfo) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Host SMBIOS information is not available"));
        return NULL;
    }

    if (virSysinfoFormat(&buf, driver->hostsysinfo) < 0)
        return NULL;
    if (virBufferError(&buf)) {
        virReportOOMError();
        return NULL;
    }
    return virBufferContentAndReset(&buf);
}
541

J
Jim Fehlig 已提交
542
static int
543
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
544 545 546
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;
547
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
548

549 550 551
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

552 553
    cfg = libxlDriverConfigGet(driver);
    ret = libxl_get_max_cpus(cfg->ctx);
554 555 556 557 558
    /* On failure, libxl_get_max_cpus() will return ERROR_FAIL from Xen 4.4
     * onward, but it ever returning 0 is obviously wrong too (and it is
     * what happens, on failure, on Xen 4.3 and earlier). Therefore, a 'less
     * or equal' is the catchall we want. */
    if (ret <= 0)
559
        ret = -1;
J
Jim Fehlig 已提交
560

561
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
562 563 564 565 566 567
    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
568 569 570
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

571
    return libxlDriverNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
572 573 574
}

static char *
575
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
576 577 578
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;
579
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
580

581 582 583
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

584 585
    cfg = libxlDriverConfigGet(driver);
    if ((xml = virCapabilitiesFormatXML(cfg->caps)) == NULL)
J
Jim Fehlig 已提交
586 587
        virReportOOMError();

588
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
589 590 591 592
    return xml;
}

static int
593
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
594 595 596 597
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

598 599 600
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

601 602
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
603 604 605 606 607

    return n;
}

static int
608
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
609 610 611 612
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

613 614 615
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

616 617
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
618 619 620 621 622 623 624 625 626 627 628 629

    return n;
}

static virDomainPtr
libxlDomainCreateXML(virConnectPtr conn, const char *xml,
                     unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virDomainDefPtr def;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
630
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
631 632 633

    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);

634
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
635
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
636 637 638
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

639 640 641
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

642
    if (!(vm = virDomainObjListAdd(driver->domains, def,
643
                                   driver->xmlopt,
644 645
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
646 647 648
        goto cleanup;
    def = NULL;

649
    if (libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0,
650
                     -1) < 0) {
651
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
652 653 654 655 656 657 658 659
        vm = NULL;
        goto cleanup;
    }

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

660
 cleanup:
J
Jim Fehlig 已提交
661 662
    virDomainDefFree(def);
    if (vm)
663
        virObjectUnlock(vm);
664
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
665 666 667 668 669 670 671 672 673 674
    return dom;
}

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

675
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
676
    if (!vm) {
677
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
678 679 680
        goto cleanup;
    }

681 682 683
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
684 685 686 687
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

688
 cleanup:
J
Jim Fehlig 已提交
689
    if (vm)
690
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
691 692 693 694 695 696 697 698 699 700
    return dom;
}

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

701
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
702
    if (!vm) {
703
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
704 705 706
        goto cleanup;
    }

707 708 709
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
710 711 712 713
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

714
 cleanup:
J
Jim Fehlig 已提交
715
    if (vm)
716
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
717 718 719 720 721 722 723 724 725 726
    return dom;
}

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

727
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
728
    if (!vm) {
729
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
730 731 732
        goto cleanup;
    }

733 734 735
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
736 737 738 739
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

740
 cleanup:
J
Jim Fehlig 已提交
741
    if (vm)
742
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
743 744 745
    return dom;
}

746 747 748 749
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
750
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
751 752
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
753
    virObjectEventPtr event = NULL;
754 755
    int ret = -1;

J
Jim Fehlig 已提交
756
    if (!(vm = libxlDomObjFromDomain(dom)))
757
        goto cleanup;
758 759 760 761

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

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

765
    if (!virDomainObjIsActive(vm)) {
766
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
767
        goto endjob;
768 769 770 771
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
772
    if (virDomainObjGetState(vm, NULL) != VIR_DOMAIN_PAUSED) {
773
        if (libxl_domain_pause(priv->ctx, vm->def->id) != 0) {
774 775
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to suspend domain '%d' with libxenlight"),
776
                           vm->def->id);
777
            goto endjob;
778 779
        }

J
Jiri Denemark 已提交
780
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
781

782
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
783 784 785
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

786
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
787
        goto endjob;
788 789 790

    ret = 0;

791
 endjob:
792 793 794
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

795
 cleanup:
796
    if (vm)
797
        virObjectUnlock(vm);
798
    if (event)
799
        libxlDomainEventQueue(driver, event);
800
    virObjectUnref(cfg);
801 802 803 804 805 806 807 808
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
809
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
810 811
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
812
    virObjectEventPtr event = NULL;
813 814
    int ret = -1;

J
Jim Fehlig 已提交
815
    if (!(vm = libxlDomObjFromDomain(dom)))
816 817
        goto cleanup;

818 819 820
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

824
    if (!virDomainObjIsActive(vm)) {
825
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
826
        goto endjob;
827 828 829 830
    }

    priv = vm->privateData;

J
Jiri Denemark 已提交
831
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
832
        if (libxl_domain_unpause(priv->ctx, vm->def->id) != 0) {
833 834
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to resume domain '%d' with libxenlight"),
835
                           vm->def->id);
836
            goto endjob;
837 838
        }

J
Jiri Denemark 已提交
839 840
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
841

842
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_RESUMED,
843 844 845
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

846
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
847
        goto endjob;
848 849 850

    ret = 0;

851
 endjob:
852 853 854
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

855
 cleanup:
856
    if (vm)
857
        virObjectUnlock(vm);
858
    if (event)
859
        libxlDomainEventQueue(driver, event);
860
    virObjectUnref(cfg);
861 862 863
    return ret;
}

J
Jim Fehlig 已提交
864
static int
865
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
866 867 868 869 870
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

871 872
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
873
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
874 875
        goto cleanup;

876
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
877 878
        goto cleanup;

J
Jim Fehlig 已提交
879
    if (!virDomainObjIsActive(vm)) {
880 881
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
882 883 884 885
        goto cleanup;
    }

    priv = vm->privateData;
886
    if (libxl_domain_shutdown(priv->ctx, vm->def->id) != 0) {
887 888
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
889
                       vm->def->id);
J
Jim Fehlig 已提交
890 891 892 893 894 895 896 897
        goto cleanup;
    }

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

898
 cleanup:
J
Jim Fehlig 已提交
899
    if (vm)
900
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
901 902 903
    return ret;
}

904 905 906 907 908 909 910
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
911
static int
E
Eric Blake 已提交
912
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
913 914 915 916 917
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

E
Eric Blake 已提交
918 919
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
920
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
921 922
        goto cleanup;

923
    if (virDomainRebootEnsureACL(dom->conn, vm->def, flags) < 0)
924 925
        goto cleanup;

J
Jim Fehlig 已提交
926
    if (!virDomainObjIsActive(vm)) {
927 928
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
929 930 931 932
        goto cleanup;
    }

    priv = vm->privateData;
933
    if (libxl_domain_reboot(priv->ctx, vm->def->id) != 0) {
934 935
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
936
                       vm->def->id);
J
Jim Fehlig 已提交
937 938 939 940
        goto cleanup;
    }
    ret = 0;

941
 cleanup:
J
Jim Fehlig 已提交
942
    if (vm)
943
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
944 945 946 947
    return ret;
}

static int
948 949
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
950 951 952 953
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
954
    virObjectEventPtr event = NULL;
J
Jim Fehlig 已提交
955
    libxlDomainObjPrivatePtr priv;
J
Jim Fehlig 已提交
956

957 958
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
959
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
960 961
        goto cleanup;

962 963 964
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
965
    if (!virDomainObjIsActive(vm)) {
966 967
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
968 969 970
        goto cleanup;
    }

971
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
972 973
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

J
Jim Fehlig 已提交
974 975
    priv = vm->privateData;
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
976
        virReportError(VIR_ERR_INTERNAL_ERROR,
977
                       _("Failed to destroy domain '%d'"), vm->def->id);
J
Jim Fehlig 已提交
978 979 980
        goto cleanup;
    }

981
    if (libxlDomainCleanupJob(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED)) {
982 983 984 985
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
J
Jim Fehlig 已提交
986 987 988 989
    }

    ret = 0;

990
 cleanup:
J
Jim Fehlig 已提交
991
    if (vm)
992
        virObjectUnlock(vm);
993 994
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
995 996 997
    return ret;
}

998 999 1000 1001 1002 1003
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1004 1005 1006 1007 1008 1009
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *type = NULL;

J
Jim Fehlig 已提交
1010
    if (!(vm = libxlDomObjFromDomain(dom)))
1011 1012
        goto cleanup;

1013 1014 1015 1016 1017
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1019
 cleanup:
1020
    if (vm)
1021
        virObjectUnlock(vm);
1022 1023 1024
    return type;
}

1025
static unsigned long long
1026 1027 1028
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    virDomainObjPtr vm;
1029
    unsigned long long ret = 0;
1030

J
Jim Fehlig 已提交
1031
    if (!(vm = libxlDomObjFromDomain(dom)))
1032
        goto cleanup;
1033 1034 1035 1036

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

1037 1038
    ret = vm->def->mem.max_balloon;

1039
 cleanup:
1040
    if (vm)
1041
        virObjectUnlock(vm);
1042 1043 1044 1045
    return ret;
}

static int
1046
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1047 1048 1049
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1050
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1051 1052
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1053 1054
    virDomainDefPtr persistentDef = NULL;
    bool isActive;
1055 1056 1057
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1058 1059
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1060

J
Jim Fehlig 已提交
1061
    if (!(vm = libxlDomObjFromDomain(dom)))
1062 1063
        goto cleanup;

1064 1065 1066
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
    isActive = virDomainObjIsActive(vm);

    if (flags == VIR_DOMAIN_MEM_CURRENT) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE;
        else
            flags = VIR_DOMAIN_MEM_CONFIG;
    }
    if (flags == VIR_DOMAIN_MEM_MAXIMUM) {
        if (isActive)
            flags = VIR_DOMAIN_MEM_LIVE | VIR_DOMAIN_MEM_MAXIMUM;
        else
            flags = VIR_DOMAIN_MEM_CONFIG | VIR_DOMAIN_MEM_MAXIMUM;
1083 1084
    }

1085
    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
1086 1087
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set memory on an inactive domain"));
1088
        goto endjob;
1089 1090 1091 1092
    }

    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
1093 1094
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a transient domain"));
1095
            goto endjob;
1096
        }
1097
        if (!(persistentDef = virDomainObjGetPersistentDef(cfg->caps,
1098
                                                           driver->xmlopt,
1099
                                                           vm)))
1100
            goto endjob;
1101 1102
    }

1103 1104
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1105

1106 1107
        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
1108
            if (libxl_domain_setmaxmem(priv->ctx, vm->def->id, newmem) < 0) {
1109 1110
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
1111
                                 " with libxenlight"), vm->def->id);
1112
                goto endjob;
1113 1114 1115 1116 1117 1118 1119 1120 1121
            }
        }

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

1126 1127
    } else {
        /* resize the current memory */
1128

1129
        if (newmem > vm->def->mem.max_balloon) {
1130 1131
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1132
            goto endjob;
1133 1134 1135
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
1136 1137
            int res;

1138
            priv = vm->privateData;
1139 1140
            /* Unlock virDomainObj while ballooning memory */
            virObjectUnlock(vm);
1141
            res = libxl_set_memory_target(priv->ctx, vm->def->id, newmem, 0,
1142 1143 1144
                                          /* force */ 1);
            virObjectLock(vm);
            if (res < 0) {
1145 1146
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
1147
                                 " with libxenlight"), vm->def->id);
1148
                goto endjob;
1149 1150 1151 1152 1153 1154
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1155
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
1156
            goto endjob;
1157
        }
1158 1159
    }

1160 1161
    ret = 0;

1162
 endjob:
1163 1164 1165
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1166
 cleanup:
1167
    if (vm)
1168
        virObjectUnlock(vm);
1169
    virObjectUnref(cfg);
1170 1171 1172 1173 1174 1175 1176 1177 1178
    return ret;
}

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

1179 1180 1181 1182 1183 1184
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1185 1186 1187 1188
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
    virDomainObjPtr vm;
1189
    libxl_dominfo d_info;
1190
    libxlDomainObjPrivatePtr priv;
J
Jim Fehlig 已提交
1191 1192
    int ret = -1;

J
Jim Fehlig 已提交
1193
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1194 1195
        goto cleanup;

1196 1197 1198
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1199
    priv = vm->privateData;
1200 1201 1202
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1203
        info->maxMem = vm->def->mem.max_balloon;
1204
    } else {
1205
        if (libxl_domain_info(priv->ctx, &d_info, vm->def->id) != 0) {
1206
            virReportError(VIR_ERR_INTERNAL_ERROR,
1207 1208
                           _("libxl_domain_info failed for domain '%d'"),
                           vm->def->id);
1209 1210 1211 1212
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1213
        info->maxMem = d_info.max_memkb;
1214 1215
    }

J
Jiri Denemark 已提交
1216
    info->state = virDomainObjGetState(vm, NULL);
J
Jim Fehlig 已提交
1217 1218 1219
    info->nrVirtCpu = vm->def->vcpus;
    ret = 0;

1220
 cleanup:
J
Jim Fehlig 已提交
1221
    if (vm)
1222
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1223 1224 1225
    return ret;
}

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1237
    if (!(vm = libxlDomObjFromDomain(dom)))
1238 1239
        goto cleanup;

1240 1241 1242
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1243
    *state = virDomainObjGetState(vm, reason);
1244 1245
    ret = 0;

1246
 cleanup:
1247
    if (vm)
1248
        virObjectUnlock(vm);
1249 1250 1251
    return ret;
}

1252 1253 1254
/*
 * virDomainObjPtr must be locked on invocation
 */
1255
static int
1256 1257
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1258
{
1259
    libxlDomainObjPrivatePtr priv = vm->privateData;
1260
    libxlSavefileHeader hdr;
1261
    virObjectEventPtr event = NULL;
1262 1263
    char *xml = NULL;
    uint32_t xml_len;
1264
    int fd = -1;
1265 1266 1267
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1268 1269 1270
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1271 1272 1273 1274
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1275
                            -1, -1, 0)) < 0) {
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
        virReportSystemError(-fd,
                             _("Failed to create domain save file '%s'"), to);
        goto cleanup;
    }

    if ((xml = virDomainDefFormat(vm->def, 0)) == NULL)
        goto cleanup;
    xml_len = strlen(xml) + 1;

    memset(&hdr, 0, sizeof(hdr));
    memcpy(hdr.magic, LIBXL_SAVE_MAGIC, sizeof(hdr.magic));
    hdr.version = LIBXL_SAVE_VERSION;
    hdr.xmlLen = xml_len;

    if (safewrite(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) {
1291 1292
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1293 1294 1295 1296
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1297 1298
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1299 1300 1301
        goto cleanup;
    }

1302 1303 1304 1305 1306 1307
    /* Unlock virDomainObj while saving domain */
    virObjectUnlock(vm);
    ret = libxl_domain_suspend(priv->ctx, vm->def->id, fd, 0, NULL);
    virObjectLock(vm);

    if (ret != 0) {
1308 1309 1310
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1311
        ret = -1;
1312 1313 1314
        goto cleanup;
    }

1315
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1316 1317
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

J
Jim Fehlig 已提交
1318
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
1319 1320
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1321 1322 1323
        goto cleanup;
    }

1324
    libxlDomainCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED);
1325
    vm->hasManagedSave = true;
1326 1327
    ret = 0;

1328
 cleanup:
1329 1330 1331 1332 1333 1334 1335 1336 1337
    VIR_FREE(xml);
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
    if (event)
        libxlDomainEventQueue(driver, event);
    return ret;
}

static int
1338 1339
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1340
{
1341 1342
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1343
    int ret = -1;
1344
    bool remove_dom = false;
1345

1346 1347
    virCheckFlags(0, -1);
    if (dxml) {
1348 1349
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1350 1351 1352
        return -1;
    }

J
Jim Fehlig 已提交
1353
    if (!(vm = libxlDomObjFromDomain(dom)))
1354 1355
        goto cleanup;

1356 1357 1358
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1362
    if (!virDomainObjIsActive(vm)) {
1363
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1364
        goto endjob;
1365 1366
    }

1367
    if (libxlDoDomainSave(driver, vm, to) < 0)
1368
        goto endjob;
1369

1370 1371
    if (!vm->persistent)
        remove_dom = true;
1372 1373

    ret = 0;
1374

1375
 endjob:
1376 1377 1378
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1379
 cleanup:
1380 1381 1382 1383
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1384
    if (vm)
1385
        virObjectUnlock(vm);
1386 1387
    return ret;
}
1388

1389
static int
1390 1391 1392 1393 1394 1395 1396 1397
libxlDomainSave(virDomainPtr dom, const char *to)
{
    return libxlDomainSaveFlags(dom, to, NULL, 0);
}

static int
libxlDomainRestoreFlags(virConnectPtr conn, const char *from,
                        const char *dxml, unsigned int flags)
1398 1399
{
    libxlDriverPrivatePtr driver = conn->privateData;
1400
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1401 1402 1403 1404 1405
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1406

1407
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1408
    if (dxml) {
1409 1410
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1411 1412 1413
        return -1;
    }

1414
    fd = libxlDomainSaveImageOpen(driver, cfg, from, &def, &hdr);
1415
    if (fd < 0)
1416
        goto cleanup_unlock;
1417

1418
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1419
        goto cleanup_unlock;
1420

1421
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1422
                                   driver->xmlopt,
1423 1424 1425
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1426
        goto cleanup_unlock;
1427 1428 1429

    def = NULL;

1430
    ret = libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_SAVE_PAUSED) != 0, fd);
1431
    if (ret < 0 && !vm->persistent) {
1432
        virDomainObjListRemove(driver->domains, vm);
1433 1434 1435
        vm = NULL;
    }

1436
 cleanup:
1437 1438
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1439 1440
    virDomainDefFree(def);
    if (vm)
1441
        virObjectUnlock(vm);
1442
    virObjectUnref(cfg);
1443
    return ret;
1444

1445
 cleanup_unlock:
1446 1447
    libxlDriverUnlock(driver);
    goto cleanup;
1448 1449
}

1450 1451 1452 1453 1454 1455
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

1456
static int
1457
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1458 1459 1460 1461
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1462
    virObjectEventPtr event = NULL;
1463
    bool remove_dom = false;
1464 1465 1466 1467 1468
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

J
Jim Fehlig 已提交
1469
    if (!(vm = libxlDomObjFromDomain(dom)))
1470 1471
        goto cleanup;

1472 1473 1474
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1478
    if (!virDomainObjIsActive(vm)) {
1479
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1480
        goto endjob;
1481 1482 1483 1484 1485 1486
    }

    priv = vm->privateData;

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
1487
        if (libxl_domain_pause(priv->ctx, vm->def->id) != 0) {
1488 1489 1490
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
1491
                           vm->def->id);
1492
            goto endjob;
1493 1494 1495 1496 1497
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

1498 1499
    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
1500
    ret = libxl_domain_core_dump(priv->ctx, vm->def->id, to, NULL);
1501 1502
    virObjectLock(vm);
    if (ret != 0) {
1503 1504
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
1505
                       vm->def->id);
1506 1507
        ret = -1;
        goto unpause;
1508 1509 1510
    }

    if (flags & VIR_DUMP_CRASH) {
1511
        if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
1512
            virReportError(VIR_ERR_INTERNAL_ERROR,
1513
                           _("Failed to destroy domain '%d'"), vm->def->id);
1514
            goto unpause;
1515 1516
        }

1517
        libxlDomainCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED);
1518
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1519
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
1520 1521
        if (!vm->persistent)
            remove_dom = true;
1522 1523 1524 1525
    }

    ret = 0;

1526
 unpause:
1527
    if (virDomainObjIsActive(vm) && paused) {
1528
        if (libxl_domain_unpause(priv->ctx, vm->def->id) != 0) {
1529 1530
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
1531
                             " libxenlight"), vm->def->id);
1532 1533 1534 1535 1536
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
1537

1538
 endjob:
1539 1540 1541
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1542
 cleanup:
1543 1544 1545 1546
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1547
    if (vm)
1548
        virObjectUnlock(vm);
1549
    if (event)
1550 1551 1552 1553
        libxlDomainEventQueue(driver, event);
    return ret;
}

1554 1555 1556 1557 1558 1559 1560
static int
libxlDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;
1561
    bool remove_dom = false;
1562 1563 1564

    virCheckFlags(0, -1);

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

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

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

1574
    if (!virDomainObjIsActive(vm)) {
1575
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1576
        goto endjob;
1577
    }
1578
    if (!vm->persistent) {
1579 1580
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
1581
        goto endjob;
1582
    }
1583 1584 1585

    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
1586
        goto endjob;
1587 1588 1589

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

1590
    if (libxlDoDomainSave(driver, vm, name) < 0)
1591
        goto endjob;
1592

1593 1594
    if (!vm->persistent)
        remove_dom = true;
1595 1596

    ret = 0;
1597

1598
 endjob:
1599 1600 1601
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1602
 cleanup:
1603 1604 1605 1606
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1607
    if (vm)
1608
        virObjectUnlock(vm);
1609 1610 1611 1612
    VIR_FREE(name);
    return ret;
}

1613 1614
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
1615 1616 1617 1618
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
1619
    int ret = -1;
1620

1621
    virObjectLock(vm);
1622 1623 1624 1625 1626 1627

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

    vm->hasManagedSave = virFileExists(name);

1628
    ret = 0;
1629
 cleanup:
1630
    virObjectUnlock(vm);
1631
    VIR_FREE(name);
1632
    return ret;
1633 1634
}

1635 1636 1637 1638 1639 1640 1641 1642
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

1646 1647 1648
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1649
    ret = vm->hasManagedSave;
1650

1651
 cleanup:
1652
    if (vm)
1653
        virObjectUnlock(vm);
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    return ret;
}

static int
libxlDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    char *name = NULL;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1667
    if (!(vm = libxlDomObjFromDomain(dom)))
1668 1669
        goto cleanup;

1670 1671 1672
    if (virDomainManagedSaveRemoveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1673 1674 1675 1676 1677
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
1678
    vm->hasManagedSave = false;
1679

1680
 cleanup:
1681 1682
    VIR_FREE(name);
    if (vm)
1683
        virObjectUnlock(vm);
1684 1685 1686
    return ret;
}

1687 1688 1689 1690 1691
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1692
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1693 1694 1695
    libxlDomainObjPrivatePtr priv;
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
1696
    libxl_bitmap map;
1697 1698
    uint8_t *bitmask = NULL;
    unsigned int maplen;
1699 1700
    size_t i;
    unsigned int pos;
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
    int max;
    int ret = -1;

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

    /* At least one of LIVE or CONFIG must be set.  MAXIMUM cannot be
     * mixed with LIVE.  */
    if ((flags & (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) == 0 ||
        (flags & (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_LIVE)) ==
         (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_LIVE)) {
1713 1714
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
1715 1716 1717 1718
        return -1;
    }

    if (!nvcpus) {
1719
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
1720 1721 1722
        return -1;
    }

J
Jim Fehlig 已提交
1723
    if (!(vm = libxlDomObjFromDomain(dom)))
1724 1725
        goto cleanup;

1726 1727 1728
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

1732
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
1733 1734
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
1735
        goto endjob;
1736 1737 1738
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
1739 1740
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
1741
        goto endjob;
1742 1743
    }

1744
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
1745 1746
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
1747
        goto endjob;
1748 1749 1750 1751 1752 1753 1754
    }

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

    if (nvcpus > max) {
1755 1756 1757
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
1758
        goto endjob;
1759 1760 1761 1762
    }

    priv = vm->privateData;

1763
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm)))
1764
        goto endjob;
1765

E
Eric Blake 已提交
1766
    maplen = VIR_CPU_MAPLEN(nvcpus);
1767
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
1768
        goto endjob;
1769 1770

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
1771
        pos = i / 8;
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
        bitmask[pos] |= 1 << (i % 8);
    }

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

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

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

    case VIR_DOMAIN_VCPU_LIVE:
1790
        if (libxl_set_vcpuonline(priv->ctx, vm->def->id, &map) != 0) {
1791 1792
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
1793
                             " with libxenlight"), vm->def->id);
1794
            goto endjob;
1795 1796 1797 1798
        }
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
1799
        if (libxl_set_vcpuonline(priv->ctx, vm->def->id, &map) != 0) {
1800 1801
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
1802
                             " with libxenlight"), vm->def->id);
1803
            goto endjob;
1804 1805 1806 1807 1808 1809 1810 1811
        }
        def->vcpus = nvcpus;
        break;
    }

    ret = 0;

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

1814
 endjob:
1815 1816 1817
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1818
 cleanup:
1819 1820
    VIR_FREE(bitmask);
     if (vm)
1821
        virObjectUnlock(vm);
1822
     virObjectUnref(cfg);
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
    return ret;
}

static int
libxlDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
    return libxlDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_VCPU_LIVE);
}

static int
libxlDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm;
    virDomainDefPtr def;
    int ret = -1;
1838
    bool active;
1839 1840 1841 1842 1843

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

J
Jim Fehlig 已提交
1844
    if (!(vm = libxlDomObjFromDomain(dom)))
1845 1846
        goto cleanup;

1847
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1848 1849
        goto cleanup;

1850 1851 1852 1853 1854 1855 1856 1857 1858
    active = virDomainObjIsActive(vm);

    if ((flags & (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) == 0) {
        if (active)
            flags |= VIR_DOMAIN_VCPU_LIVE;
        else
            flags |= VIR_DOMAIN_VCPU_CONFIG;
    }
    if ((flags & VIR_DOMAIN_VCPU_LIVE) && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
1859 1860
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
1861 1862 1863
        return -1;
    }

1864
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
1865
        if (!active) {
1866 1867
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
1868 1869 1870 1871
            goto cleanup;
        }
        def = vm->def;
    } else {
1872
        if (!vm->persistent) {
1873 1874
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
1875 1876
            goto cleanup;
        }
1877 1878 1879 1880 1881
        def = vm->newDef ? vm->newDef : vm->def;
    }

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

1882
 cleanup:
1883
    if (vm)
1884
        virObjectUnlock(vm);
1885 1886 1887 1888
    return ret;
}

static int
1889 1890 1891
libxlDomainPinVcpuFlags(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen,
                        unsigned int flags)
1892 1893
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1894
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1895
    virDomainDefPtr targetDef = NULL;
1896
    virBitmapPtr pcpumap = NULL;
1897 1898
    virDomainObjPtr vm;
    int ret = -1;
1899 1900 1901

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
1902

J
Jim Fehlig 已提交
1903
    if (!(vm = libxlDomObjFromDomain(dom)))
1904 1905
        goto cleanup;

1906
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1907 1908
        goto cleanup;

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

1912
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) && !virDomainObjIsActive(vm)) {
1913
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
1914
                       _("domain is inactive"));
1915
        goto endjob;
1916 1917
    }

1918 1919
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
1920
        goto endjob;
1921 1922 1923 1924 1925 1926 1927 1928

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

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

1929 1930
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
1931
        goto endjob;
1932

1933 1934 1935 1936 1937
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        libxl_bitmap map = { .size = maplen, .map = cpumap };
        libxlDomainObjPrivatePtr priv;

        priv = vm->privateData;
1938
        if (libxl_set_vcpuaffinity(priv->ctx, vm->def->id, vcpu, &map) != 0) {
1939 1940 1941
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"),
                           vcpu);
1942
            goto endjob;
1943
        }
1944
    }
1945

1946 1947
    /* full bitmap means reset the settings (if any). */
    if (virBitmapIsAllSet(pcpumap)) {
1948
        virDomainVcpuPinDel(targetDef, vcpu);
1949
        goto done;
1950 1951
    }

1952 1953
    if (!targetDef->cputune.vcpupin) {
        if (VIR_ALLOC(targetDef->cputune.vcpupin) < 0)
1954
            goto endjob;
1955
        targetDef->cputune.nvcpupin = 0;
H
Hu Tao 已提交
1956
    }
1957 1958
    if (virDomainVcpuPinAdd(&targetDef->cputune.vcpupin,
                            &targetDef->cputune.nvcpupin,
H
Hu Tao 已提交
1959 1960 1961
                            cpumap,
                            maplen,
                            vcpu) < 0) {
1962 1963
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to update or add vcpupin xml"));
1964
        goto endjob;
1965 1966
    }

1967
 done:
1968 1969
    ret = 0;

1970 1971 1972 1973 1974 1975
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        ret = virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm);
    } else if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
        ret = virDomainSaveConfig(cfg->configDir, targetDef);
    }

1976
 endjob:
1977 1978 1979
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1980
 cleanup:
1981
    if (vm)
1982
        virObjectUnlock(vm);
1983
    virBitmapFree(pcpumap);
1984
    virObjectUnref(cfg);
1985 1986 1987
    return ret;
}

1988 1989 1990 1991 1992 1993 1994 1995
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
static int
libxlDomainGetVcpuPinInfo(virDomainPtr dom, int ncpumaps,
                          unsigned char *cpumaps, int maplen,
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    virDomainObjPtr vm = NULL;
    virDomainDefPtr targetDef = NULL;
    virDomainVcpuPinDefPtr *vcpupin_list;
    virBitmapPtr cpumask = NULL;
    int maxcpu, hostcpus, vcpu, pcpu, n, ret = -1;
    unsigned char *cpumap;
    bool pinned;

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);

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

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

    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
        goto cleanup;

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

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

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

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

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

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

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

2067
 cleanup:
2068 2069 2070 2071 2072
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(cfg);
    return ret;
}
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082

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

J
Jim Fehlig 已提交
2086
    if (!(vm = libxlDomObjFromDomain(dom)))
2087 2088
        goto cleanup;

2089 2090 2091
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2092
    if (!virDomainObjIsActive(vm)) {
2093
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2094 2095 2096 2097
        goto cleanup;
    }

    priv = vm->privateData;
2098
    if ((vcpuinfo = libxl_list_vcpu(priv->ctx, vm->def->id, &maxcpu,
2099
                                    &hostcpus)) == NULL) {
2100 2101
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
2102
                       vm->def->id);
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
        goto cleanup;
    }

    if (cpumaps && maplen > 0)
        memset(cpumaps, 0, maplen * maxinfo);
    for (i = 0; i < maxcpu && i < maxinfo; ++i) {
        info[i].number = vcpuinfo[i].vcpuid;
        info[i].cpu = vcpuinfo[i].cpu;
        info[i].cpuTime = vcpuinfo[i].vcpu_time;
        if (vcpuinfo[i].running)
            info[i].state = VIR_VCPU_RUNNING;
        else if (vcpuinfo[i].blocked)
            info[i].state = VIR_VCPU_BLOCKED;
        else
            info[i].state = VIR_VCPU_OFFLINE;

        if (cpumaps && maplen > 0) {
            cpumap = VIR_GET_CPUMAP(cpumaps, maplen, i);
            memcpy(cpumap, vcpuinfo[i].cpumap.map,
                   MIN(maplen, vcpuinfo[i].cpumap.size));
        }

J
Jim Fehlig 已提交
2125
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2126 2127 2128 2129 2130
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

2131
 cleanup:
2132
    if (vm)
2133
        virObjectUnlock(vm);
2134 2135 2136
    return ret;
}

J
Jim Fehlig 已提交
2137
static char *
2138
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2139 2140 2141 2142
{
    virDomainObjPtr vm;
    char *ret = NULL;

2143 2144
    /* Flags checked by virDomainDefFormat */

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

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

J
Jim Fehlig 已提交
2151 2152
    ret = virDomainDefFormat(vm->def, flags);

2153
 cleanup:
J
Jim Fehlig 已提交
2154
    if (vm)
2155
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2156 2157 2158
    return ret;
}

2159
static char *
2160 2161 2162
libxlConnectDomainXMLFromNative(virConnectPtr conn,
                                const char *nativeFormat,
                                const char *nativeConfig,
2163
                                unsigned int flags)
2164 2165
{
    libxlDriverPrivatePtr driver = conn->privateData;
2166
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2167 2168 2169 2170
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2171 2172
    virCheckFlags(0, NULL);

2173 2174 2175
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
    if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
        if (!(conf = virConfReadMem(nativeConfig, strlen(nativeConfig), 0)))
            goto cleanup;

        if (!(def = xenParseXM(conf,
                               cfg->verInfo->xen_version_major,
                               cfg->caps))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("parsing xm config failed"));
            goto cleanup;
        }
    } else if (STREQ(nativeFormat, LIBXL_CONFIG_FORMAT_SEXPR)) {
        /* only support latest xend config format */
        if (!(def = xenParseSxprString(nativeConfig,
                                       XEND_CONFIG_VERSION_3_1_0,
                                       NULL,
                                       -1))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("parsing sxpr config failed"));
            goto cleanup;
        }
    } else {
2198 2199
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2200 2201 2202 2203 2204
        goto cleanup;
    }

    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);

2205
 cleanup:
2206 2207 2208
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2209
    virObjectUnref(cfg);
2210 2211 2212 2213 2214
    return xml;
}

#define MAX_CONFIG_SIZE (1024 * 65)
static char *
2215 2216 2217
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
2218 2219
{
    libxlDriverPrivatePtr driver = conn->privateData;
2220
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2221 2222 2223 2224 2225
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    int len = MAX_CONFIG_SIZE;
    char *ret = NULL;

E
Eric Blake 已提交
2226 2227
    virCheckFlags(0, NULL);

2228 2229 2230
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

2231
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2232 2233
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2234 2235 2236
        goto cleanup;
    }

2237
    if (!(def = virDomainDefParseString(domainXml,
2238
                                        cfg->caps, driver->xmlopt,
2239 2240
                                        1 << VIR_DOMAIN_VIRT_XEN,
                                        VIR_DOMAIN_XML_INACTIVE)))
2241 2242
        goto cleanup;

2243
    if (!(conf = xenFormatXM(conn, def, cfg->verInfo->xen_version_major)))
2244 2245
        goto cleanup;

2246
    if (VIR_ALLOC_N(ret, len) < 0)
2247 2248 2249 2250 2251 2252 2253
        goto cleanup;

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

2254
 cleanup:
2255 2256 2257
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2258
    virObjectUnref(cfg);
2259 2260 2261
    return ret;
}

J
Jim Fehlig 已提交
2262
static int
2263 2264
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
2265 2266 2267 2268
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2269 2270 2271
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2272 2273
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
2274 2275 2276 2277
    return n;
}

static int
2278
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
2279 2280 2281 2282
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2283 2284 2285
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2286
    n = virDomainObjListNumOfDomains(driver->domains, false,
2287 2288
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
2289 2290 2291 2292 2293
    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
2294
                           unsigned int flags)
J
Jim Fehlig 已提交
2295 2296 2297 2298 2299 2300 2301
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

J
Jim Fehlig 已提交
2302
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2303 2304
        goto cleanup;

2305 2306 2307
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2308
    if (virDomainObjIsActive(vm)) {
2309 2310
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
J
Jim Fehlig 已提交
2311 2312 2313
        goto cleanup;
    }

2314
    ret = libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0, -1);
J
Jim Fehlig 已提交
2315

2316
 cleanup:
J
Jim Fehlig 已提交
2317
    if (vm)
2318
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
    return ret;
}

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

static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    libxlDriverPrivatePtr driver = conn->privateData;
2332
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2333 2334 2335
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
2336
    virObjectEventPtr event = NULL;
2337
    virDomainDefPtr oldDef = NULL;
J
Jim Fehlig 已提交
2338

2339
    /* Lock the driver until the virDomainObj is created and locked */
J
Jim Fehlig 已提交
2340
    libxlDriverLock(driver);
2341
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
M
Matthias Bolte 已提交
2342
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
2343
                                        VIR_DOMAIN_XML_INACTIVE)))
2344
        goto cleanup_unlock;
J
Jim Fehlig 已提交
2345

2346
    if (virDomainDefineXMLEnsureACL(conn, def) < 0)
2347
        goto cleanup_unlock;
2348

2349
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2350
                                   driver->xmlopt,
2351 2352
                                   0,
                                   &oldDef)))
2353 2354
        goto cleanup_unlock;

J
Jim Fehlig 已提交
2355 2356
    def = NULL;
    vm->persistent = 1;
2357
    libxlDriverUnlock(driver);
J
Jim Fehlig 已提交
2358

2359
    if (virDomainSaveConfig(cfg->configDir,
J
Jim Fehlig 已提交
2360
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2361
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
2362 2363 2364 2365 2366 2367 2368 2369
        vm = NULL;
        goto cleanup;
    }

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

2370
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2371
                                     !oldDef ?
2372 2373 2374
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

2375
 cleanup:
J
Jim Fehlig 已提交
2376
    virDomainDefFree(def);
2377
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
2378
    if (vm)
2379
        virObjectUnlock(vm);
2380 2381
    if (event)
        libxlDomainEventQueue(driver, event);
2382
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2383
    return dom;
2384

2385
 cleanup_unlock:
2386 2387
    libxlDriverUnlock(driver);
    goto cleanup;
J
Jim Fehlig 已提交
2388 2389 2390
}

static int
2391 2392
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2393 2394
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2395
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2396
    virDomainObjPtr vm;
2397
    virObjectEventPtr event = NULL;
2398
    char *name = NULL;
J
Jim Fehlig 已提交
2399 2400
    int ret = -1;

2401 2402
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

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

2406 2407 2408
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2409
    if (!vm->persistent) {
2410 2411
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2412 2413 2414
        goto cleanup;
    }

2415 2416 2417 2418 2419 2420 2421
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2422 2423
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2424 2425 2426
                goto cleanup;
            }
        } else {
2427 2428 2429
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2430 2431 2432 2433
            goto cleanup;
        }
    }

2434
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2435 2436
        goto cleanup;

2437
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2438 2439
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2440 2441 2442
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
2443
        virDomainObjListRemove(driver->domains, vm);
2444 2445 2446
        vm = NULL;
    }

J
Jim Fehlig 已提交
2447 2448
    ret = 0;

2449
 cleanup:
2450
    VIR_FREE(name);
J
Jim Fehlig 已提交
2451
    if (vm)
2452
        virObjectUnlock(vm);
2453 2454
    if (event)
        libxlDomainEventQueue(driver, event);
2455
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2456 2457 2458
    return ret;
}

2459 2460 2461 2462 2463 2464
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2465 2466 2467 2468 2469 2470
static int
libxlDomainChangeEjectableMedia(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDiskDefPtr disk)
{
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2471
    size_t i;
2472 2473
    int ret = -1;

2474
    for (i = 0; i < vm->def->ndisks; i++) {
2475 2476 2477 2478 2479 2480 2481 2482
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
2483 2484 2485
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
2486 2487 2488 2489
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2490 2491 2492
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
2493 2494 2495
        return -1;
    }

J
Jim Fehlig 已提交
2496
    if (libxlMakeDisk(disk, &x_disk) < 0)
2497 2498
        goto cleanup;

J
Jim Fehlig 已提交
2499
    if ((ret = libxl_cdrom_insert(priv->ctx, vm->def->id, &x_disk, NULL)) < 0) {
2500 2501 2502
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
2503 2504 2505
        goto cleanup;
    }

2506 2507 2508
    if (virDomainDiskSetSource(origdisk, virDomainDiskGetSource(disk)) < 0)
        goto cleanup;
    virDomainDiskSetType(origdisk, virDomainDiskGetType(disk));
2509 2510 2511 2512 2513

    virDomainDiskDefFree(disk);

    ret = 0;

2514
 cleanup:
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
    return ret;
}

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

    switch (l_disk->device)  {
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
            ret = libxlDomainChangeEjectableMedia(priv, vm, l_disk);
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (l_disk->bus == VIR_DOMAIN_DISK_BUS_XEN) {
2532
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
2533 2534
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
2535 2536 2537
                    goto cleanup;
                }

2538
                if (!virDomainDiskGetSource(l_disk)) {
2539 2540
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
2541 2542 2543
                    goto cleanup;
                }

2544
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
2545 2546
                    goto cleanup;

J
Jim Fehlig 已提交
2547
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
2548 2549
                    goto cleanup;

J
Jim Fehlig 已提交
2550 2551
                if ((ret = libxl_device_disk_add(priv->ctx, vm->def->id,
                                                &x_disk, NULL)) < 0) {
2552 2553 2554
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
2555 2556 2557 2558 2559 2560
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
2561 2562 2563
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
2564 2565 2566
            }
            break;
        default:
2567 2568 2569
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
2570 2571 2572
            break;
    }

2573
 cleanup:
2574 2575 2576
    return ret;
}

2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
static int
libxlDomainAttachHostPCIDevice(libxlDriverPrivatePtr driver,
                               libxlDomainObjPrivatePtr priv,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    libxl_device_pci pcidev;
    virDomainHostdevDefPtr found;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

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

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

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

    if (virHostdevPreparePCIDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                    vm->def->name, vm->def->uuid,
                                    &hostdev, 1, 0) < 0)
C
Chunyan Liu 已提交
2606
        return -1;
2607

2608
    if (libxlMakePCI(hostdev, &pcidev) < 0)
C
Chunyan Liu 已提交
2609
        goto error;
2610 2611 2612 2613 2614 2615 2616 2617

    if (libxl_device_pci_add(priv->ctx, vm->def->id, &pcidev, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to attach pci device %.4x:%.2x:%.2x.%.1x"),
                       hostdev->source.subsys.u.pci.addr.domain,
                       hostdev->source.subsys.u.pci.addr.bus,
                       hostdev->source.subsys.u.pci.addr.slot,
                       hostdev->source.subsys.u.pci.addr.function);
C
Chunyan Liu 已提交
2618
        goto error;
2619 2620 2621 2622 2623
    }

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

2624
 error:
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
    virHostdevReAttachPCIDevices(hostdev_mgr, LIBXL_DRIVER_NAME,
                                 vm->def->name, &hostdev, 1, NULL);
    return -1;
}

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

    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
        return -1;
    }

    switch (hostdev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
        if (libxlDomainAttachHostPCIDevice(driver, priv, vm, hostdev) < 0)
C
Chunyan Liu 已提交
2648
            return -1;
2649 2650 2651 2652 2653 2654
        break;

    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
C
Chunyan Liu 已提交
2655
        return -1;
2656 2657 2658 2659 2660
    }

    return 0;
}

2661 2662 2663 2664 2665 2666
static int
libxlDomainDetachDeviceDiskLive(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
2667
    int idx;
2668 2669 2670 2671 2672 2673
    int ret = -1;

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

2674 2675 2676
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
2677 2678
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
2679 2680 2681
                    goto cleanup;
                }

2682
                l_disk = vm->def->disks[idx];
2683

J
Jim Fehlig 已提交
2684
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
2685 2686
                    goto cleanup;

J
Jim Fehlig 已提交
2687 2688
                if ((ret = libxl_device_disk_remove(priv->ctx, vm->def->id,
                                                    &x_disk, NULL)) < 0) {
2689 2690 2691
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
2692 2693 2694
                    goto cleanup;
                }

2695
                virDomainDiskRemove(vm->def, idx);
2696 2697 2698
                virDomainDiskDefFree(l_disk);

            } else {
2699 2700 2701
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
2702 2703 2704
            }
            break;
        default:
2705 2706 2707
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
2708 2709 2710
            break;
    }

2711
 cleanup:
2712 2713 2714 2715
    return ret;
}

static int
2716 2717 2718
libxlDomainAttachDeviceLive(libxlDriverPrivatePtr driver,
                            libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm,
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

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

2730 2731 2732 2733 2734 2735
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            ret = libxlDomainAttachHostDevice(driver, priv, vm, dev);
            if (!ret)
                dev->data.hostdev = NULL;
            break;

2736
        default:
2737 2738 2739
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
            break;
    }

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
2750 2751
    virDomainHostdevDefPtr hostdev;
    virDomainHostdevDefPtr found;
2752 2753 2754 2755

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
2756
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
2757 2758
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
2759 2760
                return -1;
            }
2761
            if (virDomainDiskInsert(vmdef, disk))
2762 2763 2764 2765
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            hostdev = dev->data.hostdev;

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

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

            virDomainHostdevInsert(vmdef, hostdev);
            break;
2785 2786

        default:
2787 2788
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
2789 2790 2791 2792 2793 2794
            return -1;
    }
    return 0;
}

static int
2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851
libxlComparePCIDevice(virDomainDefPtr def ATTRIBUTE_UNUSED,
                      virDomainDeviceDefPtr device ATTRIBUTE_UNUSED,
                      virDomainDeviceInfoPtr info1,
                      void *opaque)
{
    virDomainDeviceInfoPtr info2 = opaque;

    if (info1->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI ||
        info2->type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)
        return 0;

    if (info1->addr.pci.domain == info2->addr.pci.domain &&
        info1->addr.pci.bus == info2->addr.pci.bus &&
        info1->addr.pci.slot == info2->addr.pci.slot &&
        info1->addr.pci.function != info2->addr.pci.function)
        return -1;
    return 0;
}

static bool
libxlIsMultiFunctionDevice(virDomainDefPtr def,
                           virDomainDeviceInfoPtr dev)
{
    if (virDomainDeviceInfoIterate(def, libxlComparePCIDevice, dev) < 0)
        return true;
    return false;
}

static int
libxlDomainDetachHostPCIDevice(libxlDriverPrivatePtr driver,
                               libxlDomainObjPrivatePtr priv,
                               virDomainObjPtr vm,
                               virDomainHostdevDefPtr hostdev)
{
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;
    libxl_device_pci pcidev;
    virDomainHostdevDefPtr detach;
    int idx;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

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

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

    if (libxlIsMultiFunctionDevice(vm->def, detach->info)) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("cannot hot unplug multifunction PCI device: %.4x:%.2x:%.2x.%.1x"),
                       subsys->u.pci.addr.domain, subsys->u.pci.addr.bus,
                       subsys->u.pci.addr.slot, subsys->u.pci.addr.function);
C
Chunyan Liu 已提交
2852
        goto error;
2853 2854 2855 2856 2857
    }


    libxl_device_pci_init(&pcidev);

2858
    if (libxlMakePCI(detach, &pcidev) < 0)
C
Chunyan Liu 已提交
2859
        goto error;
2860 2861 2862 2863 2864 2865 2866

    if (libxl_device_pci_remove(priv->ctx, vm->def->id, &pcidev, 0) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to detach pci device\
                          %.4x:%.2x:%.2x.%.1x"),
                       subsys->u.pci.addr.domain, subsys->u.pci.addr.bus,
                       subsys->u.pci.addr.slot, subsys->u.pci.addr.function);
C
Chunyan Liu 已提交
2867
        goto error;
2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
    }

    libxl_device_pci_dispose(&pcidev);

    virDomainHostdevRemove(vm->def, idx);

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

    return 0;

2879
 error:
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916
    virDomainHostdevDefFree(detach);
    return -1;
}

static int
libxlDomainDetachHostDevice(libxlDriverPrivatePtr driver,
                            libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm,
                            virDomainDeviceDefPtr dev)
{
    virDomainHostdevDefPtr hostdev = dev->data.hostdev;
    virDomainHostdevSubsysPtr subsys = &hostdev->source.subsys;

    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev mode '%s' not supported"),
                       virDomainHostdevModeTypeToString(hostdev->mode));
        return -1;
    }

    switch (subsys->type) {
        case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
            return libxlDomainDetachHostPCIDevice(driver, priv, vm, hostdev);

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

    return -1;
}

static int
libxlDomainDetachDeviceLive(libxlDriverPrivatePtr driver,
                            libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm,
2917 2918 2919 2920 2921 2922 2923 2924 2925
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

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

2926 2927 2928 2929
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            ret = libxlDomainDetachHostDevice(driver, priv, vm, dev);
            break;

2930
        default:
2931 2932 2933
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
2934 2935 2936 2937 2938 2939
            break;
    }

    return ret;
}

2940

2941 2942 2943
static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
2944
    virDomainDiskDefPtr disk, detach;
2945 2946 2947 2948 2949
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
2950
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
2951 2952
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
2953 2954
                break;
            }
2955
            virDomainDiskDefFree(detach);
2956 2957 2958
            ret = 0;
            break;
        default:
2959 2960
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceLive(libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
            switch (disk->device) {
                case VIR_DOMAIN_DISK_DEVICE_CDROM:
                    ret = libxlDomainChangeEjectableMedia(priv, vm, disk);
                    if (ret == 0)
                        dev->data.disk = NULL;
                    break;
                default:
2984 2985 2986
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
2987 2988 2989 2990
                    break;
            }
            break;
        default:
2991 2992 2993
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr orig;
    virDomainDiskDefPtr disk;
3005
    int idx;
3006 3007 3008 3009 3010
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3011
            if ((idx = virDomainDiskIndexByName(vmdef, disk->dst, false)) < 0) {
3012 3013
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3014 3015
                goto cleanup;
            }
3016
            orig = vmdef->disks[idx];
3017
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3018 3019
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3020 3021 3022
                goto cleanup;
            }

3023 3024 3025 3026 3027 3028
            if (virDomainDiskSetSource(orig, virDomainDiskGetSource(disk)) < 0)
                goto cleanup;
            virDomainDiskSetType(orig, virDomainDiskGetType(disk));
            virDomainDiskSetFormat(orig, virDomainDiskGetFormat(disk));
            if (virDomainDiskSetDriver(orig, virDomainDiskGetDriver(disk)) < 0)
                goto cleanup;
3029 3030
            break;
        default:
3031 3032
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3033 3034 3035 3036 3037
            goto cleanup;
    }

    ret = 0;

3038
 cleanup:
3039 3040 3041 3042 3043
    return ret;
}


static int
3044 3045
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3046 3047
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3048
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3049 3050 3051 3052 3053 3054 3055 3056 3057
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    libxlDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3058
    if (!(vm = libxlDomObjFromDomain(dom)))
3059 3060
        goto cleanup;

3061 3062 3063
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3067 3068 3069 3070 3071 3072 3073 3074
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
3075 3076
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3077
            goto endjob;
3078 3079 3080 3081
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
3082 3083
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3084
         goto endjob;
3085 3086 3087 3088 3089
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3090
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3091
                                            cfg->caps, driver->xmlopt,
3092
                                            VIR_DOMAIN_XML_INACTIVE)))
3093
            goto endjob;
3094 3095

        /* Make a copy for updated domain. */
3096
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3097
                                                    driver->xmlopt)))
3098
            goto endjob;
3099

3100
        if ((ret = libxlDomainAttachDeviceConfig(vmdef, dev)) < 0)
3101
            goto endjob;
3102
    } else {
3103
        ret = 0;
3104
    }
3105 3106 3107 3108

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

3114
        if ((ret = libxlDomainAttachDeviceLive(driver, priv, vm, dev)) < 0)
3115
            goto endjob;
3116

3117 3118 3119 3120
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3121
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3122 3123 3124 3125 3126
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3127
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3128
        if (!ret) {
3129
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3130 3131 3132 3133
            vmdef = NULL;
        }
    }

3134
 endjob:
3135 3136 3137
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3138
 cleanup:
3139 3140 3141
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3142
        virObjectUnlock(vm);
3143
    virObjectUnref(cfg);
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157
    return ret;
}

static int
libxlDomainAttachDevice(virDomainPtr dom, const char *xml)
{
    return libxlDomainAttachDeviceFlags(dom, xml,
                                        VIR_DOMAIN_DEVICE_MODIFY_LIVE);
}

static int
libxlDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
{
3158
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3159
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3160 3161 3162 3163 3164 3165 3166 3167 3168
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    libxlDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3169
    if (!(vm = libxlDomObjFromDomain(dom)))
3170 3171
        goto cleanup;

3172 3173 3174
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3178 3179 3180 3181 3182 3183 3184 3185 3186 3187
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3188
            goto endjob;
3189 3190 3191 3192 3193 3194
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3195
         goto endjob;
3196 3197 3198 3199 3200 3201
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3202
                                            cfg->caps, driver->xmlopt,
3203
                                            VIR_DOMAIN_XML_INACTIVE)))
3204
            goto endjob;
3205 3206

        /* Make a copy for updated domain. */
3207
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3208
                                                    driver->xmlopt)))
3209
            goto endjob;
3210 3211

        if ((ret = libxlDomainDetachDeviceConfig(vmdef, dev)) < 0)
3212
            goto endjob;
3213 3214 3215 3216 3217 3218 3219 3220
    } else {
        ret = 0;
    }

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

3225
        if ((ret = libxlDomainDetachDeviceLive(driver, priv, vm, dev)) < 0)
3226
            goto endjob;
3227 3228 3229 3230 3231

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3232
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3233 3234 3235 3236 3237
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3238
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3239 3240 3241 3242 3243 3244
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3245
 endjob:
3246 3247 3248
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3249
 cleanup:
3250 3251 3252 3253
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3254
    virObjectUnref(cfg);
3255
    return ret;
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268
}

static int
libxlDomainDetachDevice(virDomainPtr dom, const char *xml)
{
    return libxlDomainDetachDeviceFlags(dom, xml,
                                        VIR_DOMAIN_DEVICE_MODIFY_LIVE);
}

static int
libxlDomainUpdateDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
{
3269
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3270
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3271 3272 3273 3274 3275 3276 3277 3278 3279
    virDomainObjPtr vm = NULL;
    virDomainDefPtr vmdef = NULL;
    virDomainDeviceDefPtr dev = NULL;
    libxlDomainObjPrivatePtr priv;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

J
Jim Fehlig 已提交
3280
    if (!(vm = libxlDomObjFromDomain(dom)))
3281 3282
        goto cleanup;

3283 3284 3285
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309
    if (virDomainObjIsActive(vm)) {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_LIVE;
    } else {
        if (flags == VIR_DOMAIN_DEVICE_MODIFY_CURRENT)
            flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
        /* check consistency between flags and the vm state */
        if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
            goto cleanup;
        }
    }

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

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3310
                                            cfg->caps, driver->xmlopt,
3311 3312 3313 3314
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3315
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
                                                    driver->xmlopt)))
            goto cleanup;

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

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_LIVE) {
        /* If dev exists it was created to modify the domain config. Free it. */
        virDomainDeviceDefFree(dev);
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3329
                                            cfg->caps, driver->xmlopt,
3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

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

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3340
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3341 3342 3343 3344 3345
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3346
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3347 3348 3349 3350 3351 3352
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3353
 cleanup:
3354 3355 3356 3357
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3358
    virObjectUnref(cfg);
3359
    return ret;
3360 3361
}

3362 3363 3364 3365 3366
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
3367 3368
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
3369

3370
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
3371
        goto cleanup;
3372

3373
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
3374 3375
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3376
        goto cleanup;
3377 3378
    }

3379 3380
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

3381
 cleanup:
3382 3383
    virObjectUnref(cfg);
    return ret;
3384 3385
}

3386 3387 3388 3389 3390 3391 3392 3393 3394 3395
static int
libxlNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;
    int ret = -1, nr_nodes = 0;
    libxl_numainfo *numa_info = NULL;
    libxlDriverPrivatePtr driver = conn->privateData;
3396
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3397 3398

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
3399
        goto cleanup;
3400

3401
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
3402
    if (numa_info == NULL || nr_nodes == 0) {
3403 3404 3405
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
3406 3407 3408
    }

    /* Check/sanitize the cell range */
3409
    if (startCell >= nr_nodes) {
3410 3411
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
3412
                       startCell, nr_nodes - 1);
3413 3414 3415
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
3416 3417
    if (lastCell >= nr_nodes)
        lastCell = nr_nodes - 1;
3418 3419 3420 3421 3422 3423 3424

    for (numCells = 0, n = startCell; n <= lastCell; n++) {
        if (numa_info[n].size == LIBXL_NUMAINFO_INVALID_ENTRY)
            freeMems[numCells++] = 0;
        else
            freeMems[numCells++] = numa_info[n].free;
    }
3425

3426 3427
    ret = numCells;

3428
 cleanup:
3429
    libxl_numainfo_list_free(numa_info, nr_nodes);
3430
    virObjectUnref(cfg);
3431 3432 3433
    return ret;
}

3434
static int
3435
libxlConnectDomainEventRegister(virConnectPtr conn,
3436 3437
                                virConnectDomainEventCallback callback,
                                void *opaque,
3438
                                virFreeCallback freecb)
3439 3440 3441
{
    libxlDriverPrivatePtr driver = conn->privateData;

3442 3443 3444
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

3445 3446 3447 3448
    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        return -1;
3449

3450
    return 0;
3451 3452 3453 3454
}


static int
3455 3456
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
3457 3458 3459
{
    libxlDriverPrivatePtr driver = conn->privateData;

3460 3461 3462
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

3463 3464 3465 3466
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
3467

3468
    return 0;
3469 3470
}

3471 3472 3473 3474 3475 3476
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
3477
    if (!(vm = libxlDomObjFromDomain(dom)))
3478 3479
        goto cleanup;

3480 3481 3482
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3483 3484 3485
    *autostart = vm->autostart;
    ret = 0;

3486
 cleanup:
3487
    if (vm)
3488
        virObjectUnlock(vm);
3489 3490 3491 3492 3493 3494 3495
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3496
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3497 3498 3499 3500
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
3501
    if (!(vm = libxlDomObjFromDomain(dom)))
3502 3503
        goto cleanup;

3504 3505 3506
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

3510
    if (!vm->persistent) {
3511 3512
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
3513
        goto endjob;
3514 3515 3516 3517 3518
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
3519
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
3520
            goto endjob;
3521
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
3522
            goto endjob;
3523 3524

        if (autostart) {
3525
            if (virFileMakePath(cfg->autostartDir) < 0) {
3526
                virReportSystemError(errno,
3527
                                     _("cannot create autostart directory %s"),
3528
                                     cfg->autostartDir);
3529
                goto endjob;
3530 3531 3532 3533 3534 3535
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
3536
                goto endjob;
3537 3538 3539 3540 3541 3542
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
3543
                goto endjob;
3544 3545 3546 3547 3548 3549 3550
            }
        }

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

3551
 endjob:
3552 3553 3554
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3555
 cleanup:
3556 3557 3558
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    if (vm)
3559
        virObjectUnlock(vm);
3560
    virObjectUnref(cfg);
3561 3562 3563
    return ret;
}

3564 3565 3566 3567 3568 3569
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    char * ret = NULL;
3570
    const char *name = NULL;
J
Jim Fehlig 已提交
3571
    libxl_scheduler sched_id;
3572

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

3576 3577 3578
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3579
    if (!virDomainObjIsActive(vm)) {
3580
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3581 3582 3583 3584
        goto cleanup;
    }

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

3587 3588
    if (nparams)
        *nparams = 0;
3589
    switch (sched_id) {
J
Jim Fehlig 已提交
3590
    case LIBXL_SCHEDULER_SEDF:
3591
        name = "sedf";
3592
        break;
J
Jim Fehlig 已提交
3593
    case LIBXL_SCHEDULER_CREDIT:
3594
        name = "credit";
3595 3596
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
3597
        break;
J
Jim Fehlig 已提交
3598
    case LIBXL_SCHEDULER_CREDIT2:
3599
        name = "credit2";
3600
        break;
J
Jim Fehlig 已提交
3601
    case LIBXL_SCHEDULER_ARINC653:
3602
        name = "arinc653";
3603 3604
        break;
    default:
J
Jim Fehlig 已提交
3605 3606
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
3607
                     " with libxenlight"), vm->def->id);
3608 3609 3610
        goto cleanup;
    }

3611
    ignore_value(VIR_STRDUP(ret, name));
3612

3613
 cleanup:
3614
    if (vm)
3615
        virObjectUnlock(vm);
3616 3617 3618
    return ret;
}

3619
static int
3620 3621 3622 3623
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
3624 3625 3626
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3627 3628
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
3629 3630
    int ret = -1;

3631 3632 3633 3634
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

J
Jim Fehlig 已提交
3636
    if (!(vm = libxlDomObjFromDomain(dom)))
3637 3638
        goto cleanup;

3639 3640 3641
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3642
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
3643 3644
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
3645 3646 3647 3648 3649
        goto cleanup;
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
3652
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3653 3654
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3655 3656 3657
        goto cleanup;
    }

3658
    if (libxl_domain_sched_params_get(priv->ctx, vm->def->id, &sc_info) != 0) {
3659 3660
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
3661
                         " with libxenlight"), vm->def->id);
3662 3663 3664
        goto cleanup;
    }

3665 3666
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
3667 3668
        goto cleanup;

3669
    if (*nparams > 1) {
3670 3671
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
3672
            goto cleanup;
3673 3674
    }

3675 3676
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
3677 3678
    ret = 0;

3679
 cleanup:
3680
    if (vm)
3681
        virObjectUnlock(vm);
3682 3683 3684 3685
    return ret;
}

static int
3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696
libxlDomainGetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int *nparams)
{
    return libxlDomainGetSchedulerParametersFlags(dom, params, nparams, 0);
}

static int
libxlDomainSetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int nparams,
                                       unsigned int flags)
3697
{
3698
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3699 3700
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3701
    libxl_domain_sched_params sc_info;
3702
    int sched_id;
3703
    size_t i;
3704 3705
    int ret = -1;

3706
    virCheckFlags(0, -1);
3707 3708 3709 3710 3711 3712
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
3713
        return -1;
3714

J
Jim Fehlig 已提交
3715
    if (!(vm = libxlDomObjFromDomain(dom)))
3716 3717
        goto cleanup;

3718 3719 3720
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3724
    if (!virDomainObjIsActive(vm)) {
3725
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3726
        goto endjob;
3727 3728 3729 3730
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
3733
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3734 3735
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3736
        goto endjob;
3737 3738
    }

3739
    if (libxl_domain_sched_params_get(priv->ctx, vm->def->id, &sc_info) != 0) {
3740 3741
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
3742
                         " with libxenlight"), vm->def->id);
3743
        goto endjob;
3744 3745 3746
    }

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

3749
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
3750
            sc_info.weight = params[i].value.ui;
3751
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
3752 3753 3754
            sc_info.cap = params[i].value.ui;
    }

3755
    if (libxl_domain_sched_params_set(priv->ctx, vm->def->id, &sc_info) != 0) {
3756 3757
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
3758
                         " with libxenlight"), vm->def->id);
3759
        goto endjob;
3760 3761 3762 3763
    }

    ret = 0;

3764
 endjob:
3765 3766 3767
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3768
 cleanup:
3769
    if (vm)
3770
        virObjectUnlock(vm);
3771 3772 3773
    return ret;
}

B
Bamvor Jian Zhang 已提交
3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795

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

    virCheckFlags(VIR_DOMAIN_CONSOLE_FORCE, -1);

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

J
Jim Fehlig 已提交
3796
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845
        goto cleanup;

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

3846
 cleanup:
B
Bamvor Jian Zhang 已提交
3847 3848 3849 3850 3851 3852
    VIR_FREE(console);
    if (vm)
        virObjectUnlock(vm);
    return ret;
}

3853 3854 3855 3856 3857 3858 3859
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889
/* NUMA node affinity information is available through libxl
 * starting from Xen 4.3. */
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY

/* Number of Xen NUMA parameters */
# define LIBXL_NUMA_NPARAM 2

static int
libxlDomainGetNumaParameters(virDomainPtr dom,
                             virTypedParameterPtr params,
                             int *nparams,
                             unsigned int flags)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    libxl_bitmap nodemap;
    virBitmapPtr nodes = NULL;
    char *nodeset = NULL;
    int rc, ret = -1;
    size_t i, j;

    /* In Xen 4.3, it is possible to query the NUMA node affinity of a domain
     * via libxl, but not to change it. We therefore only allow AFFECT_LIVE. */
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_TYPED_PARAM_STRING_OKAY, -1);

    /* We blindly return a string, and let libvirt.c and remote_driver.c do
     * the filtering on behalf of older clients that can't parse it. */
    flags &= ~VIR_TYPED_PARAM_STRING_OKAY;

3890 3891
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
3892
    if (!(vm = libxlDomObjFromDomain(dom)))
3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
        goto cleanup;

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

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

    priv = vm->privateData;

    if ((*nparams) == 0) {
        *nparams = LIBXL_NUMA_NPARAM;
        ret = 0;
        goto cleanup;
    }

    for (i = 0; i < LIBXL_NUMA_NPARAM && i < *nparams; i++) {
        virMemoryParameterPtr param = &params[i];
3914
        int numnodes;
3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932

        switch (i) {
        case 0:
            /* NUMA mode */

            /* Xen implements something that is really close to numactl's
             * 'interleave' policy (see `man 8 numactl' for details). */
            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_MODE,
                                        VIR_TYPED_PARAM_INT,
                                        VIR_DOMAIN_NUMATUNE_MEM_INTERLEAVE) < 0)
                goto cleanup;

            break;

        case 1:
            /* Node affinity */

            /* Let's allocate both libxl and libvirt bitmaps */
3933 3934 3935 3936
            numnodes = libxl_get_max_nodes(priv->ctx);
            if (numnodes <= 0)
                goto cleanup;

3937
            if (libxl_node_bitmap_alloc(priv->ctx, &nodemap, 0) ||
3938
                !(nodes = virBitmapNew(numnodes))) {
3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980
                virReportOOMError();
                goto cleanup;
            }

            rc = libxl_domain_get_nodeaffinity(priv->ctx,
                                               vm->def->id,
                                               &nodemap);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get numa affinity"));
                goto cleanup;
            }

            /* First, we convert libxl_bitmap into virBitmap. After that,
             * we format virBitmap as a string that can be returned. */
            virBitmapClearAll(nodes);
            libxl_for_each_set_bit(j, nodemap) {
                if (virBitmapSetBit(nodes, j)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Node %zu out of range"), j);
                    goto cleanup;
                }
            }

            nodeset = virBitmapFormat(nodes);
            if (!nodeset && VIR_STRDUP(nodeset, "") < 0)
                goto cleanup;

            if (virTypedParameterAssign(param, VIR_DOMAIN_NUMA_NODESET,
                                        VIR_TYPED_PARAM_STRING, nodeset) < 0)
                goto cleanup;

            nodeset = NULL;

            break;
        }
    }

    if (*nparams > LIBXL_NUMA_NPARAM)
        *nparams = LIBXL_NUMA_NPARAM;
    ret = 0;

3981
 cleanup:
3982 3983 3984 3985 3986 3987 3988 3989 3990
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
    if (vm)
        virObjectUnlock(vm);
    return ret;
}
#endif

J
Jim Fehlig 已提交
3991 3992 3993 3994 3995 3996
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
3997
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
3998
        goto cleanup;
3999 4000 4001 4002

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

J
Jim Fehlig 已提交
4003 4004
    ret = virDomainObjIsActive(obj);

4005
 cleanup:
J
Jim Fehlig 已提交
4006
    if (obj)
4007
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4008 4009 4010 4011 4012 4013 4014 4015 4016
    return ret;
}

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

J
Jim Fehlig 已提交
4017
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4018
        goto cleanup;
4019 4020 4021 4022

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

J
Jim Fehlig 已提交
4023 4024
    ret = obj->persistent;

4025
 cleanup:
J
Jim Fehlig 已提交
4026
    if (obj)
4027
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4028 4029 4030
    return ret;
}

4031 4032 4033 4034 4035 4036
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4037
    if (!(vm = libxlDomObjFromDomain(dom)))
4038
        goto cleanup;
4039 4040 4041 4042

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

4043 4044
    ret = vm->updated;

4045
 cleanup:
4046
    if (vm)
4047
        virObjectUnlock(vm);
4048 4049 4050
    return ret;
}

4051
static int
4052 4053 4054
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4055 4056 4057 4058
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4059 4060 4061
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4062 4063 4064 4065
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4066
        ret = -1;
4067 4068 4069 4070 4071 4072

    return ret;
}


static int
4073
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4074 4075 4076
{
    libxlDriverPrivatePtr driver = conn->privateData;

4077 4078 4079
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4080 4081 4082 4083
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        return -1;
4084

4085
    return 0;
4086 4087
}

J
Jim Fehlig 已提交
4088

4089
static int
4090
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4091 4092 4093 4094
{
    return 1;
}

4095
static int
4096 4097 4098
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4099 4100 4101 4102
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4103
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4104

4105 4106 4107
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4108 4109
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
4110 4111 4112 4113

    return ret;
}

4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
/* Which features are supported by this driver? */
static int
libxlConnectSupportsFeature(virConnectPtr conn, int feature)
{
    if (virConnectSupportsFeatureEnsureACL(conn) < 0)
        return -1;

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

4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153
static int
libxlNodeDeviceGetPCIInfo(virNodeDeviceDefPtr def,
                          unsigned *domain,
                          unsigned *bus,
                          unsigned *slot,
                          unsigned *function)
{
    virNodeDevCapsDefPtr cap;

    cap = def->caps;
    while (cap) {
        if (cap->type == VIR_NODE_DEV_CAP_PCI_DEV) {
            *domain   = cap->data.pci_dev.domain;
            *bus      = cap->data.pci_dev.bus;
            *slot     = cap->data.pci_dev.slot;
            *function = cap->data.pci_dev.function;
            break;
        }

        cap = cap->next;
    }

    if (!cap) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("device %s is not a PCI device"), def->name);
C
Chunyan Liu 已提交
4154
        return -1;
4155 4156
    }

C
Chunyan Liu 已提交
4157
    return 0;
4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205
}

static int
libxlNodeDeviceDetachFlags(virNodeDevicePtr dev,
                           const char *driverName,
                           unsigned int flags)
{
    virPCIDevicePtr pci = NULL;
    unsigned domain = 0, bus = 0, slot = 0, function = 0;
    int ret = -1;
    virNodeDeviceDefPtr def = NULL;
    char *xml = NULL;
    libxlDriverPrivatePtr driver = dev->conn->privateData;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

    virCheckFlags(0, -1);

    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto cleanup;

    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
    if (!def)
        goto cleanup;

    if (virNodeDeviceDetachFlagsEnsureACL(dev->conn, def) < 0)
        goto cleanup;

    if (libxlNodeDeviceGetPCIInfo(def, &domain, &bus, &slot, &function) < 0)
        goto cleanup;

    pci = virPCIDeviceNew(domain, bus, slot, function);
    if (!pci)
        goto cleanup;

    if (!driverName || STREQ(driverName, "xen")) {
        if (virPCIDeviceSetStubDriver(pci, "pciback") < 0)
            goto cleanup;
    } else {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported driver name '%s'"), driverName);
        goto cleanup;
    }

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

    ret = 0;
4206
 cleanup:
4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248
    virPCIDeviceFree(pci);
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceDettach(virNodeDevicePtr dev)
{
    return libxlNodeDeviceDetachFlags(dev, NULL, 0);
}

static int
libxlNodeDeviceReAttach(virNodeDevicePtr dev)
{
    virPCIDevicePtr pci = NULL;
    unsigned domain = 0, bus = 0, slot = 0, function = 0;
    int ret = -1;
    virNodeDeviceDefPtr def = NULL;
    char *xml = NULL;
    libxlDriverPrivatePtr driver = dev->conn->privateData;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto cleanup;

    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
    if (!def)
        goto cleanup;

    if (virNodeDeviceReAttachEnsureACL(dev->conn, def) < 0)
        goto cleanup;

    if (libxlNodeDeviceGetPCIInfo(def, &domain, &bus, &slot, &function) < 0)
        goto cleanup;

    pci = virPCIDeviceNew(domain, bus, slot, function);
    if (!pci)
        goto cleanup;

    if (virHostdevPCINodeDeviceReAttach(hostdev_mgr, pci) < 0)
C
Chunyan Liu 已提交
4249
        goto cleanup;
4250 4251

    ret = 0;
C
Chunyan Liu 已提交
4252

4253
 cleanup:
C
Chunyan Liu 已提交
4254
    virPCIDeviceFree(pci);
4255 4256 4257 4258 4259 4260 4261 4262
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
C
Chunyan Liu 已提交
4263
    virPCIDevicePtr pci = NULL;
4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289
    unsigned domain = 0, bus = 0, slot = 0, function = 0;
    int ret = -1;
    virNodeDeviceDefPtr def = NULL;
    char *xml = NULL;
    libxlDriverPrivatePtr driver = dev->conn->privateData;
    virHostdevManagerPtr hostdev_mgr = driver->hostdevMgr;

    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto cleanup;

    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
    if (!def)
        goto cleanup;

    if (virNodeDeviceResetEnsureACL(dev->conn, def) < 0)
        goto cleanup;

    if (libxlNodeDeviceGetPCIInfo(def, &domain, &bus, &slot, &function) < 0)
        goto cleanup;

    pci = virPCIDeviceNew(domain, bus, slot, function);
    if (!pci)
        goto cleanup;

    if (virHostdevPCINodeDeviceReset(hostdev_mgr, pci) < 0)
C
Chunyan Liu 已提交
4290
        goto cleanup;
4291 4292

    ret = 0;
C
Chunyan Liu 已提交
4293

4294
 cleanup:
C
Chunyan Liu 已提交
4295
    virPCIDeviceFree(pci);
4296 4297 4298 4299 4300
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

4301

J
Jim Fehlig 已提交
4302
static virDriver libxlDriver = {
4303
    .no = VIR_DRV_LIBXL,
4304
    .name = LIBXL_DRIVER_NAME,
4305 4306 4307 4308
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
4309
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
4310
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
4311
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
4312
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
4313 4314 4315 4316
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
4317 4318 4319 4320 4321 4322 4323
    .domainCreateXML = libxlDomainCreateXML, /* 0.9.0 */
    .domainLookupByID = libxlDomainLookupByID, /* 0.9.0 */
    .domainLookupByUUID = libxlDomainLookupByUUID, /* 0.9.0 */
    .domainLookupByName = libxlDomainLookupByName, /* 0.9.0 */
    .domainSuspend = libxlDomainSuspend, /* 0.9.0 */
    .domainResume = libxlDomainResume, /* 0.9.0 */
    .domainShutdown = libxlDomainShutdown, /* 0.9.0 */
4324
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
4325 4326
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
4327
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
4328 4329
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
4330
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
4331 4332 4333 4334
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
4335
    .domainSave = libxlDomainSave, /* 0.9.2 */
4336
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
4337
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
4338
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
4339
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
4340 4341 4342 4343
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
4344
    .domainPinVcpuFlags = libxlDomainPinVcpuFlags, /* 1.2.1 */
4345
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
4346
    .domainGetVcpuPinInfo = libxlDomainGetVcpuPinInfo, /* 1.2.1 */
4347
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
4348 4349 4350 4351
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
4352 4353 4354 4355
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
4356
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
4357 4358 4359 4360 4361
    .domainAttachDevice = libxlDomainAttachDevice, /* 0.9.2 */
    .domainAttachDeviceFlags = libxlDomainAttachDeviceFlags, /* 0.9.2 */
    .domainDetachDevice = libxlDomainDetachDevice,    /* 0.9.2 */
    .domainDetachDeviceFlags = libxlDomainDetachDeviceFlags, /* 0.9.2 */
    .domainUpdateDeviceFlags = libxlDomainUpdateDeviceFlags, /* 0.9.2 */
4362 4363 4364 4365
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
4366
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
4367
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
4368
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
4369 4370 4371
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
4372
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
4373
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
4374 4375
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
4376 4377 4378
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
4379
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
4380 4381 4382
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
4383 4384 4385
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
4386
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
4387 4388 4389 4390
    .nodeDeviceDettach = libxlNodeDeviceDettach, /* 1.2.3 */
    .nodeDeviceDetachFlags = libxlNodeDeviceDetachFlags, /* 1.2.3 */
    .nodeDeviceReAttach = libxlNodeDeviceReAttach, /* 1.2.3 */
    .nodeDeviceReset = libxlNodeDeviceReset, /* 1.2.3 */
J
Jim Fehlig 已提交
4391 4392 4393 4394
};

static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
4395
    .stateInitialize = libxlStateInitialize,
4396
    .stateAutoStart = libxlStateAutoStart,
4397 4398
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411
};


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

    return 0;
}