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

#include <config.h>

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

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

#define VIR_FROM_THIS VIR_FROM_LIBXL

60 61
VIR_LOG_INIT("libxl.libxl_driver");

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

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

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

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

76

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

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

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

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

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

    return vm;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
}

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

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

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

        return ret;
    }

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

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

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

    if (!libxlDriverShouldLoad(privileged))
        return 0;

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

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

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

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

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

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

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

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

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

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

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

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

    libxlReconnectDomains(libxl_driver);

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

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

J
Jim Fehlig 已提交
383 384
    return 0;

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

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

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

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

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

408 409
    cfg = libxlDriverConfigGet(libxl_driver);

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

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

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


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

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

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

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

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

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

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

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

    return VIR_DRV_OPEN_SUCCESS;
};

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

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

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

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

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

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

507

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

513 514 515
    return virGetHostname();
}

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

    virCheckFlags(0, NULL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return n;
}

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

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

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

    return n;
}

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

    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

    ret = 0;

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

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


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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

    ret = 0;

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

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

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

871 872
    virCheckFlags(0, -1);

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

957 958
    virCheckFlags(0, -1);

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

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

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

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

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

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

    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1160 1161
    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

    virCheckFlags(0, -1);

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

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

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

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

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

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

    if ((fd = virFileOpenAs(to, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR,
L
Laine Stump 已提交
1274
                            -1, -1, 0)) < 0) {
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
        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)) {
1290 1291
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to write save file header"));
1292 1293 1294 1295
        goto cleanup;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ret = 0;
1373

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

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

1388
static int
1389 1390 1391 1392 1393 1394 1395 1396
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)
1397 1398
{
    libxlDriverPrivatePtr driver = conn->privateData;
1399
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1400 1401 1402 1403 1404
    virDomainObjPtr vm = NULL;
    virDomainDefPtr def = NULL;
    libxlSavefileHeader hdr;
    int fd = -1;
    int ret = -1;
1405

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

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

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

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

    def = NULL;

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

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

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

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

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

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

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

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

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

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

    priv = vm->privateData;

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

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

    if (flags & VIR_DUMP_CRASH) {
J
Jim Fehlig 已提交
1510
        if (libxl_domain_destroy(priv->ctx, dom->id, NULL) < 0) {
1511 1512
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to destroy domain '%d'"), dom->id);
1513
            goto unpause;
1514 1515
        }

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

    ret = 0;

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

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

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

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

    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

    ret = 0;
1596

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

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

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

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

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

    vm->hasManagedSave = virFileExists(name);

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

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

    virCheckFlags(0, -1);

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

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

1648
    ret = vm->hasManagedSave;
1649

1650
 cleanup:
1651
    if (vm)
1652
        virObjectUnlock(vm);
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
    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 已提交
1666
    if (!(vm = libxlDomObjFromDomain(dom)))
1667 1668
        goto cleanup;

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

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

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

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

1686 1687 1688 1689 1690
static int
libxlDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
1691
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1692 1693 1694
    libxlDomainObjPrivatePtr priv;
    virDomainDefPtr def;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
1695
    libxl_bitmap map;
1696 1697
    uint8_t *bitmask = NULL;
    unsigned int maplen;
1698 1699
    size_t i;
    unsigned int pos;
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
    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)) {
1712 1713
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
1714 1715 1716 1717
        return -1;
    }

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

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

    ret = 0;

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

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

1817
 cleanup:
1818 1819
    VIR_FREE(bitmask);
     if (vm)
1820
        virObjectUnlock(vm);
1821
     virObjectUnref(cfg);
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
    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;
1837
    bool active;
1838 1839 1840 1841 1842

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

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

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

1849 1850 1851 1852 1853 1854 1855 1856 1857
    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)) {
1858 1859
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
1860 1861 1862
        return -1;
    }

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

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

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

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

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
1901

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

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

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

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

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

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

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

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

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

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

1945 1946 1947 1948 1949 1950
    /* full bitmap means reset the settings (if any). */
    if (virBitmapIsAllSet(pcpumap)) {
        if (virDomainVcpuPinDel(targetDef, vcpu) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to delete vcpupin xml for vcpu '%d'"),
                           vcpu);
1951
            goto endjob;
1952
        }
1953
        goto done;
1954 1955
    }

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

1971
 done:
1972 1973
    ret = 0;

1974 1975 1976 1977 1978 1979
    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);
    }

1980
 endjob:
1981 1982 1983
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

1984
 cleanup:
1985
    if (vm)
1986
        virObjectUnlock(vm);
1987
    virBitmapFree(pcpumap);
1988
    virObjectUnref(cfg);
