xen_driver.c 66.0 KB
Newer Older
1
/*
2
 * xen_driver.c: Unified Xen driver.
3
 *
4
 * Copyright (C) 2007-2012 Red Hat, Inc.
5
 *
O
Osier Yang 已提交
6 7 8 9 10 11 12 13 14 15 16
 * 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
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22
 *
 * Richard W.M. Jones <rjones@redhat.com>
 */

23
#include <config.h>
24

25 26 27
/* Note:
 *
 * This driver provides a unified interface to the five
28
 * separate underlying Xen drivers (xen_internal,
29 30 31 32 33 34 35
 * xend_internal, xs_internal and xm_internal).  Historically
 * the body of libvirt.c handled the five Xen drivers,
 * and contained Xen-specific code.
 */

#include <stdint.h>
#include <unistd.h>
36
#include <string.h>
37
#include <errno.h>
38
#include <sys/types.h>
39
#include <fcntl.h>
40 41
#include <xen/dom0_ops.h>

42
#include "virterror_internal.h"
43
#include "logging.h"
44
#include "datatypes.h"
45
#include "xen_driver.h"
46

47
#include "xen_sxpr.h"
48
#include "xen_xm.h"
49
#include "xen_hypervisor.h"
50 51 52
#include "xend_internal.h"
#include "xs_internal.h"
#include "xm_internal.h"
53
#if WITH_XEN_INOTIFY
54
# include "xen_inotify.h"
55
#endif
56
#include "xml.h"
57
#include "util.h"
58
#include "memory.h"
59 60
#include "node_device_conf.h"
#include "pci.h"
61
#include "uuid.h"
62
#include "fdstream.h"
E
Eric Blake 已提交
63
#include "virfile.h"
M
Martin Kletzander 已提交
64
#include "viruri.h"
J
Jim Fehlig 已提交
65
#include "command.h"
66
#include "virnodesuspend.h"
67
#include "nodeinfo.h"
68

69 70
#define VIR_FROM_THIS VIR_FROM_XEN

71
static int
72
xenUnifiedNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info);
73
static int
74
xenUnifiedDomainGetMaxVcpus(virDomainPtr dom);
75
static int
76 77 78
xenUnifiedDomainGetVcpus(virDomainPtr dom,
                         virVcpuInfoPtr info, int maxinfo,
                         unsigned char *cpumaps, int maplen);
79

80

81
/* The five Xen drivers below us. */
D
Daniel P. Berrange 已提交
82
static struct xenUnifiedDriver const * const drivers[XEN_UNIFIED_NR_DRIVERS] = {
83 84 85 86
    [XEN_UNIFIED_HYPERVISOR_OFFSET] = &xenHypervisorDriver,
    [XEN_UNIFIED_XEND_OFFSET] = &xenDaemonDriver,
    [XEN_UNIFIED_XS_OFFSET] = &xenStoreDriver,
    [XEN_UNIFIED_XM_OFFSET] = &xenXMDriver,
87 88 89
#if WITH_XEN_INOTIFY
    [XEN_UNIFIED_INOTIFY_OFFSET] = &xenInotifyDriver,
#endif
90 91
};

92
#if defined WITH_LIBVIRTD || defined __sun
93
static bool inside_daemon = false;
94
#endif
J
John Levon 已提交
95

96 97 98 99 100
/**
 * xenNumaInit:
 * @conn: pointer to the hypervisor connection
 *
 * Initializer for previous variables. We currently assume that
R
Richard W.M. Jones 已提交
101
 * the number of physical CPU and the number of NUMA cell is fixed
102 103 104 105 106
 * until reboot which might be false in future Xen implementations.
 */
static void
xenNumaInit(virConnectPtr conn) {
    virNodeInfo nodeInfo;
D
Daniel P. Berrange 已提交
107
    xenUnifiedPrivatePtr priv;
108 109 110 111 112 113
    int ret;

    ret = xenUnifiedNodeGetInfo(conn, &nodeInfo);
    if (ret < 0)
        return;

D
Daniel P. Berrange 已提交
114
    priv = conn->privateData;
115

D
Daniel P. Berrange 已提交
116 117
    priv->nbNodeCells = nodeInfo.nodes;
    priv->nbNodeCpus = nodeInfo.cpus;
118 119
}

D
Daniel P. Berrange 已提交
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134
/**
 * xenDomainUsedCpus:
 * @dom: the domain
 *
 * Analyze which set of CPUs are used by the domain and
 * return a string providing the ranges.
 *
 * Returns the string which needs to be freed by the caller or
 *         NULL if the domain uses all CPU or in case of error.
 */
char *
xenDomainUsedCpus(virDomainPtr dom)
{
    char *res = NULL;
D
Daniel P. Berrange 已提交
135
    int ncpus;
136
    int nb_vcpu;
137
    virBitmapPtr cpulist = NULL;
138 139 140 141 142 143
    unsigned char *cpumap = NULL;
    size_t cpumaplen;
    int nb = 0;
    int n, m;
    virVcpuInfoPtr cpuinfo = NULL;
    virNodeInfo nodeinfo;
D
Daniel P. Berrange 已提交
144
    xenUnifiedPrivatePtr priv;
145 146

    if (!VIR_IS_CONNECTED_DOMAIN(dom))
147
        return NULL;
148

D
Daniel P. Berrange 已提交
149 150 151
    priv = dom->conn->privateData;

    if (priv->nbNodeCpus <= 0)
152
        return NULL;
153 154
    nb_vcpu = xenUnifiedDomainGetMaxVcpus(dom);
    if (nb_vcpu <= 0)
155
        return NULL;
156
    if (xenUnifiedNodeGetInfo(dom->conn, &nodeinfo) < 0)
157
        return NULL;
158

159
    if (!(cpulist = virBitmapNew(priv->nbNodeCpus))) {
160
        virReportOOMError();
161
        goto done;
162 163
    }
    if (VIR_ALLOC_N(cpuinfo, nb_vcpu) < 0) {
164
        virReportOOMError();
165
        goto done;
166
    }
167
    cpumaplen = VIR_CPU_MAPLEN(VIR_NODEINFO_MAXCPUS(nodeinfo));
168
    if (xalloc_oversized(nb_vcpu, cpumaplen) ||
169
        VIR_ALLOC_N(cpumap, nb_vcpu * cpumaplen) < 0) {
170
        virReportOOMError();
171
        goto done;
172
    }
173 174 175

    if ((ncpus = xenUnifiedDomainGetVcpus(dom, cpuinfo, nb_vcpu,
                                          cpumap, cpumaplen)) >= 0) {
176
        for (n = 0 ; n < ncpus ; n++) {
D
Daniel P. Berrange 已提交
177
            for (m = 0 ; m < priv->nbNodeCpus; m++) {
178 179 180
                bool used;
                ignore_value(virBitmapGetBit(cpulist, m, &used));
                if ((!used) &&
181
                    (VIR_CPU_USABLE(cpumap, cpumaplen, n, m))) {
182
                    ignore_value(virBitmapSetBit(cpulist, m));
183 184
                    nb++;
                    /* if all CPU are used just return NULL */
D
Daniel P. Berrange 已提交
185
                    if (nb == priv->nbNodeCpus)
186 187 188 189 190
                        goto done;

                }
            }
        }
191
        res = virBitmapFormat(cpulist);
192 193 194
    }

done:
195
    virBitmapFree(cpulist);
196 197
    VIR_FREE(cpumap);
    VIR_FREE(cpuinfo);
198
    return res;
199 200
}

J
John Levon 已提交
201 202 203
#ifdef WITH_LIBVIRTD

static int
204 205 206
xenInitialize(bool privileged ATTRIBUTE_UNUSED,
              virStateInhibitCallback callback ATTRIBUTE_UNUSED,
              void *opaque ATTRIBUTE_UNUSED)
J
John Levon 已提交
207
{
208
    inside_daemon = true;
J
John Levon 已提交
209 210 211 212
    return 0;
}

static virStateDriver state_driver = {
213
    .name = "Xen",
J
John Levon 已提交
214 215 216 217 218
    .initialize = xenInitialize,
};

#endif

219 220 221 222 223 224 225 226 227 228 229
/*----- Dispatch functions. -----*/

/* These dispatch functions follow the model used historically
 * by libvirt.c -- trying each low-level Xen driver in turn
 * until one succeeds.  However since we know what low-level
 * drivers can perform which functions, it is probably better
 * in future to optimise these dispatch functions to just call
 * the single function (or small number of appropriate functions)
 * in the low level drivers directly.
 */

230
static int
231
xenUnifiedProbe(void)
232 233 234
{
#ifdef __linux__
    if (virFileExists("/proc/xen"))
235
        return 1;
236
#endif
237
#ifdef __sun
238
    int fd;
239

240 241
    if ((fd = open("/dev/xen/domcaps", O_RDONLY)) >= 0) {
        VIR_FORCE_CLOSE(fd);
242
        return 1;
243 244
    }
#endif
245
    return 0;
246 247
}

J
Jim Fehlig 已提交
248 249
#ifdef WITH_LIBXL
static int
250
xenUnifiedXendProbe(void)
J
Jim Fehlig 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264
{
    virCommandPtr cmd;
    int status;
    int ret = 0;

    cmd = virCommandNewArgList("/usr/sbin/xend", "status", NULL);
    if (virCommandRun(cmd, &status) == 0 && status == 0)
        ret = 1;
    virCommandFree(cmd);

    return ret;
}
#endif

265 266


267
static virDrvOpenStatus
268
xenUnifiedOpen(virConnectPtr conn, virConnectAuthPtr auth, unsigned int flags)
269
{
270
    int i, ret = VIR_DRV_OPEN_DECLINED;
271
    xenUnifiedPrivatePtr priv;
272

J
John Levon 已提交
273 274 275 276 277 278 279 280 281
#ifdef __sun
    /*
     * Only the libvirtd instance can open this driver.
     * Everything else falls back to the remote driver.
     */
    if (!inside_daemon)
        return VIR_DRV_OPEN_DECLINED;
#endif

282 283 284 285
    if (conn->uri == NULL) {
        if (!xenUnifiedProbe())
            return VIR_DRV_OPEN_DECLINED;

286
        if (!(conn->uri = virURIParse("xen:///")))
287
            return VIR_DRV_OPEN_ERROR;
288 289 290 291 292 293 294 295 296 297 298 299
    } else {
        if (conn->uri->scheme) {
            /* Decline any scheme which isn't "xen://" or "http://". */
            if (STRCASENEQ(conn->uri->scheme, "xen") &&
                STRCASENEQ(conn->uri->scheme, "http"))
                return VIR_DRV_OPEN_DECLINED;


            /* Return an error if the path isn't '' or '/' */
            if (conn->uri->path &&
                STRNEQ(conn->uri->path, "") &&
                STRNEQ(conn->uri->path, "/")) {
300 301 302
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected Xen URI path '%s', try xen:///"),
                               conn->uri->path);
303 304
                return VIR_DRV_OPEN_ERROR;
            }
305

306 307 308 309 310 311
            /* Decline any xen:// URI with a server specified, allowing remote
             * driver to handle, but keep any http:/// URIs */
            if (STRCASEEQ(conn->uri->scheme, "xen") &&
                conn->uri->server)
                return VIR_DRV_OPEN_DECLINED;
        } else {
312
            return VIR_DRV_OPEN_DECLINED;
313 314
        }
    }
