libxl_driver.c 128.8 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 226
    bool ret = false;
    int status;
227
    char *output = NULL;
J
Jim Fehlig 已提交
228

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

235 236 237
    if (!virFileExists(HYPERVISOR_CAPABILITIES)) {
        VIR_INFO("Disabling driver as " HYPERVISOR_CAPABILITIES
                 " does not exist");
238
        return ret;
239
    }
240 241 242 243 244
    /*
     * 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.
     */
245
    status = virFileReadAll(HYPERVISOR_CAPABILITIES, 10, &output);
246 247 248 249 250
    if (status >= 0) {
        status = strncmp(output, "control_d", 9);
    }
    VIR_FREE(output);
    if (status) {
251 252 253 254 255 256 257
        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 */
258 259 260 261 262 263 264 265 266 267 268
    if (virFileExists("/usr/sbin/xend")) {
        virCommandPtr cmd;

        cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL);
        if (virCommandRun(cmd, NULL) == 0) {
            VIR_INFO("Legacy xen tool stack seems to be in use, disabling "
                     "libxenlight driver.");
        } else {
            ret = true;
        }
        virCommandFree(cmd);
269 270
    } else {
        ret = true;
J
Jim Fehlig 已提交
271 272
    }

273 274 275 276 277 278 279 280
    return ret;
}

static int
libxlStateInitialize(bool privileged,
                     virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                     void *opaque ATTRIBUTE_UNUSED)
{
281
    libxlDriverConfigPtr cfg;
282 283 284 285 286
    char ebuf[1024];

    if (!libxlDriverShouldLoad(privileged))
        return 0;

J
Jim Fehlig 已提交
287 288 289 290
    if (VIR_ALLOC(libxl_driver) < 0)
        return -1;

    if (virMutexInit(&libxl_driver->lock) < 0) {
291 292
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
J
Jim Fehlig 已提交
293 294 295 296 297
        VIR_FREE(libxl_driver);
        return -1;
    }

    /* Allocate bitmap for vnc port reservation */
298
    if (!(libxl_driver->reservedVNCPorts =
J
Ján Tomko 已提交
299 300
          virPortAllocatorNew(_("VNC"),
                              LIBXL_VNC_PORT_MIN,
301 302
                              LIBXL_VNC_PORT_MAX)))
        goto error;
J
Jim Fehlig 已提交
303

304 305
    if (!(libxl_driver->domains = virDomainObjListNew()))
        goto error;
J
Jim Fehlig 已提交
306

307 308 309
    if (!(libxl_driver->hostdevMgr = virHostdevManagerGetDefault()))
        goto error;

310
    if (!(cfg = libxlDriverConfigNew()))
311
        goto error;
J
Jim Fehlig 已提交
312

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

343
    /* read the host sysinfo */
344
    libxl_driver->hostsysinfo = virSysinfoRead();
345

346
    libxl_driver->domainEventState = virObjectEventStateNew();
E
Eric Blake 已提交
347
    if (!libxl_driver->domainEventState)
348 349
        goto error;

350
    if ((cfg->caps = libxlMakeCapabilities(cfg->ctx)) == NULL) {
351 352
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot create capabilities for libxenlight"));
J
Jim Fehlig 已提交
353 354 355
        goto error;
    }

356
    if (!(libxl_driver->xmlopt = virDomainXMLOptionNew(&libxlDomainDefParserConfig,
357 358
                                                       &libxlDomainXMLPrivateDataCallbacks,
                                                       NULL)))
359
        goto error;
J
Jim Fehlig 已提交
360 361

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

    libxlReconnectDomains(libxl_driver);

    /* Then inactive persistent configs */
375
    if (virDomainObjListLoadAllConfigs(libxl_driver->domains,
376 377
                                       cfg->configDir,
                                       cfg->autostartDir,
378
                                       0,
379
                                       cfg->caps,
380 381
                                       libxl_driver->xmlopt,
                                       1 << VIR_DOMAIN_VIRT_XEN,
382
                                       NULL, NULL) < 0)
J
Jim Fehlig 已提交
383 384
        goto error;

385 386
    virDomainObjListForEach(libxl_driver->domains, libxlDomainManagedSaveLoad,
                            libxl_driver);
387

J
Jim Fehlig 已提交
388 389
    return 0;

390
 error:
391
    libxlStateCleanup();
392
    return -1;
J
Jim Fehlig 已提交
393 394
}

395 396 397 398 399 400 401 402 403 404
static void
libxlStateAutoStart(void)
{
    if (!libxl_driver)
        return;

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

J
Jim Fehlig 已提交
405
static int
406
libxlStateReload(void)
J
Jim Fehlig 已提交
407
{
408 409
    libxlDriverConfigPtr cfg;

J
Jim Fehlig 已提交
410 411 412
    if (!libxl_driver)
        return 0;

413 414
    cfg = libxlDriverConfigGet(libxl_driver);

415
    virDomainObjListLoadAllConfigs(libxl_driver->domains,
416 417
                                   cfg->configDir,
                                   cfg->autostartDir,
418
                                   1,
419
                                   cfg->caps,
420 421
                                   libxl_driver->xmlopt,
                                   1 << VIR_DOMAIN_VIRT_XEN,
422 423
                                   NULL, libxl_driver);

424 425
    virDomainObjListForEach(libxl_driver->domains, libxlAutostartDomain,
                            libxl_driver);
426

427
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
428 429 430 431 432
    return 0;
}


static virDrvOpenStatus
433 434 435
libxlConnectOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 unsigned int flags)
J
Jim Fehlig 已提交
436
{
E
Eric Blake 已提交
437 438
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

J
Jim Fehlig 已提交
439 440 441 442
    if (conn->uri == NULL) {
        if (libxl_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

443
        if (!(conn->uri = virURIParse("xen:///")))
J
Jim Fehlig 已提交
444 445 446 447 448 449 450 451 452 453 454 455
            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) {
456 457
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("libxenlight state driver is not active"));
J
Jim Fehlig 已提交
458 459 460 461 462 463 464 465
            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")) {
466 467 468
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected Xen URI path '%s', try xen:///"),
                           NULLSTR(conn->uri->path));
J
Jim Fehlig 已提交
469 470 471 472
            return VIR_DRV_OPEN_ERROR;
        }
    }

473 474 475
    if (virConnectOpenEnsureACL(conn) < 0)
        return VIR_DRV_OPEN_ERROR;

J
Jim Fehlig 已提交
476 477 478 479 480 481
    conn->privateData = libxl_driver;

    return VIR_DRV_OPEN_SUCCESS;
};

static int
482
libxlConnectClose(virConnectPtr conn ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
483 484 485 486 487 488
{
    conn->privateData = NULL;
    return 0;
}

static const char *
489
libxlConnectGetType(virConnectPtr conn)
J
Jim Fehlig 已提交
490
{
491 492 493
    if (virConnectGetTypeEnsureACL(conn) < 0)
        return NULL;

J
Jim Fehlig 已提交
494
    return "Xen";
J
Jim Fehlig 已提交
495 496 497
}

static int
498
libxlConnectGetVersion(virConnectPtr conn, unsigned long *version)
J
Jim Fehlig 已提交
499 500
{
    libxlDriverPrivatePtr driver = conn->privateData;
501
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
502

503 504 505
    if (virConnectGetVersionEnsureACL(conn) < 0)
        return 0;

506 507 508
    cfg = libxlDriverConfigGet(driver);
    *version = cfg->version;
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
509 510 511
    return 0;
}

512

513
static char *libxlConnectGetHostname(virConnectPtr conn)
514
{
515 516 517
    if (virConnectGetHostnameEnsureACL(conn) < 0)
        return NULL;

518 519 520
    return virGetHostname();
}

521 522 523 524 525 526 527 528
static char *
libxlConnectGetSysinfo(virConnectPtr conn, unsigned int flags)
{
    libxlDriverPrivatePtr driver = conn->privateData;
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    virCheckFlags(0, NULL);

529 530 531
    if (virConnectGetSysinfoEnsureACL(conn) < 0)
        return NULL;

532 533 534 535 536 537 538 539 540 541 542 543 544 545
    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);
}
546