1989 1990 1991
    return ret;
}

1992 1993 1994 1995 1996 1997 1998 1999
static int
libxlDomainPinVcpu(virDomainPtr dom, unsigned int vcpu, unsigned char *cpumap,
                   int maplen)
{
    return libxlDomainPinVcpuFlags(dom, vcpu, cpumap, maplen,
                                   VIR_DOMAIN_AFFECT_LIVE);
}

2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
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;

2071
 cleanup:
2072 2073 2074 2075 2076
    if (vm)
        virObjectUnlock(vm);
    virObjectUnref(cfg);
    return ret;
}
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086

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;
2087
    size_t i;
2088 2089
    unsigned char *cpumap;

J
Jim Fehlig 已提交
2090
    if (!(vm = libxlDomObjFromDomain(dom)))
2091 2092
        goto cleanup;

2093 2094 2095
    if (virDomainGetVcpusEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

2096
    if (!virDomainObjIsActive(vm)) {
2097
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
2098 2099 2100 2101
        goto cleanup;
    }

    priv = vm->privateData;
J
Jim Fehlig 已提交
2102
    if ((vcpuinfo = libxl_list_vcpu(priv->ctx, dom->id, &maxcpu,
2103
                                    &hostcpus)) == NULL) {
2104 2105 2106
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to list vcpus for domain '%d' with libxenlight"),
                       dom->id);
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
        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 已提交
2129
        libxl_vcpuinfo_dispose(&vcpuinfo[i]);
2130 2131 2132 2133 2134
    }
    VIR_FREE(vcpuinfo);

    ret = maxinfo;

2135
 cleanup:
2136
    if (vm)
2137
        virObjectUnlock(vm);
2138 2139 2140
    return ret;
}

J
Jim Fehlig 已提交
2141
static char *
2142
libxlDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
J
Jim Fehlig 已提交
2143 2144 2145 2146
{
    virDomainObjPtr vm;
    char *ret = NULL;

2147 2148
    /* Flags checked by virDomainDefFormat */

J
Jim Fehlig 已提交
2149
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2150 2151
        goto cleanup;

2152 2153 2154
    if (virDomainGetXMLDescEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

2157
 cleanup:
J
Jim Fehlig 已提交
2158
    if (vm)
2159
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2160 2161 2162
    return ret;
}

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

E
Eric Blake 已提交
2175 2176
    virCheckFlags(0, NULL);

2177 2178 2179
    if (virConnectDomainXMLFromNativeEnsureACL(conn) < 0)
        goto cleanup;

2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
    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 {
2202 2203
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2204 2205 2206 2207 2208
        goto cleanup;
    }

    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);

2209
 cleanup:
2210 2211 2212
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2213
    virObjectUnref(cfg);
2214 2215 2216 2217 2218
    return xml;
}

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

E
Eric Blake 已提交
2230 2231
    virCheckFlags(0, NULL);

2232 2233 2234
    if (virConnectDomainXMLToNativeEnsureACL(conn) < 0)
        goto cleanup;

2235
    if (STRNEQ(nativeFormat, LIBXL_CONFIG_FORMAT_XM)) {
2236 2237
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), nativeFormat);
2238 2239 2240
        goto cleanup;
    }

2241
    if (!(def = virDomainDefParseString(domainXml,
2242
                                        cfg->caps, driver->xmlopt,
2243 2244
                                        1 << VIR_DOMAIN_VIRT_XEN,
                                        VIR_DOMAIN_XML_INACTIVE)))
2245 2246
        goto cleanup;

2247
    if (!(conf = xenFormatXM(conn, def, cfg->verInfo->xen_version_major)))
2248 2249
        goto cleanup;

2250
    if (VIR_ALLOC_N(ret, len) < 0)
2251 2252 2253 2254 2255 2256 2257
        goto cleanup;

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

2258
 cleanup:
2259 2260 2261
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
2262
    virObjectUnref(cfg);
2263 2264 2265
    return ret;
}

J
Jim Fehlig 已提交
2266
static int
2267 2268
libxlConnectListDefinedDomains(virConnectPtr conn,
                               char **const names, int nnames)
J
Jim Fehlig 已提交
2269 2270 2271 2272
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2273 2274 2275
    if (virConnectListDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2276 2277
    n = virDomainObjListGetInactiveNames(driver->domains, names, nnames,
                                         virConnectListDefinedDomainsCheckACL, conn);
J
Jim Fehlig 已提交
2278 2279 2280 2281
    return n;
}

static int
2282
libxlConnectNumOfDefinedDomains(virConnectPtr conn)
J
Jim Fehlig 已提交
2283 2284 2285 2286
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int n;