315

J
Jim Fehlig 已提交
316 317 318 319 320 321 322
#ifdef WITH_LIBXL
    /* Decline xen:// URI if xend is not running and libxenlight
     * driver is potentially available. */
    if (!xenUnifiedXendProbe())
        return VIR_DRV_OPEN_DECLINED;
#endif

323 324
    /* We now know the URI is definitely for this driver, so beyond
     * here, don't return DECLINED, always use ERROR */
325 326

    /* Allocate per-connection private data. */
327
    if (VIR_ALLOC(priv) < 0) {
328
        virReportOOMError();
329 330
        return VIR_DRV_OPEN_ERROR;
    }
D
Daniel P. Berrange 已提交
331
    if (virMutexInit(&priv->lock) < 0) {
332 333
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
D
Daniel P. Berrange 已提交
334 335 336
        VIR_FREE(priv);
        return VIR_DRV_OPEN_ERROR;
    }
337

338
    if (!(priv->domainEvents = virDomainEventStateNew())) {
D
Daniel P. Berrange 已提交
339 340
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
341 342
        return VIR_DRV_OPEN_ERROR;
    }
D
Daniel P. Berrange 已提交
343 344
    conn->privateData = priv;

345 346 347 348 349
    priv->handle = -1;
    priv->xendConfigVersion = -1;
    priv->xshandle = NULL;


J
John Levon 已提交
350 351
    /* Hypervisor is only run with privilege & required to succeed */
    if (xenHavePrivilege()) {
352
        VIR_DEBUG("Trying hypervisor sub-driver");
E
Eric Blake 已提交
353
        if (xenHypervisorOpen(conn, auth, flags) == VIR_DRV_OPEN_SUCCESS) {
354
            VIR_DEBUG("Activated hypervisor sub-driver");
355
            priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET] = 1;
356 357
        } else {
            goto fail;
358
        }
359
    }
360

361
    /* XenD is required to succeed if privileged */
362
    VIR_DEBUG("Trying XenD sub-driver");
E
Eric Blake 已提交
363
    if (xenDaemonOpen(conn, auth, flags) == VIR_DRV_OPEN_SUCCESS) {
364
        VIR_DEBUG("Activated XenD sub-driver");
365 366 367 368
        priv->opened[XEN_UNIFIED_XEND_OFFSET] = 1;

        /* XenD is active, so try the xm & xs drivers too, both requird to
         * succeed if root, optional otherwise */
369
        if (priv->xendConfigVersion <= XEND_CONFIG_VERSION_3_0_3) {
370
            VIR_DEBUG("Trying XM sub-driver");
E
Eric Blake 已提交
371
            if (xenXMOpen(conn, auth, flags) == VIR_DRV_OPEN_SUCCESS) {
372
                VIR_DEBUG("Activated XM sub-driver");
373 374 375
                priv->opened[XEN_UNIFIED_XM_OFFSET] = 1;
            }
        }
376
        VIR_DEBUG("Trying XS sub-driver");
E
Eric Blake 已提交
377
        if (xenStoreOpen(conn, auth, flags) == VIR_DRV_OPEN_SUCCESS) {
378
            VIR_DEBUG("Activated XS sub-driver");
379 380
            priv->opened[XEN_UNIFIED_XS_OFFSET] = 1;
        } else {
J
John Levon 已提交
381 382
            if (xenHavePrivilege())
                goto fail; /* XS is mandatory when privileged */
383 384
        }
    } else {
J
John Levon 已提交
385 386
        if (xenHavePrivilege()) {
            goto fail; /* XenD is mandatory when privileged */
387
        } else {
388
            VIR_DEBUG("Handing off for remote driver");
389 390
            ret = VIR_DRV_OPEN_DECLINED; /* Let remote_driver try instead */
            goto clean;
391
        }
392 393
    }

D
Daniel P. Berrange 已提交
394 395
    xenNumaInit(conn);

396
    if (!(priv->caps = xenHypervisorMakeCapabilities(conn))) {
397
        VIR_DEBUG("Failed to make capabilities");
398 399 400
        goto fail;
    }

401
#if WITH_XEN_INOTIFY
402
    if (xenHavePrivilege()) {
403
        VIR_DEBUG("Trying Xen inotify sub-driver");
E
Eric Blake 已提交
404
        if (xenInotifyOpen(conn, auth, flags) == VIR_DRV_OPEN_SUCCESS) {
405
            VIR_DEBUG("Activated Xen inotify sub-driver");
406 407
            priv->opened[XEN_UNIFIED_INOTIFY_OFFSET] = 1;
        }
408 409 410
    }
#endif

411
    return VIR_DRV_OPEN_SUCCESS;
412

413 414 415
fail:
    ret = VIR_DRV_OPEN_ERROR;
clean:
416
    VIR_DEBUG("Failed to activate a mandatory sub-driver");
417
    for (i = 0 ; i < XEN_UNIFIED_NR_DRIVERS ; i++)
418 419
        if (priv->opened[i])
            drivers[i]->xenClose(conn);
D
Daniel P. Berrange 已提交
420
    virMutexDestroy(&priv->lock);
421
    VIR_FREE(priv);
D
Daniel P. Berrange 已提交
422
    conn->privateData = NULL;
D
Daniel Veillard 已提交
423
    return ret;
424 425
}

426 427 428
#define GET_PRIVATE(conn) \
    xenUnifiedPrivatePtr priv = (xenUnifiedPrivatePtr) (conn)->privateData

429
static int
430
xenUnifiedClose(virConnectPtr conn)
431
{
432
    GET_PRIVATE(conn);
433
    int i;
434

435
    virCapabilitiesFree(priv->caps);
436
    virDomainEventStateFree(priv->domainEvents);
437

438
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
439 440
        if (priv->opened[i])
            drivers[i]->xenClose(conn);
441

D
Daniel P. Berrange 已提交
442 443
    virMutexDestroy(&priv->lock);
    VIR_FREE(conn->privateData);
444

445
    return 0;
446 447
}

448 449 450 451 452 453 454 455 456 457 458

#define HV_VERSION ((DOM0_INTERFACE_VERSION >> 24) * 1000000 +         \
                    ((DOM0_INTERFACE_VERSION >> 16) & 0xFF) * 1000 +   \
                    (DOM0_INTERFACE_VERSION & 0xFFFF))

unsigned long xenUnifiedVersion(void)
{
    return HV_VERSION;
}


459
static const char *
460
xenUnifiedType(virConnectPtr conn)
461
{
462
    GET_PRIVATE(conn);
463
    int i;
464

465
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
466 467
        if (priv->opened[i])
            return "Xen";
468

469
    return NULL;
470 471
}

472 473
/* Which features are supported by this driver? */
static int
474
xenUnifiedSupportsFeature(virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
475 476
{
    switch (feature) {
477 478 479 480 481
    case VIR_DRV_FEATURE_MIGRATION_V1:
    case VIR_DRV_FEATURE_MIGRATION_DIRECT:
        return 1;
    default:
        return 0;
482 483 484
    }
}

485
static int
486
xenUnifiedGetVersion(virConnectPtr conn, unsigned long *hvVer)
487
{
488
    GET_PRIVATE(conn);
489
    int i;
490

491 492
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
        if (priv->opened[i] &&
E
Eric Blake 已提交
493
            drivers[i]->xenVersion &&
494
            drivers[i]->xenVersion(conn, hvVer) == 0)
495
            return 0;
496

497
    return -1;
498 499
}

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
static int
xenUnifiedIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return 0;
}

static int
xenUnifiedIsSecure(virConnectPtr conn)
{
    GET_PRIVATE(conn);
    int ret = 1;

    /* All drivers are secure, except for XenD over TCP */
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET] &&
        priv->addrfamily != AF_UNIX)
        ret = 0;

    return ret;
}

520 521 522 523 524 525 526
static int
xenUnifiedIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* XenD reconnects for each request */
    return 1;
}

527
int
528
xenUnifiedGetMaxVcpus(virConnectPtr conn, const char *type)
529
{
530
    GET_PRIVATE(conn);
531

532
    if (type && STRCASENEQ(type, "Xen")) {
533
        virReportError(VIR_ERR_INVALID_ARG, __FUNCTION__);
534 535
        return -1;
    }
536

537
    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET])
538
        return xenHypervisorGetMaxVcpus(conn, type);
539
    else {
540
        virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
541 542
        return -1;
    }
543 544 545
}

static int
546
xenUnifiedNodeGetInfo(virConnectPtr conn, virNodeInfoPtr info)
547
{
548
    GET_PRIVATE(conn);
549

550 551
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
        return xenDaemonNodeGetInfo(conn, info);
552
    return -1;
553 554 555
}

static char *
556
xenUnifiedGetCapabilities(virConnectPtr conn)
557
{
D
Daniel P. Berrange 已提交
558 559
    xenUnifiedPrivatePtr priv = conn->privateData;
    char *xml;
560

D
Daniel P. Berrange 已提交
561
    if (!(xml = virCapabilitiesFormatXML(priv->caps))) {
562
        virReportOOMError();
D
Daniel P. Berrange 已提交
563 564
        return NULL;
    }
565

D
Daniel P. Berrange 已提交
566
    return xml;
567 568 569
}

static int
570
xenUnifiedListDomains(virConnectPtr conn, int *ids, int maxids)
571
{
572
    GET_PRIVATE(conn);
573
    int ret;
574

575 576
    /* Try xenstore. */
    if (priv->opened[XEN_UNIFIED_XS_OFFSET]) {
577
        ret = xenStoreListDomains(conn, ids, maxids);
578 579
        if (ret >= 0) return ret;
    }
580

581 582
    /* Try HV. */
    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET]) {
583
        ret = xenHypervisorListDomains(conn, ids, maxids);
584 585 586 587 588
        if (ret >= 0) return ret;
    }

    /* Try xend. */
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
589
        ret = xenDaemonListDomains(conn, ids, maxids);