J
Jim Fehlig 已提交
547
static int
548
libxlConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
J
Jim Fehlig 已提交
549 550 551
{
    int ret;
    libxlDriverPrivatePtr driver = conn->privateData;
552
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
553

554 555 556
    if (virConnectGetMaxVcpusEnsureACL(conn) < 0)
        return -1;

557 558
    cfg = libxlDriverConfigGet(driver);
    ret = libxl_get_max_cpus(cfg->ctx);
559 560 561 562 563
    /* 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)
564
        ret = -1;
J
Jim Fehlig 已提交
565

566
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
567 568 569 570 571 572
    return ret;
}

static int
libxlNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
{
573 574 575
    if (virNodeGetInfoEnsureACL(conn) < 0)
        return -1;

576
    return libxlDriverNodeGetInfo(conn->privateData, info);
J
Jim Fehlig 已提交
577 578 579
}

static char *
580
libxlConnectGetCapabilities(virConnectPtr conn)
J
Jim Fehlig 已提交
581 582 583
{
    libxlDriverPrivatePtr driver = conn->privateData;
    char *xml;
584
    libxlDriverConfigPtr cfg;
J
Jim Fehlig 已提交
585

586 587 588
    if (virConnectGetCapabilitiesEnsureACL(conn) < 0)
        return NULL;

589 590
    cfg = libxlDriverConfigGet(driver);
    if ((xml = virCapabilitiesFormatXML(cfg->caps)) == NULL)
J
Jim Fehlig 已提交
591 592
        virReportOOMError();

593
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
594 595 596 597
    return xml;
}

static int
598
libxlConnectListDomains(virConnectPtr conn, int *ids, int nids)
J
Jim Fehlig 已提交
599 600 601 602
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

603 604 605
    if (virConnectListDomainsEnsureACL(conn) < 0)
        return -1;

606 607
    n = virDomainObjListGetActiveIDs(driver->domains, ids, nids,
                                     virConnectListDomainsCheckACL, conn);
J
Jim Fehlig 已提交
608 609 610 611 612

    return n;
}

static int
613
libxlConnectNumOfDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
614 615 616 617
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

618 619 620
    if (virConnectNumOfDomainsEnsureACL(conn) < 0)
        return -1;

621 622
    n = virDomainObjListNumOfDomains(driver->domains, true,
                                     virConnectNumOfDomainsCheckACL, conn);
J
Jim Fehlig 已提交
623 624 625 626 627 628 629 630 631 632 633 634

    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;
635
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
636 637 638

    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);

639
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
640
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
641 642 643
                                        VIR_DOMAIN_XML_INACTIVE)))
        goto cleanup;

644 645 646
    if (virDomainCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

647
    if (!(vm = virDomainObjListAdd(driver->domains, def,
648
                                   driver->xmlopt,
649 650
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
651 652 653
        goto cleanup;
    def = NULL;

654
    if (libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_START_PAUSED) != 0,
655
                     -1) < 0) {
656
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
657 658 659 660 661 662 663 664
        vm = NULL;
        goto cleanup;
    }

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

665
 cleanup:
J
Jim Fehlig 已提交
666 667
    virDomainDefFree(def);
    if (vm)
668
        virObjectUnlock(vm);
669
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
670 671 672 673 674 675 676 677 678 679
    return dom;
}

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

680
    vm = virDomainObjListFindByID(driver->domains, id);
J
Jim Fehlig 已提交
681
    if (!vm) {
682
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
683 684 685
        goto cleanup;
    }

686 687 688
    if (virDomainLookupByIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
689 690 691 692
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

693
 cleanup:
J
Jim Fehlig 已提交
694
    if (vm)
695
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
696 697 698 699 700 701 702 703 704 705
    return dom;
}

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

706
    vm = virDomainObjListFindByUUID(driver->domains, uuid);
J
Jim Fehlig 已提交
707
    if (!vm) {
708
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
709 710 711
        goto cleanup;
    }

712 713 714
    if (virDomainLookupByUUIDEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
715 716 717 718
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

719
 cleanup:
J
Jim Fehlig 已提交
720
    if (vm)
721
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
722 723 724 725 726 727 728 729 730 731
    return dom;
}

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

732
    vm = virDomainObjListFindByName(driver->domains, name);
J
Jim Fehlig 已提交
733
    if (!vm) {
734
        virReportError(VIR_ERR_NO_DOMAIN, NULL);
J
Jim Fehlig 已提交
735 736 737
        goto cleanup;
    }

738 739 740
    if (virDomainLookupByNameEnsureACL(conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
741 742 743 744
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

745
 cleanup:
J
Jim Fehlig 已提交
746
    if (vm)
747
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
748 749 750
    return dom;
}

751 752 753 754
static int
libxlDomainSuspend(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
755
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
756 757
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
758
    virObjectEventPtr event = NULL;
759 760
    int ret = -1;

J
Jim Fehlig 已提交
761
    if (!(vm = libxlDomObjFromDomain(dom)))
762
        goto cleanup;
763 764 765 766

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

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

770
    if (!virDomainObjIsActive(vm)) {
771
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
772
        goto endjob;
773 774 775 776
    }

    priv = vm->privateData;

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

J
Jiri Denemark 已提交
785
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
786

787
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
788 789 790
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

791
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
792
        goto endjob;
793 794 795

    ret = 0;

796
 endjob:
797 798 799
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

800
 cleanup:
801
    if (vm)
802
        virObjectUnlock(vm);
803
    if (event)
804
        libxlDomainEventQueue(driver, event);
805
    virObjectUnref(cfg);
806 807 808 809 810 811 812 813
    return ret;
}


static int
libxlDomainResume(virDomainPtr dom)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
814
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
815 816
    virDomainObjPtr vm;
    libxlDomainObjPrivatePtr priv;
817
    virObjectEventPtr event = NULL;
818 819
    int ret = -1;

J
Jim Fehlig 已提交
820
    if (!(vm = libxlDomObjFromDomain(dom)))
821 822
        goto cleanup;

823 824 825
    if (virDomainResumeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

829
    if (!virDomainObjIsActive(vm)) {
830
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
831
        goto endjob;
832 833 834 835
    }

    priv = vm->privateData;

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

J
Jiri Denemark 已提交
844 845
        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_UNPAUSED);
846

847
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_RESUMED,
848 849 850
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
    }

851
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
852
        goto endjob;
853 854 855

    ret = 0;

856
 endjob:
857 858 859
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

860
 cleanup:
861
    if (vm)
862
        virObjectUnlock(vm);
863
    if (event)
864
        libxlDomainEventQueue(driver, event);
865
    virObjectUnref(cfg);
866 867 868
    return ret;
}

J
Jim Fehlig 已提交
869
static int
870
libxlDomainShutdownFlags(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
871 872 873 874 875
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

876 877 878 879 880
    virCheckFlags(VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN |
                  VIR_DOMAIN_SHUTDOWN_PARAVIRT, -1);
    if (flags == 0)
        flags = VIR_DOMAIN_SHUTDOWN_PARAVIRT |
            VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN;
881

J
Jim Fehlig 已提交
882
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
883 884
        goto cleanup;

885
    if (virDomainShutdownFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
886 887
        goto cleanup;

J
Jim Fehlig 已提交
888
    if (!virDomainObjIsActive(vm)) {
889 890
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
891 892 893 894
        goto cleanup;
    }

    priv = vm->privateData;
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
    if (flags & VIR_DOMAIN_SHUTDOWN_PARAVIRT) {
        ret = libxl_domain_shutdown(priv->ctx, vm->def->id);
        if (ret == 0)
            goto cleanup;

        if (ret != ERROR_NOPARAVIRT) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to shutdown domain '%d' with libxenlight"),
                           vm->def->id);
            ret = -1;
            goto cleanup;
        }
        ret = -1;
    }

    if (flags & VIR_DOMAIN_SHUTDOWN_ACPI_POWER_BTN) {
        ret = libxl_send_trigger(priv->ctx, vm->def->id,
                                 LIBXL_TRIGGER_POWER, 0);
        if (ret == 0)
            goto cleanup;

916 917
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to shutdown domain '%d' with libxenlight"),
918
                       vm->def->id);
919
        ret = -1;
J
Jim Fehlig 已提交
920 921
    }

922
 cleanup:
J
Jim Fehlig 已提交
923
    if (vm)
924
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
925 926 927
    return ret;
}

928 929 930 931 932 933 934
static int
libxlDomainShutdown(virDomainPtr dom)
{
    return libxlDomainShutdownFlags(dom, 0);
}


J
Jim Fehlig 已提交
935
static int
E
Eric Blake 已提交
936
libxlDomainReboot(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
937 938 939 940 941
{
    virDomainObjPtr vm;
    int ret = -1;
    libxlDomainObjPrivatePtr priv;

J
Jim Fehlig 已提交
942 943 944
    virCheckFlags(VIR_DOMAIN_REBOOT_PARAVIRT, -1);
    if (flags == 0)
        flags = VIR_DOMAIN_REBOOT_PARAVIRT;
E
Eric Blake 已提交
945

J
Jim Fehlig 已提交
946
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
947 948
        goto cleanup;

949
    if (virDomainRebootEnsureACL(dom->conn, vm->def, flags) < 0)
950 951
        goto cleanup;

J
Jim Fehlig 已提交
952
    if (!virDomainObjIsActive(vm)) {
953 954
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
955 956 957 958
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
959 960 961 962 963
    if (flags & VIR_DOMAIN_REBOOT_PARAVIRT) {
        ret = libxl_domain_reboot(priv->ctx, vm->def->id);
        if (ret == 0)
            goto cleanup;

964 965
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to reboot domain '%d' with libxenlight"),
966
                       vm->def->id);
J
Jim Fehlig 已提交
967
        ret = -1;
J
Jim Fehlig 已提交
968 969
    }

970
 cleanup:
J
Jim Fehlig 已提交
971
    if (vm)
972
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
973 974 975 976
    return ret;
}

static int
977 978
libxlDomainDestroyFlags(virDomainPtr dom,
                        unsigned int flags)
J
Jim Fehlig 已提交
979 980 981 982
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
983
    virObjectEventPtr event = NULL;
J
Jim Fehlig 已提交
984
    libxlDomainObjPrivatePtr priv;
J
Jim Fehlig 已提交
985

986 987
    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
988
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
989 990
        goto cleanup;

991 992 993
    if (virDomainDestroyFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
994
    if (!virDomainObjIsActive(vm)) {
995 996
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is not running"));
J
Jim Fehlig 已提交
997 998 999
        goto cleanup;
    }

1000
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1001 1002
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);

J
Jim Fehlig 已提交
1003 1004
    priv = vm->privateData;
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
1005
        virReportError(VIR_ERR_INTERNAL_ERROR,
1006
                       _("Failed to destroy domain '%d'"), vm->def->id);
J
Jim Fehlig 已提交
1007 1008 1009
        goto cleanup;
    }

1010
    if (libxlDomainCleanupJob(driver, vm, VIR_DOMAIN_SHUTOFF_DESTROYED)) {
1011 1012 1013 1014
        if (!vm->persistent) {
            virDomainObjListRemove(driver->domains, vm);
            vm = NULL;
        }
J
Jim Fehlig 已提交
1015 1016 1017 1018
    }

    ret = 0;

1019
 cleanup:
J
Jim Fehlig 已提交
1020
    if (vm)
1021
        virObjectUnlock(vm);
1022 1023
    if (event)
        libxlDomainEventQueue(driver, event);
J
Jim Fehlig 已提交
1024 1025 1026
    return ret;
}

1027 1028 1029 1030 1031 1032
static int
libxlDomainDestroy(virDomainPtr dom)
{
    return libxlDomainDestroyFlags(dom, 0);
}

1033 1034 1035 1036 1037 1038
static char *
libxlDomainGetOSType(virDomainPtr dom)
{
    virDomainObjPtr vm;
    char *type = NULL;

J
Jim Fehlig 已提交
1039
    if (!(vm = libxlDomObjFromDomain(dom)))
1040 1041
        goto cleanup;

1042 1043 1044 1045 1046
    if (virDomainGetOSTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1048
 cleanup:
1049
    if (vm)
1050
        virObjectUnlock(vm);
1051 1052 1053
    return type;
}

1054
static unsigned long long
1055 1056 1057
libxlDomainGetMaxMemory(virDomainPtr dom)
{
    virDomainObjPtr vm;
1058
    unsigned long long ret = 0;
1059

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

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

1066 1067
    ret = vm->def->mem.max_balloon;

1068
 cleanup:
1069
    if (vm)
1070
        virObjectUnlock(vm);
1071 1072 1073 1074
    return ret;
}

static int
1075
libxlDomainSetMemoryFlags(virDomainPtr dom, unsigned long newmem,
1076 1077 1078
                          unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1079
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1080 1081
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1082 1083
    virDomainDefPtr persistentDef = NULL;
    bool isActive;
1084 1085 1086
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_MEM_LIVE |
1087 1088
                  VIR_DOMAIN_MEM_CONFIG |
                  VIR_DOMAIN_MEM_MAXIMUM, -1);
1089

J
Jim Fehlig 已提交
1090
    if (!(vm = libxlDomObjFromDomain(dom)))
1091 1092
        goto cleanup;

1093 1094 1095
    if (virDomainSetMemoryFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    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;
1112 1113
    }

1114
    if (!isActive && (flags & VIR_DOMAIN_MEM_LIVE)) {
1115 1116
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set memory on an inactive domain"));
1117
        goto endjob;
1118 1119 1120 1121
    }

    if (flags & VIR_DOMAIN_MEM_CONFIG) {
        if (!vm->persistent) {
1122 1123
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a transient domain"));
1124
            goto endjob;
1125
        }
1126
        if (!(persistentDef = virDomainObjGetPersistentDef(cfg->caps,
1127
                                                           driver->xmlopt,
1128
                                                           vm)))
1129
            goto endjob;
1130 1131
    }

1132 1133
    if (flags & VIR_DOMAIN_MEM_MAXIMUM) {
        /* resize the maximum memory */
1134

1135 1136
        if (flags & VIR_DOMAIN_MEM_LIVE) {
            priv = vm->privateData;
1137
            if (libxl_domain_setmaxmem(priv->ctx, vm->def->id, newmem) < 0) {
1138 1139
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set maximum memory for domain '%d'"
1140
                                 " with libxenlight"), vm->def->id);
1141
                goto endjob;
1142 1143 1144 1145 1146 1147 1148 1149 1150
            }
        }

        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;