2287 2288 2289
    if (virConnectNumOfDefinedDomainsEnsureACL(conn) < 0)
        return -1;

2290
    n = virDomainObjListNumOfDomains(driver->domains, false,
2291 2292
                                     virConnectNumOfDefinedDomainsCheckACL,
                                     conn);
J
Jim Fehlig 已提交
2293 2294 2295 2296 2297
    return n;
}

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

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

J
Jim Fehlig 已提交
2306
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2307 2308
        goto cleanup;

2309 2310 2311
    if (virDomainCreateWithFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

J
Jim Fehlig 已提交
2312
    if (virDomainObjIsActive(vm)) {
2313 2314
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("Domain is already running"));
J
Jim Fehlig 已提交
2315 2316 2317
        goto cleanup;
    }

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

2320
 cleanup:
J
Jim Fehlig 已提交
2321
    if (vm)
2322
        virObjectUnlock(vm);
J
Jim Fehlig 已提交
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
    return ret;
}

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

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

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

2350
    if (virDomainDefineXMLEnsureACL(conn, def) < 0)
2351
        goto cleanup_unlock;
2352

2353
    if (!(vm = virDomainObjListAdd(driver->domains, def,
2354
                                   driver->xmlopt,
2355 2356
                                   0,
                                   &oldDef)))
2357 2358
        goto cleanup_unlock;

J
Jim Fehlig 已提交
2359 2360
    def = NULL;
    vm->persistent = 1;
2361
    libxlDriverUnlock(driver);
J
Jim Fehlig 已提交
2362

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

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

2374
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_DEFINED,
2375
                                     !oldDef ?
2376 2377 2378
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);

2379
 cleanup:
J
Jim Fehlig 已提交
2380
    virDomainDefFree(def);
2381
    virDomainDefFree(oldDef);
J
Jim Fehlig 已提交
2382
    if (vm)
2383
        virObjectUnlock(vm);
2384 2385
    if (event)
        libxlDomainEventQueue(driver, event);
2386
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2387
    return dom;
2388

2389
 cleanup_unlock:
2390 2391
    libxlDriverUnlock(driver);
    goto cleanup;
J
Jim Fehlig 已提交
2392 2393 2394
}

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

2405 2406
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

J
Jim Fehlig 已提交
2407
    if (!(vm = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
2408 2409
        goto cleanup;

2410 2411 2412
    if (virDomainUndefineFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

2419 2420 2421 2422 2423 2424 2425
    name = libxlDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

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

2438
    if (virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm) < 0)
J
Jim Fehlig 已提交
2439 2440
        goto cleanup;

2441
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_UNDEFINED,
2442 2443
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);

2444 2445 2446
    if (virDomainObjIsActive(vm)) {
        vm->persistent = 0;
    } else {
2447
        virDomainObjListRemove(driver->domains, vm);
2448 2449 2450
        vm = NULL;
    }

J
Jim Fehlig 已提交
2451 2452
    ret = 0;

2453
 cleanup:
2454
    VIR_FREE(name);
J
Jim Fehlig 已提交
2455
    if (vm)
2456
        virObjectUnlock(vm);
2457 2458
    if (event)
        libxlDomainEventQueue(driver, event);
2459
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
2460 2461 2462
    return ret;
}

2463 2464 2465 2466 2467 2468
static int
libxlDomainUndefine(virDomainPtr dom)
{
    return libxlDomainUndefineFlags(dom, 0);
}

2469 2470 2471 2472 2473 2474
static int
libxlDomainChangeEjectableMedia(libxlDomainObjPrivatePtr priv,
                                virDomainObjPtr vm, virDomainDiskDefPtr disk)
{
    virDomainDiskDefPtr origdisk = NULL;
    libxl_device_disk x_disk;
2475
    size_t i;
2476 2477
    int ret = -1;

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

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

    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
2494 2495 2496
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Removable media not supported for %s device"),
                       virDomainDiskDeviceTypeToString(disk->device));
2497 2498 2499
        return -1;
    }

J
Jim Fehlig 已提交
2500
    if (libxlMakeDisk(disk, &x_disk) < 0)
2501 2502
        goto cleanup;

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

2510 2511 2512
    if (virDomainDiskSetSource(origdisk, virDomainDiskGetSource(disk)) < 0)
        goto cleanup;
    virDomainDiskSetType(origdisk, virDomainDiskGetType(disk));
2513 2514 2515 2516 2517

    virDomainDiskDefFree(disk);

    ret = 0;

2518
 cleanup:
2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
    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) {
2536
                if (virDomainDiskIndexByName(vm->def, l_disk->dst, true) >= 0) {
2537 2538
                    virReportError(VIR_ERR_OPERATION_FAILED,
                                   _("target %s already exists"), l_disk->dst);
2539 2540 2541
                    goto cleanup;
                }

2542
                if (!virDomainDiskGetSource(l_disk)) {
2543 2544
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("disk source path is missing"));
2545 2546 2547
                    goto cleanup;
                }

2548
                if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0)
2549 2550
                    goto cleanup;

J
Jim Fehlig 已提交
2551
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
2552 2553
                    goto cleanup;

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

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

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

2577
 cleanup:
2578 2579 2580
    return ret;
}

2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
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 已提交
2610
        return -1;
2611 2612

    if (libxlMakePci(hostdev, &pcidev) < 0)
C
Chunyan Liu 已提交
2613
        goto error;
2614 2615 2616 2617 2618 2619 2620 2621

    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 已提交
2622
        goto error;
2623 2624 2625 2626 2627
    }

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

2628
 error:
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
    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 已提交
2652
            return -1;
2653 2654 2655 2656 2657 2658
        break;

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

    return 0;
}

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

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

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

2686
                l_disk = vm->def->disks[idx];
2687

J
Jim Fehlig 已提交
2688
                if (libxlMakeDisk(l_disk, &x_disk) < 0)
2689 2690
                    goto cleanup;

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

2699
                virDomainDiskRemove(vm->def, idx);
2700 2701 2702
                virDomainDiskDefFree(l_disk);

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

2715
 cleanup:
2716 2717 2718 2719
    return ret;
}

static int
2720 2721 2722
libxlDomainAttachDeviceLive(libxlDriverPrivatePtr driver,
                            libxlDomainObjPrivatePtr priv,
                            virDomainObjPtr vm,
2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
                            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;

2734 2735 2736 2737 2738 2739
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            ret = libxlDomainAttachHostDevice(driver, priv, vm, dev);
            if (!ret)
                dev->data.hostdev = NULL;
            break;

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

    return ret;
}

static int
libxlDomainAttachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr disk;
2754 2755
    virDomainHostdevDefPtr hostdev;
    virDomainHostdevDefPtr found;
2756 2757 2758 2759

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

        default:
2791 2792
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent attach of device is not supported"));
2793 2794 2795 2796 2797 2798
            return -1;
    }
    return 0;
}

static int
2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855
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 已提交
2856
        goto error;
2857 2858 2859 2860 2861 2862
    }


    libxl_device_pci_init(&pcidev);

    if (libxlMakePci(detach, &pcidev) < 0)
C
Chunyan Liu 已提交
2863
        goto error;
2864 2865 2866 2867 2868 2869 2870

    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 已提交
2871
        goto error;
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
    }

    libxl_device_pci_dispose(&pcidev);

    virDomainHostdevRemove(vm->def, idx);

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

    return 0;

2883
 error:
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
    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,
2921 2922 2923 2924 2925 2926 2927 2928 2929
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

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

2930 2931 2932 2933
        case VIR_DOMAIN_DEVICE_HOSTDEV:
            ret = libxlDomainDetachHostDevice(driver, priv, vm, dev);
            break;

2934
        default:
2935 2936 2937
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be detached"),
                           virDomainDeviceTypeToString(dev->type));
2938 2939 2940 2941 2942 2943
            break;
    }

    return ret;
}

2944

2945 2946 2947
static int
libxlDomainDetachDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
2948
    virDomainDiskDefPtr disk, detach;
2949 2950 2951 2952 2953
    int ret = -1;

    switch (dev->type) {
        case VIR_DOMAIN_DEVICE_DISK:
            disk = dev->data.disk;
2954
            if (!(detach = virDomainDiskRemoveByName(vmdef, disk->dst))) {
2955 2956
                virReportError(VIR_ERR_INVALID_ARG,
                               _("no target device %s"), disk->dst);
2957 2958
                break;
            }
2959
            virDomainDiskDefFree(detach);
2960 2961 2962
            ret = 0;
            break;
        default:
2963 2964
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("persistent detach of device is not supported"));
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
            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:
2988 2989 2990
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("disk bus '%s' cannot be updated."),
                                   virDomainDiskBusTypeToString(disk->bus));
2991 2992 2993 2994
                    break;
            }
            break;
        default:
2995 2996 2997
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("device type '%s' cannot be updated"),
                           virDomainDeviceTypeToString(dev->type));
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
            break;
    }

    return ret;
}