590 591 592
        if (ret >= 0) return ret;
    }

593
    return -1;
594 595 596
}

static int
597
xenUnifiedNumOfDomains(virConnectPtr conn)
598
{
599
    GET_PRIVATE(conn);
600
    int ret;
601

602 603
    /* Try xenstore. */
    if (priv->opened[XEN_UNIFIED_XS_OFFSET]) {
604
        ret = xenStoreNumOfDomains(conn);
605 606 607 608 609
        if (ret >= 0) return ret;
    }

    /* Try HV. */
    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET]) {
610
        ret = xenHypervisorNumOfDomains(conn);
611 612 613 614 615
        if (ret >= 0) return ret;
    }

    /* Try xend. */
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
616
        ret = xenDaemonNumOfDomains(conn);
617 618 619
        if (ret >= 0) return ret;
    }

620
    return -1;
621 622 623
}

static virDomainPtr
624 625
xenUnifiedDomainCreateXML(virConnectPtr conn,
                          const char *xmlDesc, unsigned int flags)
626
{
627
    GET_PRIVATE(conn);
628

629 630
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
        return xenDaemonCreateXML(conn, xmlDesc, flags);
631
    return NULL;
632 633
}

634 635 636 637
/* Assumption made in underlying drivers:
 * If the domain is "not found" and there is no other error, then
 * the Lookup* functions return a NULL but do not set virterror.
 */
638
static virDomainPtr
639
xenUnifiedDomainLookupByID(virConnectPtr conn, int id)
640
{
641
    GET_PRIVATE(conn);
642
    virDomainPtr ret;
643

644 645 646
    /* Reset any connection-level errors in virterror first, in case
     * there is one hanging around from a previous call.
     */
647
    virConnResetLastError(conn);
648

649 650
    /* Try hypervisor/xenstore combo. */
    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET]) {
651
        ret = xenHypervisorLookupDomainByID(conn, id);
652 653 654 655
        if (ret || conn->err.code != VIR_ERR_OK)
            return ret;
    }

656 657
    /* Try xend. */
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
658
        ret = xenDaemonLookupByID(conn, id);
659 660 661
        if (ret || conn->err.code != VIR_ERR_OK)
            return ret;
    }
662

663
    /* Not found. */
664
    virReportError(VIR_ERR_NO_DOMAIN, __FUNCTION__);
665
    return NULL;
666 667 668
}

static virDomainPtr
669 670
xenUnifiedDomainLookupByUUID(virConnectPtr conn,
                             const unsigned char *uuid)
671
{
672
    GET_PRIVATE(conn);
673
    virDomainPtr ret;
674

675 676 677
    /* Reset any connection-level errors in virterror first, in case
     * there is one hanging around from a previous call.
     */
678
    virConnResetLastError(conn);
679

680 681
    /* Try hypervisor/xenstore combo. */
    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET]) {
682
        ret = xenHypervisorLookupDomainByUUID(conn, uuid);
683 684 685 686
        if (ret || conn->err.code != VIR_ERR_OK)
            return ret;
    }

687 688
    /* Try xend. */
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
689
        ret = xenDaemonLookupByUUID(conn, uuid);
690 691 692
        if (ret || conn->err.code != VIR_ERR_OK)
            return ret;
    }
693

694 695
    /* Try XM for inactive domains. */
    if (priv->opened[XEN_UNIFIED_XM_OFFSET]) {
696
        ret = xenXMDomainLookupByUUID(conn, uuid);
697 698 699 700 701
        if (ret || conn->err.code != VIR_ERR_OK)
            return ret;
    }

    /* Not found. */
702
    virReportError(VIR_ERR_NO_DOMAIN, __FUNCTION__);
703
    return NULL;
704 705 706
}

static virDomainPtr
707 708
xenUnifiedDomainLookupByName(virConnectPtr conn,
                             const char *name)
709
{
710
    GET_PRIVATE(conn);
711
    virDomainPtr ret;
712

713 714 715
    /* Reset any connection-level errors in virterror first, in case
     * there is one hanging around from a previous call.
     */
716
    virConnResetLastError(conn);
717 718 719

    /* Try xend. */
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
720
        ret = xenDaemonLookupByName(conn, name);
721 722 723 724 725 726
        if (ret || conn->err.code != VIR_ERR_OK)
            return ret;
    }

    /* Try xenstore for inactive domains. */
    if (priv->opened[XEN_UNIFIED_XS_OFFSET]) {
727
        ret = xenStoreLookupByName(conn, name);
728 729 730 731 732 733
        if (ret || conn->err.code != VIR_ERR_OK)
            return ret;
    }

    /* Try XM for inactive domains. */
    if (priv->opened[XEN_UNIFIED_XM_OFFSET]) {
734
        ret = xenXMDomainLookupByName(conn, name);
735 736 737
        if (ret || conn->err.code != VIR_ERR_OK)
            return ret;
    }
738

739
    /* Not found. */
740
    virReportError(VIR_ERR_NO_DOMAIN, __FUNCTION__);
741
    return NULL;
742 743
}

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762

static int
xenUnifiedDomainIsActive(virDomainPtr dom)
{
    virDomainPtr currdom;
    int ret = -1;

    /* ID field in dom may be outdated, so re-lookup */
    currdom = xenUnifiedDomainLookupByUUID(dom->conn, dom->uuid);

    if (currdom) {
        ret = currdom->id == -1 ? 0 : 1;
        virDomainFree(currdom);
    }

    return ret;
}

static int
763
xenUnifiedDomainIsPersistent(virDomainPtr dom)
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
{
    GET_PRIVATE(dom->conn);
    virDomainPtr currdom = NULL;
    int ret = -1;

    if (priv->opened[XEN_UNIFIED_XM_OFFSET]) {
        /* Old Xen, pre-inactive domain management.
         * If the XM driver can see the guest, it is definitely persistent */
        currdom = xenXMDomainLookupByUUID(dom->conn, dom->uuid);
        if (currdom)
            ret = 1;
        else
            ret = 0;
    } else {
        /* New Xen with inactive domain management */
        if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
            currdom = xenDaemonLookupByUUID(dom->conn, dom->uuid);
            if (currdom) {
                if (currdom->id == -1) {
                    /* If its inactive, then trivially, it must be persistent */
                    ret = 1;
                } else {
                    char *path;
                    char uuidstr[VIR_UUID_STRING_BUFLEN];

                    /* If its running there's no official way to tell, so we
                     * go behind xend's back & look at the config dir */

                    virUUIDFormat(dom->uuid, uuidstr);
                    if (virAsprintf(&path, "%s/%s", XEND_DOMAINS_DIR, uuidstr) < 0) {
794
                        virReportOOMError();
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
                        goto done;
                    }
                    if (access(path, R_OK) == 0)
                        ret = 1;
                    else if (errno == ENOENT)
                        ret = 0;
                }
            }
        }
    }

done:
    if (currdom)
        virDomainFree(currdom);

    return ret;
}

813 814 815 816 817 818
static int
xenUnifiedDomainIsUpdated(virDomainPtr dom ATTRIBUTE_UNUSED)
{
    return 0;
}

819
static int
820
xenUnifiedDomainSuspend(virDomainPtr dom)
821
{
822
    GET_PRIVATE(dom->conn);
823
    int i;
824

825 826 827
    /* Try non-hypervisor methods first, then hypervisor direct method
     * as a last resort.
     */
828
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
829
        if (i != XEN_UNIFIED_HYPERVISOR_OFFSET &&
830
            priv->opened[i] &&
E
Eric Blake 已提交
831
            drivers[i]->xenDomainSuspend &&
832
            drivers[i]->xenDomainSuspend(dom) == 0)
833
            return 0;
834

835
    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET] &&
E
Eric Blake 已提交
836
        xenHypervisorPauseDomain(dom) == 0)
837
        return 0;
838

839
    return -1;
840 841 842
}

static int
843
xenUnifiedDomainResume(virDomainPtr dom)
844
{
845
    GET_PRIVATE(dom->conn);
846
    int i;
847

848 849 850
    /* Try non-hypervisor methods first, then hypervisor direct method
     * as a last resort.
     */
851
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
852
        if (i != XEN_UNIFIED_HYPERVISOR_OFFSET &&
853
            priv->opened[i] &&
E
Eric Blake 已提交
854
            drivers[i]->xenDomainResume &&
855
            drivers[i]->xenDomainResume(dom) == 0)
856
            return 0;
857

858
    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET] &&
E
Eric Blake 已提交
859
        xenHypervisorResumeDomain(dom) == 0)
860
        return 0;
861

862
    return -1;
863 864 865
}

static int
866 867
xenUnifiedDomainShutdownFlags(virDomainPtr dom,
                              unsigned int flags)
868
{
869
    GET_PRIVATE(dom->conn);
870
    int i;
871

872 873
    virCheckFlags(0, -1);

874 875
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
        if (priv->opened[i] &&
E
Eric Blake 已提交
876
            drivers[i]->xenDomainShutdown &&
877
            drivers[i]->xenDomainShutdown(dom) == 0)
878
            return 0;
879

880
    return -1;
881 882
}

883 884 885 886 887 888
static int
xenUnifiedDomainShutdown(virDomainPtr dom)
{
    return xenUnifiedDomainShutdownFlags(dom, 0);
}

889
static int
890
xenUnifiedDomainReboot(virDomainPtr dom, unsigned int flags)
891
{
892
    GET_PRIVATE(dom->conn);
893
    int i;
894

895 896
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
        if (priv->opened[i] &&
E
Eric Blake 已提交
897
            drivers[i]->xenDomainReboot &&
898
            drivers[i]->xenDomainReboot(dom, flags) == 0)
899
            return 0;
900

901
    return -1;
902 903
}

904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
static int
xenUnifiedDomainDestroyFlags(virDomainPtr dom,
                             unsigned int flags)
{
    GET_PRIVATE(dom->conn);
    int i;

    virCheckFlags(0, -1);

    /* Try non-hypervisor methods first, then hypervisor direct method
     * as a last resort.
     */
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
        if (i != XEN_UNIFIED_HYPERVISOR_OFFSET &&
            priv->opened[i] &&
E
Eric Blake 已提交
919 920
            drivers[i]->xenDomainDestroyFlags &&
            drivers[i]->xenDomainDestroyFlags(dom, flags) == 0)
921 922 923
            return 0;

    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET] &&
E
Eric Blake 已提交
924
        xenHypervisorDestroyDomainFlags(dom, flags) == 0)
925 926 927 928 929
        return 0;

    return -1;
}

930 931 932 933 934 935
static int
xenUnifiedDomainDestroy(virDomainPtr dom)
{
    return xenUnifiedDomainDestroyFlags(dom, 0);
}

