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

#include <config.h>

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

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

#define VIR_FROM_THIS VIR_FROM_LIBXL

60 61
VIR_LOG_INIT("libxl.libxl_driver");

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

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

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

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

76

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

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

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

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

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

    return vm;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
}

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

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

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

        return ret;
    }

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

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

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

    if (!libxlDriverShouldLoad(privileged))
        return 0;

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

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

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

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

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

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

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

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

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

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

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

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

    libxlReconnectDomains(libxl_driver);

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

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

J
Jim Fehlig 已提交
383 384
    return 0;

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

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

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

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

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

408 409
    cfg = libxlDriverConfigGet(libxl_driver);

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

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

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


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

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

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

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

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

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

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

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

    return VIR_DRV_OPEN_SUCCESS;
};

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

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

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

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

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

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

507

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

513 514 515
    return virGetHostname();
}

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

    virCheckFlags(0, NULL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return n;
}

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

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

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

    return n;
}

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

    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

    ret = 0;

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

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


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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

    ret = 0;

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

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

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

871 872
    virCheckFlags(0, -1);

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

957 958
    virCheckFlags(0, -1);

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

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

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

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

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

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

    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1160 1161
    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ret = 0;
1374

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

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

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

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

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

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

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

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

    def = NULL;

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

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

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

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

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

    virCheckFlags(VIR_DUMP_LIVE | VIR_DUMP_CRASH, -1);

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

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

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

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

    priv = vm->privateData;

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

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

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

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

    ret = 0;

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

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

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

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

    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

    ret = 0;
1597

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

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

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

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

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

    vm->hasManagedSave = virFileExists(name);

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

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

    virCheckFlags(0, -1);

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

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

1649
    ret = vm->hasManagedSave;
1650

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

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

    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

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

    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
1902

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

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

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

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

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

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

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

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

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

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

1946 1947 1948 1949 1950 1951
    /* 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);
1952
            goto endjob;
1953
        }
1954
        goto done;
1955 1956
    }

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

1972
 done:
1973 1974
    ret = 0;

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

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

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

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

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

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

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

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

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

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

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

    ret = maxinfo;

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

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

2148 2149
    /* Flags checked by virDomainDefFormat */

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

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

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

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

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

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

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

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

    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2406 2407
    virCheckFlags(VIR_DOMAIN_UNDEFINE_MANAGED_SAVE, -1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    virDomainDiskDefFree(disk);

    ret = 0;

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

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

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

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

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

                virDomainDiskInsertPreAlloced(vm->def, l_disk);

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

2578
 cleanup:
2579 2580 2581
    return ret;
}

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 2610
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 已提交
2611
        return -1;
2612

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

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

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

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

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

    return 0;
}

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

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

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

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

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

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

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

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

2716
 cleanup:
2717 2718 2719 2720
    return ret;
}

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

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

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

    return ret;
}

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

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

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

static int
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 2856
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 已提交
2857
        goto error;
2858 2859 2860 2861 2862
    }


    libxl_device_pci_init(&pcidev);

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

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

    libxl_device_pci_dispose(&pcidev);

    virDomainHostdevRemove(vm->def, idx);

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

    return 0;

2884
 error:
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 2921
    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,
2922 2923 2924 2925 2926 2927 2928 2929 2930
                            virDomainDeviceDefPtr dev)
{
    int ret = -1;

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

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

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

    return ret;
}

2945

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

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

    return ret;
}

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

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

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

    ret = 0;

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


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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3431 3432
    ret = numCells;

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

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

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

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

3455
    return 0;
3456 3457 3458 3459
}


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

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

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

3473
    return 0;
3474 3475
}

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

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

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

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

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

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

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

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

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

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

    autostart = (autostart != 0);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

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

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

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

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

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

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

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

    priv = vm->privateData;

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

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

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

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

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

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

    ret = 0;

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

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

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

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 已提交
3801
    if (!(vm = libxlDomObjFromDomain(dom)))
B
Bamvor Jian Zhang 已提交
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 3850
        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;
    }

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

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

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 3894
/* 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;

3895 3896
    libxl_bitmap_init(&nodemap);

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

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

3942
            if (libxl_node_bitmap_alloc(priv->ctx, &nodemap, 0) ||
3943
                !(nodes = virBitmapNew(numnodes))) {
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 3985
                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;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4048 4049
    ret = vm->updated;

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

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

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

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

    return ret;
}


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

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

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

4090
    return 0;
4091 4092
}

J
Jim Fehlig 已提交
4093

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

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

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

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

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

    return ret;
}

4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132
/* 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;
    }
}
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 4158
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 已提交
4159
        return -1;
4160 4161
    }

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

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;
4211
 cleanup:
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 4253
    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 已提交
4254
        goto cleanup;
4255 4256

    ret = 0;
C
Chunyan Liu 已提交
4257

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

static int
libxlNodeDeviceReset(virNodeDevicePtr dev)
{
C
Chunyan Liu 已提交
4268
    virPCIDevicePtr pci = NULL;
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 4294
    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 已提交
4295
        goto cleanup;
4296 4297

    ret = 0;
C
Chunyan Liu 已提交
4298

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

4306

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

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


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

    return 0;
}