1151
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
1152
            goto endjob;
1153 1154
        }

1155 1156
    } else {
        /* resize the current memory */
1157

1158
        if (newmem > vm->def->mem.max_balloon) {
1159 1160
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("cannot set memory higher than max memory"));
1161
            goto endjob;
1162 1163 1164
        }

        if (flags & VIR_DOMAIN_MEM_LIVE) {
1165 1166
            int res;

1167
            priv = vm->privateData;
1168 1169
            /* Unlock virDomainObj while ballooning memory */
            virObjectUnlock(vm);
1170
            res = libxl_set_memory_target(priv->ctx, vm->def->id, newmem, 0,
1171 1172 1173
                                          /* force */ 1);
            virObjectLock(vm);
            if (res < 0) {
1174 1175
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to set memory for domain '%d'"
1176
                                 " with libxenlight"), vm->def->id);
1177
                goto endjob;
1178 1179 1180 1181 1182 1183
            }
        }

        if (flags & VIR_DOMAIN_MEM_CONFIG) {
            sa_assert(persistentDef);
            persistentDef->mem.cur_balloon = newmem;
1184
            ret = virDomainSaveConfig(cfg->configDir, persistentDef);
1185
            goto endjob;
1186
        }
1187 1188
    }

1189 1190
    ret = 0;

1191
 endjob:
1192 1193 1194
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1195
 cleanup:
1196
    if (vm)
1197
        virObjectUnlock(vm);
1198
    virObjectUnref(cfg);
1199 1200 1201 1202 1203 1204 1205 1206 1207
    return ret;
}

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

1208 1209 1210 1211 1212 1213
static int
libxlDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
{
    return libxlDomainSetMemoryFlags(dom, memory, VIR_DOMAIN_MEM_MAXIMUM);
}

J
Jim Fehlig 已提交
1214 1215 1216 1217
static int
libxlDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
    virDomainObjPtr vm;
1218
    libxl_dominfo d_info;
1219
    libxlDomainObjPrivatePtr priv;
J
Jim Fehlig 已提交
1220 1221
    int ret = -1;

J
Jim Fehlig 已提交
1222
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
1223 1224
        goto cleanup;

1225 1226 1227
    if (virDomainGetInfoEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1228
    priv = vm->privateData;
1229 1230 1231
    if (!virDomainObjIsActive(vm)) {
        info->cpuTime = 0;
        info->memory = vm->def->mem.cur_balloon;
1232
        info->maxMem = vm->def->mem.max_balloon;
1233
    } else {
1234
        if (libxl_domain_info(priv->ctx, &d_info, vm->def->id) != 0) {
1235
            virReportError(VIR_ERR_INTERNAL_ERROR,
1236 1237
                           _("libxl_domain_info failed for domain '%d'"),
                           vm->def->id);
1238 1239 1240 1241
            goto cleanup;
        }
        info->cpuTime = d_info.cpu_time;
        info->memory = d_info.current_memkb;
1242
        info->maxMem = d_info.max_memkb;
1243 1244
    }

J
Jiri Denemark 已提交
1245
    info->state = virDomainObjGetState(vm, NULL);
J
Jim Fehlig 已提交
1246 1247 1248
    info->nrVirtCpu = vm->def->vcpus;
    ret = 0;

1249
 cleanup:
J
Jim Fehlig 已提交
1250
    if (vm)
1251
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
1252 1253 1254
    return ret;
}

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
static int
libxlDomainGetState(virDomainPtr dom,
                    int *state,
                    int *reason,
                    unsigned int flags)
{
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1266
    if (!(vm = libxlDomObjFromDomain(dom)))
1267 1268
        goto cleanup;

1269 1270 1271
    if (virDomainGetStateEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jiri Denemark 已提交
1272
    *state = virDomainObjGetState(vm, reason);
1273 1274
    ret = 0;

1275
 cleanup:
1276
    if (vm)
1277
        virObjectUnlock(vm);
1278 1279 1280
    return ret;
}

1281 1282 1283
/*
 * virDomainObjPtr must be locked on invocation
 */
1284
static int
1285 1286
libxlDoDomainSave(libxlDriverPrivatePtr driver, virDomainObjPtr vm,
                  const char *to)
1287
{
1288
    libxlDomainObjPrivatePtr priv = vm->privateData;
1289
    libxlSavefileHeader hdr;
1290
    virObjectEventPtr event = NULL;
1291 1292
    char *xml = NULL;
    uint32_t xml_len;
1293
    int fd = -1;
1294 1295 1296
    int ret = -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
1297 1298 1299
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Domain '%d' has to be running because libxenlight will"
                         " suspend it"), vm->def->id);
1300 1301 1302 1303
        goto cleanup;
    }

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1304
                            -1, -1, 0)) < 0) {
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
        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)) {
1320 1321
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1322 1323 1324 1325
        goto cleanup;
    }

    if (safewrite(fd, xml, xml_len) != xml_len) {
1326 1327
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write xml description"));
1328 1329 1330
        goto cleanup;
    }

1331 1332 1333 1334 1335 1336
    /* Unlock virDomainObj while saving domain */
    virObjectUnlock(vm);
    ret = libxl_domain_suspend(priv->ctx, vm->def->id, fd, 0, NULL);
    virObjectLock(vm);

    if (ret != 0) {
1337 1338 1339
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to save domain '%d' with libxenlight"),
                       vm->def->id);
1340
        ret = -1;
1341 1342 1343
        goto cleanup;
    }

1344
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1345 1346
                                         VIR_DOMAIN_EVENT_STOPPED_SAVED);

J
Jim Fehlig 已提交
1347
    if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
1348 1349
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to destroy domain '%d'"), vm->def->id);
1350 1351 1352
        goto cleanup;
    }

1353
    libxlDomainCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_SAVED);
1354
    vm->hasManagedSave = true;
1355 1356
    ret = 0;

1357
 cleanup:
1358 1359 1360 1361 1362 1363 1364 1365 1366
    VIR_FREE(xml);
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
    if (event)
        libxlDomainEventQueue(driver, event);
    return ret;
}

static int
1367 1368
libxlDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                     unsigned int flags)
1369
{
1370 1371
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
1372
    int ret = -1;
1373
    bool remove_dom = false;
1374

1375 1376
    virCheckFlags(0, -1);
    if (dxml) {
1377 1378
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1379 1380 1381
        return -1;
    }

J
Jim Fehlig 已提交
1382
    if (!(vm = libxlDomObjFromDomain(dom)))
1383 1384
        goto cleanup;

1385 1386 1387
    if (virDomainSaveFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1391
    if (!virDomainObjIsActive(vm)) {
1392
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1393
        goto endjob;
1394 1395
    }

1396
    if (libxlDoDomainSave(driver, vm, to) < 0)
1397
        goto endjob;
1398

1399 1400
    if (!vm->persistent)
        remove_dom = true;
1401 1402

    ret = 0;
1403

1404
 endjob:
1405 1406 1407
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1408
 cleanup:
1409 1410 1411 1412
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1413
    if (vm)
1414
        virObjectUnlock(vm);
1415 1416
    return ret;
}
1417

1418
static int
1419 1420 1421 1422 1423 1424 1425 1426
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)
1427 1428
{
    libxlDriverPrivatePtr driver = conn->privateData;
1429
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1430 1431 1432 1433 1434
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1435

1436
    virCheckFlags(VIR_DOMAIN_SAVE_PAUSED, -1);
1437
    if (dxml) {
1438 1439
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1440 1441 1442
        return -1;
    }

1443
    fd = libxlDomainSaveImageOpen(driver, cfg, from, &def, &hdr);
1444
    if (fd < 0)
1445
        goto cleanup_unlock;
1446

1447
    if (virDomainRestoreFlagsEnsureACL(conn, def) < 0)
1448
        goto cleanup_unlock;
1449

1450
    if (!(vm = virDomainObjListAdd(driver->domains, def,
1451
                                   driver->xmlopt,
1452 1453 1454
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
1455
        goto cleanup_unlock;
1456 1457 1458

    def = NULL;

1459
    ret = libxlDomainStart(driver, vm, (flags & VIR_DOMAIN_SAVE_PAUSED) != 0, fd);
1460
    if (ret < 0 && !vm->persistent) {
1461
        virDomainObjListRemove(driver->domains, vm);
1462 1463 1464
        vm = NULL;
    }

1465
 cleanup:
1466 1467
    if (VIR_CLOSE(fd) < 0)
        virReportSystemError(errno, "%s", _("cannot close file"));
1468 1469
    virDomainDefFree(def);
    if (vm)
1470
        virObjectUnlock(vm);
1471
    virObjectUnref(cfg);
1472
    return ret;
1473

1474
 cleanup_unlock:
1475 1476
    libxlDriverUnlock(driver);
    goto cleanup;
1477 1478
}

1479 1480 1481 1482 1483 1484
static int
libxlDomainRestore(virConnectPtr conn, const char *from)
{
    return libxlDomainRestoreFlags(conn, from, NULL, 0);
}

1485
static int
1486
libxlDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1487 1488 1489 1490
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
1491
    virObjectEventPtr event = NULL;
1492
    bool remove_dom = false;
1493 1494 1495 1496 1497
    bool paused = false;
    int ret = -1;

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

J
Jim Fehlig 已提交
1498
    if (!(vm = libxlDomObjFromDomain(dom)))
1499 1500
        goto cleanup;

1501 1502 1503
    if (virDomainCoreDumpEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1507
    if (!virDomainObjIsActive(vm)) {
1508
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1509
        goto endjob;
1510 1511 1512 1513 1514 1515
    }

    priv = vm->privateData;

    if (!(flags & VIR_DUMP_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
1516
        if (libxl_domain_pause(priv->ctx, vm->def->id) != 0) {
1517 1518 1519
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Before dumping core, failed to suspend domain '%d'"
                             " with libxenlight"),
1520
                           vm->def->id);
1521
            goto endjob;
1522 1523 1524 1525 1526
        }
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_DUMP);
        paused = true;
    }

1527 1528
    /* Unlock virDomainObj while dumping core */
    virObjectUnlock(vm);
1529
    ret = libxl_domain_core_dump(priv->ctx, vm->def->id, to, NULL);
1530 1531
    virObjectLock(vm);
    if (ret != 0) {
1532 1533
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to dump core of domain '%d' with libxenlight"),
1534
                       vm->def->id);
1535 1536
        ret = -1;
        goto unpause;
1537 1538 1539
    }

    if (flags & VIR_DUMP_CRASH) {
1540
        if (libxl_domain_destroy(priv->ctx, vm->def->id, NULL) < 0) {
1541
            virReportError(VIR_ERR_INTERNAL_ERROR,
1542
                           _("Failed to destroy domain '%d'"), vm->def->id);
1543
            goto unpause;
1544 1545
        }

1546
        libxlDomainCleanup(driver, vm, VIR_DOMAIN_SHUTOFF_CRASHED);
1547
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
1548
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
1549 1550
        if (!vm->persistent)
            remove_dom = true;
1551 1552 1553 1554
    }

    ret = 0;

1555
 unpause:
1556
    if (virDomainObjIsActive(vm) && paused) {
1557
        if (libxl_domain_unpause(priv->ctx, vm->def->id) != 0) {
1558 1559
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("After dumping core, failed to resume domain '%d' with"
1560
                             " libxenlight"), vm->def->id);
1561 1562 1563 1564 1565
        } else {
            virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNPAUSED);
        }
    }