936
static char *
937
xenUnifiedDomainGetOSType(virDomainPtr dom)
938
{
939
    GET_PRIVATE(dom->conn);
940 941
    int i;
    char *ret;
942

943
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
944
        if (priv->opened[i] && drivers[i]->xenDomainGetOSType) {
945
            ret = drivers[i]->xenDomainGetOSType(dom);
946 947
            if (ret) return ret;
        }
948

949
    return NULL;
950 951
}

952
static unsigned long long
953
xenUnifiedDomainGetMaxMemory(virDomainPtr dom)
954
{
955
    GET_PRIVATE(dom->conn);
956
    int i;
957
    unsigned long long ret;
958

959
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
960
        if (priv->opened[i] && drivers[i]->xenDomainGetMaxMemory) {
961
            ret = drivers[i]->xenDomainGetMaxMemory(dom);
962 963
            if (ret != 0) return ret;
        }
964

965
    return 0;
966 967 968
}

static int
969
xenUnifiedDomainSetMaxMemory(virDomainPtr dom, unsigned long memory)
970
{
971
    GET_PRIVATE(dom->conn);
972
    int i;
973

974 975
    /* Prefer xend for setting max memory */
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
976
        if (xenDaemonDomainSetMaxMemory(dom, memory) == 0)
977 978 979
            return 0;
    }

980
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
981 982
        if (i != XEN_UNIFIED_XEND_OFFSET &&
            priv->opened[i] &&
E
Eric Blake 已提交
983
            drivers[i]->xenDomainSetMaxMemory &&
984
            drivers[i]->xenDomainSetMaxMemory(dom, memory) == 0)
985
            return 0;
986

987
    return -1;
988 989 990
}

static int
991
xenUnifiedDomainSetMemory(virDomainPtr dom, unsigned long memory)
992
{
993
    GET_PRIVATE(dom->conn);
994
    int i;
995

996 997
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
        if (priv->opened[i] &&
E
Eric Blake 已提交
998
            drivers[i]->xenDomainSetMemory &&
999
            drivers[i]->xenDomainSetMemory(dom, memory) == 0)
1000
            return 0;
1001

1002
    return -1;
1003 1004 1005
}

static int
1006
xenUnifiedDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
1007
{
1008
    GET_PRIVATE(dom->conn);
1009
    int i;
1010

1011 1012
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
        if (priv->opened[i] &&
E
Eric Blake 已提交
1013
            drivers[i]->xenDomainGetInfo &&
1014
            drivers[i]->xenDomainGetInfo(dom, info) == 0)
1015
            return 0;
1016

1017
    return -1;
1018 1019
}

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
static int
xenUnifiedDomainGetState(virDomainPtr dom,
                         int *state,
                         int *reason,
                         unsigned int flags)
{
    GET_PRIVATE(dom->conn);
    int ret;

    virCheckFlags(0, -1);

    /* trying drivers in the same order as GetInfo for consistent results:
     * hypervisor, xend, xs, and xm */

    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET]) {
        ret = xenHypervisorGetDomainState(dom, state, reason, flags);
        if (ret >= 0)
            return ret;
    }

    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
        ret = xenDaemonDomainGetState(dom, state, reason, flags);
        if (ret >= 0)
            return ret;
    }

    if (priv->opened[XEN_UNIFIED_XS_OFFSET]) {
        ret = xenStoreDomainGetState(dom, state, reason, flags);
        if (ret >= 0)
            return ret;
    }

    if (priv->opened[XEN_UNIFIED_XM_OFFSET]) {
        ret = xenXMDomainGetState(dom, state, reason, flags);
        if (ret >= 0)
            return ret;
    }

    return -1;
}

1061
static int
1062 1063
xenUnifiedDomainSaveFlags(virDomainPtr dom, const char *to, const char *dxml,
                          unsigned int flags)
1064
{
1065
    GET_PRIVATE(dom->conn);
1066

1067 1068
    virCheckFlags(0, -1);
    if (dxml) {
1069 1070
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1071 1072 1073
        return -1;
    }

1074 1075
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
        return xenDaemonDomainSave(dom, to);
1076
    return -1;
1077 1078 1079
}

static int
1080 1081 1082 1083 1084 1085 1086 1087
xenUnifiedDomainSave(virDomainPtr dom, const char *to)
{
    return xenUnifiedDomainSaveFlags(dom, to, NULL, 0);
}

static int
xenUnifiedDomainRestoreFlags(virConnectPtr conn, const char *from,
                             const char *dxml, unsigned int flags)
1088
{
1089
    GET_PRIVATE(conn);
1090

1091 1092
    virCheckFlags(0, -1);
    if (dxml) {
1093 1094
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("xml modification unsupported"));
1095 1096 1097
        return -1;
    }

1098 1099
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
        return xenDaemonDomainRestore(conn, from);
1100
    return -1;
1101 1102
}

1103
static int
1104
xenUnifiedDomainRestore(virConnectPtr conn, const char *from)
1105 1106 1107 1108
{
    return xenUnifiedDomainRestoreFlags(conn, from, NULL, 0);
}

1109
static int
1110
xenUnifiedDomainCoreDump(virDomainPtr dom, const char *to, unsigned int flags)
1111
{
1112
    GET_PRIVATE(dom->conn);
1113

1114 1115
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
        return xenDaemonDomainCoreDump(dom, to, flags);
1116
    return -1;
1117 1118 1119
}

static int
1120 1121
xenUnifiedDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                              unsigned int flags)
1122
{
1123
    GET_PRIVATE(dom->conn);
1124
    int ret;
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134
    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)) {
1135 1136
        virReportError(VIR_ERR_INVALID_ARG,
                       _("invalid flag combination: (0x%x)"), flags);
1137 1138 1139
        return -1;
    }
    if (!nvcpus || (unsigned short) nvcpus != nvcpus) {
1140 1141
        virReportError(VIR_ERR_INVALID_ARG,
                       _("argument out of range: %d"), nvcpus);
1142 1143 1144
        return -1;
    }

1145 1146 1147
    /* Try non-hypervisor methods first, then hypervisor direct method
     * as a last resort.
     */
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
        ret = xenDaemonDomainSetVcpusFlags(dom, nvcpus, flags);
        if (ret != -2)
            return ret;
    }
    if (priv->opened[XEN_UNIFIED_XM_OFFSET]) {
        ret = xenXMDomainSetVcpusFlags(dom, nvcpus, flags);
        if (ret != -2)
            return ret;
    }
    if (flags == VIR_DOMAIN_VCPU_LIVE)
        return xenHypervisorSetVcpus(dom, nvcpus);
1160

1161
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1162
    return -1;
1163 1164
}

1165
static int
1166
xenUnifiedDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
1167
{
1168 1169 1170 1171 1172 1173 1174 1175
    unsigned int flags = VIR_DOMAIN_VCPU_LIVE;
    xenUnifiedPrivatePtr priv;

    /* Per the documented API, it is hypervisor-dependent whether this
     * affects just _LIVE or _LIVE|_CONFIG; in xen's case, that
     * depends on xendConfigVersion.  */
    if (dom) {
        priv = dom->conn->privateData;
1176
        if (priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4)
1177 1178 1179
            flags |= VIR_DOMAIN_VCPU_CONFIG;
    }
    return xenUnifiedDomainSetVcpusFlags(dom, nvcpus, flags);
1180 1181
}

1182
static int
1183 1184
xenUnifiedDomainPinVcpu(virDomainPtr dom, unsigned int vcpu,
                        unsigned char *cpumap, int maplen)
1185
{
1186
    GET_PRIVATE(dom->conn);
1187
    int i;
1188

1189 1190
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
        if (priv->opened[i] &&
E
Eric Blake 已提交
1191
            drivers[i]->xenDomainPinVcpu &&
1192
            drivers[i]->xenDomainPinVcpu(dom, vcpu, cpumap, maplen) == 0)
1193
            return 0;
1194

1195
    return -1;
1196 1197 1198
}

static int
1199 1200 1201
xenUnifiedDomainGetVcpus(virDomainPtr dom,
                         virVcpuInfoPtr info, int maxinfo,
                         unsigned char *cpumaps, int maplen)
1202
{
1203
    GET_PRIVATE(dom->conn);
1204
    int i, ret;
1205

1206
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1207
        if (priv->opened[i] && drivers[i]->xenDomainGetVcpus) {
1208
            ret = drivers[i]->xenDomainGetVcpus(dom, info, maxinfo, cpumaps, maplen);
1209 1210 1211
            if (ret > 0)
                return ret;
        }
1212
    return -1;
1213 1214 1215
}

static int
1216
xenUnifiedDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
1217
{
1218
    GET_PRIVATE(dom->conn);
1219
    int ret;
1220

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
        ret = xenDaemonDomainGetVcpusFlags(dom, flags);
        if (ret != -2)
            return ret;
    }
    if (priv->opened[XEN_UNIFIED_XM_OFFSET]) {
        ret = xenXMDomainGetVcpusFlags(dom, flags);
        if (ret != -2)
            return ret;
    }
    if (flags == (VIR_DOMAIN_VCPU_CONFIG | VIR_DOMAIN_VCPU_MAXIMUM))
        return xenHypervisorGetVcpuMax(dom);
1237

1238
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1239
    return -1;
1240 1241
}

1242
static int
1243
xenUnifiedDomainGetMaxVcpus(virDomainPtr dom)
1244 1245 1246 1247 1248
{
    return xenUnifiedDomainGetVcpusFlags(dom, (VIR_DOMAIN_VCPU_LIVE |
                                               VIR_DOMAIN_VCPU_MAXIMUM));
}

1249
static char *
1250
xenUnifiedDomainGetXMLDesc(virDomainPtr dom, unsigned int flags)
1251
{
1252
    GET_PRIVATE(dom->conn);
1253

1254
    if (dom->id == -1 && priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4) {
1255
        if (priv->opened[XEN_UNIFIED_XM_OFFSET])
1256
            return xenXMDomainGetXMLDesc(dom, flags);
1257 1258 1259
    } else {
        if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
            char *cpus, *res;
D
Daniel P. Berrange 已提交
1260
            xenUnifiedLock(priv);
1261
            cpus = xenDomainUsedCpus(dom);
D
Daniel P. Berrange 已提交
1262
            xenUnifiedUnlock(priv);
1263
            res = xenDaemonDomainGetXMLDesc(dom, flags, cpus);
1264
            VIR_FREE(cpus);
1265
            return res;
1266
        }
1267
    }
1268

1269
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1270
    return NULL;
1271 1272
}

1273 1274 1275 1276 1277