static int
libxlDomainUpdateDeviceConfig(virDomainDefPtr vmdef, virDomainDeviceDefPtr dev)
{
    virDomainDiskDefPtr orig;
    virDomainDiskDefPtr disk;
3009
    int idx;
3010 3011 3012 3013 3014
    int ret = -1;

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

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

    ret = 0;

3042
 cleanup:
3043 3044 3045 3046 3047
    return ret;
}


static int
3048 3049
libxlDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                             unsigned int flags)
3050 3051
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3052
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3053 3054 3055 3056 3057 3058 3059 3060 3061
    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 已提交
3062
    if (!(vm = libxlDomObjFromDomain(dom)))
3063 3064
        goto cleanup;

3065 3066 3067
    if (virDomainAttachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3071 3072 3073 3074 3075 3076 3077 3078
    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) {
3079 3080
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("Domain is not running"));
3081
            goto endjob;
3082 3083 3084 3085
        }
    }

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

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
3094
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3095
                                            cfg->caps, driver->xmlopt,
3096
                                            VIR_DOMAIN_XML_INACTIVE)))
3097
            goto endjob;
3098 3099

        /* Make a copy for updated domain. */
3100
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3101
                                                    driver->xmlopt)))
3102
            goto endjob;
3103

3104
        if ((ret = libxlDomainAttachDeviceConfig(vmdef, dev)) < 0)
3105
            goto endjob;
3106
    } else {
3107
        ret = 0;
3108
    }
3109 3110 3111 3112

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

3118
        if ((ret = libxlDomainAttachDeviceLive(driver, priv, vm, dev)) < 0)
3119
            goto endjob;
3120

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

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

3138
 endjob:
3139 3140 3141
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3142
 cleanup:
3143 3144 3145
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
3146
        virObjectUnlock(vm);
3147
    virObjectUnref(cfg);
3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161
    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)
{
3162
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3163
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3164 3165 3166 3167 3168 3169 3170 3171 3172
    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 已提交
3173
    if (!(vm = libxlDomObjFromDomain(dom)))
3174 3175
        goto cleanup;

3176 3177 3178
    if (virDomainDetachDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
    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"));
3192
            goto endjob;
3193 3194 3195 3196 3197 3198
        }
    }

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

    priv = vm->privateData;

    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        if (!(dev = virDomainDeviceDefParse(xml, vm->def,
3206
                                            cfg->caps, driver->xmlopt,
3207
                                            VIR_DOMAIN_XML_INACTIVE)))
3208
            goto endjob;
3209 3210

        /* Make a copy for updated domain. */
3211
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3212
                                                    driver->xmlopt)))
3213
            goto endjob;
3214 3215

        if ((ret = libxlDomainDetachDeviceConfig(vmdef, dev)) < 0)
3216
            goto endjob;
3217 3218 3219 3220 3221 3222 3223 3224
    } 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,
3225
                                            cfg->caps, driver->xmlopt,
3226
                                            VIR_DOMAIN_XML_INACTIVE)))
3227
            goto endjob;
3228

3229
        if ((ret = libxlDomainDetachDeviceLive(driver, priv, vm, dev)) < 0)
3230
            goto endjob;
3231 3232 3233 3234 3235

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

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

3249
 endjob:
3250 3251 3252
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

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

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)
{
3273
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3274
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3275 3276 3277 3278 3279 3280 3281 3282 3283
    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 已提交
3284
    if (!(vm = libxlDomObjFromDomain(dom)))
3285 3286
        goto cleanup;

3287 3288 3289
    if (virDomainUpdateDeviceFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
    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,
3314
                                            cfg->caps, driver->xmlopt,
3315 3316 3317 3318
                                            VIR_DOMAIN_XML_INACTIVE)))
            goto cleanup;

        /* Make a copy for updated domain. */
3319
        if (!(vmdef = virDomainObjCopyPersistentDef(vm, cfg->caps,
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
                                                    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,
3333
                                            cfg->caps, driver->xmlopt,
3334 3335 3336 3337 3338 3339 3340 3341 3342 3343
                                            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.
         */
3344
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm) < 0)
3345 3346 3347 3348 3349
            ret = -1;
    }

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

3357
 cleanup:
3358 3359 3360 3361
    virDomainDefFree(vmdef);
    virDomainDeviceDefFree(dev);
    if (vm)
        virObjectUnlock(vm);
3362
    virObjectUnref(cfg);
3363
    return ret;
3364 3365
}

3366 3367 3368 3369 3370
static unsigned long long
libxlNodeGetFreeMemory(virConnectPtr conn)
{
    libxl_physinfo phy_info;
    libxlDriverPrivatePtr driver = conn->privateData;
3371 3372
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    unsigned long long ret = 0;
3373

3374
    if (virNodeGetFreeMemoryEnsureACL(conn) < 0)
3375
        goto cleanup;
3376

3377
    if (libxl_get_physinfo(cfg->ctx, &phy_info)) {
3378 3379
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("libxl_get_physinfo_info failed"));
3380
        goto cleanup;
3381 3382
    }