1566

1567
 endjob:
1568 1569 1570
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1571
 cleanup:
1572 1573 1574 1575
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1576
    if (vm)
1577
        virObjectUnlock(vm);
1578
    if (event)
1579 1580 1581 1582
        libxlDomainEventQueue(driver, event);
    return ret;
}

1583 1584 1585 1586 1587 1588 1589
static int
libxlDomainManagedSave(virDomainPtr dom, unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *name = NULL;
    int ret = -1;
1590
    bool remove_dom = false;
1591 1592 1593

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1594
    if (!(vm = libxlDomObjFromDomain(dom)))
1595 1596
        goto cleanup;

1597 1598 1599
    if (virDomainManagedSaveEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

1603
    if (!virDomainObjIsActive(vm)) {
1604
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
1605
        goto endjob;
1606
    }
1607
    if (!vm->persistent) {
1608 1609
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot do managed save for transient domain"));
1610
        goto endjob;
1611
    }
1612 1613 1614

    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
1615
        goto endjob;
1616 1617 1618

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

1619
    if (libxlDoDomainSave(driver, vm, name) < 0)
1620
        goto endjob;
1621

1622 1623
    if (!vm->persistent)
        remove_dom = true;
1624 1625

    ret = 0;
1626

1627
 endjob:
1628 1629 1630
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1631
 cleanup:
1632 1633 1634 1635
    if (remove_dom && vm) {
        virDomainObjListRemove(driver->domains, vm);
        vm = NULL;
    }
1636
    if (vm)
1637
        virObjectUnlock(vm);
1638 1639 1640 1641
    VIR_FREE(name);
    return ret;
}

1642 1643
static int
libxlDomainManagedSaveLoad(virDomainObjPtr vm,
1644 1645 1646 1647
                           void *opaque)
{
    libxlDriverPrivatePtr driver = opaque;
    char *name;
1648
    int ret = -1;
1649

1650
    virObjectLock(vm);
1651 1652 1653 1654 1655 1656

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

    vm->hasManagedSave = virFileExists(name);

1657
    ret = 0;
1658
 cleanup:
1659
    virObjectUnlock(vm);
1660
    VIR_FREE(name);
1661
    return ret;
1662 1663
}

1664 1665 1666 1667 1668 1669 1670 1671
static int
libxlDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

J
Jim Fehlig 已提交
1672
    if (!(vm = libxlDomObjFromDomain(dom)))
1673 1674
        goto cleanup;

1675 1676 1677
    if (virDomainHasManagedSaveImageEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

1678
    ret = vm->hasManagedSave;
1679

1680
 cleanup:
1681
    if (vm)
1682
        virObjectUnlock(vm);
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
    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 已提交
1696
    if (!(vm = libxlDomObjFromDomain(dom)))
1697 1698
        goto cleanup;

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

1702 1703 1704 1705 1706
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);
1707
    vm->hasManagedSave = false;
1708

1709
 cleanup:
1710 1711
    VIR_FREE(name);
    if (vm)
1712
        virObjectUnlock(vm);
1713 1714 1715
    return ret;
}

1716 1717 1718 1719 1720
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1721
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1722 1723 1724
    libxlDomainObjPrivatePtr priv;
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
1725
    libxl_bitmap map;
1726 1727
    uint8_t *bitmask = NULL;
    unsigned int maplen;
1728 1729
    size_t i;
    unsigned int pos;
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
    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)) {
1742 1743
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
1744 1745 1746 1747
        return -1;
    }

    if (!nvcpus) {
1748
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("nvcpus is zero"));
1749 1750 1751
        return -1;
    }

J
Jim Fehlig 已提交
1752
    if (!(vm = libxlDomObjFromDomain(dom)))
1753 1754
        goto cleanup;

1755 1756 1757
    if (virDomainSetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

1761
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
1762 1763
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot set vcpus on an inactive domain"));
1764
        goto endjob;
1765 1766 1767
    }

    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
1768 1769
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot change persistent config of a transient domain"));
1770
        goto endjob;
1771 1772
    }

1773
    if ((max = libxlConnectGetMaxVcpus(dom->conn, NULL)) < 0) {
1774 1775
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not determine max vcpus for the domain"));
1776
        goto endjob;
1777 1778 1779 1780 1781 1782 1783
    }

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

    if (nvcpus > max) {
1784 1785 1786
        virReportError(VIR_ERR_INVALID_ARG,
                       _("requested vcpus is greater than max allowable"
                         " vcpus for the domain: %d > %d"), nvcpus, max);
1787
        goto endjob;
1788 1789 1790 1791
    }

    priv = vm->privateData;

1792
    if (!(def = virDomainObjGetPersistentDef(cfg->caps, driver->xmlopt, vm)))
1793
        goto endjob;
1794

E
Eric Blake 已提交
1795
    maplen = VIR_CPU_MAPLEN(nvcpus);
1796
    if (VIR_ALLOC_N(bitmask, maplen) < 0)
1797
        goto endjob;
1798 1799

    for (i = 0; i < nvcpus; ++i) {
E
Eric Blake 已提交
1800
        pos = i / 8;
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
        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:
1819
        if (libxl_set_vcpuonline(priv->ctx, vm->def->id, &map) != 0) {
1820 1821
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
1822
                             " with libxenlight"), vm->def->id);
1823
            goto endjob;
1824 1825 1826 1827
        }
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
1828
        if (libxl_set_vcpuonline(priv->ctx, vm->def->id, &map) != 0) {
1829 1830
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to set vcpus for domain '%d'"
1831
                             " with libxenlight"), vm->def->id);
1832
            goto endjob;
1833 1834 1835 1836 1837 1838 1839 1840
        }
        def->vcpus = nvcpus;
        break;
    }

    ret = 0;

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

1843
 endjob:
1844 1845 1846
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1847
 cleanup:
1848 1849
    VIR_FREE(bitmask);
     if (vm)
1850
        virObjectUnlock(vm);
1851
     virObjectUnref(cfg);
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
    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;
1867
    bool active;
1868 1869 1870 1871 1872

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

J
Jim Fehlig 已提交
1873
    if (!(vm = libxlDomObjFromDomain(dom)))
1874 1875
        goto cleanup;

1876
    if (virDomainGetVcpusFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1877 1878
        goto cleanup;

1879 1880 1881 1882 1883 1884 1885 1886 1887
    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)) {
1888 1889
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
1890 1891 1892
        return -1;
    }

1893
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
1894
        if (!active) {
1895 1896
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
1897 1898 1899 1900
            goto cleanup;
        }
        def = vm->def;
    } else {
1901
        if (!vm->persistent) {
1902 1903
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is transient"));
1904 1905
            goto cleanup;
        }
1906 1907 1908 1909 1910
        def = vm->newDef ? vm->newDef : vm->def;
    }

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

1911
 cleanup:
1912
    if (vm)
1913
        virObjectUnlock(vm);
1914 1915 1916 1917
    return ret;
}

static int
1918 1919 1920
libxlDomainPinVcpuFlags(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen,
                        unsigned int flags)
1921 1922
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1923
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1924
    virDomainDefPtr targetDef = NULL;
1925
    virBitmapPtr pcpumap = NULL;
1926 1927
    virDomainObjPtr vm;
    int ret = -1;
1928 1929 1930

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
1931

J
Jim Fehlig 已提交
1932
    if (!(vm = libxlDomObjFromDomain(dom)))
1933 1934
        goto cleanup;

1935
    if (virDomainPinVcpuFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
1936 1937
        goto cleanup;

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

1941
    if ((flags & VIR_DOMAIN_AFFECT_LIVE) && !virDomainObjIsActive(vm)) {
1942
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
1943
                       _("domain is inactive"));
1944
        goto endjob;
1945 1946
    }

1947 1948
    if (virDomainLiveConfigHelperMethod(cfg->caps, driver->xmlopt, vm,
                                        &flags, &targetDef) < 0)
1949
        goto endjob;
1950 1951 1952 1953 1954 1955 1956 1957

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

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

1958 1959
    pcpumap = virBitmapNewData(cpumap, maplen);
    if (!pcpumap)
1960
        goto endjob;
1961

1962 1963 1964 1965 1966
    if (flags & VIR_DOMAIN_AFFECT_LIVE) {
        libxl_bitmap map = { .size = maplen, .map = cpumap };
        libxlDomainObjPrivatePtr priv;

        priv = vm->privateData;
1967
        if (libxl_set_vcpuaffinity(priv->ctx, vm->def->id, vcpu, &map) != 0) {
1968 1969 1970
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to pin vcpu '%d' with libxenlight"),
                           vcpu);
1971
            goto endjob;
1972
        }
1973
    }
1974

1975 1976
    /* full bitmap means reset the settings (if any). */
    if (virBitmapIsAllSet(pcpumap)) {
1977
        virDomainVcpuPinDel(targetDef, vcpu);
1978
        goto done;
1979 1980
    }

1981 1982
    if (!targetDef->cputune.vcpupin) {
        if (VIR_ALLOC(targetDef->cputune.vcpupin) < 0)
1983
            goto endjob;
1984
        targetDef->cputune.nvcpupin = 0;
H
Hu Tao 已提交
1985
    }
1986 1987
    if (virDomainVcpuPinAdd(&targetDef->cputune.vcpupin,
                            &targetDef->cputune.nvcpupin,
H
Hu Tao 已提交
1988 1989 1990
                            cpumap,
                            maplen,
                            vcpu) < 0) {
1991 1992
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to update or add vcpupin xml"));
1993
        goto endjob;
1994 1995
    }

1996
 done:
1997 1998
    ret = 0;

1999 2000 2001 2002 2003 2004
    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);
    }

2005
 endjob:
2006 2007 2008
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