static char *
xenUnifiedDomainXMLFromNative(virConnectPtr conn,
                              const char *format,
                              const char *config,
E
Eric Blake 已提交
1278
                              unsigned int flags)
1279 1280 1281 1282
{
    virDomainDefPtr def = NULL;
    char *ret = NULL;
    virConfPtr conf = NULL;
1283 1284 1285
    int id;
    char * tty;
    int vncport;
1286 1287
    GET_PRIVATE(conn);

E
Eric Blake 已提交
1288 1289
    virCheckFlags(0, NULL);

1290 1291
    if (STRNEQ(format, XEN_CONFIG_FORMAT_XM) &&
        STRNEQ(format, XEN_CONFIG_FORMAT_SEXPR)) {
1292 1293
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), format);
1294 1295 1296 1297
        return NULL;
    }

    if (STREQ(format, XEN_CONFIG_FORMAT_XM)) {
1298
        conf = virConfReadMem(config, strlen(config), 0);
1299 1300 1301
        if (!conf)
            goto cleanup;

M
Markus Groß 已提交
1302
        def = xenParseXM(conf, priv->xendConfigVersion, priv->caps);
1303
    } else if (STREQ(format, XEN_CONFIG_FORMAT_SEXPR)) {
1304 1305 1306 1307 1308
        id = xenGetDomIdFromSxprString(config, priv->xendConfigVersion);
        xenUnifiedLock(priv);
        tty = xenStoreDomainGetConsolePath(conn, id);
        vncport = xenStoreDomainGetVNCPort(conn, id);
        xenUnifiedUnlock(priv);
M
Markus Groß 已提交
1309
        def = xenParseSxprString(config, priv->xendConfigVersion, tty,
1310
                                       vncport);
1311 1312 1313 1314
    }
    if (!def)
        goto cleanup;

1315
    ret = virDomainDefFormat(def, 0);
1316 1317 1318

cleanup:
    virDomainDefFree(def);
1319 1320
    if (conf)
        virConfFree(conf);
1321 1322 1323 1324 1325 1326 1327 1328 1329
    return ret;
}


#define MAX_CONFIG_SIZE (1024 * 65)
static char *
xenUnifiedDomainXMLToNative(virConnectPtr conn,
                            const char *format,
                            const char *xmlData,
E
Eric Blake 已提交
1330
                            unsigned int flags)
1331 1332 1333 1334 1335 1336
{
    virDomainDefPtr def = NULL;
    char *ret = NULL;
    virConfPtr conf = NULL;
    GET_PRIVATE(conn);

E
Eric Blake 已提交
1337 1338
    virCheckFlags(0, NULL);

1339 1340
    if (STRNEQ(format, XEN_CONFIG_FORMAT_XM) &&
        STRNEQ(format, XEN_CONFIG_FORMAT_SEXPR)) {
1341 1342
        virReportError(VIR_ERR_INVALID_ARG,
                       _("unsupported config type %s"), format);
1343 1344 1345
        goto cleanup;
    }

M
Matthias Bolte 已提交
1346 1347
    if (!(def = virDomainDefParseString(priv->caps, xmlData,
                                        1 << VIR_DOMAIN_VIRT_XEN, 0)))
1348 1349 1350 1351
        goto cleanup;

    if (STREQ(format, XEN_CONFIG_FORMAT_XM)) {
        int len = MAX_CONFIG_SIZE;
M
Markus Groß 已提交
1352
        conf = xenFormatXM(conn, def, priv->xendConfigVersion);
1353 1354 1355 1356
        if (!conf)
            goto cleanup;

        if (VIR_ALLOC_N(ret, len) < 0) {
1357
            virReportOOMError();
1358 1359 1360 1361 1362 1363 1364 1365
            goto cleanup;
        }

        if (virConfWriteMem(ret, &len, conf) < 0) {
            VIR_FREE(ret);
            goto cleanup;
        }
    } else if (STREQ(format, XEN_CONFIG_FORMAT_SEXPR)) {
M
Markus Groß 已提交
1366
        ret = xenFormatSxpr(conn, def, priv->xendConfigVersion);
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    }

cleanup:
    virDomainDefFree(def);
    if (conf)
        virConfFree(conf);
    return ret;
}


1377
static int
1378 1379 1380 1381 1382 1383 1384 1385
xenUnifiedDomainMigratePrepare(virConnectPtr dconn,
                               char **cookie,
                               int *cookielen,
                               const char *uri_in,
                               char **uri_out,
                               unsigned long flags,
                               const char *dname,
                               unsigned long resource)
1386 1387 1388
{
    GET_PRIVATE(dconn);

E
Eric Blake 已提交
1389 1390
    virCheckFlags(XEN_MIGRATION_FLAGS, -1);

1391
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
1392 1393 1394
        return xenDaemonDomainMigratePrepare(dconn, cookie, cookielen,
                                             uri_in, uri_out,
                                             flags, dname, resource);
1395

1396
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1397 1398 1399 1400
    return -1;
}

static int
1401 1402 1403 1404 1405 1406 1407
xenUnifiedDomainMigratePerform(virDomainPtr dom,
                               const char *cookie,
                               int cookielen,
                               const char *uri,
                               unsigned long flags,
                               const char *dname,
                               unsigned long resource)
1408 1409 1410
{
    GET_PRIVATE(dom->conn);

E
Eric Blake 已提交
1411 1412
    virCheckFlags(XEN_MIGRATION_FLAGS, -1);

1413
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
1414 1415
        return xenDaemonDomainMigratePerform(dom, cookie, cookielen, uri,
                                             flags, dname, resource);
1416

1417
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1418 1419 1420 1421
    return -1;
}

static virDomainPtr
1422 1423 1424 1425 1426 1427
xenUnifiedDomainMigrateFinish(virConnectPtr dconn,
                              const char *dname,
                              const char *cookie ATTRIBUTE_UNUSED,
                              int cookielen ATTRIBUTE_UNUSED,
                              const char *uri ATTRIBUTE_UNUSED,
                              unsigned long flags)
1428
{
1429 1430 1431 1432
    virDomainPtr dom = NULL;
    char *domain_xml = NULL;
    virDomainPtr dom_new = NULL;

E
Eric Blake 已提交
1433 1434
    virCheckFlags(XEN_MIGRATION_FLAGS, NULL);

1435
    dom = xenUnifiedDomainLookupByName(dconn, dname);
1436 1437 1438 1439 1440
    if (! dom) {
        return NULL;
    }

    if (flags & VIR_MIGRATE_PERSIST_DEST) {
1441
        domain_xml = xenDaemonDomainGetXMLDesc(dom, 0, NULL);
1442
        if (! domain_xml) {
1443 1444
            virReportError(VIR_ERR_MIGRATE_PERSIST_FAILED,
                           "%s", _("failed to get XML representation of migrated domain"));
1445 1446 1447
            goto failure;
        }

1448
        dom_new = xenDaemonDomainDefineXML(dconn, domain_xml);
1449
        if (! dom_new) {
1450 1451
            virReportError(VIR_ERR_MIGRATE_PERSIST_FAILED,
                           "%s", _("failed to define domain on destination host"));
1452 1453 1454 1455
            goto failure;
        }

        /* Free additional reference added by Define */
1456
        virDomainFree(dom_new);
1457 1458
    }

1459
    VIR_FREE(domain_xml);
1460 1461 1462 1463 1464

    return dom;


failure:
1465
    virDomainFree(dom);
1466

1467
    VIR_FREE(domain_xml);
1468 1469

    return NULL;
1470 1471
}

1472
static int
1473 1474
xenUnifiedListDefinedDomains(virConnectPtr conn, char **const names,
                             int maxnames)
1475
{
1476
    GET_PRIVATE(conn);
1477 1478
    int i;
    int ret;
1479

1480
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1481
        if (priv->opened[i] && drivers[i]->xenListDefinedDomains) {
1482
            ret = drivers[i]->xenListDefinedDomains(conn, names, maxnames);
1483 1484
            if (ret >= 0) return ret;
        }
1485

1486
    return -1;
1487 1488 1489
}

static int
1490
xenUnifiedNumOfDefinedDomains(virConnectPtr conn)
1491
{
1492
    GET_PRIVATE(conn);
1493 1494
    int i;
    int ret;
1495

1496
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1497
        if (priv->opened[i] && drivers[i]->xenNumOfDefinedDomains) {
1498
            ret = drivers[i]->xenNumOfDefinedDomains(conn);
1499 1500
            if (ret >= 0) return ret;
        }
1501

1502
    return -1;
1503 1504 1505
}

static int
1506
xenUnifiedDomainCreateWithFlags(virDomainPtr dom, unsigned int flags)
1507
{
1508
    GET_PRIVATE(dom->conn);
1509
    int i;
1510

1511 1512
    virCheckFlags(0, -1);

1513
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1514
        if (priv->opened[i] && drivers[i]->xenDomainCreate &&
1515
            drivers[i]->xenDomainCreate(dom) == 0)
1516
            return 0;
1517

1518
    return -1;
1519 1520
}

1521
static int
1522
xenUnifiedDomainCreate(virDomainPtr dom)
1523 1524 1525 1526
{
    return xenUnifiedDomainCreateWithFlags(dom, 0);
}

1527
static virDomainPtr
1528
xenUnifiedDomainDefineXML(virConnectPtr conn, const char *xml)
1529
{
1530
    GET_PRIVATE(conn);
1531 1532
    int i;
    virDomainPtr ret;
1533

1534
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1535
        if (priv->opened[i] && drivers[i]->xenDomainDefineXML) {
1536
            ret = drivers[i]->xenDomainDefineXML(conn, xml);
1537 1538
            if (ret) return ret;
        }
1539

1540
    return NULL;
1541 1542 1543
}

static int
1544
xenUnifiedDomainUndefineFlags(virDomainPtr dom, unsigned int flags)
1545
{
1546
    GET_PRIVATE(dom->conn);
1547
    int i;
1548

1549
    virCheckFlags(0, -1);
1550
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1551
        if (priv->opened[i] && drivers[i]->xenDomainUndefine &&
1552
            drivers[i]->xenDomainUndefine(dom) == 0)
1553
            return 0;
1554

1555
    return -1;
1556 1557
}

1558
static int
1559
xenUnifiedDomainUndefine(virDomainPtr dom) {
1560 1561 1562
    return xenUnifiedDomainUndefineFlags(dom, 0);
}

1563
static int
1564
xenUnifiedDomainAttachDevice(virDomainPtr dom, const char *xml)
1565 1566 1567
{
    GET_PRIVATE(dom->conn);
    int i;
1568
    unsigned int flags = VIR_DOMAIN_DEVICE_MODIFY_LIVE;
1569

1570 1571 1572 1573 1574 1575
    /*
     * HACK: xend with xendConfigVersion >= 3 does not support changing live
     * config without touching persistent config, we add the extra flag here
     * to make this API work
     */
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET] &&
1576
        priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4)