3383 3384
    ret = phy_info.free_pages * cfg->verInfo->pagesize;

3385
 cleanup:
3386 3387
    virObjectUnref(cfg);
    return ret;
3388 3389
}

3390 3391 3392 3393 3394 3395 3396 3397 3398 3399
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;
3400
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3401 3402

    if (virNodeGetCellsFreeMemoryEnsureACL(conn) < 0)
3403
        goto cleanup;
3404

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

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

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

3430 3431
    ret = numCells;

3432
 cleanup:
3433
    libxl_numainfo_list_free(numa_info, nr_nodes);
3434
    virObjectUnref(cfg);
3435 3436 3437
    return ret;
}

3438
static int
3439
libxlConnectDomainEventRegister(virConnectPtr conn,
3440 3441
                                virConnectDomainEventCallback callback,
                                void *opaque,
3442
                                virFreeCallback freecb)
3443 3444 3445
{
    libxlDriverPrivatePtr driver = conn->privateData;

3446 3447 3448
    if (virConnectDomainEventRegisterEnsureACL(conn) < 0)
        return -1;

3449 3450 3451 3452
    if (virDomainEventStateRegister(conn,
                                    driver->domainEventState,
                                    callback, opaque, freecb) < 0)
        return -1;
3453

3454
    return 0;
3455 3456 3457 3458
}


static int
3459 3460
libxlConnectDomainEventDeregister(virConnectPtr conn,
                                  virConnectDomainEventCallback callback)
3461 3462 3463
{
    libxlDriverPrivatePtr driver = conn->privateData;

3464 3465 3466
    if (virConnectDomainEventDeregisterEnsureACL(conn) < 0)
        return -1;

3467 3468 3469 3470
    if (virDomainEventStateDeregister(conn,
                                      driver->domainEventState,
                                      callback) < 0)
        return -1;
3471

3472
    return 0;
3473 3474
}

3475 3476 3477 3478 3479 3480
static int
libxlDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
3481
    if (!(vm = libxlDomObjFromDomain(dom)))
3482 3483
        goto cleanup;

3484 3485 3486
    if (virDomainGetAutostartEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3487 3488 3489
    *autostart = vm->autostart;
    ret = 0;

3490
 cleanup:
3491
    if (vm)
3492
        virObjectUnlock(vm);
3493 3494 3495 3496 3497 3498 3499
    return ret;
}

static int
libxlDomainSetAutostart(virDomainPtr dom, int autostart)
{
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3500
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
3501 3502 3503 3504
    virDomainObjPtr vm;
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;

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

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

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

3514
    if (!vm->persistent) {
3515 3516
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("cannot set autostart for transient domain"));
3517
        goto endjob;
3518 3519 3520 3521 3522
    }

    autostart = (autostart != 0);

    if (vm->autostart != autostart) {
3523
        if (!(configFile = virDomainConfigFile(cfg->configDir, vm->def->name)))
3524
            goto endjob;
3525
        if (!(autostartLink = virDomainConfigFile(cfg->autostartDir, vm->def->name)))
3526
            goto endjob;
3527 3528

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

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

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

3555
 endjob:
3556 3557 3558
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3559
 cleanup:
3560 3561 3562
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    if (vm)
3563
        virObjectUnlock(vm);
3564
    virObjectUnref(cfg);
3565 3566 3567
    return ret;
}

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

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

3580 3581 3582
    if (virDomainGetSchedulerTypeEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

3583
    if (!virDomainObjIsActive(vm)) {
3584
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3585 3586 3587 3588
        goto cleanup;
    }

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

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

3615
    ignore_value(VIR_STRDUP(ret, name));
3616

3617
 cleanup:
3618
    if (vm)
3619
        virObjectUnlock(vm);
3620 3621 3622
    return ret;
}

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

3635 3636 3637 3638
    virCheckFlags(VIR_TYPED_PARAM_STRING_OKAY, -1);

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

J
Jim Fehlig 已提交
3640
    if (!(vm = libxlDomObjFromDomain(dom)))
3641 3642
        goto cleanup;

3643 3644 3645
    if (virDomainGetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def) < 0)
        goto cleanup;

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

    priv = vm->privateData;

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

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

J
Jim Fehlig 已提交
3662
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
3663 3664 3665
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3666 3667 3668
        goto cleanup;
    }