2009
 cleanup:
2010
    if (vm)
2011
        virObjectUnlock(vm);
2012
    virBitmapFree(pcpumap);
2013
    virObjectUnref(cfg);
2014 2015 2016
    return ret;
}

2017 2018 2019 2020 2021 2022 2023 2024
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

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 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
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;

2096
 cleanup:
2097 2098 2099 2100 2101
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(cfg);
    return ret;
}
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111

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;
2112
    size_t i;
2113 2114
    unsigned char *cpumap;

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

2118 2119 2120
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2121
    if (!virDomainObjIsActive(vm)) {
2122
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2123 2124 2125 2126
        goto cleanup;
    }

    priv = vm->privateData;
2127
    if ((vcpuinfo = libxl_list_vcpu(priv->ctx, vm->def->id, &maxcpu,
2128
                                    &hostcpus)) == NULL) {
2129 2130
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
2131
                       vm->def->id);
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
        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 已提交
2154
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2155 2156 2157 2158 2159
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

2160
 cleanup:
2161
    if (vm)
2162
        virObjectUnlock(vm);
2163 2164 2165
    return ret;
}

J
Jim Fehlig 已提交
2166
static char *
2167
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2168 2169 2170 2171
{
    virDomainObjPtr vm;
    char *ret = NULL;

2172 2173
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2174
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2175 2176
        goto cleanup;

2177 2178 2179
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

2182
 cleanup:
J
Jim Fehlig 已提交
2183
    if (vm)
2184
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2185 2186 2187
    return ret;
}

2188
static char *
2189 2190 2191
libxlConnectDomainXMLFromNative(virConnectPtr conn,
                                const char *nativeFormat,
                                const char *nativeConfig,
2192
                                unsigned int flags)
2193 2194
{
    libxlDriverPrivatePtr driver = conn->privateData;
2195
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2196 2197 2198 2199
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    char *xml = NULL;

E
Eric Blake 已提交
2200 2201
    virCheckFlags(0, NULL);

2202 2203 2204
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
    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 {
2227 2228
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2229 2230 2231 2232 2233
        goto cleanup;
    }

    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);

2234
 cleanup:
2235 2236 2237
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2238
    virObjectUnref(cfg);
2239 2240 2241 2242 2243
    return xml;
}

#define MAX_CONFIG_SIZE (1024 * 65)
static char *
2244 2245 2246
libxlConnectDomainXMLToNative(virConnectPtr conn, const char * nativeFormat,
                              const char * domainXml,
                              unsigned int flags)
2247 2248
{
    libxlDriverPrivatePtr driver = conn->privateData;
2249
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
2250 2251 2252 2253 2254
    virDomainDefPtr def = NULL;
    virConfPtr conf = NULL;
    int len = MAX_CONFIG_SIZE;
    char *ret = NULL;

E
Eric Blake 已提交
2255 2256
    virCheckFlags(0, NULL);

2257 2258 2259
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

2260
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2261 2262
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2263 2264 2265
        goto cleanup;
    }

2266
    if (!(def = virDomainDefParseString(domainXml,
2267
                                        cfg->caps, driver->xmlopt,
2268 2269
                                        1 << VIR_DOMAIN_VIRT_XEN,
                                        VIR_DOMAIN_XML_INACTIVE)))
2270 2271
        goto cleanup;

2272
    if (!(conf = xenFormatXM(conn, def, cfg->verInfo->xen_version_major)))
2273 2274
        goto cleanup;

2275
    if (VIR_ALLOC_N(ret, len) < 0)
2276 2277 2278 2279 2280 2281 2282
        goto cleanup;

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

2283
 cleanup:
2284 2285 2286
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2287
    virObjectUnref(cfg);
2288 2289 2290
    return ret;
}

J
Jim Fehlig 已提交
2291
static int
2292 2293
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
2294 2295 2296 2297
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2298 2299 2300
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2301 2302
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
2303 2304 2305 2306
    return n;
}

static int
2307
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
2308 2309 2310 2311
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2312 2313 2314
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2315
    n = virDomainObjListNumOfDomains(driver->domains, false,
2316 2317
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
2318 2319 2320 2321 2322
    return n;
}

static int
libxlDomainCreateWithFlags(virDomainPtr dom,
E
Eric Blake 已提交
2323
                           unsigned int flags)
J
Jim Fehlig 已提交
2324 2325 2326 2327 2328 2329 2330
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

J
Jim Fehlig 已提交
2331
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2332 2333
        goto cleanup;

2334 2335 2336
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2337
    if (virDomainObjIsActive(vm)) {
2338 2339
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
J
Jim Fehlig 已提交
2340 2341 2342
        goto cleanup;
    }

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

2345
 cleanup:
J
Jim Fehlig 已提交
2346
    if (vm)
2347
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
    return ret;
}

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

static virDomainPtr
libxlDomainDefineXML(virConnectPtr conn, const char *xml)
{
    libxlDriverPrivatePtr driver = conn->privateData;
2361
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2362 2363 2364
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    virDomainPtr dom = NULL;
2365
    virObjectEventPtr event = NULL;
2366
    virDomainDefPtr oldDef = NULL;
J
Jim Fehlig 已提交
2367

2368
    /* Lock the driver until the virDomainObj is created and locked */
J
Jim Fehlig 已提交
2369
    libxlDriverLock(driver);
2370
    if (!(def = virDomainDefParseString(xml, cfg->caps, driver->xmlopt,
M
Matthias Bolte 已提交
2371
                                        1 << VIR_DOMAIN_VIRT_XEN,
J
Jim Fehlig 已提交
2372
                                        VIR_DOMAIN_XML_INACTIVE)))
2373
        goto cleanup_unlock;
J
Jim Fehlig 已提交
2374

2375
    if (virDomainDefineXMLEnsureACL(conn, def) < 0)
2376
        goto cleanup_unlock;
2377

2378
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2379
                                   driver->xmlopt,
2380 2381
                                   0,
                                   &oldDef)))
2382 2383
        goto cleanup_unlock;

J
Jim Fehlig 已提交
2384 2385
    def = NULL;
    vm->persistent = 1;
2386
    libxlDriverUnlock(driver);
J
Jim Fehlig 已提交
2387

2388
    if (virDomainSaveConfig(cfg->configDir,
J
Jim Fehlig 已提交
2389
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2390
        virDomainObjListRemove(driver->domains, vm);
J
Jim Fehlig 已提交
2391 2392 2393 2394 2395 2396 2397 2398
        vm = NULL;
        goto cleanup;
    }

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

2399
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2400
                                     !oldDef ?
2401 2402 2403
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

2404
 cleanup:
J
Jim Fehlig 已提交
2405
    virDomainDefFree(def);
2406
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
2407
    if (vm)
2408
        virObjectUnlock(vm);
2409 2410
    if (event)
        libxlDomainEventQueue(driver, event);
2411
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2412
    return dom;
2413

2414
 cleanup_unlock:
2415 2416
    libxlDriverUnlock(driver);
    goto cleanup;
J
Jim Fehlig 已提交
2417 2418 2419
}

static int
2420 2421
libxlDomainUndefineFlags(virDomainPtr dom,
                         unsigned int flags)
J
Jim Fehlig 已提交
2422 2423
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
2424
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
2425
    virDomainObjPtr vm;
2426
    virObjectEventPtr event = NULL;
2427
    char *name = NULL;
J
Jim Fehlig 已提交
2428 2429
    int ret = -1;

2430 2431
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2432
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2433 2434
        goto cleanup;

2435 2436 2437
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2438
    if (!vm->persistent) {
2439 2440
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot undefine transient domain"));
J
Jim Fehlig 已提交
2441 2442 2443
        goto cleanup;
    }

2444 2445 2446 2447 2448 2449 2450
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    if (virFileExists(name)) {
        if (flags & VIR_DOMAIN_UNDEFINE_MANAGED_SAVE) {
            if (unlink(name) < 0) {
2451 2452
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Failed to remove domain managed save image"));
2453 2454 2455
                goto cleanup;
            }
        } else {
2456 2457 2458
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("Refusing to undefine while domain managed "
                             "save image exists"));
2459 2460 2461 2462
            goto cleanup;
        }
    }

2463
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2464 2465
        goto cleanup;

2466
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2467 2468
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2469 2470 2471
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
2472
        virDomainObjListRemove(driver->domains, vm);
2473 2474 2475
        vm = NULL;
    }

J
Jim Fehlig 已提交
2476 2477
    ret = 0;

2478
 cleanup:
2479
    VIR_FREE(name);
J
Jim Fehlig 已提交
2480
    if (vm)
2481
        virObjectUnlock(vm);
2482 2483
    if (event)
        libxlDomainEventQueue(driver, event);
2484
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2485 2486 2487
    return ret;
}

2488 2489 2490 2491 2492 2493
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2494 2495 2496 2497 2498 2499
static int
libxlDomainChangeEjectableMedia(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDiskDefPtr disk)
{
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2500
    size_t i;
2501 2502
    int ret = -1;

2503
    for (i = 0; i < vm->def->ndisks; i++) {
2504 2505 2506 2507 2508 2509 2510 2511
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
            origdisk = vm->def->disks[i];
            break;
        }
    }

    if (!origdisk) {
2512 2513 2514
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("No device with bus '%s' and target '%s'"),
                       virDomainDiskBusTypeToString(disk->bus), disk->dst);
2515 2516 2517 2518
        goto cleanup;
    }

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2519 2520 2521
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
2522 2523 2524
        return -1;
    }

J
Jim Fehlig 已提交
2525
    if (libxlMakeDisk(disk, &x_disk) < 0)
2526 2527
        goto cleanup;

J
Jim Fehlig 已提交
2528
    if ((ret = libxl_cdrom_insert(priv->ctx, vm->def->id, &x_disk, NULL)) < 0) {
2529 2530 2531
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("libxenlight failed to change media for disk '%s'"),
                       disk->dst);
2532 2533 2534
        goto cleanup;
    }

2535 2536 2537
    if (virDomainDiskSetSource(origdisk, virDomainDiskGetSource(disk)) < 0)
        goto cleanup;
    virDomainDiskSetType(origdisk, virDomainDiskGetType(disk));
2538 2539 2540 2541 2542

    virDomainDiskDefFree(disk);

    ret = 0;

2543
 cleanup:
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
    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) {
2561
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
2562 2563
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
2564 2565 2566
                    goto cleanup;
                }

2567
                if (!virDomainDiskGetSource(l_disk)) {
2568 2569
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
2570 2571 2572
                    goto cleanup;
                }

2573
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
2574 2575
                    goto cleanup;

J
Jim Fehlig 已提交
2576
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
2577 2578
                    goto cleanup;

J
Jim Fehlig 已提交
2579 2580
                if ((ret = libxl_device_disk_add(priv->ctx, vm->def->id,
                                                &x_disk, NULL)) < 0) {
2581 2582 2583
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to attach disk '%s'"),
                                   l_disk->dst);