1577
        flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
1578 1579

    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1580 1581
        if (priv->opened[i] && drivers[i]->xenDomainAttachDeviceFlags &&
            drivers[i]->xenDomainAttachDeviceFlags(dom, xml, flags) == 0)
1582 1583 1584 1585 1586 1587
            return 0;

    return -1;
}

static int
1588 1589
xenUnifiedDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                  unsigned int flags)
1590
{
1591
    GET_PRIVATE(dom->conn);
1592
    int i;
1593

1594
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1595 1596
        if (priv->opened[i] && drivers[i]->xenDomainAttachDeviceFlags &&
            drivers[i]->xenDomainAttachDeviceFlags(dom, xml, flags) == 0)
1597
            return 0;
1598

1599
    return -1;
1600 1601 1602
}

static int
1603
xenUnifiedDomainDetachDevice(virDomainPtr dom, const char *xml)
1604 1605 1606
{
    GET_PRIVATE(dom->conn);
    int i;
1607
    unsigned int flags = VIR_DOMAIN_DEVICE_MODIFY_LIVE;
1608

1609 1610 1611 1612 1613 1614
    /*
     * HACK: xend with xendConfigVersion >= 3 does not support changing live
     * config without touching persistent config, we add the extra flag here
     * to make this API work
     */
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET] &&
1615
        priv->xendConfigVersion >= XEND_CONFIG_VERSION_3_0_4)
1616
        flags |= VIR_DOMAIN_DEVICE_MODIFY_CONFIG;
1617 1618

    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1619 1620
        if (priv->opened[i] && drivers[i]->xenDomainDetachDeviceFlags &&
            drivers[i]->xenDomainDetachDeviceFlags(dom, xml, flags) == 0)
1621 1622 1623 1624 1625 1626
            return 0;

    return -1;
}

static int
1627 1628
xenUnifiedDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                  unsigned int flags)
1629
{
1630
    GET_PRIVATE(dom->conn);
1631
    int i;
1632

1633
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i)
E
Eric Blake 已提交
1634 1635
        if (priv->opened[i] && drivers[i]->xenDomainDetachDeviceFlags &&
            drivers[i]->xenDomainDetachDeviceFlags(dom, xml, flags) == 0)
1636
            return 0;
1637

1638
    return -1;
1639 1640
}

1641
static int
1642 1643
xenUnifiedDomainUpdateDeviceFlags(virDomainPtr dom, const char *xml,
                                  unsigned int flags)
1644 1645 1646
{
    GET_PRIVATE(dom->conn);

1647 1648
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
        return xenDaemonUpdateDeviceFlags(dom, xml, flags);
1649 1650 1651
    return -1;
}

1652
static int
1653
xenUnifiedDomainGetAutostart(virDomainPtr dom, int *autostart)
1654 1655 1656
{
    GET_PRIVATE(dom->conn);

1657
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4) {
1658 1659 1660 1661 1662 1663
        if (priv->opened[XEN_UNIFIED_XM_OFFSET])
            return xenXMDomainGetAutostart(dom, autostart);
    } else {
        if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
            return xenDaemonDomainGetAutostart(dom, autostart);
    }
1664

1665
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1666 1667 1668 1669
    return -1;
}

static int
1670
xenUnifiedDomainSetAutostart(virDomainPtr dom, int autostart)
1671 1672 1673
{
    GET_PRIVATE(dom->conn);

1674
    if (priv->xendConfigVersion < XEND_CONFIG_VERSION_3_0_4) {
1675 1676 1677 1678 1679 1680
        if (priv->opened[XEN_UNIFIED_XM_OFFSET])
            return xenXMDomainSetAutostart(dom, autostart);
    } else {
        if (priv->opened[XEN_UNIFIED_XEND_OFFSET])
            return xenDaemonDomainSetAutostart(dom, autostart);
    }
1681

1682
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1683 1684 1685
    return -1;
}

1686
static char *
1687
xenUnifiedDomainGetSchedulerType(virDomainPtr dom, int *nparams)
1688 1689 1690 1691 1692 1693
{
    GET_PRIVATE(dom->conn);
    int i;
    char *schedulertype;

    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; i++) {
E
Eric Blake 已提交
1694
        if (priv->opened[i] && drivers[i]->xenDomainGetSchedulerType) {
1695
            schedulertype = drivers[i]->xenDomainGetSchedulerType(dom, nparams);
1696
            if (schedulertype != NULL)
1697
                return schedulertype;
1698 1699
        }
    }
1700
    return NULL;
1701 1702 1703
}

static int
1704 1705 1706 1707
xenUnifiedDomainGetSchedulerParametersFlags(virDomainPtr dom,
                                            virTypedParameterPtr params,
                                            int *nparams,
                                            unsigned int flags)
1708 1709 1710 1711
{
    GET_PRIVATE(dom->conn);
    int i, ret;

1712 1713
    virCheckFlags(0, -1);

1714
    for (i = 0; i < XEN_UNIFIED_NR_DRIVERS; ++i) {
E
Eric Blake 已提交
1715 1716
        if (priv->opened[i] && drivers[i]->xenDomainGetSchedulerParameters) {
           ret = drivers[i]->xenDomainGetSchedulerParameters(dom, params, nparams);
1717
           if (ret == 0)
1718
               return 0;
1719
        }
1720
    }
1721
    return -1;
1722 1723 1724
}

static int
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
xenUnifiedDomainGetSchedulerParameters(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int *nparams)
{
    return xenUnifiedDomainGetSchedulerParametersFlags(dom, params,
                                                       nparams, 0);
}

static int
xenUnifiedDomainSetSchedulerParametersFlags(virDomainPtr dom,
                                            virTypedParameterPtr params,
                                            int nparams,
                                            unsigned int flags)
1738 1739 1740 1741
{
    GET_PRIVATE(dom->conn);
    int i, ret;

1742 1743
    virCheckFlags(0, -1);

1744 1745
    /* do the hypervisor call last to get better error */
    for (i = XEN_UNIFIED_NR_DRIVERS - 1; i >= 0; i--) {
E
Eric Blake 已提交
1746 1747
        if (priv->opened[i] && drivers[i]->xenDomainSetSchedulerParameters) {
           ret = drivers[i]->xenDomainSetSchedulerParameters(dom, params, nparams);
1748 1749 1750
           if (ret == 0)
               return 0;
        }
1751 1752
    }

1753
    return -1;
1754 1755
}

1756 1757 1758 1759 1760 1761 1762 1763 1764
static int
xenUnifiedDomainSetSchedulerParameters(virDomainPtr dom,
                                       virTypedParameterPtr params,
                                       int nparams)
{
    return xenUnifiedDomainSetSchedulerParametersFlags(dom, params,
                                                       nparams, 0);
}

1765
static int
1766 1767
xenUnifiedDomainBlockStats(virDomainPtr dom, const char *path,
                           struct _virDomainBlockStats *stats)
1768
{
1769
    GET_PRIVATE(dom->conn);
1770 1771

    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET])
1772
        return xenHypervisorDomainBlockStats(dom, path, stats);
1773

1774
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1775 1776 1777 1778
    return -1;
}

static int
1779 1780
xenUnifiedDomainInterfaceStats(virDomainPtr dom, const char *path,
                               struct _virDomainInterfaceStats *stats)
1781
{
1782
    GET_PRIVATE(dom->conn);
1783 1784

    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET])
1785
        return xenHypervisorDomainInterfaceStats(dom, path, stats);
1786

1787
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1788 1789 1790
    return -1;
}

R
Richard W.M. Jones 已提交
1791
static int
1792 1793 1794
xenUnifiedDomainBlockPeek(virDomainPtr dom, const char *path,
                          unsigned long long offset, size_t size,
                          void *buffer, unsigned int flags)
R
Richard W.M. Jones 已提交
1795 1796
{
    int r;
1797
    GET_PRIVATE(dom->conn);
R
Richard W.M. Jones 已提交
1798

E
Eric Blake 已提交
1799 1800
    virCheckFlags(0, -1);

R
Richard W.M. Jones 已提交
1801
    if (priv->opened[XEN_UNIFIED_XEND_OFFSET]) {
1802
        r = xenDaemonDomainBlockPeek(dom, path, offset, size, buffer);
R
Richard W.M. Jones 已提交
1803 1804 1805 1806 1807
        if (r != -2) return r;
        /* r == -2 means declined, so fall through to XM driver ... */
    }

    if (priv->opened[XEN_UNIFIED_XM_OFFSET]) {
1808
        if (xenXMDomainBlockPeek(dom, path, offset, size, buffer) == 0)
R
Richard W.M. Jones 已提交
1809 1810 1811
            return 0;
    }

1812
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
R
Richard W.M. Jones 已提交
1813 1814 1815
    return -1;
}

1816
static int
1817 1818
xenUnifiedNodeGetCellsFreeMemory(virConnectPtr conn, unsigned long long *freeMems,
                                 int startCell, int maxCells)
1819
{
1820
    GET_PRIVATE(conn);
1821 1822

    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET])
1823 1824
        return xenHypervisorNodeGetCellsFreeMemory(conn, freeMems,
                                                   startCell, maxCells);
1825

1826
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1827 1828 1829
    return -1;
}

1830
static unsigned long long
1831
xenUnifiedNodeGetFreeMemory(virConnectPtr conn)
1832 1833 1834
{
    unsigned long long freeMem = 0;
    int ret;
1835
    GET_PRIVATE(conn);
1836 1837

    if (priv->opened[XEN_UNIFIED_HYPERVISOR_OFFSET]) {
1838 1839
        ret = xenHypervisorNodeGetCellsFreeMemory(conn, &freeMem,
                                                  -1, 1);
1840
        if (ret != 1)
1841 1842
            return 0;
        return freeMem;
1843 1844
    }

1845
    virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1846
    return 0;
1847 1848
}

1849

1850
static int
1851 1852 1853 1854
xenUnifiedDomainEventRegister(virConnectPtr conn,
                              virConnectDomainEventCallback callback,
                              void *opaque,
                              virFreeCallback freefunc)
1855
{
1856
    GET_PRIVATE(conn);
D
Daniel P. Berrange 已提交
1857

1858
    int ret;
D
Daniel P. Berrange 已提交
1859
    xenUnifiedLock(priv);
1860

1861
    if (priv->xsWatch == -1) {
1862
        virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
D
Daniel P. Berrange 已提交
1863
        xenUnifiedUnlock(priv);
1864 1865 1866
        return -1;
    }

1867 1868
    ret = virDomainEventStateRegister(conn, priv->domainEvents,
                                      callback, opaque, freefunc);
1869

D
Daniel P. Berrange 已提交
1870
    xenUnifiedUnlock(priv);
1871
    return ret;
1872 1873
}