3669 3670
    if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_WEIGHT,
                                VIR_TYPED_PARAM_UINT, sc_info.weight) < 0)
3671 3672
        goto cleanup;

3673
    if (*nparams > 1) {
3674 3675
        if (virTypedParameterAssign(&params[0], VIR_DOMAIN_SCHEDULER_CAP,
                                    VIR_TYPED_PARAM_UINT, sc_info.cap) < 0)
3676
            goto cleanup;
3677 3678
    }

3679 3680
    if (*nparams > XEN_SCHED_CREDIT_NPARAM)
        *nparams = XEN_SCHED_CREDIT_NPARAM;
3681 3682
    ret = 0;

3683
 cleanup:
3684
    if (vm)
3685
        virObjectUnlock(vm);
3686 3687 3688 3689
    return ret;
}

static int
3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700
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)
3701
{
3702
    libxlDriverPrivatePtr driver = dom->conn->privateData;
3703 3704
    libxlDomainObjPrivatePtr priv;
    virDomainObjPtr vm;
J
Jim Fehlig 已提交
3705
    libxl_domain_sched_params sc_info;
3706
    int sched_id;
3707
    size_t i;
3708 3709
    int ret = -1;

3710
    virCheckFlags(0, -1);
3711 3712 3713 3714 3715 3716
    if (virTypedParamsValidate(params, nparams,
                               VIR_DOMAIN_SCHEDULER_WEIGHT,
                               VIR_TYPED_PARAM_UINT,
                               VIR_DOMAIN_SCHEDULER_CAP,
                               VIR_TYPED_PARAM_UINT,
                               NULL) < 0)
3717
        return -1;
3718

J
Jim Fehlig 已提交
3719
    if (!(vm = libxlDomObjFromDomain(dom)))
3720 3721
        goto cleanup;

3722 3723 3724
    if (virDomainSetSchedulerParametersFlagsEnsureACL(dom->conn, vm->def, flags) < 0)
        goto cleanup;

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

3728
    if (!virDomainObjIsActive(vm)) {
3729
        virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("Domain is not running"));
3730
        goto endjob;
3731 3732 3733 3734
    }

    priv = vm->privateData;

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

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

J
Jim Fehlig 已提交
3743
    if (libxl_domain_sched_params_get(priv->ctx, dom->id, &sc_info) != 0) {
3744 3745 3746
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to get scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3747
        goto endjob;
3748 3749 3750
    }

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

3753
        if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_WEIGHT))
3754
            sc_info.weight = params[i].value.ui;
3755
        else if (STREQ(param->field, VIR_DOMAIN_SCHEDULER_CAP))
3756 3757 3758
            sc_info.cap = params[i].value.ui;
    }

J
Jim Fehlig 已提交
3759
    if (libxl_domain_sched_params_set(priv->ctx, dom->id, &sc_info) != 0) {
3760 3761 3762
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to set scheduler parameters for domain '%d'"
                         " with libxenlight"), dom->id);
3763
        goto endjob;
3764 3765 3766 3767
    }

    ret = 0;

3768
 endjob:
3769 3770 3771
    if (!libxlDomainObjEndJob(driver, vm))
        vm = NULL;

3772
 cleanup:
3773
    if (vm)
3774
        virObjectUnlock(vm);
3775 3776 3777
    return ret;
}

B
Bamvor Jian Zhang 已提交
3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799

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

    virCheckFlags(VIR_DOMAIN_CONSOLE_FORCE, -1);

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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

3850
 cleanup:
B
Bamvor Jian Zhang 已提交
3851 3852 3853 3854 3855 3856
    VIR_FREE(console);
    if (vm)
        virObjectUnlock(vm);
    return ret;
}

3857 3858 3859 3860 3861 3862 3863
static int
libxlDomainSetSchedulerParameters(virDomainPtr dom, virTypedParameterPtr params,
                                  int nparams)
{
    return libxlDomainSetSchedulerParametersFlags(dom, params, nparams, 0);
}

3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893
/* 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;

3894 3895
    libxl_bitmap_init(&nodemap);

J
Jim Fehlig 已提交
3896
    if (!(vm = libxlDomObjFromDomain(dom)))
3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
        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];
3918
        int numnodes;
3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936

        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 */
3937 3938 3939 3940
            numnodes = libxl_get_max_nodes(priv->ctx);
            if (numnodes <= 0)
                goto cleanup;

3941
            if (libxl_node_bitmap_alloc(priv->ctx, &nodemap, 0) ||
3942
                !(nodes = virBitmapNew(numnodes))) {
3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984
                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;

3985
 cleanup:
3986 3987 3988 3989 3990 3991 3992 3993 3994
    VIR_FREE(nodeset);
    virBitmapFree(nodes);
    libxl_bitmap_dispose(&nodemap);
    if (vm)
        virObjectUnlock(vm);
    return ret;
}
#endif