2584 2585 2586 2587 2588 2589
                    goto cleanup;
                }

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

            } else {
2590 2591 2592
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hotplugged."),
                               virDomainDiskBusTypeToString(l_disk->bus));
2593 2594 2595
            }
            break;
        default:
2596 2597 2598
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk device type '%s' cannot be hotplugged"),
                           virDomainDiskDeviceTypeToString(l_disk->device));
2599 2600 2601
            break;
    }

2602
 cleanup:
2603 2604 2605
    return ret;
}

2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
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 已提交
2635
        return -1;
2636

2637
    if (libxlMakePCI(hostdev, &pcidev) < 0)
C
Chunyan Liu 已提交
2638
        goto error;
2639 2640 2641 2642 2643 2644 2645 2646

    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 已提交
2647
        goto error;
2648 2649 2650 2651 2652
    }

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

2653
 error:
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
    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 已提交
2677
            return -1;
2678 2679 2680 2681 2682 2683
        break;

    default:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("hostdev subsys type '%s' not supported"),
                       virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
C
Chunyan Liu 已提交
2684
        return -1;
2685 2686 2687 2688 2689
    }

    return 0;
}

2690 2691 2692 2693 2694 2695
static int
libxlDomainDetachDeviceDiskLive(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr l_disk = NULL;
    libxl_device_disk x_disk;
2696
    int idx;
2697 2698 2699 2700 2701 2702
    int ret = -1;

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

2703 2704 2705
                if ((idx = virDomainDiskIndexByName(vm->def,
                                                    dev->data.disk->dst,
                                                    false)) < 0) {
2706 2707
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("disk %s not found"), dev->data.disk->dst);
2708 2709 2710
                    goto cleanup;
                }

2711
                l_disk = vm->def->disks[idx];
2712

J
Jim Fehlig 已提交
2713
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
2714 2715
                    goto cleanup;

J
Jim Fehlig 已提交
2716 2717
                if ((ret = libxl_device_disk_remove(priv->ctx, vm->def->id,
                                                    &x_disk, NULL)) < 0) {
2718 2719 2720
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("libxenlight failed to detach disk '%s'"),
                                   l_disk->dst);
2721 2722 2723
                    goto cleanup;
                }

2724
                virDomainDiskRemove(vm->def, idx);
2725 2726 2727
                virDomainDiskDefFree(l_disk);

            } else {
2728 2729 2730
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("disk bus '%s' cannot be hot unplugged."),
                               virDomainDiskBusTypeToString(dev->data.disk->bus));
2731 2732 2733
            }
            break;
        default:
2734 2735 2736
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot hot unplugged"),
                           virDomainDiskDeviceTypeToString(dev->data.disk->device));
2737 2738 2739
            break;
    }

2740
 cleanup:
2741 2742 2743 2744
    return ret;
}

static int
2745 2746 2747
libxlDomainAttachDeviceLive(libxlDriverPrivatePtr driver,
                            libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm,
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
                            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;

2759 2760 2761 2762 2763 2764
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            ret = libxlDomainAttachHostDevice(driver, priv, vm, dev);
            if (!ret)
                dev->data.hostdev = NULL;
            break;

2765
        default:
2766 2767 2768
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be attached"),
                           virDomainDeviceTypeToString(dev->type));
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
            break;
    }

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
2779 2780
    virDomainHostdevDefPtr hostdev;
    virDomainHostdevDefPtr found;
2781 2782 2783 2784

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
2785
            if (virDomainDiskIndexByName(vmdef, disk->dst, true) >= 0) {
2786 2787
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s already exists."), disk->dst);
2788 2789
                return -1;
            }
2790
            if (virDomainDiskInsert(vmdef, disk))
2791 2792 2793 2794
                return -1;
            /* vmdef has the pointer. Generic codes for vmdef will do all jobs */
            dev->data.disk = NULL;
            break;
2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813
        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;
2814 2815

        default:
2816 2817
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
2818 2819 2820 2821 2822 2823
            return -1;
    }
    return 0;
}

static int
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 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
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 已提交
2881
        goto error;
2882 2883 2884 2885 2886
    }


    libxl_device_pci_init(&pcidev);

2887
    if (libxlMakePCI(detach, &pcidev) < 0)
C
Chunyan Liu 已提交
2888
        goto error;
2889 2890 2891 2892 2893 2894 2895

    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 已提交
2896
        goto error;
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
    }

    libxl_device_pci_dispose(&pcidev);

    virDomainHostdevRemove(vm->def, idx);

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

    return 0;

2908
 error:
2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945
    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,
2946 2947 2948 2949 2950 2951 2952 2953 2954
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

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

2955 2956 2957 2958
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            ret = libxlDomainDetachHostDevice(driver, priv, vm, dev);
            break;

2959
        default:
2960 2961 2962
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
2963 2964 2965 2966 2967 2968
            break;
    }

    return ret;
}

2969

2970 2971 2972
static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
2973
    virDomainDiskDefPtr disk, detach;
2974 2975 2976 2977 2978
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
2979
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
2980 2981
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
2982 2983
                break;
            }
2984
            virDomainDiskDefFree(detach);
2985 2986 2987
            ret = 0;
            break;
        default:
2988 2989
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012
            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:
3013 3014 3015
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
3016 3017 3018 3019
                    break;
            }
            break;
        default:
3020 3021 3022
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr orig;
    virDomainDiskDefPtr disk;
3034
    int idx;
3035 3036 3037 3038 3039
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
3040
            if ((idx = virDomainDiskIndexByName(vmdef, disk->dst, false)) < 0) {
3041 3042
                virReportError(VIR_ERR_INVALID_ARG,
                               _("target %s doesn't exist."), disk->dst);
3043 3044
                goto cleanup;
            }
3045
            orig = vmdef->disks[idx];
3046
            if (!(orig->device == VIR_DOMAIN_DISK_DEVICE_CDROM)) {
3047 3048
                virReportError(VIR_ERR_INVALID_ARG, "%s",
                               _("this disk doesn't support update"));
3049 3050 3051
                goto cleanup;
            }

3052 3053 3054 3055 3056 3057
            if (virDomainDiskSetSource(orig, virDomainDiskGetSource(disk)) < 0)
                goto cleanup;
            virDomainDiskSetType(orig, virDomainDiskGetType(disk));
            virDomainDiskSetFormat(orig, virDomainDiskGetFormat(disk));
            if (virDomainDiskSetDriver(orig, virDomainDiskGetDriver(disk)) < 0)
                goto cleanup;
3058 3059
            break;
        default:
3060 3061
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent update of device is not supported"));
3062 3063 3064 3065 3066
            goto cleanup;
    }

    ret = 0;

3067
 cleanup:
3068 3069 3070 3071 3072
    return ret;
}


static int
3073 3074
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3075 3076
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3077
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3078 3079 3080 3081 3082 3083 3084 3085 3086
    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 已提交
3087
    if (!(vm = libxlDomObjFromDomain(dom)))
3088 3089
        goto cleanup;

3090 3091 3092
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3096 3097 3098 3099 3100 3101 3102 3103
    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) {
3104 3105
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3106
            goto endjob;
3107 3108 3109 3110
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
3111 3112
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3113
         goto endjob;
3114 3115 3116 3117 3118
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3119
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3120
                                            cfg->caps, driver->xmlopt,
3121
                                            VIR_DOMAIN_XML_INACTIVE)))
3122
            goto endjob;
3123 3124

        /* Make a copy for updated domain. */
3125
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3126
                                                    driver->xmlopt)))
3127
            goto endjob;
3128

3129
        if ((ret = libxlDomainAttachDeviceConfig(vmdef, dev)) < 0)
3130
            goto endjob;
3131
    } else {
3132
        ret = 0;
3133
    }
3134 3135 3136 3137

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

3143
        if ((ret = libxlDomainAttachDeviceLive(driver, priv, vm, dev)) < 0)
3144
            goto endjob;
3145

3146 3147 3148 3149
        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3150
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3151 3152 3153 3154 3155
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3156
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3157
        if (!ret) {
3158
            virDomainObjAssignDef(vm, vmdef, false, NULL);
3159 3160 3161 3162
            vmdef = NULL;
        }
    }

3163
 endjob:
3164 3165 3166
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3167
 cleanup:
3168 3169 3170
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3171
        virObjectUnlock(vm);
3172
    virObjectUnref(cfg);
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
    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)
{
3187
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3188
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3189 3190 3191 3192 3193 3194 3195 3196 3197
    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 已提交
3198
    if (!(vm = libxlDomObjFromDomain(dom)))
3199 3200
        goto cleanup;

3201 3202 3203
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3207 3208 3209 3210 3211 3212 3213 3214 3215 3216
    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"));
3217
            goto endjob;
3218 3219 3220 3221 3222 3223
        }
    }

    if ((flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) && !vm->persistent) {
         virReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify device on transient domain"));
3224
         goto endjob;
3225 3226 3227 3228 3229 3230
    }

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3231
                                            cfg->caps, driver->xmlopt,
3232
                                            VIR_DOMAIN_XML_INACTIVE)))
3233
            goto endjob;
3234 3235

        /* Make a copy for updated domain. */
3236
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3237
                                                    driver->xmlopt)))
3238
            goto endjob;
3239 3240

        if ((ret = libxlDomainDetachDeviceConfig(vmdef, dev)) < 0)
3241
            goto endjob;
3242 3243 3244 3245 3246 3247 3248 3249
    } 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,
3250
                                            cfg->caps, driver->xmlopt,
3251
                                            VIR_DOMAIN_XML_INACTIVE)))
3252
            goto endjob;
3253

3254
        if ((ret = libxlDomainDetachDeviceLive(driver, priv, vm, dev)) < 0)
3255
            goto endjob;
3256 3257 3258 3259 3260

        /*
         * update domain status forcibly because the domain status may be
         * changed even if we attach the device failed.
         */
3261
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3262 3263 3264 3265 3266
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3267
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3268 3269 3270 3271 3272 3273
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3274
 endjob:
3275 3276 3277
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3278
 cleanup:
3279 3280 3281 3282
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3283
    virObjectUnref(cfg);
3284
    return ret;
3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297
}

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)
{
3298
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3299
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3300 3301 3302 3303 3304 3305 3306 3307 3308
    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 已提交
3309
    if (!(vm = libxlDomObjFromDomain(dom)))
3310 3311
        goto cleanup;

3312 3313 3314
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338
    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,
3339
                                            cfg->caps, driver->xmlopt,
3340 3341 3342 3343
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3344
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
                                                    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,
3358
                                            cfg->caps, driver->xmlopt,
3359 3360 3361 3362 3363 3364 3365 3366 3367 3368
                                            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.
         */
3369
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3370 3371 3372 3373 3374
            ret = -1;
    }

    /* Finally, if no error until here, we can save config. */
    if (!ret && (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG)) {
3375
        ret = virDomainSaveConfig(cfg->configDir, vmdef);
3376 3377 3378 3379 3380 3381
        if (!ret) {
            virDomainObjAssignDef(vm, vmdef, false, NULL);
            vmdef = NULL;
        }
    }