1874

1875
static int
1876 1877
xenUnifiedDomainEventDeregister(virConnectPtr conn,
                                virConnectDomainEventCallback callback)
1878 1879
{
    int ret;
1880
    GET_PRIVATE(conn);
D
Daniel P. Berrange 已提交
1881 1882
    xenUnifiedLock(priv);

1883
    if (priv->xsWatch == -1) {
1884
        virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
D
Daniel P. Berrange 已提交
1885
        xenUnifiedUnlock(priv);
1886 1887 1888
        return -1;
    }

1889 1890 1891
    ret = virDomainEventStateDeregister(conn,
                                        priv->domainEvents,
                                        callback);
1892

D
Daniel P. Berrange 已提交
1893
    xenUnifiedUnlock(priv);
1894 1895 1896
    return ret;
}

1897

1898 1899 1900 1901 1902 1903 1904 1905
static int
xenUnifiedDomainEventRegisterAny(virConnectPtr conn,
                                 virDomainPtr dom,
                                 int eventID,
                                 virConnectDomainEventGenericCallback callback,
                                 void *opaque,
                                 virFreeCallback freefunc)
{
1906
    GET_PRIVATE(conn);
1907 1908 1909 1910 1911

    int ret;
    xenUnifiedLock(priv);

    if (priv->xsWatch == -1) {
1912
        virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1913 1914 1915 1916
        xenUnifiedUnlock(priv);
        return -1;
    }

1917 1918 1919
    if (virDomainEventStateRegisterID(conn, priv->domainEvents,
                                      dom, eventID,
                                      callback, opaque, freefunc, &ret) < 0)
1920
        ret = -1;
1921 1922

    xenUnifiedUnlock(priv);
1923
    return ret;
1924 1925 1926 1927 1928 1929 1930
}

static int
xenUnifiedDomainEventDeregisterAny(virConnectPtr conn,
                                   int callbackID)
{
    int ret;
1931
    GET_PRIVATE(conn);
1932 1933 1934
    xenUnifiedLock(priv);

    if (priv->xsWatch == -1) {
1935
        virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
1936 1937 1938 1939
        xenUnifiedUnlock(priv);
        return -1;
    }

1940 1941 1942
    ret = virDomainEventStateDeregisterID(conn,
                                          priv->domainEvents,
                                          callbackID);
1943 1944 1945 1946 1947 1948

    xenUnifiedUnlock(priv);
    return ret;
}


1949
static int
1950 1951 1952 1953 1954
xenUnifiedNodeDeviceGetPciInfo(virNodeDevicePtr dev,
                               unsigned *domain,
                               unsigned *bus,
                               unsigned *slot,
                               unsigned *function)
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
{
    virNodeDeviceDefPtr def = NULL;
    virNodeDevCapsDefPtr cap;
    char *xml = NULL;
    int ret = -1;

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

1965
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL);
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
    if (!def)
        goto out;

    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) {
1983 1984
        virReportError(VIR_ERR_INVALID_ARG,
                       _("device %s is not a PCI device"), dev->name);
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
        goto out;
    }

    ret = 0;
out:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
1996
xenUnifiedNodeDeviceDettach(virNodeDevicePtr dev)
1997 1998 1999 2000 2001 2002 2003 2004
{
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (xenUnifiedNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

2005
    pci = pciGetDevice(domain, bus, slot, function);
2006 2007 2008
    if (!pci)
        return -1;

2009
    if (pciDettachDevice(pci, NULL, NULL) < 0)
2010 2011 2012 2013
        goto out;

    ret = 0;
out:
2014
    pciFreeDevice(pci);
2015 2016 2017
    return ret;
}

2018
static int
2019
xenUnifiedNodeDeviceAssignedDomainId(virNodeDevicePtr dev)
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
{
    int numdomains;
    int ret = -1, i;
    int *ids = NULL;
    char *bdf = NULL;
    char *xref = NULL;
    unsigned int domain, bus, slot, function;
    virConnectPtr conn = dev->conn;
    xenUnifiedPrivatePtr priv = conn->privateData;

    /* Get active domains */
    numdomains = xenUnifiedNumOfDomains(conn);
    if (numdomains < 0) {
        return ret;
    }
    if (numdomains > 0){
        if (VIR_ALLOC_N(ids, numdomains) < 0) {
            virReportOOMError();
            goto out;
        }
        if ((numdomains = xenUnifiedListDomains(conn, &ids[0], numdomains)) < 0) {
            goto out;
        }
    }

    /* Get pci bdf */
    if (xenUnifiedNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        goto out;

    if (virAsprintf(&bdf, "%04x:%02x:%02x.%0x",
                    domain, bus, slot, function) < 0) {
        virReportOOMError();
        goto out;
    }

    xenUnifiedLock(priv);
    /* Check if bdf is assigned to one of active domains */
2057
    for (i = 0; i < numdomains; i++) {
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
        xref = xenStoreDomainGetPCIID(conn, ids[i], bdf);
        if (xref == NULL) {
            continue;
        } else {
            ret = ids[i];
            break;
        }
    }
    xenUnifiedUnlock(priv);

    VIR_FREE(xref);
    VIR_FREE(bdf);
out:
    VIR_FREE(ids);

    return ret;
}

2076
static int
2077
xenUnifiedNodeDeviceReAttach(virNodeDevicePtr dev)
2078 2079 2080 2081
{
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;
2082
    int domid;
2083 2084 2085 2086

    if (xenUnifiedNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

2087
    pci = pciGetDevice(domain, bus, slot, function);
2088 2089 2090
    if (!pci)
        return -1;

2091 2092
    /* Check if device is assigned to an active guest */
    if ((domid = xenUnifiedNodeDeviceAssignedDomainId(dev)) >= 0) {
2093 2094 2095
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Device %s has been assigned to guest %d"),
                       dev->name, domid);
2096 2097 2098
        goto out;
    }

2099
    if (pciReAttachDevice(pci, NULL, NULL) < 0)
2100 2101 2102 2103
        goto out;

    ret = 0;
out:
2104
    pciFreeDevice(pci);
2105 2106 2107 2108
    return ret;
}

static int
2109
xenUnifiedNodeDeviceReset(virNodeDevicePtr dev)
2110 2111 2112 2113 2114 2115 2116 2117
{
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (xenUnifiedNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

2118
    pci = pciGetDevice(domain, bus, slot, function);
2119 2120 2121
    if (!pci)
        return -1;

2122
    if (pciResetDevice(pci, NULL, NULL) < 0)
2123 2124 2125 2126
        goto out;

    ret = 0;
out:
2127
    pciFreeDevice(pci);
2128 2129 2130 2131
    return ret;
}


2132 2133
static int
xenUnifiedDomainOpenConsole(virDomainPtr dom,
2134
                            const char *dev_name,
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
                            virStreamPtr st,
                            unsigned int flags)
{
    virDomainDefPtr def = NULL;
    int ret = -1;
    virDomainChrDefPtr chr = NULL;

    virCheckFlags(0, -1);

    if (dom->id == -1) {
2145 2146
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
2147 2148 2149
        goto cleanup;
    }

2150
    if (dev_name) {
2151
        /* XXX support device aliases in future */
2152 2153
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Named device aliases are not supported"));
2154 2155 2156 2157 2158 2159 2160
        goto cleanup;
    }

    def = xenDaemonDomainFetch(dom->conn, dom->id, dom->name, NULL);
    if (!def)
        goto cleanup;

2161 2162
    if (def->nconsoles)
        chr = def->consoles[0];
2163 2164 2165 2166
    else if (def->nserials)
        chr = def->serials[0];

    if (!chr) {
2167 2168
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot find default console device"));
2169 2170 2171
        goto cleanup;
    }

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

2178
    if (virFDStreamOpenFile(st, chr->source.data.file.path,
E
Eric Blake 已提交
2179
                            0, 0, O_RDWR) < 0)
2180 2181 2182 2183 2184 2185 2186
        goto cleanup;

    ret = 0;
cleanup:
    virDomainDefFree(def);
    return ret;
}
E
Eric Blake 已提交
2187
/*----- Register with libvirt.c, and initialize Xen drivers. -----*/
2188 2189 2190

/* The interface which we export upwards to libvirt.c. */
static virDriver xenUnifiedDriver = {
2191 2192
    .no = VIR_DRV_XEN_UNIFIED,
    .name = "Xen",
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
    .open = xenUnifiedOpen, /* 0.0.3 */
    .close = xenUnifiedClose, /* 0.0.3 */
    .supports_feature = xenUnifiedSupportsFeature, /* 0.3.2 */
    .type = xenUnifiedType, /* 0.0.3 */
    .version = xenUnifiedGetVersion, /* 0.0.3 */
    .getHostname = virGetHostname, /* 0.7.3 */
    .getMaxVcpus = xenUnifiedGetMaxVcpus, /* 0.2.1 */
    .nodeGetInfo = xenUnifiedNodeGetInfo, /* 0.1.0 */
    .getCapabilities = xenUnifiedGetCapabilities, /* 0.2.1 */
    .listDomains = xenUnifiedListDomains, /* 0.0.3 */
    .numOfDomains = xenUnifiedNumOfDomains, /* 0.0.3 */
    .domainCreateXML = xenUnifiedDomainCreateXML, /* 0.0.3 */
    .domainLookupByID = xenUnifiedDomainLookupByID, /* 0.0.3 */
    .domainLookupByUUID = xenUnifiedDomainLookupByUUID, /* 0.0.5 */
    .domainLookupByName = xenUnifiedDomainLookupByName, /* 0.0.3 */
    .domainSuspend = xenUnifiedDomainSuspend, /* 0.0.3 */
    .domainResume = xenUnifiedDomainResume, /* 0.0.3 */
    .domainShutdown = xenUnifiedDomainShutdown, /* 0.0.3 */
2211
    .domainShutdownFlags = xenUnifiedDomainShutdownFlags, /* 0.9.10 */
2212 2213
    .domainReboot = xenUnifiedDomainReboot, /* 0.1.0 */
    .domainDestroy = xenUnifiedDomainDestroy, /* 0.0.3 */
2214
    .domainDestroyFlags = xenUnifiedDomainDestroyFlags, /* 0.9.4 */
2215 2216 2217 2218 2219 2220 2221
    .domainGetOSType = xenUnifiedDomainGetOSType, /* 0.0.3 */
    .domainGetMaxMemory = xenUnifiedDomainGetMaxMemory, /* 0.0.3 */
    .domainSetMaxMemory = xenUnifiedDomainSetMaxMemory, /* 0.0.3 */
    .domainSetMemory = xenUnifiedDomainSetMemory, /* 0.1.1 */
    .domainGetInfo = xenUnifiedDomainGetInfo, /* 0.0.3 */
    .domainGetState = xenUnifiedDomainGetState, /* 0.9.2 */
    .domainSave = xenUnifiedDomainSave, /* 0.0.3 */
2222
    .domainSaveFlags = xenUnifiedDomainSaveFlags, /* 0.9.4 */
2223
    .domainRestore = xenUnifiedDomainRestore, /* 0.0.3 */
2224
    .domainRestoreFlags = xenUnifiedDomainRestoreFlags, /* 0.9.4 */
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
    .domainCoreDump = xenUnifiedDomainCoreDump, /* 0.1.9 */
    .domainSetVcpus = xenUnifiedDomainSetVcpus, /* 0.1.4 */
    .domainSetVcpusFlags = xenUnifiedDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = xenUnifiedDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = xenUnifiedDomainPinVcpu, /* 0.1.4 */
    .domainGetVcpus = xenUnifiedDomainGetVcpus, /* 0.1.4 */
    .domainGetMaxVcpus = xenUnifiedDomainGetMaxVcpus, /* 0.2.1 */
    .domainGetXMLDesc = xenUnifiedDomainGetXMLDesc, /* 0.0.3 */
    .domainXMLFromNative = xenUnifiedDomainXMLFromNative, /* 0.6.4 */
    .domainXMLToNative = xenUnifiedDomainXMLToNative, /* 0.6.4 */
    .listDefinedDomains = xenUnifiedListDefinedDomains, /* 0.1.1 */
    .numOfDefinedDomains = xenUnifiedNumOfDefinedDomains, /* 0.1.5 */
    .domainCreate = xenUnifiedDomainCreate, /* 0.1.1 */
    .domainCreateWithFlags = xenUnifiedDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = xenUnifiedDomainDefineXML, /* 0.1.1 */
    .domainUndefine = xenUnifiedDomainUndefine, /* 0.1.1 */
2241
    .domainUndefineFlags = xenUnifiedDomainUndefineFlags, /* 0.9.4 */
2242 2243 2244 2245 2246 2247 2248 2249 2250
    .domainAttachDevice = xenUnifiedDomainAttachDevice, /* 0.1.9 */
    .domainAttachDeviceFlags = xenUnifiedDomainAttachDeviceFlags, /* 0.7.7 */
    .domainDetachDevice = xenUnifiedDomainDetachDevice, /* 0.1.9 */
    .domainDetachDeviceFlags = xenUnifiedDomainDetachDeviceFlags, /* 0.7.7 */
    .domainUpdateDeviceFlags = xenUnifiedDomainUpdateDeviceFlags, /* 0.8.0 */
    .domainGetAutostart = xenUnifiedDomainGetAutostart, /* 0.4.4 */
    .domainSetAutostart = xenUnifiedDomainSetAutostart, /* 0.4.4 */
    .domainGetSchedulerType = xenUnifiedDomainGetSchedulerType, /* 0.2.3 */
    .domainGetSchedulerParameters = xenUnifiedDomainGetSchedulerParameters, /* 0.2.3 */
2251
    .domainGetSchedulerParametersFlags = xenUnifiedDomainGetSchedulerParametersFlags, /* 0.9.2 */
2252
    .domainSetSchedulerParameters = xenUnifiedDomainSetSchedulerParameters, /* 0.2.3 */
2253
    .domainSetSchedulerParametersFlags = xenUnifiedDomainSetSchedulerParametersFlags, /* 0.9.2 */
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
    .domainMigratePrepare = xenUnifiedDomainMigratePrepare, /* 0.3.2 */
    .domainMigratePerform = xenUnifiedDomainMigratePerform, /* 0.3.2 */
    .domainMigrateFinish = xenUnifiedDomainMigrateFinish, /* 0.3.2 */
    .domainBlockStats = xenUnifiedDomainBlockStats, /* 0.3.2 */
    .domainInterfaceStats = xenUnifiedDomainInterfaceStats, /* 0.3.2 */
    .domainBlockPeek = xenUnifiedDomainBlockPeek, /* 0.4.4 */
    .nodeGetCellsFreeMemory = xenUnifiedNodeGetCellsFreeMemory, /* 0.3.3 */
    .nodeGetFreeMemory = xenUnifiedNodeGetFreeMemory, /* 0.3.3 */
    .domainEventRegister = xenUnifiedDomainEventRegister, /* 0.5.0 */
    .domainEventDeregister = xenUnifiedDomainEventDeregister, /* 0.5.0 */
    .nodeDeviceDettach = xenUnifiedNodeDeviceDettach, /* 0.6.1 */
    .nodeDeviceReAttach = xenUnifiedNodeDeviceReAttach, /* 0.6.1 */
    .nodeDeviceReset = xenUnifiedNodeDeviceReset, /* 0.6.1 */
    .isEncrypted = xenUnifiedIsEncrypted, /* 0.7.3 */
    .isSecure = xenUnifiedIsSecure, /* 0.7.3 */
    .domainIsActive = xenUnifiedDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = xenUnifiedDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = xenUnifiedDomainIsUpdated, /* 0.8.6 */
    .domainEventRegisterAny = xenUnifiedDomainEventRegisterAny, /* 0.8.0 */
    .domainEventDeregisterAny = xenUnifiedDomainEventDeregisterAny, /* 0.8.0 */
    .domainOpenConsole = xenUnifiedDomainOpenConsole, /* 0.8.6 */
2275
    .isAlive = xenUnifiedIsAlive, /* 0.9.8 */
2276
    .nodeSuspendForDuration = nodeSuspendForDuration, /* 0.9.8 */
2277 2278
    .nodeGetMemoryParameters = nodeGetMemoryParameters, /* 0.10.2 */
    .nodeSetMemoryParameters = nodeSetMemoryParameters, /* 0.10.2 */
2279 2280
};

2281
/**
2282
 * xenRegister:
2283 2284 2285 2286 2287
 *
 * Register xen related drivers
 *
 * Returns the driver priority or -1 in case of error.
 */
2288
int
2289
xenRegister(void)
2290
{
J
John Levon 已提交
2291
#ifdef WITH_LIBVIRTD
2292
    if (virRegisterStateDriver(&state_driver) == -1) return -1;
J
John Levon 已提交
2293 2294
#endif

2295
    return virRegisterDriver(&xenUnifiedDriver);
2296 2297
}

2298 2299 2300 2301 2302 2303 2304 2305 2306
/**
 * xenUnifiedDomainInfoListFree:
 *
 * Free the Domain Info List
 */
void
xenUnifiedDomainInfoListFree(xenUnifiedDomainInfoListPtr list)
{
    int i;
J
John Levon 已提交
2307 2308 2309 2310

    if (list == NULL)
        return;

2311 2312 2313 2314
    for (i=0; i<list->count; i++) {
        VIR_FREE(list->doms[i]->name);
        VIR_FREE(list->doms[i]);
    }
2315
    VIR_FREE(list->doms);
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
    VIR_FREE(list);
}

/**
 * xenUnifiedAddDomainInfo:
 *
 * Add name and uuid to the domain info list
 *
 * Returns: 0 on success, -1 on failure
 */
int
xenUnifiedAddDomainInfo(xenUnifiedDomainInfoListPtr list,
                        int id, char *name,
                        unsigned char *uuid)
{
    xenUnifiedDomainInfoPtr info;
    int n;

    /* check if we already have this callback on our list */
    for (n=0; n < list->count; n++) {
        if (STREQ(list->doms[n]->name, name) &&
            !memcmp(list->doms[n]->uuid, uuid, VIR_UUID_BUFLEN)) {
2338
            VIR_DEBUG("WARNING: dom already tracked");
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
            return -1;
        }
    }

    if (VIR_ALLOC(info) < 0)
        goto memory_error;
    if (!(info->name = strdup(name)))
        goto memory_error;

    memcpy(info->uuid, uuid, VIR_UUID_BUFLEN);
    info->id = id;

    /* Make space on list */
    n = list->count;
    if (VIR_REALLOC_N(list->doms, n + 1) < 0) {
        goto memory_error;
    }

    list->doms[n] = info;
    list->count++;
    return 0;
memory_error:
2361
    virReportOOMError();
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
    if (info)
        VIR_FREE(info->name);
    VIR_FREE(info);
    return -1;
}

/**
 * xenUnifiedRemoveDomainInfo:
 *
 * Removes name and uuid to the domain info list
 *
 * Returns: 0 on success, -1 on failure
 */
int
xenUnifiedRemoveDomainInfo(xenUnifiedDomainInfoListPtr list,
                           int id, char *name,
                           unsigned char *uuid)
{
    int i;
    for (i = 0 ; i < list->count ; i++) {
2382
        if (list->doms[i]->id == id &&
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
            STREQ(list->doms[i]->name, name) &&
            !memcmp(list->doms[i]->uuid, uuid, VIR_UUID_BUFLEN)) {

            VIR_FREE(list->doms[i]->name);
            VIR_FREE(list->doms[i]);

            if (i < (list->count - 1))
                memmove(list->doms + i,
                        list->doms + i + 1,
                        sizeof(*(list->doms)) *
                                (list->count - (i + 1)));

            if (VIR_REALLOC_N(list->doms,
                              list->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            list->count--;

            return 0;
        }
    }
    return -1;
}

2407

2408 2409
/**
 * xenUnifiedDomainEventDispatch:
D
Daniel P. Berrange 已提交
2410 2411
 * @priv: the connection to dispatch events on
 * @event: the event to dispatch
2412 2413 2414
 *
 * Dispatch domain events to registered callbacks
 *
D
Daniel P. Berrange 已提交
2415 2416
 * The caller must hold the lock in 'priv' before invoking
 *
2417
 */
2418
void xenUnifiedDomainEventDispatch(xenUnifiedPrivatePtr priv,
2419
                                    virDomainEventPtr event)
2420
{
D
Daniel P. Berrange 已提交
2421
    if (!priv)
2422
        return;
2423

2424
    virDomainEventStateQueue(priv->domainEvents, event);
D
Daniel P. Berrange 已提交
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
}

void xenUnifiedLock(xenUnifiedPrivatePtr priv)
{
    virMutexLock(&priv->lock);
}

void xenUnifiedUnlock(xenUnifiedPrivatePtr priv)
{
    virMutexUnlock(&priv->lock);
2435
}