J
Jim Fehlig 已提交
3995 3996 3997 3998 3999 4000
static int
libxlDomainIsActive(virDomainPtr dom)
{
    virDomainObjPtr obj;
    int ret = -1;

J
Jim Fehlig 已提交
4001
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4002
        goto cleanup;
4003 4004 4005 4006

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

J
Jim Fehlig 已提交
4007 4008
    ret = virDomainObjIsActive(obj);

4009
 cleanup:
J
Jim Fehlig 已提交
4010
    if (obj)
4011
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4012 4013 4014 4015 4016 4017 4018 4019 4020
    return ret;
}

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

J
Jim Fehlig 已提交
4021
    if (!(obj = libxlDomObjFromDomain(dom)))
J
Jim Fehlig 已提交
4022
        goto cleanup;
4023 4024 4025 4026

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

J
Jim Fehlig 已提交
4027 4028
    ret = obj->persistent;

4029
 cleanup:
J
Jim Fehlig 已提交
4030
    if (obj)
4031
        virObjectUnlock(obj);
J
Jim Fehlig 已提交
4032 4033 4034
    return ret;
}

4035 4036 4037 4038 4039 4040
static int
libxlDomainIsUpdated(virDomainPtr dom)
{
    virDomainObjPtr vm;
    int ret = -1;

J
Jim Fehlig 已提交
4041
    if (!(vm = libxlDomObjFromDomain(dom)))
4042
        goto cleanup;
4043 4044 4045 4046

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

4047 4048
    ret = vm->updated;

4049
 cleanup:
4050
    if (vm)
4051
        virObjectUnlock(vm);
4052 4053 4054
    return ret;
}

4055
static int
4056 4057 4058
libxlConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID,
                                   virConnectDomainEventGenericCallback callback,
                                   void *opaque, virFreeCallback freecb)
4059 4060 4061 4062
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret;

4063 4064 4065
    if (virConnectDomainEventRegisterAnyEnsureACL(conn) < 0)
        return -1;

4066 4067 4068 4069
    if (virDomainEventStateRegisterID(conn,
                                      driver->domainEventState,
                                      dom, eventID, callback, opaque,
                                      freecb, &ret) < 0)
4070
        ret = -1;
4071 4072 4073 4074 4075 4076

    return ret;
}


static int
4077
libxlConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID)
4078 4079 4080
{
    libxlDriverPrivatePtr driver = conn->privateData;

4081 4082 4083
    if (virConnectDomainEventDeregisterAnyEnsureACL(conn) < 0)
        return -1;

4084 4085 4086 4087
    if (virObjectEventStateDeregisterID(conn,
                                        driver->domainEventState,
                                        callbackID) < 0)
        return -1;
4088

4089
    return 0;
4090 4091
}

J
Jim Fehlig 已提交
4092

4093
static int
4094
libxlConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
4095 4096 4097 4098
{
    return 1;
}

4099
static int
4100 4101 4102
libxlConnectListAllDomains(virConnectPtr conn,
                           virDomainPtr **domains,
                           unsigned int flags)
4103 4104 4105 4106
{
    libxlDriverPrivatePtr driver = conn->privateData;
    int ret = -1;

O
Osier Yang 已提交
4107
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
4108

4109 4110 4111
    if (virConnectListAllDomainsEnsureACL(conn) < 0)
        return -1;

4112 4113
    ret = virDomainObjListExport(driver->domains, conn, domains,
                                 virConnectListAllDomainsCheckACL, flags);
4114 4115 4116 4117

    return ret;
}

4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131
/* 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;
    }
}
4132

4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157
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 已提交
4158
        return -1;
4159 4160
    }

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

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;
4210
 cleanup:
4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252
    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 已提交
4253
        goto cleanup;
4254 4255

    ret = 0;
C
Chunyan Liu 已提交
4256

4257
 cleanup:
C
Chunyan Liu 已提交
4258
    virPCIDeviceFree(pci);
4259 4260 4261 4262 4263 4264 4265 4266
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
C
Chunyan Liu 已提交
4267
    virPCIDevicePtr pci = NULL;
4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293
    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 已提交
4294
        goto cleanup;
4295 4296

    ret = 0;
C
Chunyan Liu 已提交
4297

4298
 cleanup:
C
Chunyan Liu 已提交
4299
    virPCIDeviceFree(pci);
4300 4301 4302 4303 4304
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

4305

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

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


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

    return 0;
}