3382
 cleanup:
3383 3384 3385 3386
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3387
    virObjectUnref(cfg);
3388
    return ret;
3389 3390
}

3391 3392 3393 3394 3395
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
3396 3397
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
3398

3399
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
3400
        goto cleanup;
3401

3402
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
3403 3404
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3405
        goto cleanup;
3406 3407
    }

3408 3409
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

3410
 cleanup:
3411 3412
    virObjectUnref(cfg);
    return ret;
3413 3414
}

3415 3416 3417 3418 3419 3420 3421 3422 3423 3424
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;
3425
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3426 3427

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
3428
        goto cleanup;
3429

3430
    numa_info = libxl_get_numainfo(cfg->ctx, &nr_nodes);
3431
    if (numa_info == NULL || nr_nodes == 0) {
3432 3433 3434
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_numainfo failed"));
        goto cleanup;
3435 3436 3437
    }

    /* Check/sanitize the cell range */
3438
    if (startCell >= nr_nodes) {
3439 3440
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("start cell %d out of range (0-%d)"),
3441
                       startCell, nr_nodes - 1);
3442 3443 3444
        goto cleanup;
    }
    lastCell = startCell + maxCells - 1;
3445 3446
    if (lastCell >= nr_nodes)
        lastCell = nr_nodes - 1;
3447 3448 3449 3450 3451 3452 3453

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

3455 3456
    ret = numCells;

3457
 cleanup:
3458
    libxl_numainfo_list_free(numa_info, nr_nodes);
3459
    virObjectUnref(cfg);
3460 3461 3462
    return ret;
}

3463
static int
3464
libxlConnectDomainEventRegister(virConnectPtr conn,
3465 3466
                                virConnectDomainEventCallback callback,
                                void *opaque,
3467
                                virFreeCallback freecb)
3468 3469 3470
{
    libxlDriverPrivatePtr driver = conn->privateData;

3471 3472 3473
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

3474 3475 3476 3477
    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        return -1;
3478

3479
    return 0;
3480 3481 3482 3483
}


static int
3484 3485
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
3486 3487 3488
{
    libxlDriverPrivatePtr driver = conn->privateData;

3489 3490 3491
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

3492 3493 3494 3495
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
3496

3497
    return 0;
3498 3499
}

3500 3501 3502 3503 3504 3505
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
3506
    if (!(vm = libxlDomObjFromDomain(dom)))
3507 3508
        goto cleanup;

3509 3510 3511
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3512 3513 3514
    *autostart = vm->autostart;
    ret = 0;

3515
 cleanup:
3516
    if (vm)
3517
        virObjectUnlock(vm);
3518 3519 3520 3521 3522 3523 3524
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3525
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3526 3527 3528 3529
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

J
Jim Fehlig 已提交
3530
    if (!(vm = libxlDomObjFromDomain(dom)))
3531 3532
        goto cleanup;

3533 3534 3535
    if (virDomainSetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

3539
    if (!vm->persistent) {
3540 3541
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
3542
        goto endjob;
3543 3544 3545 3546 3547
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
3548
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
3549
            goto endjob;
3550
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
3551
            goto endjob;
3552 3553

        if (autostart) {
3554
            if (virFileMakePath(cfg->autostartDir) < 0) {
3555
                virReportSystemError(errno,
3556
                                     _("cannot create autostart directory %s"),
3557
                                     cfg->autostartDir);
3558
                goto endjob;
3559 3560 3561 3562 3563 3564
            }

            if (symlink(configFile, autostartLink) < 0) {
                virReportSystemError(errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
3565
                goto endjob;
3566 3567 3568 3569 3570 3571
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                virReportSystemError(errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
3572
                goto endjob;
3573 3574 3575 3576 3577 3578 3579
            }
        }

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

3580
 endjob:
3581 3582 3583
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3584
 cleanup:
3585 3586 3587
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    if (vm)
3588
        virObjectUnlock(vm);
3589
    virObjectUnref(cfg);
3590 3591 3592
    return ret;
}

3593 3594 3595 3596 3597 3598
static char *
libxlDomainGetSchedulerType(virDomainPtr dom, int *nparams)
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
    char * ret = NULL;
3599
    const char *name = NULL;
J
Jim Fehlig 已提交
3600
    libxl_scheduler sched_id;
3601

J
Jim Fehlig 已提交
3602
    if (!(vm = libxlDomObjFromDomain(dom)))
3603 3604
        goto cleanup;

3605 3606 3607
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3608
    if (!virDomainObjIsActive(vm)) {
3609
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3610 3611 3612 3613
        goto cleanup;
    }

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

3616 3617
    if (nparams)
        *nparams = 0;
3618
    switch (sched_id) {
J
Jim Fehlig 已提交
3619
    case LIBXL_SCHEDULER_SEDF:
3620
        name = "sedf";
3621
        break;
J
Jim Fehlig 已提交
3622
    case LIBXL_SCHEDULER_CREDIT:
3623
        name = "credit";
3624 3625
        if (nparams)
            *nparams = XEN_SCHED_CREDIT_NPARAM;
3626
        break;
J
Jim Fehlig 已提交
3627
    case LIBXL_SCHEDULER_CREDIT2:
3628
        name = "credit2";
3629
        break;
J
Jim Fehlig 已提交
3630
    case LIBXL_SCHEDULER_ARINC653:
3631
        name = "arinc653";
3632 3633
        break;
    default:
J
Jim Fehlig 已提交
3634 3635
        virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Failed to get scheduler id for domain '%d'"
3636
                     " with libxenlight"), vm->def->id);
3637 3638 3639
        goto cleanup;
    }

3640
    ignore_value(VIR_STRDUP(ret, name));
3641

3642
 cleanup:
3643
    if (vm)
3644
        virObjectUnlock(vm);
3645 3646 3647
    return ret;
}

3648
static int
3649 3650 3651 3652
libxlDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams,
                                       unsigned int flags)
3653 3654 3655
{
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3656 3657
    libxl_domain_sched_params sc_info;
    libxl_scheduler sched_id;
3658 3659
    int ret = -1;

3660 3661 3662 3663
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

J
Jim Fehlig 已提交
3665
    if (!(vm = libxlDomObjFromDomain(dom)))
3666 3667
        goto cleanup;

3668 3669 3670
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3671
    if (!virDomainObjIsActive(vm)) {
J
Jim Fehlig 已提交
3672 3673
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Domain is not running"));
3674 3675 3676 3677 3678
        goto cleanup;
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
3681
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3682 3683
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3684 3685 3686
        goto cleanup;
    }

3687
    if (libxl_domain_sched_params_get(priv->ctx, vm->def->id, &sc_info) != 0) {
3688 3689
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
3690
                         " with libxenlight"), vm->def->id);
3691 3692 3693
        goto cleanup;
    }

3694 3695
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
3696 3697
        goto cleanup;

3698
    if (*nparams > 1) {
3699 3700
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
3701
            goto cleanup;
3702 3703
    }

3704 3705
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
3706 3707
    ret = 0;

3708
 cleanup:
3709
    if (vm)
3710
        virObjectUnlock(vm);
3711 3712 3713 3714
    return ret;
}

static int
3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725
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)
3726
{
3727
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3728 3729
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3730
    libxl_domain_sched_params sc_info;
3731
    int sched_id;
3732
    size_t i;
3733 3734
    int ret = -1;

3735
    virCheckFlags(0, -1);
3736 3737 3738 3739 3740 3741
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
3742
        return -1;
3743

J
Jim Fehlig 已提交
3744
    if (!(vm = libxlDomObjFromDomain(dom)))
3745 3746
        goto cleanup;

3747 3748 3749
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3753
    if (!virDomainObjIsActive(vm)) {
3754
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3755
        goto endjob;
3756 3757 3758 3759
    }

    priv = vm->privateData;

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

J
Jim Fehlig 已提交
3762
    if (sched_id != LIBXL_SCHEDULER_CREDIT) {
3763 3764
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Only 'credit' scheduler is supported"));
3765
        goto endjob;
3766 3767
    }

3768
    if (libxl_domain_sched_params_get(priv->ctx, vm->def->id, &sc_info) != 0) {
3769 3770
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
3771
                         " with libxenlight"), vm->def->id);
3772
        goto endjob;
3773 3774 3775
    }

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

3778
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
3779
            sc_info.weight = params[i].value.ui;
3780
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
3781 3782 3783
            sc_info.cap = params[i].value.ui;
    }

3784
    if (libxl_domain_sched_params_set(priv->ctx, vm->def->id, &sc_info) != 0) {
3785 3786
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
3787
                         " with libxenlight"), vm->def->id);
3788
        goto endjob;
3789 3790 3791 3792
    }

    ret = 0;

3793
 endjob:
3794 3795 3796
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3797
 cleanup:
3798
    if (vm)
3799
        virObjectUnlock(vm);
3800 3801 3802
    return ret;
}

B
Bamvor Jian Zhang 已提交
3803 3804 3805 3806 3807 3808 3809 3810 3811

static int
libxlDomainOpenConsole(virDomainPtr dom,
                       const char *dev_name,
                       virStreamPtr st,
                       unsigned int flags)
{
    virDomainObjPtr vm = NULL;
    int ret = -1;
I
Ian Campbell 已提交
3812
    libxl_console_type console_type;
B
Bamvor Jian Zhang 已提交
3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
    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 已提交
3826
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839
        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;

I
Ian Campbell 已提交
3840 3841
    if (vm->def->nconsoles)
        chr = vm->def->consoles[0];
B
Bamvor Jian Zhang 已提交
3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856

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

I
Ian Campbell 已提交
3857 3858 3859 3860 3861 3862
    console_type =
        (chr->targetType == VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_SERIAL ?
                            LIBXL_CONSOLE_TYPE_SERIAL : LIBXL_CONSOLE_TYPE_PV);

    ret = libxl_console_get_tty(priv->ctx, vm->def->id, chr->target.port,
                                console_type, &console);
B
Bamvor Jian Zhang 已提交
3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880
    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;
    }

3881
 cleanup:
B
Bamvor Jian Zhang 已提交
3882 3883 3884 3885 3886 3887
    VIR_FREE(console);
    if (vm)
        virObjectUnlock(vm);
    return ret;
}

3888 3889 3890 3891 3892 3893 3894
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924
/* 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;

3925 3926
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
3927
    if (!(vm = libxlDomObjFromDomain(dom)))
3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948
        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];
3949
        int numnodes;
3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967

        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 */
3968 3969 3970 3971
            numnodes = libxl_get_max_nodes(priv->ctx);
            if (numnodes <= 0)
                goto cleanup;

3972
            if (libxl_node_bitmap_alloc(priv->ctx, &nodemap, 0) ||
3973
                !(nodes = virBitmapNew(numnodes))) {
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015
                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;

4016
 cleanup:
4017 4018 4019 4020 4021 4022 4023 4024 4025
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
    if (vm)
        virObjectUnlock(vm);
    return ret;
}
#endif

J
Jim Fehlig 已提交
4026 4027 4028 4029 4030 4031
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4032
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4033
        goto cleanup;
4034 4035 4036 4037

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

J
Jim Fehlig 已提交
4038 4039
    ret = virDomainObjIsActive(obj);

4040
 cleanup:
J
Jim Fehlig 已提交
4041
    if (obj)
4042
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4043 4044 4045 4046 4047 4048 4049 4050 4051
    return ret;
}

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

J
Jim Fehlig 已提交
4052
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4053
        goto cleanup;
4054 4055 4056 4057

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

J
Jim Fehlig 已提交
4058 4059
    ret = obj->persistent;

4060
 cleanup:
J
Jim Fehlig 已提交
4061
    if (obj)
4062
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4063 4064 4065
    return ret;
}

4066 4067 4068 4069 4070 4071
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4072
    if (!(vm = libxlDomObjFromDomain(dom)))
4073
        goto cleanup;
4074 4075 4076 4077

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

4078 4079
    ret = vm->updated;

4080
 cleanup:
4081
    if (vm)
4082
        virObjectUnlock(vm);
4083 4084 4085
    return ret;
}

4086
static int
4087 4088 4089
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4090 4091 4092 4093
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4094 4095 4096
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4097 4098 4099 4100
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4101
        ret = -1;
4102 4103 4104 4105 4106 4107

    return ret;
}


static int
4108
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4109 4110 4111
{
    libxlDriverPrivatePtr driver = conn->privateData;

4112 4113 4114
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4115 4116 4117 4118
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        return -1;
4119

4120
    return 0;
4121 4122
}

J
Jim Fehlig 已提交
4123

4124
static int
4125
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4126 4127 4128 4129
{
    return 1;
}

4130
static int
4131 4132 4133
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4134 4135 4136 4137
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4138
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4139

4140 4141 4142
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4143 4144
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
4145 4146 4147 4148

    return ret;
}

4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162
/* 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;
    }
}
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
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 已提交
4189
        return -1;
4190 4191
    }

C
Chunyan Liu 已提交
4192
    return 0;
4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 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
}

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;
4241
 cleanup:
4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283
    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 已提交
4284
        goto cleanup;
4285 4286

    ret = 0;
C
Chunyan Liu 已提交
4287

4288
 cleanup:
C
Chunyan Liu 已提交
4289
    virPCIDeviceFree(pci);
4290 4291 4292 4293 4294 4295 4296 4297
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
C
Chunyan Liu 已提交
4298
    virPCIDevicePtr pci = NULL;
4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324
    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 已提交
4325
        goto cleanup;
4326 4327

    ret = 0;
C
Chunyan Liu 已提交
4328

4329
 cleanup:
C
Chunyan Liu 已提交
4330
    virPCIDeviceFree(pci);
4331 4332 4333 4334 4335
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

4336

J
Jim Fehlig 已提交
4337
static virDriver libxlDriver = {
4338
    .no = VIR_DRV_LIBXL,
4339
    .name = LIBXL_DRIVER_NAME,
4340 4341 4342 4343
    .connectOpen = libxlConnectOpen, /* 0.9.0 */
    .connectClose = libxlConnectClose, /* 0.9.0 */
    .connectGetType = libxlConnectGetType, /* 0.9.0 */
    .connectGetVersion = libxlConnectGetVersion, /* 0.9.0 */
4344
    .connectGetHostname = libxlConnectGetHostname, /* 0.9.0 */
4345
    .connectGetSysinfo = libxlConnectGetSysinfo, /* 1.1.0 */
4346
    .connectGetMaxVcpus = libxlConnectGetMaxVcpus, /* 0.9.0 */
4347
    .nodeGetInfo = libxlNodeGetInfo, /* 0.9.0 */
4348 4349 4350 4351
    .connectGetCapabilities = libxlConnectGetCapabilities, /* 0.9.0 */
    .connectListDomains = libxlConnectListDomains, /* 0.9.0 */
    .connectNumOfDomains = libxlConnectNumOfDomains, /* 0.9.0 */
    .connectListAllDomains = libxlConnectListAllDomains, /* 0.9.13 */
4352 4353 4354 4355 4356 4357 4358
    .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 */
4359
    .domainShutdownFlags = libxlDomainShutdownFlags, /* 0.9.10 */
4360 4361
    .domainReboot = libxlDomainReboot, /* 0.9.0 */
    .domainDestroy = libxlDomainDestroy, /* 0.9.0 */
4362
    .domainDestroyFlags = libxlDomainDestroyFlags, /* 0.9.4 */
4363 4364
    .domainGetOSType = libxlDomainGetOSType, /* 0.9.0 */
    .domainGetMaxMemory = libxlDomainGetMaxMemory, /* 0.9.0 */
4365
    .domainSetMaxMemory = libxlDomainSetMaxMemory, /* 0.9.2 */
4366 4367 4368 4369
    .domainSetMemory = libxlDomainSetMemory, /* 0.9.0 */
    .domainSetMemoryFlags = libxlDomainSetMemoryFlags, /* 0.9.0 */
    .domainGetInfo = libxlDomainGetInfo, /* 0.9.0 */
    .domainGetState = libxlDomainGetState, /* 0.9.2 */
4370
    .domainSave = libxlDomainSave, /* 0.9.2 */
4371
    .domainSaveFlags = libxlDomainSaveFlags, /* 0.9.4 */
4372
    .domainRestore = libxlDomainRestore, /* 0.9.2 */
4373
    .domainRestoreFlags = libxlDomainRestoreFlags, /* 0.9.4 */
4374
    .domainCoreDump = libxlDomainCoreDump, /* 0.9.2 */
4375 4376 4377 4378
    .domainSetVcpus = libxlDomainSetVcpus, /* 0.9.0 */
    .domainSetVcpusFlags = libxlDomainSetVcpusFlags, /* 0.9.0 */
    .domainGetVcpusFlags = libxlDomainGetVcpusFlags, /* 0.9.0 */
    .domainPinVcpu = libxlDomainPinVcpu, /* 0.9.0 */
4379
    .domainPinVcpuFlags = libxlDomainPinVcpuFlags, /* 1.2.1 */
4380
    .domainGetVcpus = libxlDomainGetVcpus, /* 0.9.0 */
4381
    .domainGetVcpuPinInfo = libxlDomainGetVcpuPinInfo, /* 1.2.1 */
4382
    .domainGetXMLDesc = libxlDomainGetXMLDesc, /* 0.9.0 */
4383 4384 4385 4386
    .connectDomainXMLFromNative = libxlConnectDomainXMLFromNative, /* 0.9.0 */
    .connectDomainXMLToNative = libxlConnectDomainXMLToNative, /* 0.9.0 */
    .connectListDefinedDomains = libxlConnectListDefinedDomains, /* 0.9.0 */
    .connectNumOfDefinedDomains = libxlConnectNumOfDefinedDomains, /* 0.9.0 */
4387 4388 4389 4390
    .domainCreate = libxlDomainCreate, /* 0.9.0 */
    .domainCreateWithFlags = libxlDomainCreateWithFlags, /* 0.9.0 */
    .domainDefineXML = libxlDomainDefineXML, /* 0.9.0 */
    .domainUndefine = libxlDomainUndefine, /* 0.9.0 */
4391
    .domainUndefineFlags = libxlDomainUndefineFlags, /* 0.9.4 */
4392 4393 4394 4395 4396
    .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 */
4397 4398 4399 4400
    .domainGetAutostart = libxlDomainGetAutostart, /* 0.9.0 */
    .domainSetAutostart = libxlDomainSetAutostart, /* 0.9.0 */
    .domainGetSchedulerType = libxlDomainGetSchedulerType, /* 0.9.0 */
    .domainGetSchedulerParameters = libxlDomainGetSchedulerParameters, /* 0.9.0 */
4401
    .domainGetSchedulerParametersFlags = libxlDomainGetSchedulerParametersFlags, /* 0.9.2 */
4402
    .domainSetSchedulerParameters = libxlDomainSetSchedulerParameters, /* 0.9.0 */
4403
    .domainSetSchedulerParametersFlags = libxlDomainSetSchedulerParametersFlags, /* 0.9.2 */
4404 4405 4406
#ifdef LIBXL_HAVE_DOMAIN_NODEAFFINITY
    .domainGetNumaParameters = libxlDomainGetNumaParameters, /* 1.1.1 */
#endif
4407
    .nodeGetFreeMemory = libxlNodeGetFreeMemory, /* 0.9.0 */
4408
    .nodeGetCellsFreeMemory = libxlNodeGetCellsFreeMemory, /* 1.1.1 */
4409 4410
    .connectDomainEventRegister = libxlConnectDomainEventRegister, /* 0.9.0 */
    .connectDomainEventDeregister = libxlConnectDomainEventDeregister, /* 0.9.0 */
4411 4412 4413
    .domainManagedSave = libxlDomainManagedSave, /* 0.9.2 */
    .domainHasManagedSaveImage = libxlDomainHasManagedSaveImage, /* 0.9.2 */
    .domainManagedSaveRemove = libxlDomainManagedSaveRemove, /* 0.9.2 */
B
Bamvor Jian Zhang 已提交
4414
    .domainOpenConsole = libxlDomainOpenConsole, /* 1.1.2 */
4415 4416 4417
    .domainIsActive = libxlDomainIsActive, /* 0.9.0 */
    .domainIsPersistent = libxlDomainIsPersistent, /* 0.9.0 */
    .domainIsUpdated = libxlDomainIsUpdated, /* 0.9.0 */
4418 4419 4420
    .connectDomainEventRegisterAny = libxlConnectDomainEventRegisterAny, /* 0.9.0 */
    .connectDomainEventDeregisterAny = libxlConnectDomainEventDeregisterAny, /* 0.9.0 */
    .connectIsAlive = libxlConnectIsAlive, /* 0.9.8 */
4421
    .connectSupportsFeature = libxlConnectSupportsFeature, /* 1.1.1 */
4422 4423 4424 4425
    .nodeDeviceDettach = libxlNodeDeviceDettach, /* 1.2.3 */
    .nodeDeviceDetachFlags = libxlNodeDeviceDetachFlags, /* 1.2.3 */
    .nodeDeviceReAttach = libxlNodeDeviceReAttach, /* 1.2.3 */
    .nodeDeviceReset = libxlNodeDeviceReset, /* 1.2.3 */
J
Jim Fehlig 已提交
4426 4427 4428 4429
};

static virStateDriver libxlStateDriver = {
    .name = "LIBXL",
4430
    .stateInitialize = libxlStateInitialize,
4431
    .stateAutoStart = libxlStateAutoStart,
4432 4433
    .stateCleanup = libxlStateCleanup,
    .stateReload = libxlStateReload,
J
Jim Fehlig 已提交
4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446
};


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

    return 0;
}