“79d9d2432ff6142102c4e9489d79741b6baf54c7”上不存在“src/qemu/qemu_driver.c”
qemu_driver.c 411.0 KB
Newer Older
D
Daniel P. Berrange 已提交
1 2 3
/*
 * driver.c: core driver methods for managing qemu guests
 *
4
 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

24
#include <config.h>
25

D
Daniel P. Berrange 已提交
26 27
#include <sys/types.h>
#include <sys/poll.h>
28
#include <sys/time.h>
D
Daniel P. Berrange 已提交
29 30 31
#include <dirent.h>
#include <limits.h>
#include <string.h>
32
#include <stdbool.h>
D
Daniel P. Berrange 已提交
33 34 35 36 37
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
38
#include <sys/utsname.h>
39 40 41 42
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
43
#include <pwd.h>
44
#include <grp.h>
45
#include <stdio.h>
46
#include <sys/wait.h>
47
#include <sys/ioctl.h>
48
#include <sys/un.h>
D
Daniel P. Berrange 已提交
49

50 51
#include <libxml/xpathInternals.h>

52
#include "virterror_internal.h"
53
#include "logging.h"
54
#include "datatypes.h"
55 56
#include "qemu_driver.h"
#include "qemu_conf.h"
57
#include "qemu_monitor.h"
58
#include "qemu_bridge_filter.h"
J
Jim Meyering 已提交
59
#include "c-ctype.h"
60
#include "event.h"
61
#include "buf.h"
62
#include "util.h"
63
#include "nodeinfo.h"
64
#include "stats_linux.h"
65
#include "capabilities.h"
66
#include "memory.h"
67
#include "uuid.h"
68
#include "domain_conf.h"
69 70
#include "node_device_conf.h"
#include "pci.h"
71
#include "hostusb.h"
72
#include "processinfo.h"
73 74
#include "qemu_security_stacked.h"
#include "qemu_security_dac.h"
75
#include "cgroup.h"
C
Chris Lalancette 已提交
76
#include "libvirt_internal.h"
77
#include "xml.h"
78
#include "cpu/cpu.h"
79
#include "macvtap.h"
80
#include "domain_nwfilter.h"
81
#include "hooks.h"
82
#include "storage_file.h"
83
#include "virtaudit.h"
84

85

86 87
#define VIR_FROM_THIS VIR_FROM_QEMU

88 89 90
#define QEMU_VNC_PORT_MIN  5900
#define QEMU_VNC_PORT_MAX  65535

91 92
#define QEMU_NB_MEM_PARAM  3

93 94
#define QEMU_NAMESPACE_HREF "http://libvirt.org/schemas/domain/qemu/1.0"

95 96 97 98 99 100
/* Only 1 job is allowed at any time
 * A job includes *all* monitor commands, even those just querying
 * information, not merely actions */
enum qemuDomainJob {
    QEMU_JOB_NONE = 0,  /* Always set to 0 for easy if (jobActive) conditions */
    QEMU_JOB_UNSPECIFIED,
101 102
    QEMU_JOB_MIGRATION_OUT,
    QEMU_JOB_MIGRATION_IN,
103 104 105 106 107
};

enum qemuDomainJobSignals {
    QEMU_JOB_SIGNAL_CANCEL  = 1 << 0, /* Request job cancellation */
    QEMU_JOB_SIGNAL_SUSPEND = 1 << 1, /* Request VM suspend to finish live migration offline */
108 109 110 111 112
    QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME = 1 << 2, /* Request migration downtime change */
};

struct qemuDomainJobSignalsData {
    unsigned long long migrateDowntime; /* Data for QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME */
113 114
};

115 116 117
typedef struct _qemuDomainObjPrivate qemuDomainObjPrivate;
typedef qemuDomainObjPrivate *qemuDomainObjPrivatePtr;
struct _qemuDomainObjPrivate {
118
    virCond jobCond; /* Use in conjunction with main virDomainObjPtr lock */
119 120
    enum qemuDomainJob jobActive;   /* Currently running job */
    unsigned int jobSignals;        /* Signals for running job */
121
    struct qemuDomainJobSignalsData jobSignalsData; /* Signal specific data */
122 123
    virDomainJobInfo jobInfo;
    unsigned long long jobStart;
124

125
    qemuMonitorPtr mon;
126
    virDomainChrDefPtr monConfig;
D
Daniel P. Berrange 已提交
127
    int monJSON;
128
    int monitor_warned;
129 130 131

    int nvcpupids;
    int *vcpupids;
132 133

    qemuDomainPCIAddressSetPtr pciaddrs;
134
    int persistentAddrs;
135 136
};

137 138
static int qemudShutdown(void);

139 140
static void qemuDriverLock(struct qemud_driver *driver)
{
141
    virMutexLock(&driver->lock);
142 143 144
}
static void qemuDriverUnlock(struct qemud_driver *driver)
{
145
    virMutexUnlock(&driver->lock);
146 147
}

148 149 150
static void qemuDomainEventFlush(int timer, void *opaque);
static void qemuDomainEventQueue(struct qemud_driver *driver,
                                 virDomainEventPtr event);
151

J
Jiri Denemark 已提交
152 153
static int qemudDomainObjStart(virConnectPtr conn,
                               struct qemud_driver *driver,
154 155
                               virDomainObjPtr vm,
                               bool start_paused);
J
Jiri Denemark 已提交
156

157 158
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
159
                              virDomainObjPtr vm,
160
                              const char *migrateFrom,
161
                              bool start_paused,
162 163
                              int stdin_fd,
                              const char *stdin_path);
164

165
static void qemudShutdownVMDaemon(struct qemud_driver *driver,
166 167
                                  virDomainObjPtr vm,
                                  int migrated);
168

169 170 171
static void qemuDomainStartAudit(virDomainObjPtr vm, const char *reason, bool success);
static void qemuDomainStopAudit(virDomainObjPtr vm, const char *reason);

172
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
173

174
static int qemuDetectVcpuPIDs(struct qemud_driver *driver,
175
                              virDomainObjPtr vm);
176

177 178 179
static int qemuUpdateActivePciHostdevs(struct qemud_driver *driver,
                                       virDomainDefPtr def);

180 181 182
static int qemudVMFiltersInstantiate(virConnectPtr conn,
                                     virDomainDefPtr def);

J
Jim Meyering 已提交
183
static struct qemud_driver *qemu_driver = NULL;
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

static void *qemuDomainObjPrivateAlloc(void)
{
    qemuDomainObjPrivatePtr priv;

    if (VIR_ALLOC(priv) < 0)
        return NULL;

    return priv;
}

static void qemuDomainObjPrivateFree(void *data)
{
    qemuDomainObjPrivatePtr priv = data;

200
    qemuDomainPCIAddressSetFree(priv->pciaddrs);
201 202 203
    virDomainChrDefFree(priv->monConfig);
    VIR_FREE(priv->vcpupids);

204 205
    /* This should never be non-NULL if we get here, but just in case... */
    if (priv->mon) {
206
        VIR_ERROR0(_("Unexpected QEMU monitor still active during domain deletion"));
207 208 209 210 211 212
        qemuMonitorClose(priv->mon);
    }
    VIR_FREE(priv);
}


213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
static int qemuDomainObjPrivateXMLFormat(virBufferPtr buf, void *data)
{
    qemuDomainObjPrivatePtr priv = data;
    const char *monitorpath;

    /* priv->monitor_chr is set only for qemu */
    if (priv->monConfig) {
        switch (priv->monConfig->type) {
        case VIR_DOMAIN_CHR_TYPE_UNIX:
            monitorpath = priv->monConfig->data.nix.path;
            break;
        default:
        case VIR_DOMAIN_CHR_TYPE_PTY:
            monitorpath = priv->monConfig->data.file.path;
            break;
        }

        virBufferEscapeString(buf, "  <monitor path='%s'", monitorpath);
D
Daniel P. Berrange 已提交
231 232
        if (priv->monJSON)
            virBufferAddLit(buf, " json='1'");
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        virBufferVSprintf(buf, " type='%s'/>\n",
                          virDomainChrTypeToString(priv->monConfig->type));
    }


    if (priv->nvcpupids) {
        int i;
        virBufferAddLit(buf, "  <vcpus>\n");
        for (i = 0 ; i < priv->nvcpupids ; i++) {
            virBufferVSprintf(buf, "    <vcpu pid='%d'/>\n", priv->vcpupids[i]);
        }
        virBufferAddLit(buf, "  </vcpus>\n");
    }

    return 0;
}

static int qemuDomainObjPrivateXMLParse(xmlXPathContextPtr ctxt, void *data)
{
    qemuDomainObjPrivatePtr priv = data;
    char *monitorpath;
    char *tmp;
    int n, i;
    xmlNodePtr *nodes = NULL;

    if (VIR_ALLOC(priv->monConfig) < 0) {
259
        virReportOOMError();
260 261 262
        goto error;
    }

263
    if (!(priv->monConfig->info.alias = strdup("monitor"))) {
264
        virReportOOMError();
265 266 267
        goto error;
    }

268
    if (!(monitorpath =
269
          virXPathString("string(./monitor[1]/@path)", ctxt))) {
270 271
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no monitor path"));
272 273 274
        goto error;
    }

275
    tmp = virXPathString("string(./monitor[1]/@type)", ctxt);
276 277 278 279 280 281
    if (tmp)
        priv->monConfig->type = virDomainChrTypeFromString(tmp);
    else
        priv->monConfig->type = VIR_DOMAIN_CHR_TYPE_PTY;
    VIR_FREE(tmp);

282
    if (virXPathBoolean("count(./monitor[@json = '1']) > 0", ctxt)) {
D
Daniel P. Berrange 已提交
283
        priv->monJSON = 1;
284 285 286
    } else {
        priv->monJSON = 0;
    }
D
Daniel P. Berrange 已提交
287

288 289 290 291 292 293 294 295 296
    switch (priv->monConfig->type) {
    case VIR_DOMAIN_CHR_TYPE_PTY:
        priv->monConfig->data.file.path = monitorpath;
        break;
    case VIR_DOMAIN_CHR_TYPE_UNIX:
        priv->monConfig->data.nix.path = monitorpath;
        break;
    default:
        VIR_FREE(monitorpath);
297 298 299
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unsupported monitor type '%s'"),
                        virDomainChrTypeToString(priv->monConfig->type));
300 301 302
        goto error;
    }

303
    n = virXPathNodeSet("./vcpus/vcpu", ctxt, &nodes);
304 305 306 307 308
    if (n < 0)
        goto error;
    if (n) {
        priv->nvcpupids = n;
        if (VIR_REALLOC_N(priv->vcpupids, priv->nvcpupids) < 0) {
309
            virReportOOMError();
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
            goto error;
        }

        for (i = 0 ; i < n ; i++) {
            char *pidstr = virXMLPropString(nodes[i], "pid");
            if (!pidstr)
                goto error;

            if (virStrToLong_i(pidstr, NULL, 10, &(priv->vcpupids[i])) < 0) {
                VIR_FREE(pidstr);
                goto error;
            }
            VIR_FREE(pidstr);
        }
        VIR_FREE(nodes);
    }

    return 0;

error:
330 331
    virDomainChrDefFree(priv->monConfig);
    priv->monConfig = NULL;
332 333 334 335 336 337
    VIR_FREE(nodes);
    return -1;
}



338 339 340 341 342 343 344 345 346
/*
 * obj must be locked before calling, qemud_driver must NOT be locked
 *
 * This must be called by anything that will change the VM state
 * in any way, or anything that will use the QEMU monitor.
 *
 * Upon successful return, the object will have its ref count increased,
 * successful calls must be followed by EndJob eventually
 */
347 348 349 350

/* Give up waiting for mutex after 30 seconds */
#define QEMU_JOB_WAIT_TIME (1000ull * 30)

351 352 353 354
static int qemuDomainObjBeginJob(virDomainObjPtr obj) ATTRIBUTE_RETURN_CHECK;
static int qemuDomainObjBeginJob(virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
355 356 357 358
    struct timeval now;
    unsigned long long then;

    if (gettimeofday(&now, NULL) < 0) {
359
        virReportSystemError(errno, "%s",
360 361 362 363 364
                             _("cannot get time of day"));
        return -1;
    }
    then = (now.tv_sec * 1000ull) + (now.tv_usec / 1000);
    then += QEMU_JOB_WAIT_TIME;
365 366 367 368

    virDomainObjRef(obj);

    while (priv->jobActive) {
369
        if (virCondWaitUntil(&priv->jobCond, &obj->lock, then) < 0) {
370
            virDomainObjUnref(obj);
371
            if (errno == ETIMEDOUT)
372 373
                qemuReportError(VIR_ERR_OPERATION_TIMEOUT,
                                "%s", _("cannot acquire state change lock"));
374
            else
375
                virReportSystemError(errno,
376
                                     "%s", _("cannot acquire job mutex"));
377 378 379
            return -1;
        }
    }
380 381
    priv->jobActive = QEMU_JOB_UNSPECIFIED;
    priv->jobSignals = 0;
382
    memset(&priv->jobSignalsData, 0, sizeof(priv->jobSignalsData));
383 384
    priv->jobStart = (now.tv_sec * 1000ull) + (now.tv_usec / 1000);
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400

    return 0;
}

/*
 * obj must be locked before calling, qemud_driver must be locked
 *
 * This must be called by anything that will change the VM state
 * in any way, or anything that will use the QEMU monitor.
 */
static int qemuDomainObjBeginJobWithDriver(struct qemud_driver *driver,
                                           virDomainObjPtr obj) ATTRIBUTE_RETURN_CHECK;
static int qemuDomainObjBeginJobWithDriver(struct qemud_driver *driver,
                                           virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
401 402 403 404
    struct timeval now;
    unsigned long long then;

    if (gettimeofday(&now, NULL) < 0) {
405
        virReportSystemError(errno, "%s",
406 407 408 409 410
                             _("cannot get time of day"));
        return -1;
    }
    then = (now.tv_sec * 1000ull) + (now.tv_usec / 1000);
    then += QEMU_JOB_WAIT_TIME;
411 412 413 414 415

    virDomainObjRef(obj);
    qemuDriverUnlock(driver);

    while (priv->jobActive) {
416
        if (virCondWaitUntil(&priv->jobCond, &obj->lock, then) < 0) {
417
            virDomainObjUnref(obj);
418
            if (errno == ETIMEDOUT)
419 420
                qemuReportError(VIR_ERR_OPERATION_TIMEOUT,
                                "%s", _("cannot acquire state change lock"));
421
            else
422
                virReportSystemError(errno,
423
                                     "%s", _("cannot acquire job mutex"));
M
Matthias Bolte 已提交
424
            qemuDriverLock(driver);
425 426 427
            return -1;
        }
    }
428 429
    priv->jobActive = QEMU_JOB_UNSPECIFIED;
    priv->jobSignals = 0;
430
    memset(&priv->jobSignalsData, 0, sizeof(priv->jobSignalsData));
431 432
    priv->jobStart = (now.tv_sec * 1000ull) + (now.tv_usec / 1000);
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
433 434 435 436 437 438 439 440 441 442 443 444 445

    virDomainObjUnlock(obj);
    qemuDriverLock(driver);
    virDomainObjLock(obj);

    return 0;
}

/*
 * obj must be locked before calling, qemud_driver does not matter
 *
 * To be called after completing the work associated with the
 * earlier  qemuDomainBeginJob() call
446 447 448
 *
 * Returns remaining refcount on 'obj', maybe 0 to indicated it
 * was deleted
449
 */
450
static int ATTRIBUTE_RETURN_CHECK qemuDomainObjEndJob(virDomainObjPtr obj)
451 452 453
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

454 455
    priv->jobActive = QEMU_JOB_NONE;
    priv->jobSignals = 0;
456
    memset(&priv->jobSignalsData, 0, sizeof(priv->jobSignalsData));
457 458
    priv->jobStart = 0;
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
459 460
    virCondSignal(&priv->jobCond);

461
    return virDomainObjUnref(obj);
462 463 464 465 466 467 468 469 470 471 472
}


/*
 * obj must be locked before calling, qemud_driver must be unlocked
 *
 * To be called immediately before any QEMU monitor API call
 * Must have alrady called qemuDomainObjBeginJob().
 *
 * To be followed with qemuDomainObjExitMonitor() once complete
 */
473 474 475 476 477
static void qemuDomainObjEnterMonitor(virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

    qemuMonitorLock(priv->mon);
478
    qemuMonitorRef(priv->mon);
479
    virDomainObjUnlock(obj);
480 481 482
}


483 484 485 486
/* obj must NOT be locked before calling, qemud_driver must be unlocked
 *
 * Should be paired with an earlier  qemuDomainObjEnterMonitor() call
 */
487 488 489
static void qemuDomainObjExitMonitor(virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
490 491 492 493 494 495
    int refs;

    refs = qemuMonitorUnref(priv->mon);

    if (refs > 0)
        qemuMonitorUnlock(priv->mon);
496

497
    virDomainObjLock(obj);
498 499 500 501 502

    if (refs == 0) {
        virDomainObjUnref(obj);
        priv->mon = NULL;
    }
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
}


/*
 * obj must be locked before calling, qemud_driver must be locked
 *
 * To be called immediately before any QEMU monitor API call
 * Must have alrady called qemuDomainObjBeginJob().
 *
 * To be followed with qemuDomainObjExitMonitorWithDriver() once complete
 */
static void qemuDomainObjEnterMonitorWithDriver(struct qemud_driver *driver, virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;

    qemuMonitorLock(priv->mon);
519
    qemuMonitorRef(priv->mon);
520 521 522 523 524 525 526 527 528 529 530 531 532
    virDomainObjUnlock(obj);
    qemuDriverUnlock(driver);
}


/* obj must NOT be locked before calling, qemud_driver must be unlocked,
 * and will be locked after returning
 *
 * Should be paired with an earlier  qemuDomainObjEnterMonitor() call
 */
static void qemuDomainObjExitMonitorWithDriver(struct qemud_driver *driver, virDomainObjPtr obj)
{
    qemuDomainObjPrivatePtr priv = obj->privateData;
533 534 535 536 537 538
    int refs;

    refs = qemuMonitorUnref(priv->mon);

    if (refs > 0)
        qemuMonitorUnlock(priv->mon);
539 540 541

    qemuDriverLock(driver);
    virDomainObjLock(obj);
542 543 544 545 546

    if (refs == 0) {
        virDomainObjUnref(obj);
        priv->mon = NULL;
    }
547 548
}

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
static void qemuDomainObjEnterRemoteWithDriver(struct qemud_driver *driver,
                                               virDomainObjPtr obj)
{
    virDomainObjRef(obj);
    virDomainObjUnlock(obj);
    qemuDriverUnlock(driver);
}

static void qemuDomainObjExitRemoteWithDriver(struct qemud_driver *driver,
                                              virDomainObjPtr obj)
{
    qemuDriverLock(driver);
    virDomainObjLock(obj);
    virDomainObjUnref(obj);
}
564

565
void qemuDomainDefNamespaceFree(void *nsdata)
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
{
    qemuDomainCmdlineDefPtr cmd = nsdata;
    unsigned int i;

    if (!cmd)
        return;

    for (i = 0; i < cmd->num_args; i++)
        VIR_FREE(cmd->args[i]);
    for (i = 0; i < cmd->num_env; i++) {
        VIR_FREE(cmd->env_name[i]);
        VIR_FREE(cmd->env_value[i]);
    }
    VIR_FREE(cmd->args);
    VIR_FREE(cmd->env_name);
    VIR_FREE(cmd->env_value);
    VIR_FREE(cmd);
}

585 586 587 588
int qemuDomainDefNamespaceParse(xmlDocPtr xml,
                                xmlNodePtr root,
                                xmlXPathContextPtr ctxt,
                                void **data)
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
{
    qemuDomainCmdlineDefPtr cmd = NULL;
    xmlNsPtr ns;
    xmlNodePtr *nodes = NULL;
    int n, i;

    ns = xmlSearchNs(xml, root, BAD_CAST "qemu");
    if (!ns)
        /* this is fine; it just means there was no qemu namespace listed */
        return 0;

    if (STRNEQ((const char *)ns->href, QEMU_NAMESPACE_HREF)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Found namespace '%s' doesn't match expected '%s'"),
                        ns->href, QEMU_NAMESPACE_HREF);
        return -1;
    }

    if (xmlXPathRegisterNs(ctxt, ns->prefix, ns->href) < 0) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Failed to register xml namespace '%s'"), ns->href);
        return -1;
    }

    if (VIR_ALLOC(cmd) < 0) {
        virReportOOMError();
        return -1;
    }

    /* first handle the extra command-line arguments */
    n = virXPathNodeSet("./qemu:commandline/qemu:arg", ctxt, &nodes);
    if (n < 0)
        /* virXPathNodeSet already set the error */
        goto error;

    if (n && VIR_ALLOC_N(cmd->args, n) < 0)
        goto no_memory;

    for (i = 0; i < n; i++) {
        cmd->args[cmd->num_args] = virXMLPropString(nodes[i], "value");
        if (cmd->args[cmd->num_args] == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("No qemu command-line argument specified"));
            goto error;
        }
        cmd->num_args++;
    }

    VIR_FREE(nodes);

    /* now handle the extra environment variables */
    n = virXPathNodeSet("./qemu:commandline/qemu:env", ctxt, &nodes);
    if (n < 0)
        /* virXPathNodeSet already set the error */
        goto error;

    if (n && VIR_ALLOC_N(cmd->env_name, n) < 0)
        goto no_memory;

    if (n && VIR_ALLOC_N(cmd->env_value, n) < 0)
        goto no_memory;

    for (i = 0; i < n; i++) {
        char *tmp;

        tmp = virXMLPropString(nodes[i], "name");
        if (tmp == NULL) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("No qemu environment name specified"));
            goto error;
        }
        if (tmp[0] == '\0') {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Empty qemu environment name specified"));
            goto error;
        }
        if (!c_isalpha(tmp[0]) && tmp[0] != '_') {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Invalid environment name, it must begin with a letter or underscore"));
            goto error;
        }
        if (strspn(tmp, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != strlen(tmp)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Invalid environment name, it must contain only alphanumerics and underscore"));
            goto error;
        }

        cmd->env_name[cmd->num_env] = tmp;

        cmd->env_value[cmd->num_env] = virXMLPropString(nodes[i], "value");
        /* a NULL value for command is allowed, since it might be empty */
        cmd->num_env++;
    }

    VIR_FREE(nodes);

    *data = cmd;

    return 0;

no_memory:
    virReportOOMError();

error:
    VIR_FREE(nodes);
    qemuDomainDefNamespaceFree(cmd);
    return -1;
}

698 699
int qemuDomainDefNamespaceFormatXML(virBufferPtr buf,
                                    void *nsdata)
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
{
    qemuDomainCmdlineDefPtr cmd = nsdata;
    unsigned int i;

    if (!cmd->num_args && !cmd->num_env)
        return 0;

    virBufferAddLit(buf, "  <qemu:commandline>\n");
    for (i = 0; i < cmd->num_args; i++)
        virBufferEscapeString(buf, "    <qemu:arg value='%s'/>\n",
                              cmd->args[i]);
    for (i = 0; i < cmd->num_env; i++) {
        virBufferVSprintf(buf, "    <qemu:env name='%s'", cmd->env_name[i]);
        if (cmd->env_value[i])
            virBufferEscapeString(buf, " value='%s'", cmd->env_value[i]);
        virBufferAddLit(buf, "/>\n");
    }
    virBufferAddLit(buf, "  </qemu:commandline>\n");

    return 0;
}

722
const char *qemuDomainDefNamespaceHref(void)
723 724 725 726
{
    return "xmlns:qemu='" QEMU_NAMESPACE_HREF "'";
}

727 728 729 730 731 732 733 734 735
static int qemuCgroupControllerActive(struct qemud_driver *driver,
                                      int controller)
{
    if (driver->cgroup == NULL)
        return 0;
    if (driver->cgroupControllers & (1 << controller))
        return 1;
    return 0;
}
736

737
static int
738
qemudLogFD(struct qemud_driver *driver, const char* name)
739 740 741
{
    char logfile[PATH_MAX];
    mode_t logmode;
G
Guido Günther 已提交
742
    int ret, fd = -1;
743

744 745
    if ((ret = snprintf(logfile, sizeof(logfile), "%s/%s.log",
                        driver->logDir, name))
G
Guido Günther 已提交
746
        < 0 || ret >= sizeof(logfile)) {
747
        virReportOOMError();
748 749 750 751
        return -1;
    }

    logmode = O_CREAT | O_WRONLY;
752 753
    /* Only logrotate files in /var/log, so only append if running privileged */
    if (driver->privileged)
754
        logmode |= O_APPEND;
755 756 757
    else
        logmode |= O_TRUNC;

758
    if ((fd = open(logfile, logmode, S_IRUSR | S_IWUSR)) < 0) {
759
        virReportSystemError(errno,
760 761
                             _("failed to create logfile %s"),
                             logfile);
762 763
        return -1;
    }
764
    if (virSetCloseExec(fd) < 0) {
765
        virReportSystemError(errno, "%s",
766
                             _("Unable to set VM logfile close-on-exec flag"));
767 768 769 770 771 772 773
        close(fd);
        return -1;
    }
    return fd;
}


774
static int
775
qemudLogReadFD(const char* logDir, const char* name, off_t pos)
776 777 778 779 780 781 782
{
    char logfile[PATH_MAX];
    mode_t logmode = O_RDONLY;
    int ret, fd = -1;

    if ((ret = snprintf(logfile, sizeof(logfile), "%s/%s.log", logDir, name))
        < 0 || ret >= sizeof(logfile)) {
783 784 785
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("failed to build logfile name %s/%s.log"),
                        logDir, name);
786 787 788 789 790
        return -1;
    }


    if ((fd = open(logfile, logmode)) < 0) {
791
        virReportSystemError(errno,
792 793
                             _("failed to create logfile %s"),
                             logfile);
794 795
        return -1;
    }
796
    if (virSetCloseExec(fd) < 0) {
797
        virReportSystemError(errno, "%s",
798
                             _("Unable to set VM logfile close-on-exec flag"));
799 800 801
        close(fd);
        return -1;
    }
802
    if (pos < 0 || lseek(fd, pos, SEEK_SET) < 0) {
803
      virReportSystemError(pos < 0 ? 0 : errno,
804 805
                             _("Unable to seek to %lld in %s"),
                             (long long) pos, logfile);
806 807 808 809 810 811
        close(fd);
    }
    return fd;
}


812 813 814 815 816 817 818 819 820
struct qemuAutostartData {
    struct qemud_driver *driver;
    virConnectPtr conn;
};
static void
qemuAutostartDomain(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
{
    virDomainObjPtr vm = payload;
    struct qemuAutostartData *data = opaque;
821
    virErrorPtr err;
822 823

    virDomainObjLock(vm);
824 825 826 827 828 829 830 831 832
    virResetLastError();
    if (qemuDomainObjBeginJobWithDriver(data->driver, vm) < 0) {
        err = virGetLastError();
        VIR_ERROR(_("Failed to start job on VM '%s': %s"),
                  vm->def->name,
                  err ? err->message : _("unknown error"));
    } else {
        if (vm->autostart &&
            !virDomainObjIsActive(vm) &&
833
            qemudDomainObjStart(data->conn, data->driver, vm, false) < 0) {
834
            err = virGetLastError();
835
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
836
                      vm->def->name,
837
                      err ? err->message : _("unknown error"));
838
        }
839 840 841

        if (qemuDomainObjEndJob(vm) == 0)
            vm = NULL;
842
    }
843 844 845

    if (vm)
        virDomainObjUnlock(vm);
846 847
}

848 849
static void
qemudAutostartConfigs(struct qemud_driver *driver) {
850 851 852 853 854
    /* XXX: Figure out a better way todo this. The domain
     * startup code needs a connection handle in order
     * to lookup the bridge associated with a virtual
     * network
     */
855 856 857
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "qemu:///system" :
                                        "qemu:///session");
858
    /* Ignoring NULL conn which is mostly harmless here */
859
    struct qemuAutostartData data = { driver, conn };
860

861
    qemuDriverLock(driver);
862
    virHashForEach(driver->domains.objs, qemuAutostartDomain, &data);
863
    qemuDriverUnlock(driver);
864

865 866
    if (conn)
        virConnectClose(conn);
867 868
}

869 870 871 872 873 874 875 876 877

/**
 * qemudRemoveDomainStatus
 *
 * remove all state files of a domain from statedir
 *
 * Returns 0 on success
 */
static int
878
qemudRemoveDomainStatus(struct qemud_driver *driver,
879 880
                        virDomainObjPtr vm)
{
881
    char ebuf[1024];
882 883 884
    char *file = NULL;

    if (virAsprintf(&file, "%s/%s.xml", driver->stateDir, vm->def->name) < 0) {
885
        virReportOOMError();
D
Daniel Veillard 已提交
886
        return(-1);
887 888
    }

889
    if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR)
890
        VIR_WARN("Failed to remove domain XML for %s: %s",
D
Daniel Veillard 已提交
891 892 893
                 vm->def->name, virStrerror(errno, ebuf, sizeof(ebuf)));
    VIR_FREE(file);

894
    if (virFileDeletePid(driver->stateDir, vm->def->name) != 0)
895
        VIR_WARN("Failed to remove PID file for %s: %s",
896
                 vm->def->name, virStrerror(errno, ebuf, sizeof(ebuf)));
897

D
Daniel Veillard 已提交
898

899
    return 0;
900 901
}

902 903 904 905 906 907 908 909 910 911 912 913 914 915

/*
 * This is a callback registered with a qemuMonitorPtr  instance,
 * and to be invoked when the monitor console hits an end of file
 * condition, or error, thus indicating VM shutdown should be
 * performed
 */
static void
qemuHandleMonitorEOF(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
                     virDomainObjPtr vm,
                     int hasError) {
    struct qemud_driver *driver = qemu_driver;
    virDomainEventPtr event = NULL;

916
    VIR_DEBUG("Received EOF on %p '%s'", vm, vm->def->name);
917

918 919 920 921 922 923 924 925
    virDomainObjLock(vm);

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     hasError ?
                                     VIR_DOMAIN_EVENT_STOPPED_FAILED :
                                     VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);

926
    qemudShutdownVMDaemon(driver, vm, 0);
927 928
    qemuDomainStopAudit(vm, hasError ? "failed" : "shutdown");

929 930 931 932 933 934 935 936 937 938 939 940 941
    if (!vm->persistent)
        virDomainRemoveInactive(&driver->domains, vm);
    else
        virDomainObjUnlock(vm);

    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
}


942 943 944
static virDomainDiskDefPtr
findDomainDiskByPath(virDomainObjPtr vm,
                     const char *path)
945 946 947 948 949 950 951
{
    int i;

    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk;

        disk = vm->def->disks[i];
952 953
        if (disk->src != NULL && STREQ(disk->src, path))
            return disk;
954
    }
955 956 957 958

    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                    _("no disk found with path %s"),
                    path);
959 960 961
    return NULL;
}

962 963 964 965 966 967
static virDomainDiskDefPtr
findDomainDiskByAlias(virDomainObjPtr vm,
                      const char *alias)
{
    int i;

968 969 970
    if (STRPREFIX(alias, QEMU_DRIVE_HOST_PREFIX))
        alias += strlen(QEMU_DRIVE_HOST_PREFIX);

971 972 973 974 975 976 977 978 979 980 981 982 983 984
    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk;

        disk = vm->def->disks[i];
        if (disk->info.alias != NULL && STREQ(disk->info.alias, alias))
            return disk;
    }

    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                    _("no disk found with alias %s"),
                    alias);
    return NULL;
}

985
static int
986 987 988 989
getVolumeQcowPassphrase(virConnectPtr conn,
                        virDomainDiskDefPtr disk,
                        char **secretRet,
                        size_t *secretLen)
990 991 992 993 994
{
    virSecretPtr secret;
    char *passphrase;
    unsigned char *data;
    size_t size;
995
    int ret = -1;
996
    virStorageEncryptionPtr enc;
997

998 999 1000 1001 1002 1003 1004
    if (!disk->encryption) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("disk %s does not have any encryption information"),
                        disk->src);
        return -1;
    }
    enc = disk->encryption;
1005 1006

    if (!conn) {
1007
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
1008
                        "%s", _("cannot find secrets without a connection"));
1009
        goto cleanup;
1010 1011 1012 1013 1014
    }

    if (conn->secretDriver == NULL ||
        conn->secretDriver->lookupByUUID == NULL ||
        conn->secretDriver->getValue == NULL) {
1015 1016
        qemuReportError(VIR_ERR_NO_SUPPORT, "%s",
                        _("secret storage not supported"));
1017
        goto cleanup;
1018 1019 1020 1021 1022 1023
    }

    if (enc->format != VIR_STORAGE_ENCRYPTION_FORMAT_QCOW ||
        enc->nsecrets != 1 ||
        enc->secrets[0]->type !=
        VIR_STORAGE_ENCRYPTION_SECRET_TYPE_PASSPHRASE) {
1024
        qemuReportError(VIR_ERR_INVALID_DOMAIN,
1025
                        _("invalid <encryption> for volume %s"), disk->src);
1026
        goto cleanup;
1027 1028 1029 1030 1031
    }

    secret = conn->secretDriver->lookupByUUID(conn,
                                              enc->secrets[0]->uuid);
    if (secret == NULL)
1032
        goto cleanup;
1033 1034 1035 1036
    data = conn->secretDriver->getValue(secret, &size,
                                        VIR_SECRET_GET_VALUE_INTERNAL_CALL);
    virUnrefSecret(secret);
    if (data == NULL)
1037
        goto cleanup;
1038 1039 1040 1041

    if (memchr(data, '\0', size) != NULL) {
        memset(data, 0, size);
        VIR_FREE(data);
1042 1043
        qemuReportError(VIR_ERR_INVALID_SECRET,
                        _("format='qcow' passphrase for %s must not contain a "
1044
                          "'\\0'"), disk->src);
1045
        goto cleanup;
1046 1047 1048 1049 1050
    }

    if (VIR_ALLOC_N(passphrase, size + 1) < 0) {
        memset(data, 0, size);
        VIR_FREE(data);
1051
        virReportOOMError();
1052
        goto cleanup;
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    }
    memcpy(passphrase, data, size);
    passphrase[size] = '\0';

    memset(data, 0, size);
    VIR_FREE(data);

    *secretRet = passphrase;
    *secretLen = size;

1063 1064 1065
    ret = 0;

cleanup:
1066 1067
    return ret;
}
1068

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
static int
findVolumeQcowPassphrase(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
                         virConnectPtr conn,
                         virDomainObjPtr vm,
                         const char *path,
                         char **secretRet,
                         size_t *secretLen)
{
    virDomainDiskDefPtr disk;
    int ret = -1;

    virDomainObjLock(vm);
    disk = findDomainDiskByPath(vm, path);

    if (!disk)
        goto cleanup;

    ret = getVolumeQcowPassphrase(conn, disk, secretRet, secretLen);

cleanup:
    virDomainObjUnlock(vm);
1090
    return ret;
1091 1092
}

1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

static int
qemuHandleDomainReset(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
                      virDomainObjPtr vm)
{
    struct qemud_driver *driver = qemu_driver;
    virDomainEventPtr event;

    virDomainObjLock(vm);
    event = virDomainEventRebootNewFromObj(vm);
    virDomainObjUnlock(vm);

    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }

    return 0;
}


1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
static int
qemuHandleDomainStop(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
                     virDomainObjPtr vm)
{
    struct qemud_driver *driver = qemu_driver;
    virDomainEventPtr event = NULL;

    virDomainObjLock(vm);
    if (vm->state == VIR_DOMAIN_RUNNING) {
        VIR_DEBUG("Transitioned guest %s to paused state due to unknown event", vm->def->name);

        vm->state = VIR_DOMAIN_PAUSED;
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);

        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            VIR_WARN("Unable to save status on vm %s after IO error", vm->def->name);
    }
    virDomainObjUnlock(vm);

    if (event) {
        qemuDriverLock(driver);
        if (event)
            qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }

    return 0;
}


1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
static int
qemuHandleDomainRTCChange(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
                          virDomainObjPtr vm,
                          long long offset)
{
    struct qemud_driver *driver = qemu_driver;
    virDomainEventPtr event;

    virDomainObjLock(vm);
    event = virDomainEventRTCChangeNewFromObj(vm, offset);

    if (vm->def->clock.offset == VIR_DOMAIN_CLOCK_OFFSET_VARIABLE)
        vm->def->clock.data.adjustment = offset;

    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        VIR_WARN0("unable to save domain status with RTC change");

    virDomainObjUnlock(vm);

    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }

    return 0;
}


1176 1177 1178 1179 1180 1181
static int
qemuHandleDomainWatchdog(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
                         virDomainObjPtr vm,
                         int action)
{
    struct qemud_driver *driver = qemu_driver;
1182 1183
    virDomainEventPtr watchdogEvent = NULL;
    virDomainEventPtr lifecycleEvent = NULL;
1184 1185

    virDomainObjLock(vm);
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    watchdogEvent = virDomainEventWatchdogNewFromObj(vm, action);

    if (action == VIR_DOMAIN_EVENT_WATCHDOG_PAUSE &&
        vm->state == VIR_DOMAIN_RUNNING) {
        VIR_DEBUG("Transitioned guest %s to paused state due to watchdog", vm->def->name);

        vm->state = VIR_DOMAIN_PAUSED;
        lifecycleEvent = virDomainEventNewFromObj(vm,
                                                  VIR_DOMAIN_EVENT_SUSPENDED,
                                                  VIR_DOMAIN_EVENT_SUSPENDED_WATCHDOG);

        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            VIR_WARN("Unable to save status on vm %s after IO error", vm->def->name);
    }
1200 1201
    virDomainObjUnlock(vm);

1202
    if (watchdogEvent || lifecycleEvent) {
1203
        qemuDriverLock(driver);
1204 1205 1206 1207
        if (watchdogEvent)
            qemuDomainEventQueue(driver, watchdogEvent);
        if (lifecycleEvent)
            qemuDomainEventQueue(driver, lifecycleEvent);
1208 1209 1210 1211 1212 1213 1214
        qemuDriverUnlock(driver);
    }

    return 0;
}


1215 1216 1217 1218
static int
qemuHandleDomainIOError(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
                        virDomainObjPtr vm,
                        const char *diskAlias,
1219 1220
                        int action,
                        const char *reason)
1221 1222
{
    struct qemud_driver *driver = qemu_driver;
1223
    virDomainEventPtr ioErrorEvent = NULL;
1224
    virDomainEventPtr ioErrorEvent2 = NULL;
1225
    virDomainEventPtr lifecycleEvent = NULL;
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
    const char *srcPath;
    const char *devAlias;
    virDomainDiskDefPtr disk;

    virDomainObjLock(vm);
    disk = findDomainDiskByAlias(vm, diskAlias);

    if (disk) {
        srcPath = disk->src;
        devAlias = disk->info.alias;
    } else {
        srcPath = "";
        devAlias = "";
    }

1241
    ioErrorEvent = virDomainEventIOErrorNewFromObj(vm, srcPath, devAlias, action);
1242
    ioErrorEvent2 = virDomainEventIOErrorReasonNewFromObj(vm, srcPath, devAlias, action, reason);
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

    if (action == VIR_DOMAIN_EVENT_IO_ERROR_PAUSE &&
        vm->state == VIR_DOMAIN_RUNNING) {
        VIR_DEBUG("Transitioned guest %s to paused state due to IO error", vm->def->name);

        vm->state = VIR_DOMAIN_PAUSED;
        lifecycleEvent = virDomainEventNewFromObj(vm,
                                                  VIR_DOMAIN_EVENT_SUSPENDED,
                                                  VIR_DOMAIN_EVENT_SUSPENDED_IOERROR);

        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            VIR_WARN("Unable to save status on vm %s after IO error", vm->def->name);
    }
1256 1257
    virDomainObjUnlock(vm);

1258
    if (ioErrorEvent || ioErrorEvent2 || lifecycleEvent) {
1259
        qemuDriverLock(driver);
1260 1261
        if (ioErrorEvent)
            qemuDomainEventQueue(driver, ioErrorEvent);
1262 1263
        if (ioErrorEvent2)
            qemuDomainEventQueue(driver, ioErrorEvent2);
1264 1265
        if (lifecycleEvent)
            qemuDomainEventQueue(driver, lifecycleEvent);
1266 1267 1268 1269 1270 1271 1272
        qemuDriverUnlock(driver);
    }

    return 0;
}


1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
static int
qemuHandleDomainGraphics(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
                         virDomainObjPtr vm,
                         int phase,
                         int localFamily,
                         const char *localNode,
                         const char *localService,
                         int remoteFamily,
                         const char *remoteNode,
                         const char *remoteService,
                         const char *authScheme,
                         const char *x509dname,
                         const char *saslUsername)
{
    struct qemud_driver *driver = qemu_driver;
    virDomainEventPtr event;
    virDomainEventGraphicsAddressPtr localAddr = NULL;
    virDomainEventGraphicsAddressPtr remoteAddr = NULL;
    virDomainEventGraphicsSubjectPtr subject = NULL;
    int i;

    virDomainObjLock(vm);

    if (VIR_ALLOC(localAddr) < 0)
        goto no_memory;
    localAddr->family = localFamily;
    if (!(localAddr->service = strdup(localService)) ||
        !(localAddr->node = strdup(localNode)))
        goto no_memory;

    if (VIR_ALLOC(remoteAddr) < 0)
        goto no_memory;
    remoteAddr->family = remoteFamily;
    if (!(remoteAddr->service = strdup(remoteService)) ||
        !(remoteAddr->node = strdup(remoteNode)))
        goto no_memory;

    if (VIR_ALLOC(subject) < 0)
        goto no_memory;
    if (x509dname) {
        if (VIR_REALLOC_N(subject->identities, subject->nidentity+1) < 0)
            goto no_memory;
        if (!(subject->identities[subject->nidentity].type = strdup("x509dname")) ||
            !(subject->identities[subject->nidentity].name = strdup(x509dname)))
            goto no_memory;
        subject->nidentity++;
    }
    if (saslUsername) {
        if (VIR_REALLOC_N(subject->identities, subject->nidentity+1) < 0)
            goto no_memory;
        if (!(subject->identities[subject->nidentity].type = strdup("saslUsername")) ||
            !(subject->identities[subject->nidentity].name = strdup(saslUsername)))
            goto no_memory;
        subject->nidentity++;
    }

    event = virDomainEventGraphicsNewFromObj(vm, phase, localAddr, remoteAddr, authScheme, subject);
    virDomainObjUnlock(vm);

    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }

    return 0;

no_memory:
    virReportOOMError();
    if (localAddr) {
        VIR_FREE(localAddr->service);
        VIR_FREE(localAddr->node);
        VIR_FREE(localAddr);
    }
    if (remoteAddr) {
        VIR_FREE(remoteAddr->service);
        VIR_FREE(remoteAddr->node);
        VIR_FREE(remoteAddr);
    }
    if (subject) {
        for (i = 0 ; i < subject->nidentity ; i++) {
            VIR_FREE(subject->identities[i].type);
            VIR_FREE(subject->identities[i].name);
        }
        VIR_FREE(subject->identities);
        VIR_FREE(subject);
    }

    return -1;
}


1365 1366 1367 1368 1369 1370 1371 1372 1373
static void qemuHandleMonitorDestroy(qemuMonitorPtr mon,
                                     virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    if (priv->mon == mon)
        priv->mon = NULL;
    virDomainObjUnref(vm);
}

1374
static qemuMonitorCallbacks monitorCallbacks = {
1375
    .destroy = qemuHandleMonitorDestroy,
1376 1377
    .eofNotify = qemuHandleMonitorEOF,
    .diskSecretLookup = findVolumeQcowPassphrase,
1378
    .domainStop = qemuHandleDomainStop,
1379
    .domainReset = qemuHandleDomainReset,
1380
    .domainRTCChange = qemuHandleDomainRTCChange,
1381
    .domainWatchdog = qemuHandleDomainWatchdog,
1382
    .domainIOError = qemuHandleDomainIOError,
1383
    .domainGraphics = qemuHandleDomainGraphics,
1384 1385
};

1386
static int
1387
qemuConnectMonitor(struct qemud_driver *driver, virDomainObjPtr vm)
1388
{
1389
    qemuDomainObjPrivatePtr priv = vm->privateData;
1390
    int ret = -1;
1391

1392 1393 1394 1395 1396 1397
    if (driver->securityDriver &&
        driver->securityDriver->domainSetSecuritySocketLabel &&
        driver->securityDriver->domainSetSecuritySocketLabel
          (driver->securityDriver,vm) < 0) {
        VIR_ERROR(_("Failed to set security context for monitor for %s"),
                  vm->def->name);
1398 1399 1400
        goto error;
    }

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
    /* Hold an extra reference because we can't allow 'vm' to be
     * deleted while the monitor is active */
    virDomainObjRef(vm);

    priv->mon = qemuMonitorOpen(vm,
                                priv->monConfig,
                                priv->monJSON,
                                &monitorCallbacks);

    if (priv->mon == NULL)
        virDomainObjUnref(vm);
1412

1413 1414 1415 1416 1417 1418
    if (driver->securityDriver &&
        driver->securityDriver->domainClearSecuritySocketLabel &&
        driver->securityDriver->domainClearSecuritySocketLabel
          (driver->securityDriver,vm) < 0) {
        VIR_ERROR(_("Failed to clear security context for monitor for %s"),
                  vm->def->name);
1419
        goto error;
1420
    }
1421

1422 1423 1424 1425 1426 1427
    if (priv->mon == NULL) {
        VIR_INFO("Failed to connect monitor for %s", vm->def->name);
        goto error;
    }


1428 1429 1430 1431
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorSetCapabilities(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

1432
error:
1433
    if (ret < 0)
1434 1435 1436
        qemuMonitorClose(priv->mon);

    return ret;
1437
}
1438

1439 1440 1441 1442
struct virReconnectDomainData {
    virConnectPtr conn;
    struct qemud_driver *driver;
};
1443 1444 1445
/*
 * Open an existing VM's monitor, re-detect VCPU threads
 * and re-reserve the security labels in use
1446
 */
1447 1448
static void
qemuReconnectDomain(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
1449
{
1450
    virDomainObjPtr obj = payload;
1451 1452
    struct virReconnectDomainData *data = opaque;
    struct qemud_driver *driver = data->driver;
1453
    qemuDomainObjPrivatePtr priv;
1454
    unsigned long long qemuCmdFlags;
1455
    virConnectPtr conn = data->conn;
1456 1457

    virDomainObjLock(obj);
1458

1459 1460
    VIR_DEBUG("Reconnect monitor to %p '%s'", obj, obj->def->name);

1461 1462
    priv = obj->privateData;

1463
    /* XXX check PID liveliness & EXE path */
1464
    if (qemuConnectMonitor(driver, obj) < 0)
1465
        goto error;
1466

1467 1468 1469 1470
    if (qemuUpdateActivePciHostdevs(driver, obj->def) < 0) {
        goto error;
    }

1471 1472 1473 1474 1475 1476
    /* XXX we should be persisting the original flags in the XML
     * not re-detecting them, since the binary may have changed
     * since launch time */
    if (qemudExtractVersionInfo(obj->def->emulator,
                                NULL,
                                &qemuCmdFlags) >= 0 &&
1477
        (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
1478 1479
        priv->persistentAddrs = 1;

1480 1481 1482 1483
        if (!(priv->pciaddrs = qemuDomainPCIAddressSetCreate(obj->def)) ||
            qemuAssignDevicePCISlots(obj->def, priv->pciaddrs) < 0)
            goto error;
    }
1484

1485
    if (driver->securityDriver &&
1486
        driver->securityDriver->domainReserveSecurityLabel &&
1487 1488
        driver->securityDriver->domainReserveSecurityLabel(driver->securityDriver,
                                                           obj) < 0)
1489
        goto error;
1490

1491 1492 1493
    if (qemudVMFiltersInstantiate(conn, obj->def))
        goto error;

1494 1495
    if (obj->def->id >= driver->nextvmid)
        driver->nextvmid = obj->def->id + 1;
1496

1497 1498
    virDomainObjUnlock(obj);
    return;
1499

1500
error:
1501 1502 1503
    /* We can't get the monitor back, so must kill the VM
     * to remove danger of it ending up running twice if
     * user tries to start it again later */
1504
    qemudShutdownVMDaemon(driver, obj, 0);
1505 1506 1507 1508
    if (!obj->persistent)
        virDomainRemoveInactive(&driver->domains, obj);
    else
        virDomainObjUnlock(obj);
1509
}
1510

1511
/**
1512
 * qemudReconnectDomains
1513 1514 1515 1516 1517
 *
 * Try to re-open the resources for live VMs that we care
 * about.
 */
static void
1518
qemuReconnectDomains(virConnectPtr conn, struct qemud_driver *driver)
1519
{
1520 1521
    struct virReconnectDomainData data = {conn, driver};
    virHashForEach(driver->domains.objs, qemuReconnectDomain, &data);
1522 1523
}

1524

1525 1526 1527 1528 1529 1530
static int
qemudSecurityInit(struct qemud_driver *qemud_drv)
{
    int ret;
    virSecurityDriverPtr security_drv;

1531 1532 1533
    qemuSecurityStackedSetDriver(qemud_drv);
    qemuSecurityDACSetDriver(qemud_drv);

1534
    ret = virSecurityDriverStartup(&security_drv,
1535 1536
                                   qemud_drv->securityDriverName,
                                   qemud_drv->allowDiskFormatProbing);
1537 1538 1539 1540
    if (ret == -1) {
        VIR_ERROR0(_("Failed to start security driver"));
        return -1;
    }
1541 1542 1543

    /* No primary security driver wanted to be enabled: just setup
     * the DAC driver on its own */
1544
    if (ret == -2) {
1545
        qemud_drv->securityDriver = &qemuDACSecurityDriver;
1546
        VIR_INFO0(_("No security driver available"));
1547 1548 1549 1550 1551
    } else {
        qemud_drv->securityPrimaryDriver = security_drv;
        qemud_drv->securitySecondaryDriver = &qemuDACSecurityDriver;
        qemud_drv->securityDriver = &qemuStackedSecurityDriver;
        VIR_INFO("Initialized security driver %s", security_drv->name);
1552 1553
    }

1554
    return 0;
1555
}
1556 1557


1558 1559
static virCapsPtr
qemuCreateCapabilities(virCapsPtr oldcaps,
1560
                       struct qemud_driver *driver)
1561 1562 1563 1564 1565
{
    virCapsPtr caps;

    /* Basic host arch / guest machine capabilities */
    if (!(caps = qemudCapsInit(oldcaps))) {
1566
        virReportOOMError();
1567 1568 1569
        return NULL;
    }

1570 1571 1572 1573 1574 1575 1576 1577
    if (driver->allowDiskFormatProbing) {
        caps->defaultDiskDriverName = NULL;
        caps->defaultDiskDriverType = NULL;
    } else {
        caps->defaultDiskDriverName = "qemu";
        caps->defaultDiskDriverType = "raw";
    }

1578 1579 1580 1581 1582 1583
    /* Domain XML parser hooks */
    caps->privateDataAllocFunc = qemuDomainObjPrivateAlloc;
    caps->privateDataFreeFunc = qemuDomainObjPrivateFree;
    caps->privateDataXMLFormat = qemuDomainObjPrivateXMLFormat;
    caps->privateDataXMLParse = qemuDomainObjPrivateXMLParse;

1584 1585 1586 1587 1588
    if (virGetHostUUID(caps->host.host_uuid)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot get the host uuid"));
        goto err_exit;
    }
1589

1590 1591 1592 1593 1594 1595
    /* Domain Namespace XML parser hooks */
    caps->ns.parse = qemuDomainDefNamespaceParse;
    caps->ns.free = qemuDomainDefNamespaceFree;
    caps->ns.format = qemuDomainDefNamespaceFormatXML;
    caps->ns.href = qemuDomainDefNamespaceHref;

1596
    /* Security driver data */
1597
    if (driver->securityPrimaryDriver) {
1598 1599
        const char *doi, *model;

1600 1601
        doi = virSecurityDriverGetDOI(driver->securityPrimaryDriver);
        model = virSecurityDriverGetModel(driver->securityPrimaryDriver);
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614

        if (!(caps->host.secModel.model = strdup(model)))
            goto no_memory;
        if (!(caps->host.secModel.doi = strdup(doi)))
            goto no_memory;

        VIR_DEBUG("Initialized caps for security driver \"%s\" with "
                  "DOI \"%s\"", model, doi);
    }

    return caps;

no_memory:
1615
    virReportOOMError();
1616
err_exit:
1617 1618 1619
    virCapabilitiesFree(caps);
    return NULL;
}
1620

C
Chris Lalancette 已提交
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
static void qemuDomainSnapshotLoad(void *payload,
                                   const char *name ATTRIBUTE_UNUSED,
                                   void *data)
{
    virDomainObjPtr vm = (virDomainObjPtr)payload;
    char *baseDir = (char *)data;
    char *snapDir = NULL;
    DIR *dir = NULL;
    struct dirent *entry;
    char *xmlStr;
    int ret;
    char *fullpath;
    virDomainSnapshotDefPtr def = NULL;
    char ebuf[1024];

    virDomainObjLock(vm);
    if (virAsprintf(&snapDir, "%s/%s", baseDir, vm->def->name) < 0) {
1638
        VIR_ERROR(_("Failed to allocate memory for snapshot directory for domain %s"),
C
Chris Lalancette 已提交
1639 1640 1641 1642 1643 1644 1645 1646 1647
                   vm->def->name);
        goto cleanup;
    }

    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
             snapDir);

    if (!(dir = opendir(snapDir))) {
        if (errno != ENOENT)
1648
            VIR_ERROR(_("Failed to open snapshot directory %s for domain %s: %s"),
C
Chris Lalancette 已提交
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
                      snapDir, vm->def->name,
                      virStrerror(errno, ebuf, sizeof(ebuf)));
        goto cleanup;
    }

    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;

        /* NB: ignoring errors, so one malformed config doesn't
           kill the whole process */
        VIR_INFO("Loading snapshot file '%s'", entry->d_name);

        if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
1663
            VIR_ERROR0(_("Failed to allocate memory for path"));
C
Chris Lalancette 已提交
1664 1665 1666 1667 1668 1669
            continue;
        }

        ret = virFileReadAll(fullpath, 1024*1024*1, &xmlStr);
        if (ret < 0) {
            /* Nothing we can do here, skip this one */
1670
            VIR_ERROR(_("Failed to read snapshot file %s: %s"), fullpath,
C
Chris Lalancette 已提交
1671
                      virStrerror(errno, ebuf, sizeof(ebuf)));
1672
            VIR_FREE(fullpath);
C
Chris Lalancette 已提交
1673 1674 1675 1676 1677 1678
            continue;
        }

        def = virDomainSnapshotDefParseString(xmlStr, 0);
        if (def == NULL) {
            /* Nothing we can do here, skip this one */
1679
            VIR_ERROR(_("Failed to parse snapshot XML from file '%s'"), fullpath);
1680
            VIR_FREE(fullpath);
C
Chris Lalancette 已提交
1681 1682 1683 1684
            VIR_FREE(xmlStr);
            continue;
        }

1685
        virDomainSnapshotAssignDef(&vm->snapshots, def);
C
Chris Lalancette 已提交
1686

1687
        VIR_FREE(fullpath);
C
Chris Lalancette 已提交
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
        VIR_FREE(xmlStr);
    }

    /* FIXME: qemu keeps internal track of snapshots.  We can get access
     * to this info via the "info snapshots" monitor command for running
     * domains, or via "qemu-img snapshot -l" for shutoff domains.  It would
     * be nice to update our internal state based on that, but there is a
     * a problem.  qemu doesn't track all of the same metadata that we do.
     * In particular we wouldn't be able to fill in the <parent>, which is
     * pretty important in our metadata.
     */

    virResetLastError();

cleanup:
    if (dir)
        closedir(dir);
    VIR_FREE(snapDir);
    virDomainObjUnlock(vm);
}

1709 1710 1711 1712 1713 1714
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
1715
qemudStartup(int privileged) {
1716
    char *base = NULL;
D
Daniel P. Berrange 已提交
1717
    char driverConf[PATH_MAX];
1718
    int rc;
1719
    virConnectPtr conn = NULL;
1720

1721
    if (VIR_ALLOC(qemu_driver) < 0)
1722 1723
        return -1;

1724
    if (virMutexInit(&qemu_driver->lock) < 0) {
1725
        VIR_ERROR0(_("cannot initialize mutex"));
1726 1727 1728
        VIR_FREE(qemu_driver);
        return -1;
    }
1729
    qemuDriverLock(qemu_driver);
1730
    qemu_driver->privileged = privileged;
1731

1732 1733 1734
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;

1735 1736 1737
    if (virDomainObjListInit(&qemu_driver->domains) < 0)
        goto out_of_memory;

1738
    /* Init callback list */
1739
    if (VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
1740
        goto out_of_memory;
1741 1742 1743 1744 1745 1746
    if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
        goto out_of_memory;

    if ((qemu_driver->domainEventTimer =
         virEventAddTimeout(-1, qemuDomainEventFlush, qemu_driver, NULL)) < 0)
        goto error;
1747

1748 1749 1750 1751 1752
    /* Allocate bitmap for vnc port reservation */
    if ((qemu_driver->reservedVNCPorts =
         virBitmapAlloc(QEMU_VNC_PORT_MAX - QEMU_VNC_PORT_MIN)) == NULL)
        goto out_of_memory;

1753
    if (privileged) {
1754 1755
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
1756
            goto out_of_memory;
1757

D
Daniel P. Berrange 已提交
1758
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
1759
            goto out_of_memory;
1760 1761

        if (virAsprintf(&qemu_driver->stateDir,
1762
                      "%s/run/libvirt/qemu", LOCAL_STATE_DIR) == -1)
1763
            goto out_of_memory;
1764 1765 1766 1767 1768 1769 1770 1771

        if (virAsprintf(&qemu_driver->libDir,
                      "%s/lib/libvirt/qemu", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;

        if (virAsprintf(&qemu_driver->cacheDir,
                      "%s/cache/libvirt/qemu", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
1772 1773 1774
        if (virAsprintf(&qemu_driver->saveDir,
                      "%s/lib/libvirt/qemu/save/", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
C
Chris Lalancette 已提交
1775 1776 1777
        if (virAsprintf(&qemu_driver->snapshotDir,
                        "%s/lib/libvirt/qemu/snapshot", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
1778
    } else {
1779
        uid_t uid = geteuid();
1780
        char *userdir = virGetUserDirectory(uid);
1781
        if (!userdir)
1782
            goto error;
1783

1784
        if (virAsprintf(&qemu_driver->logDir,
1785 1786
                        "%s/.libvirt/qemu/log", userdir) == -1) {
            VIR_FREE(userdir);
1787
            goto out_of_memory;
1788
        }
1789

1790 1791
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
1792
            goto out_of_memory;
1793 1794
        }
        VIR_FREE(userdir);
1795 1796 1797

        if (virAsprintf(&qemu_driver->stateDir, "%s/qemu/run", base) == -1)
            goto out_of_memory;
1798 1799 1800 1801
        if (virAsprintf(&qemu_driver->libDir, "%s/qemu/lib", base) == -1)
            goto out_of_memory;
        if (virAsprintf(&qemu_driver->cacheDir, "%s/qemu/cache", base) == -1)
            goto out_of_memory;
1802 1803
        if (virAsprintf(&qemu_driver->saveDir, "%s/qemu/save", base) == -1)
            goto out_of_memory;
C
Chris Lalancette 已提交
1804 1805
        if (virAsprintf(&qemu_driver->snapshotDir, "%s/qemu/snapshot", base) == -1)
            goto out_of_memory;
1806 1807
    }

L
Laine Stump 已提交
1808
    if (virFileMakePath(qemu_driver->stateDir) != 0) {
1809
        char ebuf[1024];
1810
        VIR_ERROR(_("Failed to create state dir '%s': %s"),
1811
                  qemu_driver->stateDir, virStrerror(errno, ebuf, sizeof ebuf));
1812
        goto error;
1813
    }
L
Laine Stump 已提交
1814
    if (virFileMakePath(qemu_driver->libDir) != 0) {
1815
        char ebuf[1024];
1816
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
1817 1818 1819
                  qemu_driver->libDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
L
Laine Stump 已提交
1820
    if (virFileMakePath(qemu_driver->cacheDir) != 0) {
1821
        char ebuf[1024];
1822
        VIR_ERROR(_("Failed to create cache dir '%s': %s"),
1823 1824 1825
                  qemu_driver->cacheDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
1826 1827 1828 1829 1830 1831
    if (virFileMakePath(qemu_driver->saveDir) != 0) {
        char ebuf[1024];
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
                  qemu_driver->saveDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
C
Chris Lalancette 已提交
1832 1833 1834 1835 1836 1837
    if (virFileMakePath(qemu_driver->snapshotDir) != 0) {
        char ebuf[1024];
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
                  qemu_driver->snapshotDir, virStrerror(errno, ebuf, sizeof ebuf));
        goto error;
    }
1838 1839 1840 1841

    /* Configuration paths are either ~/.libvirt/qemu/... (session) or
     * /etc/libvirt/qemu/... (system).
     */
D
Daniel P. Berrange 已提交
1842
    if (snprintf (driverConf, sizeof(driverConf), "%s/qemu.conf", base) == -1)
1843
        goto out_of_memory;
D
Daniel P. Berrange 已提交
1844
    driverConf[sizeof(driverConf)-1] = '\0';
1845

1846
    if (virAsprintf(&qemu_driver->configDir, "%s/qemu", base) == -1)
1847 1848
        goto out_of_memory;

1849
    if (virAsprintf(&qemu_driver->autostartDir, "%s/qemu/autostart", base) == -1)
1850 1851
        goto out_of_memory;

1852
    VIR_FREE(base);
1853

1854 1855 1856 1857 1858 1859 1860
    rc = virCgroupForDriver("qemu", &qemu_driver->cgroup, privileged, 1);
    if (rc < 0) {
        char buf[1024];
        VIR_WARN("Unable to create cgroup for driver: %s",
                 virStrerror(-rc, buf, sizeof(buf)));
    }

1861 1862 1863 1864
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
        goto error;
    }

1865 1866
    if (qemudSecurityInit(qemu_driver) < 0)
        goto error;
D
Daniel P. Berrange 已提交
1867

1868
    if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
1869
                                                    qemu_driver)) == NULL)
1870
        goto error;
1871

1872
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
1873 1874
        goto error;

1875 1876
    if (privileged) {
        if (chown(qemu_driver->libDir, qemu_driver->user, qemu_driver->group) < 0) {
1877
            virReportSystemError(errno,
1878 1879 1880 1881 1882
                                 _("unable to set ownership of '%s' to user %d:%d"),
                                 qemu_driver->libDir, qemu_driver->user, qemu_driver->group);
            goto error;
        }
        if (chown(qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group) < 0) {
1883
            virReportSystemError(errno,
1884 1885 1886 1887
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group);
            goto error;
        }
1888 1889 1890 1891 1892 1893
        if (chown(qemu_driver->saveDir, qemu_driver->user, qemu_driver->group) < 0) {
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->saveDir, qemu_driver->user, qemu_driver->group);
            goto error;
        }
C
Chris Lalancette 已提交
1894 1895 1896 1897 1898 1899
        if (chown(qemu_driver->snapshotDir, qemu_driver->user, qemu_driver->group) < 0) {
            virReportSystemError(errno,
                                 _("unable to set ownership of '%s' to %d:%d"),
                                 qemu_driver->snapshotDir, qemu_driver->user, qemu_driver->group);
            goto error;
        }
1900 1901
    }

1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
    /* If hugetlbfs is present, then we need to create a sub-directory within
     * it, since we can't assume the root mount point has permissions that
     * will let our spawned QEMU instances use it.
     *
     * NB the check for '/', since user may config "" to disable hugepages
     * even when mounted
     */
    if (qemu_driver->hugetlbfs_mount &&
        qemu_driver->hugetlbfs_mount[0] == '/') {
        char *mempath = NULL;
        if (virAsprintf(&mempath, "%s/libvirt/qemu", qemu_driver->hugetlbfs_mount) < 0)
            goto out_of_memory;

        if ((rc = virFileMakePath(mempath)) != 0) {
1916
            virReportSystemError(rc,
1917 1918 1919 1920 1921 1922
                                 _("unable to create hugepage path %s"), mempath);
            VIR_FREE(mempath);
            goto error;
        }
        if (qemu_driver->privileged &&
            chown(mempath, qemu_driver->user, qemu_driver->group) < 0) {
1923
            virReportSystemError(errno,
1924 1925 1926 1927 1928 1929 1930 1931 1932
                                 _("unable to set ownership on %s to %d:%d"),
                                 mempath, qemu_driver->user, qemu_driver->group);
            VIR_FREE(mempath);
            goto error;
        }

        qemu_driver->hugepage_path = mempath;
    }

1933
    /* Get all the running persistent or transient configs first */
1934
    if (virDomainLoadAllConfigs(qemu_driver->caps,
1935 1936 1937 1938 1939 1940
                                &qemu_driver->domains,
                                qemu_driver->stateDir,
                                NULL,
                                1, NULL, NULL) < 0)
        goto error;

1941 1942 1943 1944 1945
    conn = virConnectOpen(qemu_driver->privileged ?
                          "qemu:///system" :
                          "qemu:///session");

    qemuReconnectDomains(conn, qemu_driver);
1946 1947

    /* Then inactive persistent configs */
1948
    if (virDomainLoadAllConfigs(qemu_driver->caps,
1949 1950
                                &qemu_driver->domains,
                                qemu_driver->configDir,
1951
                                qemu_driver->autostartDir,
1952
                                0, NULL, NULL) < 0)
1953
        goto error;
C
Chris Lalancette 已提交
1954 1955 1956 1957 1958


    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
                   qemu_driver->snapshotDir);

1959 1960
    qemuDriverUnlock(qemu_driver);

1961 1962
    qemudAutostartConfigs(qemu_driver);

1963 1964
    if (conn)
        virConnectClose(conn);
1965

1966 1967
    return 0;

1968
out_of_memory:
1969
    virReportOOMError();
1970 1971 1972
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
1973 1974
    if (conn)
        virConnectClose(conn);
1975
    VIR_FREE(base);
1976
    qemudShutdown();
1977 1978 1979
    return -1;
}

1980 1981 1982 1983
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;

1984 1985 1986 1987 1988 1989 1990 1991
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
    }
1992 1993
}

1994 1995 1996 1997 1998 1999 2000 2001
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
2002 2003 2004
    if (!qemu_driver)
        return 0;

2005
    qemuDriverLock(qemu_driver);
2006
    virDomainLoadAllConfigs(qemu_driver->caps,
2007 2008
                            &qemu_driver->domains,
                            qemu_driver->configDir,
2009
                            qemu_driver->autostartDir,
2010
                            0, qemudNotifyLoadDomain, qemu_driver);
2011
    qemuDriverUnlock(qemu_driver);
2012

2013
    qemudAutostartConfigs(qemu_driver);
2014 2015

    return 0;
2016 2017
}

2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
/**
 * qemudActive:
 *
 * Checks if the QEmu daemon is active, i.e. has an active domain or
 * an active network
 *
 * Returns 1 if active, 0 otherwise
 */
static int
qemudActive(void) {
2028
    int active = 0;
2029

2030 2031 2032
    if (!qemu_driver)
        return 0;

2033
    /* XXX having to iterate here is not great because it requires many locks */
2034
    qemuDriverLock(qemu_driver);
2035
    active = virDomainObjListNumOfDomains(&qemu_driver->domains, 1);
2036 2037
    qemuDriverUnlock(qemu_driver);
    return active;
2038 2039
}

2040 2041 2042 2043 2044 2045 2046
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
2047
    int i;
2048

2049
    if (!qemu_driver)
2050
        return -1;
2051

2052
    qemuDriverLock(qemu_driver);
2053
    pciDeviceListFree(qemu_driver->activePciHostdevs);
2054 2055
    virCapabilitiesFree(qemu_driver->caps);

2056
    virDomainObjListDeinit(&qemu_driver->domains);
2057
    virBitmapFree(qemu_driver->reservedVNCPorts);
2058

2059
    VIR_FREE(qemu_driver->securityDriverName);
2060
    VIR_FREE(qemu_driver->logDir);
2061 2062
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
2063
    VIR_FREE(qemu_driver->stateDir);
2064 2065
    VIR_FREE(qemu_driver->libDir);
    VIR_FREE(qemu_driver->cacheDir);
2066
    VIR_FREE(qemu_driver->saveDir);
C
Chris Lalancette 已提交
2067
    VIR_FREE(qemu_driver->snapshotDir);
2068
    VIR_FREE(qemu_driver->vncTLSx509certdir);
J
Jim Meyering 已提交
2069
    VIR_FREE(qemu_driver->vncListen);
2070
    VIR_FREE(qemu_driver->vncPassword);
2071
    VIR_FREE(qemu_driver->vncSASLdir);
2072
    VIR_FREE(qemu_driver->saveImageFormat);
2073 2074
    VIR_FREE(qemu_driver->hugetlbfs_mount);
    VIR_FREE(qemu_driver->hugepage_path);
D
Daniel P. Berrange 已提交
2075

2076 2077 2078 2079 2080 2081
    if (qemu_driver->cgroupDeviceACL) {
        for (i = 0 ; qemu_driver->cgroupDeviceACL[i] != NULL ; i++)
            VIR_FREE(qemu_driver->cgroupDeviceACL[i]);
        VIR_FREE(qemu_driver->cgroupDeviceACL);
    }

2082 2083
    /* Free domain callback list */
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
2084 2085 2086 2087
    virDomainEventQueueFree(qemu_driver->domainEventQueue);

    if (qemu_driver->domainEventTimer != -1)
        virEventRemoveTimeout(qemu_driver->domainEventTimer);
2088

2089 2090 2091
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);

2092 2093
    virCgroupFree(&qemu_driver->cgroup);

2094
    qemuDriverUnlock(qemu_driver);
2095
    virMutexDestroy(&qemu_driver->lock);
2096
    VIR_FREE(qemu_driver);
2097 2098

    return 0;
2099 2100
}

2101
typedef int qemuLogHandleOutput(virDomainObjPtr vm,
2102 2103
                                const char *output,
                                int fd);
2104 2105 2106 2107 2108

/*
 * Returns -1 for error, 0 on success
 */
static int
2109
qemudReadLogOutput(virDomainObjPtr vm,
2110 2111
                   int fd,
                   char *buf,
G
Guido Günther 已提交
2112
                   size_t buflen,
2113
                   qemuLogHandleOutput func,
2114 2115 2116
                   const char *what,
                   int timeout)
{
2117
    int retries = (timeout*10);
2118
    int got = 0;
2119 2120 2121
    buf[0] = '\0';

    while (retries) {
2122
        ssize_t func_ret, ret;
2123
        int isdead = 0;
G
Guido Günther 已提交
2124

2125
        func_ret = func(vm, buf, fd);
2126

2127 2128
        if (kill(vm->pid, 0) == -1 && errno == ESRCH)
            isdead = 1;
2129

2130 2131
        /* Any failures should be detected before we read the log, so we
         * always have something useful to report on failure. */
2132 2133
        ret = saferead(fd, buf+got, buflen-got-1);
        if (ret < 0) {
2134
            virReportSystemError(errno,
2135 2136 2137 2138 2139
                                 _("Failure while reading %s log output"),
                                 what);
            return -1;
        }

2140 2141 2142
        got += ret;
        buf[got] = '\0';
        if (got == buflen-1) {
2143
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2144 2145
                            _("Out of space while reading %s log output: %s"),
                            what, buf);
2146 2147 2148 2149
            return -1;
        }

        if (isdead) {
2150
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2151 2152
                            _("Process exited while reading %s log output: %s"),
                            what, buf);
2153 2154 2155
            return -1;
        }

2156 2157
        if (func_ret <= 0)
            return func_ret;
2158 2159 2160 2161

        usleep(100*1000);
        retries--;
    }
2162

2163
    qemuReportError(VIR_ERR_INTERNAL_ERROR,
2164 2165
                    _("Timed out while reading %s log output: %s"),
                    what, buf);
2166 2167 2168
    return -1;
}

2169

2170 2171 2172 2173 2174 2175 2176 2177
/*
 * Look at a chunk of data from the QEMU stdout logs and try to
 * find a TTY device, as indicated by a line like
 *
 * char device redirected to /dev/pts/3
 *
 * Returns -1 for error, 0 success, 1 continue reading
 */
2178
static int
2179
qemudExtractTTYPath(const char *haystack,
2180 2181
                    size_t *offset,
                    char **path)
2182
{
2183
    static const char needle[] = "char device redirected to";
2184
    char *tmp, *dev;
2185

2186
    VIR_FREE(*path);
2187
    /* First look for our magic string */
2188 2189 2190 2191 2192
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
2193

2194 2195 2196 2197 2198
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
2199
        if (c_isspace(*tmp)) {
2200 2201
            *path = strndup(dev, tmp-dev);
            if (*path == NULL) {
2202
                virReportOOMError();
2203 2204
                return -1;
            }
2205

2206
            /* ... now further update offset till we get EOL */
2207
            *offset = tmp - haystack;
2208 2209
            return 0;
        }
2210
        tmp++;
2211 2212 2213 2214 2215
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
2216 2217
     * least see a \n - indicate that we want to carry
     * on trying again
2218
     */
2219
    return 1;
2220 2221
}

2222
static int
2223
qemudFindCharDevicePTYsMonitor(virDomainObjPtr vm,
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
                               virHashTablePtr paths)
{
    int i;

#define LOOKUP_PTYS(array, arraylen, idprefix)                            \
    for (i = 0 ; i < (arraylen) ; i++) {                                  \
        virDomainChrDefPtr chr = (array)[i];                              \
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {                       \
            char id[16];                                                  \
                                                                          \
            if (snprintf(id, sizeof(id), idprefix "%i", i) >= sizeof(id)) \
                return -1;                                                \
                                                                          \
            const char *path = (const char *) virHashLookup(paths, id);   \
            if (path == NULL) {                                           \
2239 2240 2241
                if (chr->data.file.path == NULL) {                        \
                    /* neither the log output nor 'info chardev' had a */ \
                    /* pty path for this chardev, report an error */      \
2242 2243 2244
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,               \
                                    _("no assigned pty for device %s"), id); \
                    return -1;                                            \
2245 2246 2247 2248 2249
                } else {                                                  \
                    /* 'info chardev' had no pty path for this chardev, */\
                    /* but the log output had, so we're fine */           \
                    continue;                                             \
                }                                                         \
2250 2251
            }                                                             \
                                                                          \
2252
            VIR_FREE(chr->data.file.path);                                \
2253
            chr->data.file.path = strdup(path);                           \
2254 2255
                                                                          \
            if (chr->data.file.path == NULL) {                            \
2256
                virReportOOMError();                                      \
2257 2258
                return -1;                                                \
            }                                                             \
2259 2260 2261 2262 2263 2264
        }                                                                 \
    }

    LOOKUP_PTYS(vm->def->serials,   vm->def->nserials,   "serial");
    LOOKUP_PTYS(vm->def->parallels, vm->def->nparallels, "parallel");
    LOOKUP_PTYS(vm->def->channels,  vm->def->nchannels,  "channel");
C
Cole Robinson 已提交
2265 2266
    if (vm->def->console)
        LOOKUP_PTYS(&vm->def->console, 1,  "console");
2267
#undef LOOKUP_PTYS
2268 2269 2270 2271

    return 0;
}

2272
static int
2273
qemudFindCharDevicePTYs(virDomainObjPtr vm,
2274 2275
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
2276
{
2277
    size_t offset = 0;
2278
    int ret, i;
2279 2280

    /* The order in which QEMU prints out the PTY paths is
2281 2282
       the order in which it procsses its serial and parallel
       device args. This code must match that ordering.... */
2283

2284
    /* first comes the serial devices */
2285 2286
    for (i = 0 ; i < vm->def->nserials ; i++) {
        virDomainChrDefPtr chr = vm->def->serials[i];
2287
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
2288
            if ((ret = qemudExtractTTYPath(output, &offset,
2289
                                           &chr->data.file.path)) != 0)
2290
                return ret;
2291 2292 2293
        }
    }

2294
    /* then the parallel devices */
2295 2296
    for (i = 0 ; i < vm->def->nparallels ; i++) {
        virDomainChrDefPtr chr = vm->def->parallels[i];
2297
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
2298
            if ((ret = qemudExtractTTYPath(output, &offset,
2299
                                           &chr->data.file.path)) != 0)
2300
                return ret;
2301 2302 2303
        }
    }

2304 2305 2306 2307
    /* then the channel devices */
    for (i = 0 ; i < vm->def->nchannels ; i++) {
        virDomainChrDefPtr chr = vm->def->channels[i];
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
2308
            if ((ret = qemudExtractTTYPath(output, &offset,
2309 2310 2311 2312 2313
                                           &chr->data.file.path)) != 0)
                return ret;
        }
    }

2314
    return 0;
2315 2316
}

2317 2318 2319 2320 2321
static void qemudFreePtyPath(void *payload, const char *name ATTRIBUTE_UNUSED)
{
    VIR_FREE(payload);
}

2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
static void
qemuReadLogFD(int logfd, char *buf, int maxlen, int off)
{
    int ret;
    char *tmpbuf = buf + off;

    ret = saferead(logfd, tmpbuf, maxlen - off - 1);
    if (ret < 0) {
        ret = 0;
    }

    tmpbuf[ret] = '\0';
}

2336
static int
2337
qemudWaitForMonitor(struct qemud_driver* driver,
2338
                    virDomainObjPtr vm, off_t pos)
2339
{
2340
    char buf[4096] = ""; /* Plenty of space to get startup greeting */
2341
    int logfd;
2342
    int ret = -1;
2343
    virHashTablePtr paths = NULL;
2344

2345
    if ((logfd = qemudLogReadFD(driver->logDir, vm->def->name, pos)) < 0)
2346
        return -1;
2347

2348 2349 2350 2351
    if (qemudReadLogOutput(vm, logfd, buf, sizeof(buf),
                           qemudFindCharDevicePTYs,
                           "console", 30) < 0)
        goto closelog;
2352

2353
    VIR_DEBUG("Connect monitor to %p '%s'", vm, vm->def->name);
2354 2355 2356
    if (qemuConnectMonitor(driver, vm) < 0) {
        goto cleanup;
    }
2357

2358 2359 2360 2361
    /* Try to get the pty path mappings again via the monitor. This is much more
     * reliable if it's available.
     * Note that the monitor itself can be on a pty, so we still need to try the
     * log output method. */
2362
    paths = virHashCreate(0);
2363
    if (paths == NULL) {
2364
        virReportOOMError();
2365 2366 2367
        goto cleanup;
    }

2368
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2369 2370
    qemuDomainObjPrivatePtr priv = vm->privateData;
    ret = qemuMonitorGetPtyPaths(priv->mon, paths);
2371
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2372 2373 2374

    VIR_DEBUG("qemuMonitorGetPtyPaths returned %i", ret);
    if (ret == 0) {
2375
        ret = qemudFindCharDevicePTYsMonitor(vm, paths);
2376 2377 2378 2379 2380 2381 2382
    }

cleanup:
    if (paths) {
        virHashFree(paths, qemudFreePtyPath);
    }

2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
    if (kill(vm->pid, 0) == -1 && errno == ESRCH) {
        /* VM is dead, any other error raised in the interim is probably
         * not as important as the qemu cmdline output */
        qemuReadLogFD(logfd, buf, sizeof(buf), strlen(buf));
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("process exited while connecting to monitor: %s"),
                        buf);
        ret = -1;
    }

closelog:
    if (close(logfd) < 0) {
        char ebuf[4096];
2396
        VIR_WARN("Unable to close logfile: %s",
2397 2398 2399
                 virStrerror(errno, ebuf, sizeof ebuf));
    }

2400
    return ret;
2401 2402
}

2403
static int
2404
qemuDetectVcpuPIDs(struct qemud_driver *driver,
2405 2406 2407
                   virDomainObjPtr vm) {
    pid_t *cpupids = NULL;
    int ncpupids;
2408
    qemuDomainObjPrivatePtr priv = vm->privateData;
2409

2410
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
2411 2412
        priv->nvcpupids = 1;
        if (VIR_ALLOC_N(priv->vcpupids, priv->nvcpupids) < 0) {
2413
            virReportOOMError();
2414 2415
            return -1;
        }
2416
        priv->vcpupids[0] = vm->pid;
2417 2418 2419
        return 0;
    }

2420
    /* What follows is now all KVM specific */
2421

2422
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2423
    if ((ncpupids = qemuMonitorGetCPUInfo(priv->mon, &cpupids)) < 0) {
2424
        qemuDomainObjExitMonitorWithDriver(driver, vm);
2425
        return -1;
2426
    }
2427
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2428

2429 2430 2431
    /* Treat failure to get VCPU<->PID mapping as non-fatal */
    if (ncpupids == 0)
        return 0;
2432

2433
    if (ncpupids != vm->def->vcpus) {
2434
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
E
Eric Blake 已提交
2435 2436 2437
                        _("got wrong number of vCPU pids from QEMU monitor. "
                          "got %d, wanted %d"),
                        ncpupids, vm->def->vcpus);
2438 2439 2440
        VIR_FREE(cpupids);
        return -1;
    }
2441

2442 2443
    priv->nvcpupids = ncpupids;
    priv->vcpupids = cpupids;
2444 2445 2446
    return 0;
}

2447 2448 2449
/*
 * To be run between fork/exec of QEMU only
 */
2450
static int
2451 2452
qemudInitCpuAffinity(virDomainObjPtr vm)
{
2453
    int i, hostcpus, maxcpu = QEMUD_CPUMASK_LEN;
2454
    virNodeInfo nodeinfo;
2455 2456
    unsigned char *cpumap;
    int cpumaplen;
2457 2458

    DEBUG0("Setting CPU affinity");
2459

2460
    if (nodeGetInfo(NULL, &nodeinfo) < 0)
2461 2462 2463 2464
        return -1;

    /* setaffinity fails if you set bits for CPUs which
     * aren't present, so we have to limit ourselves */
2465 2466 2467
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
2468

2469 2470
    cpumaplen = VIR_CPU_MAPLEN(maxcpu);
    if (VIR_ALLOC_N(cpumap, cpumaplen) < 0) {
2471
        virReportOOMError();
2472 2473 2474
        return -1;
    }

D
Daniel P. Berrange 已提交
2475
    if (vm->def->cpumask) {
2476 2477 2478
        /* XXX why don't we keep 'cpumask' in the libvirt cpumap
         * format to start with ?!?! */
        for (i = 0 ; i < maxcpu && i < vm->def->cpumasklen ; i++)
D
Daniel P. Berrange 已提交
2479
            if (vm->def->cpumask[i])
2480
                VIR_USE_CPU(cpumap, i);
D
Daniel P. Berrange 已提交
2481
    } else {
2482 2483 2484 2485
        /* You may think this is redundant, but we can't assume libvirtd
         * itself is running on all pCPUs, so we need to explicitly set
         * the spawned QEMU instance to all pCPUs if no map is given in
         * its config file */
D
Daniel P. Berrange 已提交
2486
        for (i = 0 ; i < maxcpu ; i++)
2487
            VIR_USE_CPU(cpumap, i);
D
Daniel P. Berrange 已提交
2488
    }
2489

2490 2491 2492 2493 2494 2495 2496 2497
    /* We are pressuming we are running between fork/exec of QEMU
     * so use '0' to indicate our own process ID. No threads are
     * running at this point
     */
    if (virProcessInfoSetAffinity(0, /* Self */
                                  cpumap, cpumaplen, maxcpu) < 0) {
        VIR_FREE(cpumap);
        return -1;
2498
    }
2499
    VIR_FREE(cpumap);
2500 2501 2502 2503 2504

    return 0;
}


2505
static int
2506 2507 2508 2509
qemuInitPasswords(virConnectPtr conn,
                  struct qemud_driver *driver,
                  virDomainObjPtr vm,
                  unsigned long long qemuCmdFlags) {
2510
    int ret = 0;
2511
    qemuDomainObjPrivatePtr priv = vm->privateData;
2512

2513 2514 2515
    if ((vm->def->ngraphics == 1) &&
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        (vm->def->graphics[0]->data.vnc.passwd || driver->vncPassword)) {
2516

2517
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
2518
        ret = qemuMonitorSetVNCPassword(priv->mon,
2519 2520 2521
                                        vm->def->graphics[0]->data.vnc.passwd ?
                                        vm->def->graphics[0]->data.vnc.passwd :
                                        driver->vncPassword);
2522
        qemuDomainObjExitMonitorWithDriver(driver, vm);
2523 2524
    }

2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
    if (ret < 0)
        goto cleanup;

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        int i;

        for (i = 0 ; i < vm->def->ndisks ; i++) {
            char *secret;
            size_t secretLen;

            if (!vm->def->disks[i]->encryption ||
                !vm->def->disks[i]->src)
                continue;

            if (getVolumeQcowPassphrase(conn,
                                        vm->def->disks[i],
                                        &secret, &secretLen) < 0)
                goto cleanup;

            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            ret = qemuMonitorSetDrivePassphrase(priv->mon,
                                                vm->def->disks[i]->info.alias,
                                                secret);
2548
            VIR_FREE(secret);
2549 2550 2551 2552 2553 2554 2555
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            if (ret < 0)
                goto cleanup;
        }
    }

cleanup:
2556
    return ret;
2557 2558 2559
}


2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
#define QEMU_PCI_VENDOR_INTEL     0x8086
#define QEMU_PCI_VENDOR_LSI_LOGIC 0x1000
#define QEMU_PCI_VENDOR_REDHAT    0x1af4
#define QEMU_PCI_VENDOR_CIRRUS    0x1013
#define QEMU_PCI_VENDOR_REALTEK   0x10ec
#define QEMU_PCI_VENDOR_AMD       0x1022
#define QEMU_PCI_VENDOR_ENSONIQ   0x1274
#define QEMU_PCI_VENDOR_VMWARE    0x15ad
#define QEMU_PCI_VENDOR_QEMU      0x1234

#define QEMU_PCI_PRODUCT_DISK_VIRTIO 0x1001

2572 2573
#define QEMU_PCI_PRODUCT_BALLOON_VIRTIO 0x1002

2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
#define QEMU_PCI_PRODUCT_NIC_NE2K     0x8029
#define QEMU_PCI_PRODUCT_NIC_PCNET    0x2000
#define QEMU_PCI_PRODUCT_NIC_RTL8139  0x8139
#define QEMU_PCI_PRODUCT_NIC_E1000    0x100E
#define QEMU_PCI_PRODUCT_NIC_VIRTIO   0x1000

#define QEMU_PCI_PRODUCT_VGA_CIRRUS 0x00b8
#define QEMU_PCI_PRODUCT_VGA_VMWARE 0x0405
#define QEMU_PCI_PRODUCT_VGA_STDVGA 0x1111

#define QEMU_PCI_PRODUCT_AUDIO_AC97    0x2415
#define QEMU_PCI_PRODUCT_AUDIO_ES1370  0x5000

#define QEMU_PCI_PRODUCT_CONTROLLER_PIIX 0x7010
#define QEMU_PCI_PRODUCT_CONTROLLER_LSI  0x0012

#define QEMU_PCI_PRODUCT_WATCHDOG_I63000ESB 0x25ab

static int
qemuAssignNextPCIAddress(virDomainDeviceInfo *info,
                         int vendor,
                         int product,
                         qemuMonitorPCIAddress *addrs,
                         int naddrs)
{
    int found = 0;
    int i;

    VIR_DEBUG("Look for %x:%x out of %d", vendor, product, naddrs);

    for (i = 0 ; (i < naddrs) && !found; i++) {
        VIR_DEBUG("Maybe %x:%x", addrs[i].vendor, addrs[i].product);
        if (addrs[i].vendor == vendor &&
            addrs[i].product == product) {
            VIR_DEBUG("Match %d", i);
            found = 1;
            break;
        }
    }
    if (!found) {
        return -1;
    }

    /* Blank it out so this device isn't matched again */
    addrs[i].vendor = 0;
    addrs[i].product = 0;

    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
        info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;

    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
        info->addr.pci.domain = addrs[i].addr.domain;
        info->addr.pci.bus = addrs[i].addr.bus;
        info->addr.pci.slot = addrs[i].addr.slot;
        info->addr.pci.function = addrs[i].addr.function;
    }

    return 0;
}

static int
qemuGetPCIDiskVendorProduct(virDomainDiskDefPtr def,
                            unsigned *vendor,
                            unsigned *product)
{
    switch (def->bus) {
    case VIR_DOMAIN_DISK_BUS_VIRTIO:
        *vendor = QEMU_PCI_VENDOR_REDHAT;
        *product = QEMU_PCI_PRODUCT_DISK_VIRTIO;
        break;

    default:
        return -1;
    }

    return 0;
}

static int
qemuGetPCINetVendorProduct(virDomainNetDefPtr def,
                            unsigned *vendor,
                            unsigned *product)
{
    if (!def->model)
        return -1;

    if (STREQ(def->model, "ne2k_pci")) {
        *vendor = QEMU_PCI_VENDOR_REALTEK;
        *product = QEMU_PCI_PRODUCT_NIC_NE2K;
    } else if (STREQ(def->model, "pcnet")) {
        *vendor = QEMU_PCI_VENDOR_AMD;
        *product = QEMU_PCI_PRODUCT_NIC_PCNET;
    } else if (STREQ(def->model, "rtl8139")) {
        *vendor = QEMU_PCI_VENDOR_REALTEK;
        *product = QEMU_PCI_PRODUCT_NIC_RTL8139;
    } else if (STREQ(def->model, "e1000")) {
        *vendor = QEMU_PCI_VENDOR_INTEL;
        *product = QEMU_PCI_PRODUCT_NIC_E1000;
    } else if (STREQ(def->model, "virtio")) {
        *vendor = QEMU_PCI_VENDOR_REDHAT;
        *product = QEMU_PCI_PRODUCT_NIC_VIRTIO;
    } else {
        VIR_INFO("Unexpected NIC model %s, cannot get PCI address",
                 def->model);
        return -1;
    }
    return 0;
}

static int
qemuGetPCIControllerVendorProduct(virDomainControllerDefPtr def,
                                  unsigned *vendor,
                                  unsigned *product)
{
    switch (def->type) {
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
        *vendor = QEMU_PCI_VENDOR_LSI_LOGIC;
        *product = QEMU_PCI_PRODUCT_CONTROLLER_LSI;
        break;

    case VIR_DOMAIN_CONTROLLER_TYPE_FDC:
        /* XXX we could put in the ISA bridge address, but
           that's not technically the FDC's address */
        return -1;

    case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
        *vendor = QEMU_PCI_VENDOR_INTEL;
        *product = QEMU_PCI_PRODUCT_CONTROLLER_PIIX;
        break;

    default:
        VIR_INFO("Unexpected controller type %s, cannot get PCI address",
                 virDomainControllerTypeToString(def->type));
        return -1;
    }

    return 0;
}

static int
qemuGetPCIVideoVendorProduct(virDomainVideoDefPtr def,
                             unsigned *vendor,
                             unsigned *product)
{
    switch (def->type) {
    case VIR_DOMAIN_VIDEO_TYPE_CIRRUS:
        *vendor = QEMU_PCI_VENDOR_CIRRUS;
        *product = QEMU_PCI_PRODUCT_VGA_CIRRUS;
        break;

    case VIR_DOMAIN_VIDEO_TYPE_VGA:
        *vendor = QEMU_PCI_VENDOR_QEMU;
        *product = QEMU_PCI_PRODUCT_VGA_STDVGA;
        break;

    case VIR_DOMAIN_VIDEO_TYPE_VMVGA:
        *vendor = QEMU_PCI_VENDOR_VMWARE;
        *product = QEMU_PCI_PRODUCT_VGA_VMWARE;
        break;

    default:
        return -1;
    }
    return 0;
}

static int
qemuGetPCISoundVendorProduct(virDomainSoundDefPtr def,
                             unsigned *vendor,
                             unsigned *product)
{
    switch (def->model) {
    case VIR_DOMAIN_SOUND_MODEL_ES1370:
        *vendor = QEMU_PCI_VENDOR_ENSONIQ;
        *product = QEMU_PCI_PRODUCT_AUDIO_ES1370;
        break;

    case VIR_DOMAIN_SOUND_MODEL_AC97:
        *vendor = QEMU_PCI_VENDOR_INTEL;
        *product = QEMU_PCI_PRODUCT_AUDIO_AC97;
        break;

    default:
        return -1;
    }

    return 0;
}

static int
qemuGetPCIWatchdogVendorProduct(virDomainWatchdogDefPtr def,
                                unsigned *vendor,
                                unsigned *product)
{
    switch (def->model) {
    case VIR_DOMAIN_WATCHDOG_MODEL_I6300ESB:
        *vendor = QEMU_PCI_VENDOR_INTEL;
        *product = QEMU_PCI_PRODUCT_WATCHDOG_I63000ESB;
        break;

    default:
        return -1;
    }

    return 0;
}


2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800
static int
qemuGetPCIMemballoonVendorProduct(virDomainMemballoonDefPtr def,
                                  unsigned *vendor,
                                  unsigned *product)
{
    switch (def->model) {
    case VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO:
        *vendor = QEMU_PCI_VENDOR_REDHAT;
        *product = QEMU_PCI_PRODUCT_BALLOON_VIRTIO;
        break;

    default:
        return -1;
    }

    return 0;
}


2801 2802 2803 2804 2805 2806 2807 2808 2809
/*
 * This entire method assumes that PCI devices in 'info pci'
 * match ordering of devices specified on the command line
 * wrt to devices of matching vendor+product
 *
 * XXXX this might not be a valid assumption if we assign
 * some static addrs on CLI. Have to check that...
 */
static int
2810
qemuDetectPCIAddresses(virDomainObjPtr vm,
2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
                       qemuMonitorPCIAddress *addrs,
                       int naddrs)
{
    unsigned int vendor = 0, product = 0;
    int i;

    /* XXX should all these vendor/product IDs be kept in the
     * actual device data structure instead ?
     */

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (qemuGetPCIDiskVendorProduct(vm->def->disks[i], &vendor, &product) < 0)
            continue;

        if (qemuAssignNextPCIAddress(&(vm->def->disks[i]->info),
                                     vendor, product,
                                     addrs, naddrs) < 0) {
2828 2829 2830
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find PCI address for VirtIO disk %s"),
                            vm->def->disks[i]->dst);
2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
            return -1;
        }
    }

    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (qemuGetPCINetVendorProduct(vm->def->nets[i], &vendor, &product) < 0)
            continue;

        if (qemuAssignNextPCIAddress(&(vm->def->nets[i]->info),
                                     vendor, product,
                                     addrs,  naddrs) < 0) {
2842 2843 2844
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find PCI address for %s NIC"),
                            vm->def->nets[i]->model);
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855
            return -1;
        }
    }

    for (i = 0 ; i < vm->def->ncontrollers ; i++) {
        if (qemuGetPCIControllerVendorProduct(vm->def->controllers[i], &vendor, &product) < 0)
            continue;

        if (qemuAssignNextPCIAddress(&(vm->def->controllers[i]->info),
                                     vendor, product,
                                     addrs,  naddrs) < 0) {
2856 2857 2858
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find PCI address for controller %s"),
                            virDomainControllerTypeToString(vm->def->controllers[i]->type));
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
            return -1;
        }
    }

    for (i = 0 ; i < vm->def->nvideos ; i++) {
        if (qemuGetPCIVideoVendorProduct(vm->def->videos[i], &vendor, &product) < 0)
            continue;

        if (qemuAssignNextPCIAddress(&(vm->def->videos[i]->info),
                                     vendor, product,
                                     addrs,  naddrs) < 0) {
2870 2871 2872
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find PCI address for video adapter %s"),
                            virDomainVideoTypeToString(vm->def->videos[i]->type));
2873 2874 2875 2876 2877 2878 2879 2880 2881
            return -1;
        }
    }

    for (i = 0 ; i < vm->def->nsounds ; i++) {
        if (qemuGetPCISoundVendorProduct(vm->def->sounds[i], &vendor, &product) < 0)
            continue;

        if (qemuAssignNextPCIAddress(&(vm->def->sounds[i]->info),
2882
                                    vendor, product,
2883
                                     addrs,  naddrs) < 0) {
2884 2885 2886
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find PCI address for sound adapter %s"),
                            virDomainSoundModelTypeToString(vm->def->sounds[i]->model));
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
            return -1;
        }
    }


    if (vm->def->watchdog &&
        qemuGetPCIWatchdogVendorProduct(vm->def->watchdog, &vendor, &product) == 0) {
        if (qemuAssignNextPCIAddress(&(vm->def->watchdog->info),
                                     vendor, product,
                                     addrs,  naddrs) < 0) {
2897 2898 2899
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find PCI address for watchdog %s"),
                            virDomainWatchdogModelTypeToString(vm->def->watchdog->model));
2900 2901 2902 2903
            return -1;
        }
    }

2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
    if (vm->def->memballoon &&
        qemuGetPCIMemballoonVendorProduct(vm->def->memballoon, &vendor, &product) == 0) {
        if (qemuAssignNextPCIAddress(&(vm->def->memballoon->info),
                                     vendor, product,
                                     addrs, naddrs) < 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("cannot find PCI address for balloon %s"),
                            virDomainMemballoonModelTypeToString(vm->def->memballoon->model));
            return -1;
        }
    }

2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
    /* XXX console (virtio) */


    /* ... and now things we don't have in our xml */

    /* XXX USB controller ? */

    /* XXX what about other PCI devices (ie bridges) */

    return 0;
}

static int
qemuInitPCIAddresses(struct qemud_driver *driver,
                     virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int naddrs;
    int ret;
    qemuMonitorPCIAddress *addrs = NULL;

    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    naddrs = qemuMonitorGetAllPCIAddresses(priv->mon,
                                           &addrs);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

2942
    ret = qemuDetectPCIAddresses(vm, addrs, naddrs);
2943 2944 2945 2946 2947 2948

    VIR_FREE(addrs);

    return ret;
}

2949
static int qemudNextFreeVNCPort(struct qemud_driver *driver) {
2950 2951
    int i;

2952
    for (i = QEMU_VNC_PORT_MIN; i < QEMU_VNC_PORT_MAX; i++) {
2953 2954 2955
        int fd;
        int reuse = 1;
        struct sockaddr_in addr;
2956 2957 2958 2959 2960 2961 2962 2963 2964
        bool used = false;

        if (virBitmapGetBit(driver->reservedVNCPorts,
                            i - QEMU_VNC_PORT_MIN, &used) < 0)
            VIR_DEBUG("virBitmapGetBit failed on bit %d", i - QEMU_VNC_PORT_MIN);

        if (used)
            continue;

2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
        addr.sin_family = AF_INET;
        addr.sin_port = htons(i);
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
        fd = socket(PF_INET, SOCK_STREAM, 0);
        if (fd < 0)
            return -1;

        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*)&reuse, sizeof(reuse)) < 0) {
            close(fd);
            break;
        }

        if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == 0) {
            /* Not in use, lets grab it */
            close(fd);
2980 2981 2982 2983 2984 2985
            /* Add port to bitmap of reserved ports */
            if (virBitmapSetBit(driver->reservedVNCPorts,
                                i - QEMU_VNC_PORT_MIN) < 0) {
                VIR_DEBUG("virBitmapSetBit failed on bit %d",
                          i - QEMU_VNC_PORT_MIN);
            }
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999
            return i;
        }
        close(fd);

        if (errno == EADDRINUSE) {
            /* In use, try next */
            continue;
        }
        /* Some other bad failure, get out.. */
        break;
    }
    return -1;
}

3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037

static int
qemuAssignPCIAddresses(virDomainDefPtr def)
{
    int ret = -1;
    unsigned long long qemuCmdFlags = 0;
    qemuDomainPCIAddressSetPtr addrs = NULL;
    struct stat sb;

    if (stat(def->emulator, &sb) < 0) {
        virReportSystemError(errno,
                             _("Cannot find QEMU binary %s"),
                             def->emulator);
        goto cleanup;
    }

    if (qemudExtractVersionInfo(def->emulator,
                                NULL,
                                &qemuCmdFlags) < 0)
        goto cleanup;

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (!(addrs = qemuDomainPCIAddressSetCreate(def)))
            goto cleanup;

        if (qemuAssignDevicePCISlots(def, addrs) < 0)
            goto cleanup;
    }

    ret = 0;

cleanup:
    qemuDomainPCIAddressSetFree(addrs);

    return ret;
}


3038
static pciDeviceList *
3039
qemuGetPciHostDeviceList(virDomainHostdevDefPtr *hostdevs, int nhostdevs)
3040 3041
{
    pciDeviceList *list;
3042 3043
    int i;

3044
    if (!(list = pciDeviceListNew()))
3045
        return NULL;
3046

3047 3048
    for (i = 0 ; i < nhostdevs ; i++) {
        virDomainHostdevDefPtr hostdev = hostdevs[i];
3049 3050 3051 3052 3053 3054 3055
        pciDevice *dev;

        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;
        if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
            continue;

3056
        dev = pciGetDevice(hostdev->source.subsys.u.pci.domain,
3057 3058 3059
                           hostdev->source.subsys.u.pci.bus,
                           hostdev->source.subsys.u.pci.slot,
                           hostdev->source.subsys.u.pci.function);
3060
        if (!dev) {
3061
            pciDeviceListFree(list);
3062 3063
            return NULL;
        }
3064

3065 3066 3067
        if (pciDeviceListAdd(list, dev) < 0) {
            pciFreeDevice(dev);
            pciDeviceListFree(list);
3068
            return NULL;
3069 3070
        }

3071
        pciDeviceSetManaged(dev, hostdev->managed);
3072 3073
    }

3074 3075 3076 3077
    return list;
}

static int
3078 3079 3080 3081
qemuUpdateActivePciHostdevs(struct qemud_driver *driver,
                            virDomainDefPtr def)
{
    pciDeviceList *pcidevs;
3082
    int i;
3083
    int ret = -1;
3084 3085 3086 3087

    if (!def->nhostdevs)
        return 0;

3088
    if (!(pcidevs = qemuGetPciHostDeviceList(def->hostdevs, def->nhostdevs)))
3089 3090
        return -1;

3091 3092
    for (i = 0; i < pciDeviceListCount(pcidevs); i++) {
        pciDevice *dev = pciDeviceListGet(pcidevs, i);
3093 3094 3095
        pciDeviceListSteal(pcidevs, dev);
        if (pciDeviceListAdd(driver->activePciHostdevs, dev) < 0) {
            pciFreeDevice(dev);
3096
            goto cleanup;
3097 3098 3099
        }
    }

3100 3101 3102
    ret = 0;

cleanup:
3103
    pciDeviceListFree(pcidevs);
3104 3105 3106
    return ret;
}

3107

3108
static int
3109 3110 3111
qemuPrepareHostdevPCIDevices(struct qemud_driver *driver,
                             virDomainHostdevDefPtr *hostdevs,
                             int nhostdevs)
3112 3113 3114
{
    pciDeviceList *pcidevs;
    int i;
3115
    int ret = -1;
3116

3117
    if (!(pcidevs = qemuGetPciHostDeviceList(hostdevs, nhostdevs)))
3118 3119
        return -1;

3120
    /* We have to use 3 loops here. *All* devices must
3121 3122
     * be detached before we reset any of them, because
     * in some cases you have to reset the whole PCI,
3123 3124
     * which impacts all devices on it. Also, all devices
     * must be reset before being marked as active.
3125 3126 3127 3128 3129 3130 3131
     */

    /* XXX validate that non-managed device isn't in use, eg
     * by checking that device is either un-bound, or bound
     * to pci-stub.ko
     */

3132 3133
    for (i = 0; i < pciDeviceListCount(pcidevs); i++) {
        pciDevice *dev = pciDeviceListGet(pcidevs, i);
3134
        if (!pciDeviceIsAssignable(dev, !driver->relaxedACS))
3135 3136
            goto cleanup;

3137
        if (pciDeviceGetManaged(dev) &&
3138
            pciDettachDevice(dev, driver->activePciHostdevs) < 0)
3139 3140
            goto cleanup;
    }
3141 3142 3143

    /* Now that all the PCI hostdevs have be dettached, we can safely
     * reset them */
3144 3145
    for (i = 0; i < pciDeviceListCount(pcidevs); i++) {
        pciDevice *dev = pciDeviceListGet(pcidevs, i);
3146
        if (pciResetDevice(dev, driver->activePciHostdevs, pcidevs) < 0)
3147 3148
            goto cleanup;
    }
3149

3150
    /* Now mark all the devices as active */
3151 3152
    for (i = 0; i < pciDeviceListCount(pcidevs); i++) {
        pciDevice *dev = pciDeviceListGet(pcidevs, i);
3153 3154 3155
        pciDeviceListSteal(pcidevs, dev);
        if (pciDeviceListAdd(driver->activePciHostdevs, dev) < 0) {
            pciFreeDevice(dev);
3156 3157
            goto cleanup;
        }
3158 3159
    }

3160
    ret = 0;
3161

3162
cleanup:
3163
    pciDeviceListFree(pcidevs);
3164
    return ret;
3165 3166
}

3167 3168 3169 3170 3171 3172 3173
static int
qemuPrepareHostPCIDevices(struct qemud_driver *driver,
                          virDomainDefPtr def)
{
    return qemuPrepareHostdevPCIDevices(driver, def->hostdevs, def->nhostdevs);
}

3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184

static int
qemuPrepareHostUSBDevices(struct qemud_driver *driver ATTRIBUTE_UNUSED,
                          virDomainDefPtr def)
{
    int i;
    for (i = 0 ; i < def->nhostdevs ; i++) {
        virDomainHostdevDefPtr hostdev = def->hostdevs[i];

        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;
3185
        if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223
            continue;

        /* Resolve a vendor/product to bus/device */
        if (hostdev->source.subsys.u.usb.vendor) {
            usbDevice *usb
                = usbFindDevice(hostdev->source.subsys.u.usb.vendor,
                                hostdev->source.subsys.u.usb.product);

            if (!usb)
                return -1;

            hostdev->source.subsys.u.usb.bus = usbDeviceGetBus(usb);
            hostdev->source.subsys.u.usb.device = usbDeviceGetDevno(usb);

            usbFreeDevice(usb);
        }
    }

    return 0;
}

static int
qemuPrepareHostDevices(struct qemud_driver *driver,
                       virDomainDefPtr def)
{
    if (!def->nhostdevs)
        return 0;

    if (qemuPrepareHostPCIDevices(driver, def) < 0)
        return -1;

    if (qemuPrepareHostUSBDevices(driver, def) < 0)
        return -1;

    return 0;
}


3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
static int
qemuPrepareChardevDevice(virDomainDefPtr def ATTRIBUTE_UNUSED,
                         virDomainChrDefPtr dev,
                         void *opaque ATTRIBUTE_UNUSED)
{
    int fd;
    if (dev->type != VIR_DOMAIN_CHR_TYPE_FILE)
        return 0;

    if ((fd = open(dev->data.file.path, O_CREAT | O_APPEND, S_IRUSR|S_IWUSR)) < 0) {
        virReportSystemError(errno,
                             _("Unable to pre-create chardev file '%s'"),
                             dev->data.file.path);
        return -1;
    }

    close(fd);

    return 0;
}


3246
static void
3247
qemudReattachPciDevice(pciDevice *dev, struct qemud_driver *driver)
3248 3249 3250
{
    int retries = 100;

3251 3252 3253 3254 3255 3256
    while (pciWaitForDeviceCleanup(dev, "kvm_assigned_device")
           && retries) {
        usleep(100*1000);
        retries--;
    }

3257
    if (pciDeviceGetManaged(dev)) {
3258
        if (pciReAttachDevice(dev, driver->activePciHostdevs) < 0) {
3259 3260
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to re-attach PCI device: %s"),
3261
                      err ? err->message : _("unknown error"));
3262 3263 3264 3265 3266
            virResetError(err);
        }
    }
}

3267
static void
3268 3269 3270
qemuDomainReAttachHostdevDevices(struct qemud_driver *driver,
                              virDomainHostdevDefPtr *hostdevs,
                              int nhostdevs)
3271
{
3272
    pciDeviceList *pcidevs;
3273 3274
    int i;

3275
    if (!(pcidevs = qemuGetPciHostDeviceList(hostdevs, nhostdevs))) {
3276
        virErrorPtr err = virGetLastError();
3277
        VIR_ERROR(_("Failed to allocate pciDeviceList: %s"),
3278
                  err ? err->message : _("unknown error"));
3279 3280
        virResetError(err);
        return;
3281 3282
    }

3283 3284
    /* Again 3 loops; mark all devices as inactive before reset
     * them and reset all the devices before re-attach */
3285

3286 3287
    for (i = 0; i < pciDeviceListCount(pcidevs); i++) {
        pciDevice *dev = pciDeviceListGet(pcidevs, i);
3288
        pciDeviceListDel(driver->activePciHostdevs, dev);
3289
    }
3290

3291 3292
    for (i = 0; i < pciDeviceListCount(pcidevs); i++) {
        pciDevice *dev = pciDeviceListGet(pcidevs, i);
3293
        if (pciResetDevice(dev, driver->activePciHostdevs, pcidevs) < 0) {
3294
            virErrorPtr err = virGetLastError();
3295
            VIR_ERROR(_("Failed to reset PCI device: %s"),
3296
                      err ? err->message : _("unknown error"));
3297 3298
            virResetError(err);
        }
3299
    }
3300

3301 3302
    for (i = 0; i < pciDeviceListCount(pcidevs); i++) {
        pciDevice *dev = pciDeviceListGet(pcidevs, i);
3303
        qemudReattachPciDevice(dev, driver);
3304
    }
3305

3306
    pciDeviceListFree(pcidevs);
3307 3308
}

3309 3310 3311 3312 3313 3314 3315 3316 3317 3318
static void
qemuDomainReAttachHostDevices(struct qemud_driver *driver,
                              virDomainDefPtr def)
{
    if (!def->nhostdevs)
        return;

    qemuDomainReAttachHostdevDevices(driver, def->hostdevs, def->nhostdevs);
}

3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
static const char *const defaultDeviceACL[] = {
    "/dev/null", "/dev/full", "/dev/zero",
    "/dev/random", "/dev/urandom",
    "/dev/ptmx", "/dev/kvm", "/dev/kqemu",
    "/dev/rtc", "/dev/hpet", "/dev/net/tun",
    NULL,
};
#define DEVICE_PTY_MAJOR 136
#define DEVICE_SND_MAJOR 116

3329

3330 3331 3332 3333 3334 3335 3336
static int qemuSetupDiskPathAllow(virDomainDiskDefPtr disk ATTRIBUTE_UNUSED,
                                  const char *path,
                                  size_t depth ATTRIBUTE_UNUSED,
                                  void *opaque)
{
    virCgroupPtr cgroup = opaque;
    int rc;
3337

3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
    VIR_DEBUG("Process path %s for disk", path);
    /* XXX RO vs RW */
    rc = virCgroupAllowDevicePath(cgroup, path);
    if (rc != 0) {
        /* Get this for non-block devices */
        if (rc == -EINVAL) {
            VIR_DEBUG("Ignoring EINVAL for %s", path);
        } else if (rc == -EACCES) { /* Get this for root squash NFS */
            VIR_DEBUG("Ignoring EACCES for %s", path);
        } else {
            virReportSystemError(-rc,
                                 _("Unable to allow access for disk path %s"),
                                 path);
            return -1;
3352
        }
3353
    }
3354 3355
    return 0;
}
3356 3357


3358 3359
static int qemuSetupDiskCgroup(struct qemud_driver *driver,
                               virCgroupPtr cgroup,
3360 3361 3362
                               virDomainDiskDefPtr disk)
{
    return virDomainDiskDefForeachPath(disk,
3363
                                       driver->allowDiskFormatProbing,
3364 3365 3366
                                       true,
                                       qemuSetupDiskPathAllow,
                                       cgroup);
3367 3368 3369
}


3370 3371 3372 3373
static int qemuTeardownDiskPathDeny(virDomainDiskDefPtr disk ATTRIBUTE_UNUSED,
                                    const char *path,
                                    size_t depth ATTRIBUTE_UNUSED,
                                    void *opaque)
3374
{
3375 3376
    virCgroupPtr cgroup = opaque;
    int rc;
3377

3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391
    VIR_DEBUG("Process path %s for disk", path);
    /* XXX RO vs RW */
    rc = virCgroupDenyDevicePath(cgroup, path);
    if (rc != 0) {
        /* Get this for non-block devices */
        if (rc == -EINVAL) {
            VIR_DEBUG("Ignoring EINVAL for %s", path);
        } else if (rc == -EACCES) { /* Get this for root squash NFS */
            VIR_DEBUG("Ignoring EACCES for %s", path);
        } else {
            virReportSystemError(-rc,
                                 _("Unable to allow access for disk path %s"),
                                 path);
            return -1;
3392
        }
3393
    }
3394 3395
    return 0;
}
3396 3397


3398 3399
static int qemuTeardownDiskCgroup(struct qemud_driver *driver,
                                  virCgroupPtr cgroup,
3400 3401 3402
                                  virDomainDiskDefPtr disk)
{
    return virDomainDiskDefForeachPath(disk,
3403
                                       driver->allowDiskFormatProbing,
3404 3405 3406
                                       true,
                                       qemuTeardownDiskPathDeny,
                                       cgroup);
3407 3408 3409
}


3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
static int qemuSetupChardevCgroup(virDomainDefPtr def,
                                  virDomainChrDefPtr dev,
                                  void *opaque)
{
    virCgroupPtr cgroup = opaque;
    int rc;

    if (dev->type != VIR_DOMAIN_CHR_TYPE_DEV)
        return 0;


    VIR_DEBUG("Process path '%s' for disk", dev->data.file.path);
    rc = virCgroupAllowDevicePath(cgroup, dev->data.file.path);
    if (rc != 0) {
        virReportSystemError(-rc,
                             _("Unable to allow device %s for %s"),
                             dev->data.file.path, def->name);
        return -1;
    }

    return 0;
}


3434
static int qemuSetupCgroup(struct qemud_driver *driver,
3435 3436 3437 3438
                           virDomainObjPtr vm)
{
    virCgroupPtr cgroup = NULL;
    int rc;
3439
    unsigned int i;
3440 3441 3442 3443
    const char *const *deviceACL =
        driver->cgroupDeviceACL ?
        (const char *const *)driver->cgroupDeviceACL :
        defaultDeviceACL;
3444 3445 3446 3447 3448 3449

    if (driver->cgroup == NULL)
        return 0; /* Not supported, so claim success */

    rc = virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 1);
    if (rc != 0) {
3450
        virReportSystemError(-rc,
3451 3452 3453 3454 3455
                             _("Unable to create cgroup for %s"),
                             vm->def->name);
        goto cleanup;
    }

3456 3457
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        rc = virCgroupDenyAllDevices(cgroup);
3458
        if (rc != 0) {
3459 3460 3461 3462 3463
            if (rc == -EPERM) {
                VIR_WARN0("Group devices ACL is not accessible, disabling whitelisting");
                goto done;
            }

3464
            virReportSystemError(-rc,
3465
                                 _("Unable to deny all devices for %s"), vm->def->name);
3466 3467 3468
            goto cleanup;
        }

3469
        for (i = 0; i < vm->def->ndisks ; i++) {
3470
            if (qemuSetupDiskCgroup(driver, cgroup, vm->def->disks[i]) < 0)
3471 3472
                goto cleanup;
        }
3473

3474
        rc = virCgroupAllowDeviceMajor(cgroup, 'c', DEVICE_PTY_MAJOR);
3475
        if (rc != 0) {
3476
            virReportSystemError(-rc, "%s",
3477
                                 _("unable to allow /dev/pts/ devices"));
3478 3479 3480
            goto cleanup;
        }

3481 3482 3483
        if (vm->def->nsounds) {
            rc = virCgroupAllowDeviceMajor(cgroup, 'c', DEVICE_SND_MAJOR);
            if (rc != 0) {
3484
                virReportSystemError(-rc, "%s",
3485 3486 3487 3488 3489 3490 3491 3492 3493 3494
                                     _("unable to allow /dev/snd/ devices"));
                goto cleanup;
            }
        }

        for (i = 0; deviceACL[i] != NULL ; i++) {
            rc = virCgroupAllowDevicePath(cgroup,
                                          deviceACL[i]);
            if (rc < 0 &&
                rc != -ENOENT) {
3495
                virReportSystemError(-rc,
3496 3497 3498 3499
                                     _("unable to allow device %s"),
                                     deviceACL[i]);
                goto cleanup;
            }
3500
        }
3501 3502 3503 3504 3505 3506

        if (virDomainChrDefForeach(vm->def,
                                   true,
                                   qemuSetupChardevCgroup,
                                   cgroup) < 0)
            goto cleanup;
3507 3508
    }

3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
    if ((rc = qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY))) {
        if (vm->def->mem.hard_limit != 0) {
            rc = virCgroupSetMemoryHardLimit(cgroup, vm->def->mem.hard_limit);
            if (rc != 0) {
                virReportSystemError(-rc,
                                     _("Unable to set memory hard limit for domain %s"),
                                     vm->def->name);
                goto cleanup;
            }
        }
        if (vm->def->mem.soft_limit != 0) {
            rc = virCgroupSetMemorySoftLimit(cgroup, vm->def->mem.soft_limit);
            if (rc != 0) {
                virReportSystemError(-rc,
                                     _("Unable to set memory soft limit for domain %s"),
                                     vm->def->name);
                goto cleanup;
            }
        }

        if (vm->def->mem.swap_hard_limit != 0) {
            rc = virCgroupSetSwapHardLimit(cgroup, vm->def->mem.swap_hard_limit);
            if (rc != 0) {
                virReportSystemError(-rc,
                                     _("Unable to set swap hard limit for domain %s"),
                                     vm->def->name);
                goto cleanup;
            }
        }
    } else {
        VIR_WARN("Memory cgroup is disabled in qemu configuration file: %s",
                 vm->def->name);
    }

3543
done:
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555
    virCgroupFree(&cgroup);
    return 0;

cleanup:
    if (cgroup) {
        virCgroupRemove(cgroup);
        virCgroupFree(&cgroup);
    }
    return -1;
}


3556
static int qemuRemoveCgroup(struct qemud_driver *driver,
3557 3558
                            virDomainObjPtr vm,
                            int quiet)
3559 3560 3561 3562 3563 3564 3565 3566 3567
{
    virCgroupPtr cgroup;
    int rc;

    if (driver->cgroup == NULL)
        return 0; /* Not supported, so claim success */

    rc = virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0);
    if (rc != 0) {
3568
        if (!quiet)
3569 3570 3571
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Unable to find cgroup for %s\n"),
                            vm->def->name);
3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591
        return rc;
    }

    rc = virCgroupRemove(cgroup);
    virCgroupFree(&cgroup);
    return rc;
}

static int qemuAddToCgroup(struct qemud_driver *driver,
                           virDomainDefPtr def)
{
    virCgroupPtr cgroup = NULL;
    int ret = -1;
    int rc;

    if (driver->cgroup == NULL)
        return 0; /* Not supported, so claim success */

    rc = virCgroupForDomain(driver->cgroup, def->name, &cgroup, 0);
    if (rc != 0) {
3592
        virReportSystemError(-rc,
3593 3594 3595 3596 3597 3598 3599
                             _("unable to find cgroup for domain %s"),
                             def->name);
        goto cleanup;
    }

    rc = virCgroupAddTask(cgroup, getpid());
    if (rc != 0) {
3600
        virReportSystemError(-rc,
3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617
                             _("unable to add domain %s task %d to cgroup"),
                             def->name, getpid());
        goto cleanup;
    }

    ret = 0;

cleanup:
    virCgroupFree(&cgroup);
    return ret;
}


struct qemudHookData {
    virConnectPtr conn;
    virDomainObjPtr vm;
    struct qemud_driver *driver;
3618 3619 3620
};

static int qemudSecurityHook(void *data) {
3621 3622
    struct qemudHookData *h = data;

3623 3624 3625
    /* This must take place before exec(), so that all QEMU
     * memory allocation is on the correct NUMA node
     */
3626
    if (qemuAddToCgroup(h->driver, h->vm->def) < 0)
3627 3628
        return -1;

3629 3630 3631
    /* This must be done after cgroup placement to avoid resetting CPU
     * affinity */
    if (qemudInitCpuAffinity(h->vm) < 0)
3632
        return -1;
3633

3634 3635
    if (h->driver->securityDriver &&
        h->driver->securityDriver->domainSetSecurityProcessLabel &&
3636
        h->driver->securityDriver->domainSetSecurityProcessLabel(h->driver->securityDriver, h->vm) < 0)
3637 3638 3639
        return -1;

    return 0;
3640 3641
}

3642
static int
3643
qemuPrepareMonitorChr(struct qemud_driver *driver,
3644
                      virDomainChrDefPtr monConfig,
3645 3646
                      const char *vm)
{
3647
    monConfig->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_MONITOR;
3648

3649 3650
    monConfig->type = VIR_DOMAIN_CHR_TYPE_UNIX;
    monConfig->data.nix.listen = 1;
3651

D
Daniel P. Berrange 已提交
3652
    if (!(monConfig->info.alias = strdup("monitor"))) {
3653
        virReportOOMError();
D
Daniel P. Berrange 已提交
3654 3655 3656
        return -1;
    }

3657
    if (virAsprintf(&monConfig->data.nix.path, "%s/%s.monitor",
3658
                    driver->libDir, vm) < 0) {
3659
        virReportOOMError();
3660 3661 3662 3663 3664 3665
        return -1;
    }

    return 0;
}

C
Chris Lalancette 已提交
3666 3667 3668 3669 3670
static int qemuDomainSnapshotSetActive(virDomainObjPtr vm,
                                       char *snapshotDir);
static int qemuDomainSnapshotSetInactive(virDomainObjPtr vm,
                                         char *snapshotDir);

3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
static void qemuDomainDiskAudit(virDomainObjPtr vm,
                                virDomainDiskDefPtr oldDef,
                                virDomainDiskDefPtr newDef,
                                const char *reason,
                                bool success)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    char *vmname;
    char *oldsrc = NULL;
    char *newsrc = NULL;

    virUUIDFormat(vm->def->uuid, uuidstr);
    if (!(vmname = virAuditEncode("vm", vm->def->name))) {
        VIR_WARN0("OOM while encoding audit message");
        return;
    }

    if (!(oldsrc = virAuditEncode("old-disk",
                                  oldDef && oldDef->src ?
                                  oldDef->src : "?"))) {
        VIR_WARN0("OOM while encoding audit message");
        goto cleanup;
    }
    if (!(newsrc = virAuditEncode("new-disk",
                                  newDef && newDef->src ?
                                  newDef->src : "?"))) {
        VIR_WARN0("OOM while encoding audit message");
        goto cleanup;
    }

    VIR_AUDIT(VIR_AUDIT_RECORD_RESOURCE, success,
              "resrc=disk reason=%s %s uuid=%s %s %s",
              reason, vmname, uuidstr,
              oldsrc, newsrc);

cleanup:
    VIR_FREE(vmname);
    VIR_FREE(oldsrc);
    VIR_FREE(newsrc);
}


static void qemuDomainNetAudit(virDomainObjPtr vm,
                               virDomainNetDefPtr oldDef,
                               virDomainNetDefPtr newDef,
                               const char *reason,
                               bool success)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    char newMacstr[VIR_MAC_STRING_BUFLEN];
    char oldMacstr[VIR_MAC_STRING_BUFLEN];
    char *vmname;

    virUUIDFormat(vm->def->uuid, uuidstr);
    if (oldDef)
        virFormatMacAddr(oldDef->mac, oldMacstr);
    if (newDef)
        virFormatMacAddr(newDef->mac, newMacstr);
    if (!(vmname = virAuditEncode("vm", vm->def->name))) {
        VIR_WARN0("OOM while encoding audit message");
        return;
    }

    VIR_AUDIT(VIR_AUDIT_RECORD_RESOURCE, success,
              "resrc=net reason=%s %s uuid=%s old-net='%s' new-net='%s'",
              reason, vmname, uuidstr,
              oldDef ? oldMacstr : "?",
              newDef ? newMacstr : "?");

    VIR_FREE(vmname);
}


3744 3745 3746 3747 3748 3749 3750 3751 3752
static void qemuDomainLifecycleAudit(virDomainObjPtr vm,
                                     const char *op,
                                     const char *reason,
                                     bool success)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    char *vmname;

    virUUIDFormat(vm->def->uuid, uuidstr);
3753

3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766
    if (!(vmname = virAuditEncode("vm", vm->def->name))) {
        VIR_WARN0("OOM while encoding audit message");
        return;
    }

    VIR_AUDIT(VIR_AUDIT_RECORD_MACHINE_CONTROL, success,
              "op=%s reason=%s %s uuid=%s", op, reason, vmname, uuidstr);

    VIR_FREE(vmname);
}

static void qemuDomainStartAudit(virDomainObjPtr vm, const char *reason, bool success)
{
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779
    int i;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
        if (disk->src) /* Skips CDROM without media initially inserted */
            qemuDomainDiskAudit(vm, NULL, disk, "start", true);
    }

    for (i = 0 ; i < vm->def->nnets ; i++) {
        virDomainNetDefPtr net = vm->def->nets[i];
        qemuDomainNetAudit(vm, NULL, net, "start", true);
    }

3780 3781 3782 3783 3784 3785 3786 3787
    qemuDomainLifecycleAudit(vm, "start", reason, success);
}

static void qemuDomainStopAudit(virDomainObjPtr vm, const char *reason)
{
    qemuDomainLifecycleAudit(vm, "stop", reason, true);
}

3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808
static void qemuDomainSecurityLabelAudit(virDomainObjPtr vm, bool success)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    char *vmname;

    virUUIDFormat(vm->def->uuid, uuidstr);
    if (!(vmname = virAuditEncode("vm", vm->def->name))) {
        VIR_WARN0("OOM while encoding audit message");
        return;
    }

    VIR_AUDIT(VIR_AUDIT_RECORD_MACHINE_ID, success,
              "%s uuid=%s vm-ctx=%s img-ctx=%s",
              vmname, uuidstr,
              VIR_AUDIT_STR(vm->def->seclabel.label),
              VIR_AUDIT_STR(vm->def->seclabel.imagelabel));

    VIR_FREE(vmname);
}


3809 3810
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
3811
                              virDomainObjPtr vm,
3812
                              const char *migrateFrom,
3813
                              bool start_paused,
3814 3815
                              int stdin_fd,
                              const char *stdin_path) {
3816
    const char **argv = NULL, **tmp;
3817
    const char **progenv = NULL;
3818
    int i, ret, runflags;
3819
    struct stat sb;
3820 3821
    int *vmfds = NULL;
    int nvmfds = 0;
3822
    unsigned long long qemuCmdFlags;
3823
    fd_set keepfd;
3824
    const char *emulator;
G
Guido Günther 已提交
3825
    pid_t child;
3826
    int pos = -1;
3827
    char ebuf[1024];
3828
    char *pidfile = NULL;
3829
    int logfile = -1;
3830
    qemuDomainObjPrivatePtr priv = vm->privateData;
3831

3832
    struct qemudHookData hookData;
3833 3834 3835 3836
    hookData.conn = conn;
    hookData.vm = vm;
    hookData.driver = driver;

3837
    FD_ZERO(&keepfd);
3838

3839 3840
    DEBUG0("Beginning VM startup process");

D
Daniel P. Berrange 已提交
3841
    if (virDomainObjIsActive(vm)) {
3842 3843
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("VM is already active"));
3844 3845 3846
        return -1;
    }

3847 3848 3849 3850 3851
    /* Must be run before security labelling */
    DEBUG0("Preparing host devices");
    if (qemuPrepareHostDevices(driver, vm->def) < 0)
        goto cleanup;

3852 3853 3854 3855 3856 3857 3858
    DEBUG0("Preparing chr devices");
    if (virDomainChrDefForeach(vm->def,
                               true,
                               qemuPrepareChardevDevice,
                               NULL) < 0)
        goto cleanup;

3859 3860
    /* If you are using a SecurityDriver with dynamic labelling,
       then generate a security label for isolation */
3861
    DEBUG0("Generating domain security label (if required)");
3862
    if (driver->securityDriver &&
3863 3864 3865 3866 3867 3868 3869
        driver->securityDriver->domainGenSecurityLabel) {
        ret = driver->securityDriver->domainGenSecurityLabel(driver->securityDriver,
                                                             vm);
        qemuDomainSecurityLabelAudit(vm, ret >= 0);
        if (ret < 0)
            goto cleanup;
    }
3870

3871
    DEBUG0("Generating setting domain security labels (if required)");
3872 3873
    if (driver->securityDriver &&
        driver->securityDriver->domainSetSecurityAllLabel &&
3874 3875
        driver->securityDriver->domainSetSecurityAllLabel(driver->securityDriver,
                                                          vm, stdin_path) < 0) {
3876
        if (stdin_path && virStorageFileIsSharedFS(stdin_path) != 1)
3877 3878
            goto cleanup;
    }
3879

3880 3881 3882
    /* Ensure no historical cgroup for this VM is lying around bogus
     * settings */
    DEBUG0("Ensuring no historical cgroup is lying around");
3883
    qemuRemoveCgroup(driver, vm, 1);
3884

3885 3886 3887
    if ((vm->def->ngraphics == 1) &&
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics[0]->data.vnc.autoport) {
3888
        DEBUG0("Determining VNC port");
3889
        int port = qemudNextFreeVNCPort(driver);
3890
        if (port < 0) {
3891 3892
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Unable to find an unused VNC port"));
3893
            goto cleanup;
3894
        }
3895
        vm->def->graphics[0]->data.vnc.port = port;
3896
    }
3897

L
Laine Stump 已提交
3898
    if (virFileMakePath(driver->logDir) != 0) {
3899
        virReportSystemError(errno,
3900 3901
                             _("cannot create log directory %s"),
                             driver->logDir);
3902
        goto cleanup;
3903 3904
    }

3905
    DEBUG0("Creating domain log file");
3906
    if ((logfile = qemudLogFD(driver, vm->def->name)) < 0)
3907
        goto cleanup;
3908

3909 3910
    emulator = vm->def->emulator;

3911 3912 3913 3914
    /* Make sure the binary we are about to try exec'ing exists.
     * Technically we could catch the exec() failure, but that's
     * in a sub-process so its hard to feed back a useful error
     */
3915
    if (stat(emulator, &sb) < 0) {
3916
        virReportSystemError(errno,
3917 3918
                             _("Cannot find QEMU binary %s"),
                             emulator);
3919
        goto cleanup;
3920 3921
    }

3922
    DEBUG0("Determing emulator version");
3923
    if (qemudExtractVersionInfo(emulator,
3924
                                NULL,
3925
                                &qemuCmdFlags) < 0)
3926
        goto cleanup;
3927

3928
    DEBUG0("Setting up domain cgroup (if required)");
3929
    if (qemuSetupCgroup(driver, vm) < 0)
3930 3931
        goto cleanup;

3932
    if (VIR_ALLOC(priv->monConfig) < 0) {
3933
        virReportOOMError();
3934 3935 3936
        goto cleanup;
    }

3937
    DEBUG0("Preparing monitor state");
3938
    if (qemuPrepareMonitorChr(driver, priv->monConfig, vm->def->name) < 0)
3939
        goto cleanup;
3940

D
Daniel P. Berrange 已提交
3941 3942 3943
#if HAVE_YAJL
    if (qemuCmdFlags & QEMUD_CMD_FLAG_MONITOR_JSON)
        priv->monJSON = 1;
3944
    else
D
Daniel P. Berrange 已提交
3945
#endif
3946
        priv->monJSON = 0;
D
Daniel P. Berrange 已提交
3947

3948 3949
    priv->monitor_warned = 0;

D
Daniel P. Berrange 已提交
3950
    if ((ret = virFileDeletePid(driver->stateDir, vm->def->name)) != 0) {
3951
        virReportSystemError(ret,
D
Daniel P. Berrange 已提交
3952 3953 3954 3955 3956
                             _("Cannot remove stale PID file for %s"),
                             vm->def->name);
        goto cleanup;
    }

3957
    if (!(pidfile = virFilePid(driver->stateDir, vm->def->name))) {
3958
        virReportSystemError(errno,
3959 3960 3961
                             "%s", _("Failed to build pidfile path."));
        goto cleanup;
    }
D
Daniel P. Berrange 已提交
3962

3963
    /*
M
Matthew Booth 已提交
3964
     * Normally PCI addresses are assigned in the virDomainCreate
3965 3966 3967 3968 3969
     * or virDomainDefine methods. We might still need to assign
     * some here to cope with the question of upgrades. Regardless
     * we also need to populate the PCi address set cache for later
     * use in hotplug
     */
3970
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
3971
        DEBUG0("Assigning domain PCI addresses");
3972
        /* Populate cache with current addresses */
3973 3974 3975 3976 3977 3978 3979
        if (priv->pciaddrs) {
            qemuDomainPCIAddressSetFree(priv->pciaddrs);
            priv->pciaddrs = NULL;
        }
        if (!(priv->pciaddrs = qemuDomainPCIAddressSetCreate(vm->def)))
            goto cleanup;

3980 3981

        /* Assign any remaining addresses */
3982 3983
        if (qemuAssignDevicePCISlots(vm->def, priv->pciaddrs) < 0)
            goto cleanup;
3984 3985 3986 3987

        priv->persistentAddrs = 1;
    } else {
        priv->persistentAddrs = 0;
3988 3989
    }

3990
    DEBUG0("Building emulator command line");
3991
    vm->def->id = driver->nextvmid++;
3992
    if (qemudBuildCommandLine(conn, driver, vm->def, priv->monConfig,
D
Daniel P. Berrange 已提交
3993
                              priv->monJSON, qemuCmdFlags, &argv, &progenv,
3994
                              &vmfds, &nvmfds, migrateFrom,
C
Chris Lalancette 已提交
3995 3996 3997 3998
                              vm->current_snapshot) < 0)
        goto cleanup;

    if (qemuDomainSnapshotSetInactive(vm, driver->snapshotDir) < 0)
3999
        goto cleanup;
4000

4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
    /* now that we know it is about to start call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_QEMU)) {
        char *xml = virDomainDefFormat(vm->def, 0);
        int hookret;

        hookret = virHookCall(VIR_HOOK_DRIVER_QEMU, vm->def->name,
                    VIR_HOOK_QEMU_OP_START, VIR_HOOK_SUBOP_BEGIN, NULL, xml);
        VIR_FREE(xml);

        /*
         * If the script raised an error abort the launch
         */
        if (hookret < 0)
            goto cleanup;
    }

4017 4018
    tmp = progenv;
    while (*tmp) {
4019
        if (safewrite(logfile, *tmp, strlen(*tmp)) < 0)
4020
            VIR_WARN("Unable to write envv to logfile: %s",
4021
                     virStrerror(errno, ebuf, sizeof ebuf));
4022
        if (safewrite(logfile, " ", 1) < 0)
4023
            VIR_WARN("Unable to write envv to logfile: %s",
4024
                     virStrerror(errno, ebuf, sizeof ebuf));
4025 4026
        tmp++;
    }
4027 4028
    tmp = argv;
    while (*tmp) {
4029
        if (safewrite(logfile, *tmp, strlen(*tmp)) < 0)
4030
            VIR_WARN("Unable to write argv to logfile: %s",
4031
                     virStrerror(errno, ebuf, sizeof ebuf));
4032
        if (safewrite(logfile, " ", 1) < 0)
4033
            VIR_WARN("Unable to write argv to logfile: %s",
4034
                     virStrerror(errno, ebuf, sizeof ebuf));
4035 4036
        tmp++;
    }
4037
    if (safewrite(logfile, "\n", 1) < 0)
4038
        VIR_WARN("Unable to write argv to logfile: %s",
4039
                 virStrerror(errno, ebuf, sizeof ebuf));
4040

4041
    if ((pos = lseek(logfile, 0, SEEK_END)) < 0)
4042
        VIR_WARN("Unable to seek to end of logfile: %s",
4043
                 virStrerror(errno, ebuf, sizeof ebuf));
4044

4045 4046
    for (i = 0 ; i < nvmfds ; i++)
        FD_SET(vmfds[i], &keepfd);
4047

4048 4049 4050 4051 4052 4053 4054
    VIR_DEBUG("Clear emulator capabilities: %d",
              driver->clearEmulatorCapabilities);
    runflags = VIR_EXEC_NONBLOCK;
    if (driver->clearEmulatorCapabilities) {
        runflags |= VIR_EXEC_CLEAR_CAPS;
    }

4055
    ret = virExecDaemonize(argv, progenv, &keepfd, &child,
4056
                           stdin_fd, &logfile, &logfile,
4057
                           runflags,
4058 4059 4060
                           qemudSecurityHook, &hookData,
                           pidfile);
    VIR_FREE(pidfile);
G
Guido Günther 已提交
4061 4062 4063

    /* wait for qemu process to to show up */
    if (ret == 0) {
4064
        if (virFileReadPid(driver->stateDir, vm->def->name, &vm->pid)) {
4065 4066
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Domain %s didn't show up\n"), vm->def->name);
4067
            ret = -1;
G
Guido Günther 已提交
4068
        }
4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079
    } else if (ret == -2) {
        /* The virExec process that launches the daemon failed. Pending on
         * when it failed (we can't determine for sure), there may be
         * extra info in the domain log (if the hook failed for example).
         *
         * Pretend like things succeeded, and let 'WaitForMonitor' report
         * the log contents for us.
         */
        vm->pid = child;
        ret = 0;
    }
4080

4081 4082 4083
    if (migrateFrom)
        start_paused = true;
    vm->state = start_paused ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
4084

4085
    for (i = 0 ; argv[i] ; i++)
4086 4087
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
4088

4089 4090 4091 4092
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

4093
    if (ret == -1) /* The VM failed to start; tear filters before taps */
4094
        virDomainConfVMNWFilterTeardown(vm);
4095

4096 4097 4098
    if (vmfds) {
        for (i = 0 ; i < nvmfds ; i++) {
            close(vmfds[i]);
4099
        }
4100
        VIR_FREE(vmfds);
4101 4102
    }

4103
    if (ret == -1) /* The VM failed to start */
4104 4105
        goto cleanup;

4106
    DEBUG0("Waiting for monitor to show up");
4107
    if (qemudWaitForMonitor(driver, vm, pos) < 0)
4108
        goto cleanup;
4109

4110
    DEBUG0("Detecting VCPU PIDs");
4111
    if (qemuDetectVcpuPIDs(driver, vm) < 0)
4112
        goto cleanup;
4113

4114
    DEBUG0("Setting any required VM passwords");
4115
    if (qemuInitPasswords(conn, driver, vm, qemuCmdFlags) < 0)
4116
        goto cleanup;
4117

D
Daniel P. Berrange 已提交
4118 4119 4120
    /* If we have -device, then addresses are assigned explicitly.
     * If not, then we have to detect dynamic ones here */
    if (!(qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
4121
        DEBUG0("Determining domain device PCI addresses");
D
Daniel P. Berrange 已提交
4122
        if (qemuInitPCIAddresses(driver, vm) < 0)
4123
            goto cleanup;
D
Daniel P. Berrange 已提交
4124
    }
4125

4126
    DEBUG0("Setting initial memory amount");
4127
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
4128
    if (qemuMonitorSetBalloon(priv->mon, vm->def->mem.cur_balloon) < 0) {
4129
        qemuDomainObjExitMonitorWithDriver(driver, vm);
4130
        goto cleanup;
4131
    }
4132

4133
    if (!start_paused) {
4134
        DEBUG0("Starting domain CPUs");
4135 4136 4137
        /* Allow the CPUS to start executing */
        if (qemuMonitorStartCPUs(priv->mon, conn) < 0) {
            if (virGetLastError() == NULL)
4138 4139
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("resume operation failed"));
4140
            qemuDomainObjExitMonitorWithDriver(driver, vm);
4141
            goto cleanup;
4142 4143
        }
    }
4144
    qemuDomainObjExitMonitorWithDriver(driver, vm);
4145

4146

4147
    DEBUG0("Writing domain status to disk");
4148
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
4149
        goto cleanup;
4150

4151 4152 4153
    if (logfile != -1)
        close(logfile);

4154
    return 0;
4155 4156

cleanup:
4157 4158 4159
    /* We jump here if we failed to start the VM for any reason, or
     * if we failed to initialize the now running VM. kill it off and
     * pretend we never started it */
4160
    qemudShutdownVMDaemon(driver, vm, 0);
4161 4162 4163 4164 4165

    if (logfile != -1)
        close(logfile);

    return -1;
4166 4167 4168
}


4169
static void qemudShutdownVMDaemon(struct qemud_driver *driver,
4170 4171
                                  virDomainObjPtr vm,
                                  int migrated) {
D
Daniel P. Berrange 已提交
4172
    int ret;
4173
    int retries = 0;
4174
    qemuDomainObjPrivatePtr priv = vm->privateData;
4175
    virErrorPtr orig_err;
4176 4177
    virDomainDefPtr def;
    int i;
D
Daniel P. Berrange 已提交
4178

4179 4180
    VIR_DEBUG("Shutting down VM '%s' pid=%d migrated=%d",
              vm->def->name, vm->pid, migrated);
4181

4182 4183 4184 4185
    /* This method is routinely used in clean up paths. Disable error
     * reporting so we don't squash a legit error. */
    orig_err = virSaveLastError();

4186
    virDomainConfVMNWFilterTeardown(vm);
S
Stefan Berger 已提交
4187

4188
    if (driver->macFilter) {
4189
        def = vm->def;
4190 4191 4192 4193
        for (i = 0 ; i < def->nnets ; i++) {
            virDomainNetDefPtr net = def->nets[i];
            if (net->ifname == NULL)
                continue;
4194
            if ((errno = networkDisallowMacOnPort(driver, net->ifname,
4195
                                                  net->mac))) {
4196
                virReportSystemError(errno,
4197 4198 4199 4200 4201 4202
             _("failed to remove ebtables rule to allow MAC address on  '%s'"),
                                     net->ifname);
            }
        }
    }

4203
    /* This will safely handle a non-running guest with pid=0 or pid=-1*/
G
Guido Günther 已提交
4204 4205
    if (virKillProcess(vm->pid, 0) == 0 &&
        virKillProcess(vm->pid, SIGTERM) < 0)
4206
        virReportSystemError(errno,
4207 4208
                             _("Failed to send SIGTERM to %s (%d)"),
                             vm->def->name, vm->pid);
4209

4210 4211
    if (priv->mon)
        qemuMonitorClose(priv->mon);
4212

4213 4214 4215 4216 4217
    if (priv->monConfig) {
        if (priv->monConfig->type == VIR_DOMAIN_CHR_TYPE_UNIX)
            unlink(priv->monConfig->data.nix.path);
        virDomainChrDefFree(priv->monConfig);
        priv->monConfig = NULL;
4218 4219
    }

G
Guido Günther 已提交
4220 4221
    /* shut it off for sure */
    virKillProcess(vm->pid, SIGKILL);
4222

4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
    /* now that we know it's stopped call the hook if present */
    if (virHookPresent(VIR_HOOK_DRIVER_QEMU)) {
        char *xml = virDomainDefFormat(vm->def, 0);

        /* we can't stop the operation even if the script raised an error */
        virHookCall(VIR_HOOK_DRIVER_QEMU, vm->def->name,
                    VIR_HOOK_QEMU_OP_STOPPED, VIR_HOOK_SUBOP_END, NULL, xml);
        VIR_FREE(xml);
    }

4233
    /* Reset Security Labels */
4234
    if (driver->securityDriver &&
4235
        driver->securityDriver->domainRestoreSecurityAllLabel)
4236 4237
        driver->securityDriver->domainRestoreSecurityAllLabel(driver->securityDriver,
                                                              vm, migrated);
4238 4239
    if (driver->securityDriver &&
        driver->securityDriver->domainReleaseSecurityLabel)
4240 4241
        driver->securityDriver->domainReleaseSecurityLabel(driver->securityDriver,
                                                           vm);
4242

4243 4244 4245 4246 4247 4248 4249
    /* Clear out dynamically assigned labels */
    if (vm->def->seclabel.type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        VIR_FREE(vm->def->seclabel.model);
        VIR_FREE(vm->def->seclabel.label);
        VIR_FREE(vm->def->seclabel.imagelabel);
    }

D
Daniel P. Berrange 已提交
4250
    virDomainDefClearDeviceAliases(vm->def);
4251 4252 4253 4254 4255
    if (!priv->persistentAddrs) {
        virDomainDefClearPCIAddresses(vm->def);
        qemuDomainPCIAddressSetFree(priv->pciaddrs);
        priv->pciaddrs = NULL;
    }
4256

4257
    qemuDomainReAttachHostDevices(driver, vm->def);
4258

S
Stefan Berger 已提交
4259 4260 4261 4262
#if WITH_MACVTAP
    def = vm->def;
    for (i = 0; i < def->nnets; i++) {
        virDomainNetDefPtr net = def->nets[i];
4263
        if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
4264
            delMacvtap(net->ifname, net->mac, net->data.direct.linkdev,
4265
                       &net->data.direct.virtPortProfile);
4266 4267
            VIR_FREE(net->ifname);
        }
S
Stefan Berger 已提交
4268 4269 4270
    }
#endif

4271
retry:
4272
    if ((ret = qemuRemoveCgroup(driver, vm, 0)) < 0) {
4273 4274 4275 4276 4277 4278 4279 4280
        if (ret == -EBUSY && (retries++ < 5)) {
            usleep(200*1000);
            goto retry;
        }
        VIR_WARN("Failed to remove cgroup for %s",
                 vm->def->name);
    }

4281
    qemudRemoveDomainStatus(driver, vm);
D
Daniel P. Berrange 已提交
4282

4283 4284 4285 4286 4287 4288
    /* Remove VNC port from port reservation bitmap, but only if it was
       reserved by the driver (autoport=yes)
    */
    if ((vm->def->ngraphics == 1) &&
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics[0]->data.vnc.autoport &&
4289
        vm->def->graphics[0]->data.vnc.port >= QEMU_VNC_PORT_MIN) {
4290 4291 4292 4293 4294 4295 4296 4297
        if (virBitmapClearBit(driver->reservedVNCPorts,
                              vm->def->graphics[0]->data.vnc.port - \
                              QEMU_VNC_PORT_MIN) < 0) {
            VIR_DEBUG("virBitmapClearBit failed on bit %d",
                      vm->def->graphics[0]->data.vnc.port - QEMU_VNC_PORT_MIN);
       }
    }

4298
    vm->pid = -1;
4299
    vm->def->id = -1;
4300
    vm->state = VIR_DOMAIN_SHUTOFF;
4301 4302
    VIR_FREE(priv->vcpupids);
    priv->nvcpupids = 0;
4303 4304

    if (vm->newDef) {
4305
        virDomainDefFree(vm->def);
4306
        vm->def = vm->newDef;
4307
        vm->def->id = -1;
4308 4309
        vm->newDef = NULL;
    }
4310 4311 4312 4313 4314

    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
4315 4316 4317
}


4318
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
4319
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
4320
                                  int flags ATTRIBUTE_UNUSED) {
4321
    if (conn->uri == NULL) {
4322 4323 4324
        if (qemu_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

4325
        conn->uri = xmlParseURI(qemu_driver->privileged ?
4326 4327
                                "qemu:///system" :
                                "qemu:///session");
4328
        if (!conn->uri) {
4329
            virReportOOMError();
4330 4331
            return VIR_DRV_OPEN_ERROR;
        }
4332 4333 4334 4335 4336 4337 4338 4339 4340 4341
    } else {
        /* If URI isn't 'qemu' its definitely not for us */
        if (conn->uri->scheme == NULL ||
            STRNEQ(conn->uri->scheme, "qemu"))
            return VIR_DRV_OPEN_DECLINED;

        /* Allow remote driver to deal with URIs with hostname server */
        if (conn->uri->server != NULL)
            return VIR_DRV_OPEN_DECLINED;

4342
        if (qemu_driver == NULL) {
4343 4344
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("qemu state driver is not active"));
4345 4346 4347
            return VIR_DRV_OPEN_ERROR;
        }

4348
        if (conn->uri->path == NULL) {
4349 4350 4351 4352 4353
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("no QEMU URI path given, try %s"),
                            qemu_driver->privileged
                            ? "qemu:///system"
                            : "qemu:///session");
4354 4355 4356
                return VIR_DRV_OPEN_ERROR;
        }

4357
        if (qemu_driver->privileged) {
4358 4359
            if (STRNEQ (conn->uri->path, "/system") &&
                STRNEQ (conn->uri->path, "/session")) {
4360 4361 4362
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///system"),
                                conn->uri->path);
4363 4364 4365 4366
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
4367 4368 4369
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("unexpected QEMU URI path '%s', try qemu:///session"),
                                conn->uri->path);
4370 4371 4372
                return VIR_DRV_OPEN_ERROR;
            }
        }
4373 4374 4375 4376 4377 4378 4379
    }
    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

static int qemudClose(virConnectPtr conn) {
4380
    struct qemud_driver *driver = conn->privateData;
4381 4382

    /* Get rid of callbacks registered for this conn */
4383
    qemuDriverLock(driver);
4384
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
4385
    qemuDriverUnlock(driver);
4386 4387 4388 4389 4390 4391

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
4392 4393 4394 4395 4396
/* Which features are supported by this driver? */
static int
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
{
    switch (feature) {
4397 4398 4399 4400 4401
    case VIR_DRV_FEATURE_MIGRATION_V2:
    case VIR_DRV_FEATURE_MIGRATION_P2P:
        return 1;
    default:
        return 0;
D
Daniel Veillard 已提交
4402 4403 4404
    }
}

4405
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
4406
    return "QEMU";
4407 4408
}

4409

4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422
static int qemuIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Trivially secure, since always inside the daemon */
    return 1;
}

static int qemuIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Not encrypted, but remote driver takes care of that */
    return 0;
}


4423 4424 4425 4426
static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
4427

4428 4429
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
4430
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
4431
        return -1;
4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442
    }

    r = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_NR_VCPUS);
    if (r > 0)
        maxvcpus = r;

    close(fd);
    return maxvcpus;
}


4443
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
4444 4445 4446
    if (!type)
        return 16;

4447
    if (STRCASEEQ(type, "qemu"))
4448 4449
        return 16;

4450
    if (STRCASEEQ(type, "kvm"))
4451
        return kvmGetMaxVCPUs();
4452

4453
    if (STRCASEEQ(type, "kqemu"))
4454
        return 1;
4455

4456 4457
    qemuReportError(VIR_ERR_INVALID_ARG,
                    _("unknown type '%s'"), type);
4458 4459 4460
    return -1;
}

4461

4462
static char *qemudGetCapabilities(virConnectPtr conn) {
4463
    struct qemud_driver *driver = conn->privateData;
4464
    virCapsPtr caps = NULL;
4465
    char *xml = NULL;
4466

4467
    qemuDriverLock(driver);
4468

4469
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
4470
                                       qemu_driver)) == NULL) {
4471 4472 4473
        virCapabilitiesFree(caps);
        goto cleanup;
    }
4474

4475
    virCapabilitiesFree(qemu_driver->caps);
4476 4477 4478
    qemu_driver->caps = caps;

    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
4479
        virReportOOMError();
4480 4481

cleanup:
4482
    qemuDriverUnlock(driver);
4483

4484
    return xml;
4485 4486 4487
}


4488
static int qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid, int tid) {
D
Daniel P. Berrange 已提交
4489 4490
    char proc[PATH_MAX];
    FILE *pidinfo;
4491
    unsigned long long usertime, systime;
4492 4493
    int cpu;
    int ret;
D
Daniel P. Berrange 已提交
4494

4495 4496 4497 4498 4499 4500
    if (tid)
        ret = snprintf(proc, sizeof(proc), "/proc/%d/task/%d/stat", pid, tid);
    else
        ret = snprintf(proc, sizeof(proc), "/proc/%d/stat", pid);
    if (ret >= (int)sizeof(proc)) {
        errno = E2BIG;
D
Daniel P. Berrange 已提交
4501 4502 4503 4504 4505
        return -1;
    }

    if (!(pidinfo = fopen(proc, "r"))) {
        /* VM probably shut down, so fake 0 */
4506 4507 4508 4509
        if (cpuTime)
            *cpuTime = 0;
        if (lastCpu)
            *lastCpu = 0;
D
Daniel P. Berrange 已提交
4510 4511 4512
        return 0;
    }

4513 4514 4515 4516 4517 4518 4519 4520 4521 4522
    /* See 'man proc' for information about what all these fields are. We're
     * only interested in a very few of them */
    if (fscanf(pidinfo,
               /* pid -> stime */
               "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu"
               /* cutime -> endcode */
               "%*d %*d %*d %*d %*d %*u %*u %*d %*u %*u %*u %*u"
               /* startstack -> processor */
               "%*u %*u %*u %*u %*u %*u %*u %*u %*u %*u %*d %d",
               &usertime, &systime, &cpu) != 3) {
4523
        fclose(pidinfo);
4524 4525
        VIR_WARN0("cannot parse process status data");
        errno = -EINVAL;
D
Daniel P. Berrange 已提交
4526 4527 4528 4529 4530 4531 4532 4533
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
4534 4535 4536 4537 4538
    if (cpuTime)
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
    if (lastCpu)
        *lastCpu = cpu;

D
Daniel P. Berrange 已提交
4539

4540 4541
    VIR_DEBUG("Got status for %d/%d user=%llu sys=%llu cpu=%d",
              pid, tid, usertime, systime, cpu);
D
Daniel P. Berrange 已提交
4542 4543 4544 4545 4546 4547 4548

    fclose(pidinfo);

    return 0;
}


4549
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
4550
                                          int id) {
4551 4552 4553 4554
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

4555
    qemuDriverLock(driver);
4556
    vm  = virDomainFindByID(&driver->domains, id);
4557
    qemuDriverUnlock(driver);
4558 4559

    if (!vm) {
4560 4561
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching id %d"), id);
4562
        goto cleanup;
4563 4564
    }

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

cleanup:
4569 4570
    if (vm)
        virDomainObjUnlock(vm);
4571 4572
    return dom;
}
4573

4574
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
4575
                                            const unsigned char *uuid) {
4576 4577 4578
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
4579

4580
    qemuDriverLock(driver);
4581
    vm = virDomainFindByUUID(&driver->domains, uuid);
4582 4583
    qemuDriverUnlock(driver);

4584
    if (!vm) {
4585 4586
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
4587 4588
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4589
        goto cleanup;
4590 4591
    }

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

cleanup:
4596 4597
    if (vm)
        virDomainObjUnlock(vm);
4598 4599
    return dom;
}
4600

4601
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
4602
                                            const char *name) {
4603 4604 4605
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
4606

4607
    qemuDriverLock(driver);
4608
    vm = virDomainFindByName(&driver->domains, name);
4609 4610
    qemuDriverUnlock(driver);

4611
    if (!vm) {
4612 4613
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), name);
4614
        goto cleanup;
4615 4616
    }

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

cleanup:
4621 4622
    if (vm)
        virDomainObjUnlock(vm);
4623 4624 4625
    return dom;
}

4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636

static int qemuDomainIsActive(virDomainPtr dom)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    qemuDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!obj) {
4637
        qemuReportError(VIR_ERR_NO_DOMAIN, NULL);
4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657
        goto cleanup;
    }
    ret = virDomainObjIsActive(obj);

cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}

static int qemuDomainIsPersistent(virDomainPtr dom)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr obj;
    int ret = -1;

    qemuDriverLock(driver);
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!obj) {
4658
        qemuReportError(VIR_ERR_NO_DOMAIN, NULL);
4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669
        goto cleanup;
    }
    ret = obj->persistent;

cleanup:
    if (obj)
        virDomainObjUnlock(obj);
    return ret;
}


4670
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
4671 4672 4673
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

4674
    qemuDriverLock(driver);
4675
    if (qemudExtractVersion(driver) < 0)
4676
        goto cleanup;
4677

4678
    *version = qemu_driver->qemuVersion;
4679 4680 4681
    ret = 0;

cleanup:
4682
    qemuDriverUnlock(driver);
4683
    return ret;
D
Daniel P. Berrange 已提交
4684 4685
}

4686
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
4687
    struct qemud_driver *driver = conn->privateData;
4688
    int n;
4689

4690
    qemuDriverLock(driver);
4691
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
4692
    qemuDriverUnlock(driver);
4693

4694
    return n;
D
Daniel P. Berrange 已提交
4695
}
4696

4697
static int qemudNumDomains(virConnectPtr conn) {
4698
    struct qemud_driver *driver = conn->privateData;
4699
    int n;
4700

4701
    qemuDriverLock(driver);
4702
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
4703
    qemuDriverUnlock(driver);
4704

4705
    return n;
D
Daniel P. Berrange 已提交
4706
}
4707

4708
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
4709
                                      unsigned int flags) {
4710
    struct qemud_driver *driver = conn->privateData;
4711
    virDomainDefPtr def;
4712
    virDomainObjPtr vm = NULL;
4713
    virDomainPtr dom = NULL;
4714
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
4715

4716
    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);
4717

4718
    qemuDriverLock(driver);
4719
    if (!(def = virDomainDefParseString(driver->caps, xml,
4720
                                        VIR_DOMAIN_XML_INACTIVE)))
4721
        goto cleanup;
4722

4723
    if (virSecurityDriverVerify(def) < 0)
4724 4725
        goto cleanup;

4726 4727
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
        goto cleanup;
4728

4729 4730 4731 4732 4733 4734
    if (qemudCanonicalizeMachine(driver, def) < 0)
        goto cleanup;

    if (qemuAssignPCIAddresses(def) < 0)
        goto cleanup;

4735
    if (!(vm = virDomainAssignDef(driver->caps,
4736
                                  &driver->domains,
4737
                                  def, false)))
4738 4739 4740
        goto cleanup;

    def = NULL;
D
Daniel P. Berrange 已提交
4741

4742 4743 4744
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup; /* XXXX free the 'vm' we created ? */

4745 4746 4747
    if (qemudStartVMDaemon(conn, driver, vm, NULL,
                           (flags & VIR_DOMAIN_START_PAUSED) != 0,
                           -1, NULL) < 0) {
4748
        qemuDomainStartAudit(vm, "booted", false);
4749 4750 4751
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
4752
        vm = NULL;
4753
        goto cleanup;
D
Daniel P. Berrange 已提交
4754
    }
4755 4756 4757 4758

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
4759
    qemuDomainStartAudit(vm, "booted", true);
D
Daniel P. Berrange 已提交
4760

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

4764 4765 4766
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
4767

4768 4769
cleanup:
    virDomainDefFree(def);
4770 4771
    if (vm)
        virDomainObjUnlock(vm);
4772 4773
    if (event)
        qemuDomainEventQueue(driver, event);
4774
    qemuDriverUnlock(driver);
4775
    return dom;
D
Daniel P. Berrange 已提交
4776 4777 4778
}


4779
static int qemudDomainSuspend(virDomainPtr dom) {
4780 4781 4782
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4783
    virDomainEventPtr event = NULL;
4784
    qemuDomainObjPrivatePtr priv;
4785

4786
    qemuDriverLock(driver);
4787
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4788

D
Daniel P. Berrange 已提交
4789
    if (!vm) {
4790 4791
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4792 4793
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4794
        goto cleanup;
D
Daniel P. Berrange 已提交
4795
    }
D
Daniel P. Berrange 已提交
4796
    if (!virDomainObjIsActive(vm)) {
4797 4798
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
4799
        goto cleanup;
D
Daniel P. Berrange 已提交
4800
    }
4801 4802 4803

    priv = vm->privateData;

4804
    if (priv->jobActive == QEMU_JOB_MIGRATION_OUT) {
4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818
        if (vm->state != VIR_DOMAIN_PAUSED) {
            VIR_DEBUG("Requesting domain pause on %s",
                      vm->def->name);
            priv->jobSignals |= QEMU_JOB_SIGNAL_SUSPEND;
        }
        ret = 0;
        goto cleanup;
    } else {
        if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
            goto cleanup;

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("domain is not running"));
4819
            goto endjob;
4820
        }
4821 4822
        if (vm->state != VIR_DOMAIN_PAUSED) {
            int rc;
4823
            int state = vm->state;
4824

4825
            vm->state = VIR_DOMAIN_PAUSED;
4826 4827 4828
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            rc = qemuMonitorStopCPUs(priv->mon);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
4829 4830
            if (rc < 0) {
                vm->state = state;
4831
                goto endjob;
4832
            }
4833 4834 4835 4836 4837 4838 4839
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_SUSPENDED,
                                             VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
        }
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
            goto endjob;
        ret = 0;
D
Daniel P. Berrange 已提交
4840
    }
4841

4842
endjob:
4843 4844
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
4845

4846
cleanup:
4847 4848
    if (vm)
        virDomainObjUnlock(vm);
4849

4850
    if (event)
4851
        qemuDomainEventQueue(driver, event);
4852
    qemuDriverUnlock(driver);
4853
    return ret;
D
Daniel P. Berrange 已提交
4854 4855 4856
}


4857
static int qemudDomainResume(virDomainPtr dom) {
4858 4859 4860
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4861
    virDomainEventPtr event = NULL;
4862

4863
    qemuDriverLock(driver);
4864
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4865

D
Daniel P. Berrange 已提交
4866
    if (!vm) {
4867 4868
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4869 4870
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4871
        goto cleanup;
D
Daniel P. Berrange 已提交
4872
    }
4873 4874 4875 4876

    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
4877
    if (!virDomainObjIsActive(vm)) {
4878 4879
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
4880
        goto endjob;
D
Daniel P. Berrange 已提交
4881
    }
4882
    if (vm->state == VIR_DOMAIN_PAUSED) {
4883
        qemuDomainObjPrivatePtr priv = vm->privateData;
4884
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
4885
        if (qemuMonitorStartCPUs(priv->mon, dom->conn) < 0) {
4886
            qemuDomainObjExitMonitorWithDriver(driver, vm);
4887
            if (virGetLastError() == NULL)
4888 4889
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resume operation failed"));
4890
            goto endjob;
4891
        }
4892
        qemuDomainObjExitMonitorWithDriver(driver, vm);
4893
        vm->state = VIR_DOMAIN_RUNNING;
4894 4895 4896
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
D
Daniel P. Berrange 已提交
4897
    }
4898
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
4899
        goto endjob;
4900 4901
    ret = 0;

4902
endjob:
4903 4904
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
4905

4906
cleanup:
4907 4908
    if (vm)
        virDomainObjUnlock(vm);
4909
    if (event)
4910
        qemuDomainEventQueue(driver, event);
4911
    qemuDriverUnlock(driver);
4912
    return ret;
D
Daniel P. Berrange 已提交
4913 4914 4915
}


4916
static int qemudDomainShutdown(virDomainPtr dom) {
4917 4918 4919
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4920

4921
    qemuDriverLock(driver);
4922
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4923 4924
    qemuDriverUnlock(driver);

4925
    if (!vm) {
4926 4927
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4928 4929
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4930
        goto cleanup;
4931 4932
    }

4933 4934 4935
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
4936
    if (!virDomainObjIsActive(vm)) {
4937 4938
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
4939
        goto endjob;
4940 4941
    }

4942
    qemuDomainObjPrivatePtr priv = vm->privateData;
4943 4944 4945
    qemuDomainObjEnterMonitor(vm);
    ret = qemuMonitorSystemPowerdown(priv->mon);
    qemuDomainObjExitMonitor(vm);
4946

4947
endjob:
4948 4949
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
4950

4951
cleanup:
4952 4953
    if (vm)
        virDomainObjUnlock(vm);
4954
    return ret;
4955 4956 4957
}


4958
static int qemudDomainDestroy(virDomainPtr dom) {
4959 4960 4961
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4962
    virDomainEventPtr event = NULL;
4963

4964
    qemuDriverLock(driver);
4965
    vm  = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
4966
    if (!vm) {
4967 4968
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
4969 4970
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
4971
        goto cleanup;
D
Daniel P. Berrange 已提交
4972
    }
4973 4974 4975 4976

    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
4977
    if (!virDomainObjIsActive(vm)) {
4978 4979
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
4980
        goto endjob;
4981
    }
4982

4983
    qemudShutdownVMDaemon(driver, vm, 0);
4984 4985 4986
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
4987 4988
    qemuDomainStopAudit(vm, "destroyed");

4989
    if (!vm->persistent) {
4990 4991 4992
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
4993 4994
        vm = NULL;
    }
4995 4996
    ret = 0;

4997
endjob:
4998 4999 5000
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
5001

5002
cleanup:
5003 5004
    if (vm)
        virDomainObjUnlock(vm);
5005 5006
    if (event)
        qemuDomainEventQueue(driver, event);
5007
    qemuDriverUnlock(driver);
5008
    return ret;
D
Daniel P. Berrange 已提交
5009 5010 5011
}


5012
static char *qemudDomainGetOSType(virDomainPtr dom) {
5013 5014 5015
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
5016

5017
    qemuDriverLock(driver);
5018
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5019
    qemuDriverUnlock(driver);
5020
    if (!vm) {
5021 5022
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5023 5024
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5025
        goto cleanup;
5026 5027
    }

5028
    if (!(type = strdup(vm->def->os.type)))
5029
        virReportOOMError();
5030 5031

cleanup:
5032 5033
    if (vm)
        virDomainObjUnlock(vm);
5034 5035 5036
    return type;
}

5037 5038
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
5039 5040 5041
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
5042

5043
    qemuDriverLock(driver);
5044
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5045 5046
    qemuDriverUnlock(driver);

5047
    if (!vm) {
5048 5049
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5050 5051
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5052
        goto cleanup;
5053 5054
    }

5055
    ret = vm->def->mem.max_balloon;
5056 5057

cleanup:
5058 5059
    if (vm)
        virDomainObjUnlock(vm);
5060
    return ret;
5061 5062 5063
}

static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
5064
    struct qemud_driver *driver = dom->conn->privateData;
5065
    qemuDomainObjPrivatePtr priv;
5066
    virDomainObjPtr vm;
5067
    int ret = -1, r;
5068

5069
    qemuDriverLock(driver);
5070
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5071
    qemuDriverUnlock(driver);
5072
    if (!vm) {
5073 5074
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5075 5076
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5077
        goto cleanup;
5078 5079
    }

5080 5081 5082 5083 5084 5085
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

5086
    if (newmem > vm->def->mem.max_balloon) {
5087 5088
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("cannot set memory higher than max memory"));
5089
        goto cleanup;
5090 5091
    }

5092 5093 5094
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

5095 5096 5097 5098 5099 5100
    priv = vm->privateData;
    qemuDomainObjEnterMonitor(vm);
    r = qemuMonitorSetBalloon(priv->mon, newmem);
    qemuDomainObjExitMonitor(vm);
    if (r < 0)
        goto endjob;
5101

5102 5103 5104 5105 5106
    /* Lack of balloon support is a fatal error */
    if (r == 0) {
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cannot set memory of an active domain"));
        goto endjob;
5107
    }
5108

5109
    ret = 0;
5110
endjob:
5111 5112
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
5113

5114
cleanup:
5115 5116
    if (vm)
        virDomainObjUnlock(vm);
5117
    return ret;
5118 5119
}

5120
static int qemudDomainGetInfo(virDomainPtr dom,
5121
                              virDomainInfoPtr info) {
5122 5123 5124
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
5125 5126
    int err;
    unsigned long balloon;
5127

5128
    qemuDriverLock(driver);
5129
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5130
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
5131
    if (!vm) {
5132 5133
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5134 5135
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5136
        goto cleanup;
D
Daniel P. Berrange 已提交
5137 5138
    }

5139
    info->state = vm->state;
D
Daniel P. Berrange 已提交
5140

D
Daniel P. Berrange 已提交
5141
    if (!virDomainObjIsActive(vm)) {
5142
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
5143
    } else {
5144
        if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
5145
            qemuReportError(VIR_ERR_OPERATION_FAILED, ("cannot read cputime for domain"));
5146
            goto cleanup;
D
Daniel P. Berrange 已提交
5147 5148 5149
        }
    }

5150
    info->maxMem = vm->def->mem.max_balloon;
5151

D
Daniel P. Berrange 已提交
5152
    if (virDomainObjIsActive(vm)) {
5153
        qemuDomainObjPrivatePtr priv = vm->privateData;
5154 5155 5156

        if ((vm->def->memballoon != NULL) &&
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
5157
            info->memory = vm->def->mem.max_balloon;
5158
        } else if (!priv->jobActive) {
5159 5160
            if (qemuDomainObjBeginJob(vm) < 0)
                goto cleanup;
5161

5162 5163 5164 5165
            qemuDomainObjEnterMonitor(vm);
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
            qemuDomainObjExitMonitor(vm);
            if (err < 0) {
5166 5167
                if (qemuDomainObjEndJob(vm) == 0)
                    vm = NULL;
5168 5169 5170 5171 5172
                goto cleanup;
            }

            if (err == 0)
                /* Balloon not supported, so maxmem is always the allocation */
5173
                info->memory = vm->def->mem.max_balloon;
5174 5175 5176
            else
                info->memory = balloon;

5177 5178 5179 5180
            if (qemuDomainObjEndJob(vm) == 0) {
                vm = NULL;
                goto cleanup;
            }
5181
        } else {
5182
            info->memory = vm->def->mem.cur_balloon;
5183
        }
5184
    } else {
5185
        info->memory = vm->def->mem.cur_balloon;
5186 5187
    }

5188
    info->nrVirtCpu = vm->def->vcpus;
5189 5190 5191
    ret = 0;

cleanup:
5192 5193
    if (vm)
        virDomainObjUnlock(vm);
5194
    return ret;
D
Daniel P. Berrange 已提交
5195 5196 5197
}


5198 5199 5200 5201 5202 5203 5204 5205
/** qemuDomainMigrateOffline:
 * Pause domain for non-live migration.
 */
static int
qemuDomainMigrateOffline(struct qemud_driver *driver,
                         virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
5206
    int state = vm->state;
5207 5208
    int ret;

5209
    vm->state = VIR_DOMAIN_PAUSED;
5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorStopCPUs(priv->mon);
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    if (ret == 0) {
        virDomainEventPtr event;

        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
        if (event)
            qemuDomainEventQueue(driver, event);
5222 5223
    } else
        vm->state = state;
5224 5225 5226 5227 5228

    return ret;
}


5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242
static int
qemuDomainWaitForMigrationComplete(struct qemud_driver *driver, virDomainObjPtr vm)
{
    int ret = -1;
    int status;
    unsigned long long memProcessed;
    unsigned long long memRemaining;
    unsigned long long memTotal;
    qemuDomainObjPrivatePtr priv = vm->privateData;

    priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;

    while (priv->jobInfo.type == VIR_DOMAIN_JOB_UNBOUNDED) {
        /* Poll every 50ms for progress & to allow cancellation */
5243
        struct timespec ts = { .tv_sec = 0, .tv_nsec = 50 * 1000 * 1000ull };
5244 5245 5246
        struct timeval now;
        int rc;

5247 5248 5249 5250 5251 5252
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit during migration"));
            goto cleanup;
        }

5253 5254
        if (priv->jobSignals & QEMU_JOB_SIGNAL_CANCEL) {
            priv->jobSignals ^= QEMU_JOB_SIGNAL_CANCEL;
5255 5256 5257 5258 5259 5260 5261
            VIR_DEBUG0("Cancelling migration at client request");
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            rc = qemuMonitorMigrateCancel(priv->mon);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            if (rc < 0) {
                VIR_WARN0("Unable to cancel migration");
            }
5262 5263 5264 5265 5266
        } else if (priv->jobSignals & QEMU_JOB_SIGNAL_SUSPEND) {
            priv->jobSignals ^= QEMU_JOB_SIGNAL_SUSPEND;
            VIR_DEBUG0("Pausing domain for non-live migration");
            if (qemuDomainMigrateOffline(driver, vm) < 0)
                VIR_WARN0("Unable to pause domain");
5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277
        } else if (priv->jobSignals & QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME) {
            unsigned long long ms = priv->jobSignalsData.migrateDowntime;

            priv->jobSignals ^= QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME;
            priv->jobSignalsData.migrateDowntime = 0;
            VIR_DEBUG("Setting migration downtime to %llums", ms);
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            rc = qemuMonitorSetMigrationDowntime(priv->mon, ms);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            if (rc < 0)
                VIR_WARN0("Unable to set migration downtime");
5278 5279
        }

5280 5281 5282 5283 5284 5285 5286 5287 5288
        /* Repeat check because the job signals might have caused
         * guest to die
         */
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit during migration"));
            goto cleanup;
        }

5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
        rc = qemuMonitorGetMigrationStatus(priv->mon,
                                           &status,
                                           &memProcessed,
                                           &memRemaining,
                                           &memTotal);
        qemuDomainObjExitMonitorWithDriver(driver, vm);

        if (rc < 0) {
            priv->jobInfo.type = VIR_DOMAIN_JOB_FAILED;
            goto cleanup;
        }

        if (gettimeofday(&now, NULL) < 0) {
            priv->jobInfo.type = VIR_DOMAIN_JOB_FAILED;
            virReportSystemError(errno, "%s",
                                 _("cannot get time of day"));
            goto cleanup;
        }
        priv->jobInfo.timeElapsed =
            ((now.tv_sec * 1000ull) + (now.tv_usec / 1000)) -
            priv->jobStart;

        switch (status) {
        case QEMU_MONITOR_MIGRATION_STATUS_INACTIVE:
            priv->jobInfo.type = VIR_DOMAIN_JOB_NONE;
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Migration is not active"));
            break;

        case QEMU_MONITOR_MIGRATION_STATUS_ACTIVE:
            priv->jobInfo.dataTotal = memTotal;
            priv->jobInfo.dataRemaining = memRemaining;
            priv->jobInfo.dataProcessed = memProcessed;

            priv->jobInfo.memTotal = memTotal;
            priv->jobInfo.memRemaining = memRemaining;
            priv->jobInfo.memProcessed = memProcessed;
            break;

        case QEMU_MONITOR_MIGRATION_STATUS_COMPLETED:
            priv->jobInfo.type = VIR_DOMAIN_JOB_COMPLETED;
            ret = 0;
            break;

        case QEMU_MONITOR_MIGRATION_STATUS_ERROR:
            priv->jobInfo.type = VIR_DOMAIN_JOB_FAILED;
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Migration unexpectedly failed"));
            break;

        case QEMU_MONITOR_MIGRATION_STATUS_CANCELLED:
            priv->jobInfo.type = VIR_DOMAIN_JOB_CANCELLED;
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Migration was cancelled by client"));
            break;
        }

        virDomainObjUnlock(vm);
        qemuDriverUnlock(driver);

        nanosleep(&ts, NULL);

        qemuDriverLock(driver);
        virDomainObjLock(vm);
    }

cleanup:
    return ret;
}


5361
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
5362 5363 5364
#define QEMUD_SAVE_VERSION 2

enum qemud_save_formats {
5365 5366 5367
    QEMUD_SAVE_FORMAT_RAW = 0,
    QEMUD_SAVE_FORMAT_GZIP = 1,
    QEMUD_SAVE_FORMAT_BZIP2 = 2,
5368 5369
    /*
     * Deprecated by xz and never used as part of a release
5370
     * QEMUD_SAVE_FORMAT_LZMA
5371 5372
     */
    QEMUD_SAVE_FORMAT_XZ = 3,
5373
    QEMUD_SAVE_FORMAT_LZOP = 4,
5374 5375 5376
    /* Note: add new members only at the end.
       These values are used in the on-disk format.
       Do not change or re-use numbers. */
5377 5378

    QEMUD_SAVE_FORMAT_LAST
5379
};
5380

5381 5382 5383 5384 5385
VIR_ENUM_DECL(qemudSaveCompression)
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
              "raw",
              "gzip",
              "bzip2",
5386 5387
              "xz",
              "lzop")
5388

5389 5390 5391 5392 5393
struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
    int version;
    int xml_len;
    int was_running;
5394 5395
    int compressed;
    int unused[15];
5396 5397
};

5398 5399 5400 5401 5402 5403 5404
struct fileOpHookData {
    virDomainPtr dom;
    const char *path;
    char *xml;
    struct qemud_save_header *header;
};

5405
/* return -errno on failure, or 0 on success */
5406 5407 5408 5409 5410
static int qemudDomainSaveFileOpHook(int fd, void *data) {
    struct fileOpHookData *hdata = data;
    int ret = 0;

    if (safewrite(fd, hdata->header, sizeof(*hdata->header)) != sizeof(*hdata->header)) {
5411
        ret = -errno;
5412
        qemuReportError(VIR_ERR_OPERATION_FAILED,
5413 5414
                        _("failed to write header to domain save file '%s'"),
                        hdata->path);
5415 5416 5417 5418
        goto endjob;
    }

    if (safewrite(fd, hdata->xml, hdata->header->xml_len) != hdata->header->xml_len) {
5419
        ret = -errno;
5420 5421 5422 5423 5424 5425 5426 5427
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                         _("failed to write xml to '%s'"), hdata->path);
        goto endjob;
    }
endjob:
    return ret;
}

5428 5429 5430
/* this internal function expects the driver lock to already be held on entry */
static int qemudDomainSaveFlag(struct qemud_driver *driver, virDomainPtr dom,
                               virDomainObjPtr vm, const char *path,
5431
                               int compressed)
5432
{
5433
    char *xml = NULL;
5434
    struct qemud_save_header header;
5435 5436
    struct fileOpHookData hdata;
    int bypassSecurityDriver = 0;
5437
    int ret = -1;
5438
    int rc;
5439
    virDomainEventPtr event = NULL;
5440
    qemuDomainObjPrivatePtr priv;
5441 5442
    struct stat sb;
    int is_reg = 0;
5443
    unsigned long long offset;
5444
    virCgroupPtr cgroup = NULL;
5445 5446 5447 5448 5449

    memset(&header, 0, sizeof(header));
    memcpy(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic));
    header.version = QEMUD_SAVE_VERSION;

5450
    header.compressed = compressed;
5451

5452
    priv = vm->privateData;
5453

5454 5455 5456
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
5457
    if (!virDomainObjIsActive(vm)) {
5458 5459
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5460
        goto endjob;
D
Daniel P. Berrange 已提交
5461
    }
5462

5463 5464 5465
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
    priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;

5466 5467 5468
    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
5469
        vm->state = VIR_DOMAIN_PAUSED;
5470
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
5471
        if (qemuMonitorStopCPUs(priv->mon) < 0) {
5472
            qemuDomainObjExitMonitorWithDriver(driver, vm);
5473
            vm->state = VIR_DOMAIN_RUNNING;
5474
            goto endjob;
5475
        }
5476
        qemuDomainObjExitMonitorWithDriver(driver, vm);
5477 5478 5479 5480 5481 5482

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto endjob;
        }
5483 5484 5485
    }

    /* Get XML for the domain */
5486
    xml = virDomainDefFormat(vm->def, VIR_DOMAIN_XML_SECURE);
5487
    if (!xml) {
5488 5489
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
5490
        goto endjob;
5491 5492 5493
    }
    header.xml_len = strlen(xml) + 1;

5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506
    /* path might be a pre-existing block dev, in which case
     * we need to skip the create step, and also avoid unlink
     * in the failure case */
    if (stat(path, &sb) < 0) {
        /* Avoid throwing an error here, since it is possible
         * that with NFS we can't actually stat() the file.
         * The subsequent codepaths will still raise an error
         * if a truely fatal problem is hit */
        is_reg = 1;
    } else {
        is_reg = S_ISREG(sb.st_mode);
    }

5507 5508 5509 5510 5511
    offset = sizeof(header) + header.xml_len;

    /* Due to way we append QEMU state on our header with dd,
     * we need to ensure there's a 512 byte boundary. Unfortunately
     * we don't have an explicit offset in the header, so we fake
5512 5513
     * it by padding the XML string with NULLs.
     */
5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526
    if (offset % QEMU_MONITOR_MIGRATE_TO_FILE_BS) {
        unsigned long long pad =
            QEMU_MONITOR_MIGRATE_TO_FILE_BS -
            (offset % QEMU_MONITOR_MIGRATE_TO_FILE_BS);

        if (VIR_REALLOC_N(xml, header.xml_len + pad) < 0) {
            virReportOOMError();
            goto endjob;
        }
        memset(xml + header.xml_len, 0, pad);
        offset += pad;
        header.xml_len += pad;
    }
5527

5528 5529 5530 5531 5532 5533
    /* Setup hook data needed by virFileOperation hook function */
    hdata.dom = dom;
    hdata.path = path;
    hdata.xml = xml;
    hdata.header = &header;

5534 5535
    /* Write header to file, followed by XML */

5536
    /* First try creating the file as root */
5537 5538 5539 5540
    if (!is_reg) {
        int fd = open(path, O_WRONLY | O_TRUNC);
        if (fd < 0) {
            virReportSystemError(errno, _("unable to open %s"), path);
5541 5542
            goto endjob;
        }
5543
        if (qemudDomainSaveFileOpHook(fd, &hdata) < 0) {
5544 5545 5546 5547 5548
            close(fd);
            goto endjob;
        }
        if (close(fd) < 0) {
            virReportSystemError(errno, _("unable to close %s"), path);
5549 5550
            goto endjob;
        }
5551 5552 5553 5554 5555
    } else {
        if ((rc = virFileOperation(path, O_CREAT|O_TRUNC|O_WRONLY,
                                  S_IRUSR|S_IWUSR,
                                  getuid(), getgid(),
                                  qemudDomainSaveFileOpHook, &hdata,
5556
                                  0)) < 0) {
5557
            /* If we failed as root, and the error was permission-denied
5558 5559
               (EACCES or EPERM), assume it's on a network-connected share
               where root access is restricted (eg, root-squashed NFS). If the
5560 5561 5562 5563
               qemu user (driver->user) is non-root, just set a flag to
               bypass security driver shenanigans, and retry the operation
               after doing setuid to qemu user */

5564
            if (((rc != -EACCES) && (rc != -EPERM)) ||
5565
                driver->user == getuid()) {
5566
                virReportSystemError(-rc, _("Failed to create domain save file '%s'"),
5567 5568 5569
                                     path);
                goto endjob;
            }
5570

5571
            /* On Linux we can also verify the FS-type of the directory. */
5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589
            switch (virStorageFileIsSharedFS(path)) {
                case 1:
                   /* it was on a network share, so we'll continue
                    * as outlined above
                    */
                   break;

                case -1:
                   virReportSystemError(errno,
                                        _("Failed to create domain save file "
                                          "'%s': couldn't determine fs type"),
                                        path);
                   goto endjob;
                   break;

                case 0:
                default:
                   /* local file - log the error returned by virFileOperation */
5590
                   virReportSystemError(-rc,
5591 5592 5593 5594
                                        _("Failed to create domain save file '%s'"),
                                        path);
                   goto endjob;
                   break;
5595 5596 5597

            }

5598
            /* Retry creating the file as driver->user */
5599

5600 5601 5602 5603
            if ((rc = virFileOperation(path, O_CREAT|O_TRUNC|O_WRONLY,
                                       S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
                                       driver->user, driver->group,
                                       qemudDomainSaveFileOpHook, &hdata,
5604 5605
                                       VIR_FILE_OP_AS_UID)) < 0) {
                virReportSystemError(-rc, _("Error from child process creating '%s'"),
5606
                                 path);
5607 5608
                goto endjob;
            }
5609

5610 5611 5612
            /* Since we had to setuid to create the file, and the fstype
               is NFS, we assume it's a root-squashing NFS share, and that
               the security driver stuff would have failed anyway */
5613

5614 5615
            bypassSecurityDriver = 1;
        }
5616
    }
5617

5618

5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635
    if (!is_reg &&
        qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Unable to find cgroup for %s\n"),
                            vm->def->name);
            goto endjob;
        }
        rc = virCgroupAllowDevicePath(cgroup, path);
        if (rc != 0) {
            virReportSystemError(-rc,
                                 _("Unable to allow device %s for %s"),
                                 path, vm->def->name);
            goto endjob;
        }
    }

5636 5637
    if ((!bypassSecurityDriver) &&
        driver->securityDriver &&
5638
        driver->securityDriver->domainSetSavedStateLabel &&
5639 5640
        driver->securityDriver->domainSetSavedStateLabel(driver->securityDriver,
                                                         vm, path) == -1)
5641 5642
        goto endjob;

5643 5644
    if (header.compressed == QEMUD_SAVE_FORMAT_RAW) {
        const char *args[] = { "cat", NULL };
M
Matthias Bolte 已提交
5645
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
5646 5647 5648
        rc = qemuMonitorMigrateToFile(priv->mon,
                                      QEMU_MONITOR_MIGRATE_BACKGROUND,
                                      args, path, offset);
M
Matthias Bolte 已提交
5649
        qemuDomainObjExitMonitorWithDriver(driver, vm);
5650
    } else {
5651
        const char *prog = qemudSaveCompressionTypeToString(header.compressed);
5652 5653 5654 5655 5656
        const char *args[] = {
            prog,
            "-c",
            NULL
        };
M
Matthias Bolte 已提交
5657
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
5658 5659 5660
        rc = qemuMonitorMigrateToFile(priv->mon,
                                      QEMU_MONITOR_MIGRATE_BACKGROUND,
                                      args, path, offset);
M
Matthias Bolte 已提交
5661
        qemuDomainObjExitMonitorWithDriver(driver, vm);
5662 5663
    }

5664 5665 5666 5667 5668
    if (rc < 0)
        goto endjob;

    rc = qemuDomainWaitForMigrationComplete(driver, vm);

5669
    if (rc < 0)
5670
        goto endjob;
5671

5672 5673
    if ((!bypassSecurityDriver) &&
        driver->securityDriver &&
5674
        driver->securityDriver->domainRestoreSavedStateLabel &&
5675 5676
        driver->securityDriver->domainRestoreSavedStateLabel(driver->securityDriver,
                                                             vm, path) == -1)
5677
        VIR_WARN("failed to restore save state label on %s", path);
5678

5679 5680
    if (cgroup != NULL) {
        rc = virCgroupDenyDevicePath(cgroup, path);
5681 5682 5683
        if (rc != 0)
            VIR_WARN("Unable to deny device %s for %s %d",
                     path, vm->def->name, rc);
5684 5685
    }

5686 5687
    ret = 0;

5688
    /* Shut it down */
5689
    qemudShutdownVMDaemon(driver, vm, 0);
5690
    qemuDomainStopAudit(vm, "saved");
5691 5692 5693
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
5694
    if (!vm->persistent) {
5695 5696 5697
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains,
                                    vm);
5698 5699
        vm = NULL;
    }
5700

5701
endjob:
5702
    if (vm) {
5703
        if (ret != 0) {
5704
            if (header.was_running && virDomainObjIsActive(vm)) {
5705 5706 5707 5708 5709 5710 5711 5712
                qemuDomainObjEnterMonitorWithDriver(driver, vm);
                rc = qemuMonitorStartCPUs(priv->mon, dom->conn);
                qemuDomainObjExitMonitorWithDriver(driver, vm);
                if (rc < 0)
                    VIR_WARN0("Unable to resume guest CPUs after save failure");
                else
                    vm->state = VIR_DOMAIN_RUNNING;
            }
5713

5714 5715 5716 5717 5718
            if (cgroup != NULL) {
                rc = virCgroupDenyDevicePath(cgroup, path);
                if (rc != 0)
                    VIR_WARN("Unable to deny device %s for %s: %d",
                             path, vm->def->name, rc);
5719
            }
5720 5721 5722 5723

            if ((!bypassSecurityDriver) &&
                driver->securityDriver &&
                driver->securityDriver->domainRestoreSavedStateLabel &&
5724 5725
                driver->securityDriver->domainRestoreSavedStateLabel(driver->securityDriver,
                                                                     vm, path) == -1)
5726
                VIR_WARN("failed to restore save state label on %s", path);
5727 5728
        }

5729
        if (qemuDomainObjEndJob(vm) == 0)
5730
            vm = NULL;
5731
    }
5732

5733 5734
cleanup:
    VIR_FREE(xml);
5735
    if (ret != 0 && is_reg)
5736
        unlink(path);
5737 5738
    if (event)
        qemuDomainEventQueue(driver, event);
5739
    virCgroupFree(&cgroup);
5740
    return ret;
D
Daniel P. Berrange 已提交
5741 5742
}

5743 5744 5745 5746
static int qemudDomainSave(virDomainPtr dom, const char *path)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int compressed;
5747 5748 5749 5750
    int ret = -1;
    virDomainObjPtr vm = NULL;

    qemuDriverLock(driver);
5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763

    if (driver->saveImageFormat == NULL)
        compressed = QEMUD_SAVE_FORMAT_RAW;
    else {
        compressed = qemudSaveCompressionTypeFromString(driver->saveImageFormat);
        if (compressed < 0) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("Invalid save image format specified "
                                    "in configuration file"));
            return -1;
        }
    }

5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    ret = qemudDomainSaveFlag(driver, dom, vm, path, compressed);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);

    return ret;
5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803
}

static char *
qemuDomainManagedSavePath(struct qemud_driver *driver, virDomainObjPtr vm) {
    char *ret;

    if (virAsprintf(&ret, "%s/%s.save", driver->saveDir, vm->def->name) < 0) {
        virReportOOMError();
        return(NULL);
    }

    return(ret);
}

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

5804
    virCheckFlags(0, -1);
5805 5806 5807 5808 5809 5810 5811 5812

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
5813
        goto cleanup;
5814 5815 5816 5817
    }

    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
5818
        goto cleanup;
5819 5820 5821 5822

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

    compressed = QEMUD_SAVE_FORMAT_RAW;
5823
    ret = qemudDomainSaveFlag(driver, dom, vm, name, compressed);
5824 5825 5826 5827 5828

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
5829 5830 5831
    VIR_FREE(name);

    return ret;
5832 5833 5834 5835 5836 5837 5838 5839 5840 5841
}

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

5842
    virCheckFlags(0, -1);
5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = virFileExists(name);

cleanup:
    VIR_FREE(name);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

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

5876
    virCheckFlags(0, -1);
5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    name = qemuDomainManagedSavePath(driver, vm);
    if (name == NULL)
        goto cleanup;

    ret = unlink(name);

cleanup:
    VIR_FREE(name);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
D
Daniel P. Berrange 已提交
5901

P
Paolo Bonzini 已提交
5902 5903 5904 5905 5906 5907
static int qemudDomainCoreDump(virDomainPtr dom,
                               const char *path,
                               int flags ATTRIBUTE_UNUSED) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int resume = 0, paused = 0;
5908
    int ret = -1, fd = -1;
5909
    virDomainEventPtr event = NULL;
5910 5911 5912 5913
    const char *args[] = {
        "cat",
        NULL,
    };
5914
    qemuDomainObjPrivatePtr priv;
P
Paolo Bonzini 已提交
5915 5916 5917 5918 5919 5920 5921

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
5922 5923
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
P
Paolo Bonzini 已提交
5924 5925
        goto cleanup;
    }
5926
    priv = vm->privateData;
P
Paolo Bonzini 已提交
5927

5928
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
5929 5930
        goto cleanup;

D
Daniel P. Berrange 已提交
5931
    if (!virDomainObjIsActive(vm)) {
5932 5933
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
5934
        goto endjob;
P
Paolo Bonzini 已提交
5935 5936
    }

5937 5938
    /* Create an empty file with appropriate ownership.  */
    if ((fd = open(path, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR)) < 0) {
5939 5940
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("failed to create '%s'"), path);
5941 5942 5943 5944
        goto endjob;
    }

    if (close(fd) < 0) {
5945
        virReportSystemError(errno,
5946 5947 5948 5949 5950 5951 5952
                             _("unable to save file %s"),
                             path);
        goto endjob;
    }

    if (driver->securityDriver &&
        driver->securityDriver->domainSetSavedStateLabel &&
5953 5954
        driver->securityDriver->domainSetSavedStateLabel(driver->securityDriver,
                                                         vm, path) == -1)
5955 5956
        goto endjob;

P
Paolo Bonzini 已提交
5957 5958
    /* Migrate will always stop the VM, so the resume condition is
       independent of whether the stop command is issued.  */
P
Paolo Bonzini 已提交
5959 5960 5961
    resume = (vm->state == VIR_DOMAIN_RUNNING);

    /* Pause domain for non-live dump */
P
Paolo Bonzini 已提交
5962
    if (!(flags & VIR_DUMP_LIVE) && vm->state == VIR_DOMAIN_RUNNING) {
5963
        vm->state = VIR_DOMAIN_PAUSED;
5964
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
5965
        if (qemuMonitorStopCPUs(priv->mon) < 0) {
5966
            qemuDomainObjExitMonitorWithDriver(driver, vm);
5967
            vm->state = VIR_DOMAIN_RUNNING;
5968
            goto endjob;
5969
        }
5970
        qemuDomainObjExitMonitorWithDriver(driver, vm);
P
Paolo Bonzini 已提交
5971
        paused = 1;
5972 5973 5974 5975 5976 5977

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto endjob;
        }
P
Paolo Bonzini 已提交
5978 5979
    }

5980
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
5981 5982 5983
    ret = qemuMonitorMigrateToFile(priv->mon,
                                   QEMU_MONITOR_MIGRATE_BACKGROUND,
                                   args, path, 0);
5984
    qemuDomainObjExitMonitorWithDriver(driver, vm);
5985 5986 5987 5988 5989 5990 5991 5992 5993
    if (ret < 0)
        goto endjob;

    ret = qemuDomainWaitForMigrationComplete(driver, vm);

    if (ret < 0)
        goto endjob;

    paused = 1;
5994 5995 5996

    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSavedStateLabel &&
5997 5998
        driver->securityDriver->domainRestoreSavedStateLabel(driver->securityDriver,
                                                             vm, path) == -1)
5999 6000 6001
        goto endjob;

endjob:
6002
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
6003
        qemudShutdownVMDaemon(driver, vm, 0);
6004
        qemuDomainStopAudit(vm, "crashed");
6005 6006 6007 6008 6009
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
    }

P
Paolo Bonzini 已提交
6010 6011 6012
    /* Since the monitor is always attached to a pty for libvirt, it
       will support synchronous operations so we always get here after
       the migration is complete.  */
6013
    else if (resume && paused && virDomainObjIsActive(vm)) {
6014
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
6015
        if (qemuMonitorStartCPUs(priv->mon, dom->conn) < 0) {
6016
            if (virGetLastError() == NULL)
6017 6018
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("resuming after dump failed"));
P
Paolo Bonzini 已提交
6019
        }
6020
        qemuDomainObjExitMonitorWithDriver(driver, vm);
6021
        vm->state = VIR_DOMAIN_RUNNING;
P
Paolo Bonzini 已提交
6022
    }
6023

6024 6025
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
6026
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
6027 6028 6029 6030
        virDomainRemoveInactive(&driver->domains,
                                vm);
        vm = NULL;
    }
6031 6032

cleanup:
6033 6034
    if (ret != 0)
        unlink(path);
P
Paolo Bonzini 已提交
6035 6036
    if (vm)
        virDomainObjUnlock(vm);
6037 6038
    if (event)
        qemuDomainEventQueue(driver, event);
6039
    qemuDriverUnlock(driver);
P
Paolo Bonzini 已提交
6040 6041 6042 6043
    return ret;
}


6044 6045 6046 6047 6048 6049
static int qemudDomainHotplugVcpus(virDomainObjPtr vm, unsigned int nvcpus)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int i, rc;
    int ret = -1;

6050 6051
    qemuDomainObjEnterMonitor(vm);

6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081
    /* We need different branches here, because we want to offline
     * in reverse order to onlining, so any partial fail leaves us in a
     * reasonably sensible state */
    if (nvcpus > vm->def->vcpus) {
        for (i = vm->def->vcpus ; i < nvcpus ; i++) {
            /* Online new CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

            vm->def->vcpus++;
        }
    } else {
        for (i = vm->def->vcpus - 1 ; i >= nvcpus ; i--) {
            /* Offline old CPU */
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
            if (rc == 0)
                goto unsupported;
            if (rc < 0)
                goto cleanup;

            vm->def->vcpus--;
        }
    }

    ret = 0;

cleanup:
6082
    qemuDomainObjExitMonitor(vm);
6083 6084 6085 6086 6087 6088 6089 6090 6091
    return ret;

unsupported:
    qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("cannot change vcpu count of this domain"));
    goto cleanup;
}


6092 6093 6094 6095
static int
qemudDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                         unsigned int flags)
{
6096 6097
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
6098
    virDomainDefPtr def;
6099 6100
    const char * type;
    int max;
6101
    int ret = -1;
6102

6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118
    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)) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid flag combination: (0x%x)"), flags);
        return -1;
    }
    if (!nvcpus || (unsigned short) nvcpus != nvcpus) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("argument out of range: %d"), nvcpus);
6119 6120 6121
        return -1;
    }

6122
    qemuDriverLock(driver);
6123
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6124 6125
    qemuDriverUnlock(driver);

6126
    if (!vm) {
6127 6128
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6129 6130
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6131
        goto cleanup;
6132 6133
    }

6134 6135 6136
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

6137
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
6138 6139
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                         "%s", _("domain is not running"));
6140
        goto endjob;
6141 6142
    }

6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
        goto endjob;
    }

    if ((max = qemudGetMaxVCPUs(NULL, type)) < 0) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("could not determine max vcpus for the domain"));
        goto endjob;
    }

6156 6157 6158 6159 6160
    if ((flags & (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_LIVE)) ==
        VIR_DOMAIN_VCPU_LIVE && vm->def->maxvcpus < max) {
        max = vm->def->maxvcpus;
    }

6161 6162 6163 6164 6165 6166 6167
    if (nvcpus > max) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("requested vcpus is greater than max allowable"
                          " vcpus for the domain: %d > %d"), nvcpus, max);
        goto endjob;
    }

6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210
    switch (flags) {
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
        def = vm->def;
        if (virDomainObjIsActive(vm)) {
            if (vm->newDef)
                def = vm->newDef;
            else{
                qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                _("no persistent state"));
                goto endjob;
            }
        }
        def->maxvcpus = nvcpus;
        if (nvcpus < vm->newDef->vcpus)
            def->vcpus = nvcpus;
        ret = 0;
        break;

    case VIR_DOMAIN_VCPU_CONFIG:
        def = vm->def;
        if (virDomainObjIsActive(vm)) {
            if (vm->newDef)
                def = vm->newDef;
            else {
                qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                                _("no persistent state"));
                goto endjob;
            }
        }
        def->vcpus = nvcpus;
        ret = 0;
        break;

    case VIR_DOMAIN_VCPU_LIVE:
        ret = qemudDomainHotplugVcpus(vm, nvcpus);
        break;

    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
        ret = qemudDomainHotplugVcpus(vm, nvcpus);
        if (ret == 0 && vm->newDef)
            vm->newDef->vcpus = nvcpus;
        break;
    }
6211 6212 6213 6214

endjob:
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
6215

6216
cleanup:
6217 6218
    if (vm)
        virDomainObjUnlock(vm);
6219
    return ret;
6220 6221
}

6222 6223 6224 6225 6226 6227
static int
qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
    return qemudDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_VCPU_LIVE);
}

6228 6229 6230 6231 6232 6233

static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
6234 6235
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
6236
    int maxcpu, hostcpus;
6237
    virNodeInfo nodeinfo;
6238
    int ret = -1;
6239
    qemuDomainObjPrivatePtr priv;
6240

6241
    qemuDriverLock(driver);
6242
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6243 6244
    qemuDriverUnlock(driver);

6245 6246 6247
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6248 6249
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6250 6251 6252
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
6253
    if (!virDomainObjIsActive(vm)) {
6254 6255
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",_("cannot pin vcpus on an inactive domain"));
6256
        goto cleanup;
6257 6258
    }

6259 6260 6261
    priv = vm->privateData;

    if (vcpu > (priv->nvcpupids-1)) {
6262 6263 6264
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("vcpu number out of range %d > %d"),
                        vcpu, priv->nvcpupids);
6265
        goto cleanup;
6266 6267
    }

6268
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
6269
        goto cleanup;
6270

6271
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
6272
    maxcpu = maplen * 8;
6273 6274
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
6275

6276 6277
    if (priv->vcpupids != NULL) {
        if (virProcessInfoSetAffinity(priv->vcpupids[vcpu],
6278
                                      cpumap, maplen, maxcpu) < 0)
6279
            goto cleanup;
6280
    } else {
6281 6282
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cpu affinity is not supported"));
6283
        goto cleanup;
6284
    }
6285
    ret = 0;
6286

6287
cleanup:
6288 6289
    if (vm)
        virDomainObjUnlock(vm);
6290
    return ret;
6291 6292 6293 6294 6295 6296 6297 6298
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
6299 6300
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
6301
    virNodeInfo nodeinfo;
6302
    int i, v, maxcpu, hostcpus;
6303
    int ret = -1;
6304
    qemuDomainObjPrivatePtr priv;
6305

6306
    qemuDriverLock(driver);
6307
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6308 6309
    qemuDriverUnlock(driver);

6310 6311 6312
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6313 6314
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6315 6316 6317
        goto cleanup;
    }

D
Daniel P. Berrange 已提交
6318
    if (!virDomainObjIsActive(vm)) {
6319 6320 6321
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s",
                        _("cannot list vcpu pinning for an inactive domain"));
6322
        goto cleanup;
6323 6324
    }

6325 6326
    priv = vm->privateData;

6327
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
6328
        goto cleanup;
6329

6330
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
6331
    maxcpu = maplen * 8;
6332 6333
    if (maxcpu > hostcpus)
        maxcpu = hostcpus;
6334 6335

    /* Clamp to actual number of vcpus */
6336 6337
    if (maxinfo > priv->nvcpupids)
        maxinfo = priv->nvcpupids;
6338

6339 6340 6341 6342 6343 6344
    if (maxinfo >= 1) {
        if (info != NULL) {
            memset(info, 0, sizeof(*info) * maxinfo);
            for (i = 0 ; i < maxinfo ; i++) {
                info[i].number = i;
                info[i].state = VIR_VCPU_RUNNING;
6345

6346
                if (priv->vcpupids != NULL &&
6347 6348 6349
                    qemudGetProcessInfo(&(info[i].cpuTime),
                                        &(info[i].cpu),
                                        vm->pid,
6350
                                        priv->vcpupids[i]) < 0) {
6351
                    virReportSystemError(errno, "%s",
6352 6353 6354
                                         _("cannot get vCPU placement & pCPU time"));
                    goto cleanup;
                }
6355
            }
6356 6357
        }

6358 6359
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
6360
            if (priv->vcpupids != NULL) {
6361 6362 6363
                for (v = 0 ; v < maxinfo ; v++) {
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);

6364
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
6365
                                                  cpumap, maplen, maxcpu) < 0)
6366
                        goto cleanup;
6367
                }
6368
            } else {
6369 6370
                qemuReportError(VIR_ERR_NO_SUPPORT,
                                "%s", _("cpu affinity is not available"));
6371
                goto cleanup;
6372 6373 6374
            }
        }
    }
6375
    ret = maxinfo;
6376

6377
cleanup:
6378 6379
    if (vm)
        virDomainObjUnlock(vm);
6380
    return ret;
6381 6382 6383
}


6384 6385 6386
static int
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
6387 6388
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
6389
    virDomainDefPtr def;
6390
    int ret = -1;
6391

6392 6393 6394 6395 6396 6397 6398 6399
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
                  VIR_DOMAIN_VCPU_CONFIG |
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);

    /* Exactly one of LIVE or CONFIG must be set.  */
    if (!(flags & VIR_DOMAIN_VCPU_LIVE) == !(flags & VIR_DOMAIN_VCPU_CONFIG)) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid flag combination: (0x%x)"), flags);
6400 6401 6402
        return -1;
    }

6403
    qemuDriverLock(driver);
6404
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6405 6406
    qemuDriverUnlock(driver);

6407
    if (!vm) {
6408 6409
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6410 6411
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6412
        goto cleanup;
6413 6414
    }

6415 6416 6417 6418 6419 6420 6421 6422 6423
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
                            _("domain not active"));
            goto cleanup;
        }
        def = vm->def;
    } else {
        def = vm->newDef ? vm->newDef : vm->def;
6424 6425
    }

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

6428
cleanup:
6429 6430
    if (vm)
        virDomainObjUnlock(vm);
6431 6432 6433
    return ret;
}

6434 6435 6436 6437 6438 6439 6440
static int
qemudDomainGetMaxVcpus(virDomainPtr dom)
{
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_VCPU_LIVE |
                                          VIR_DOMAIN_VCPU_MAXIMUM));
}

6441 6442 6443 6444 6445 6446 6447 6448 6449
static int qemudDomainGetSecurityLabel(virDomainPtr dom, virSecurityLabelPtr seclabel)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

6450 6451
    memset(seclabel, 0, sizeof(*seclabel));

6452 6453 6454
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
6455 6456
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
6457 6458 6459
        goto cleanup;
    }

6460
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
6461 6462 6463
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unknown virt type in domain definition '%d'"),
                        vm->def->virtType);
6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480
        goto cleanup;
    }

    /*
     * Theoretically, the pid can be replaced during this operation and
     * return the label of a different process.  If atomicity is needed,
     * further validation will be required.
     *
     * Comment from Dan Berrange:
     *
     *   Well the PID as stored in the virDomainObjPtr can't be changed
     *   because you've got a locked object.  The OS level PID could have
     *   exited, though and in extreme circumstances have cycled through all
     *   PIDs back to ours. We could sanity check that our PID still exists
     *   after reading the label, by checking that our FD connecting to the
     *   QEMU monitor hasn't seen SIGHUP/ERR on poll().
     */
D
Daniel P. Berrange 已提交
6481
    if (virDomainObjIsActive(vm)) {
6482 6483 6484 6485 6486 6487 6488
        if (driver->securityDriver &&
            driver->securityDriver->domainGetSecurityProcessLabel &&
            driver->securityDriver->domainGetSecurityProcessLabel(driver->securityDriver,
                                                                  vm, seclabel) < 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            "%s", _("Failed to get security label"));
            goto cleanup;
6489 6490 6491 6492 6493 6494 6495 6496
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
6497
    qemuDriverUnlock(driver);
6498 6499 6500
    return ret;
}

6501 6502
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
6503 6504 6505
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
6506
    int ret = 0;
6507

6508
    qemuDriverLock(driver);
6509
    if (!driver->securityPrimaryDriver) {
6510
        memset(secmodel, 0, sizeof (*secmodel));
6511 6512
        goto cleanup;
    }
6513

6514 6515
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
6516 6517 6518
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security model string exceeds max %d bytes"),
                        VIR_SECURITY_MODEL_BUFLEN-1);
6519 6520
        ret = -1;
        goto cleanup;
6521 6522 6523 6524 6525
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
6526 6527 6528
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("security DOI string exceeds max %d bytes"),
                        VIR_SECURITY_DOI_BUFLEN-1);
6529 6530
        ret = -1;
        goto cleanup;
6531 6532
    }
    strcpy(secmodel->doi, p);
6533 6534 6535 6536

cleanup:
    qemuDriverUnlock(driver);
    return ret;
6537 6538
}

6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611
/* qemudOpenAsUID() - pipe/fork/setuid/open a file, and return the
   pipe fd to caller, so that it can read from the file. Also return
   the pid of the child process, so the caller can wait for it to exit
   after it's finished reading (to avoid a zombie, if nothing
   else). */

static int qemudOpenAsUID(const char *path, uid_t uid, pid_t *child_pid) {
    int pipefd[2];
    int fd = -1;

    *child_pid = -1;

    if (pipe(pipefd) < 0) {
        virReportSystemError(errno,
                             _("failed to create pipe to read '%s'"),
                             path);
        pipefd[0] = pipefd[1] = -1;
        goto parent_cleanup;
    }

    int forkRet = virFork(child_pid);

    if (*child_pid < 0) {
        virReportSystemError(errno,
                             _("failed to fork child to read '%s'"),
                             path);
        goto parent_cleanup;
    }

    if (*child_pid > 0) {

        /* parent */

        /* parent doesn't need the write side of the pipe */
        close(pipefd[1]);
        pipefd[1] = -1;

        if (forkRet < 0) {
            virReportSystemError(errno,
                                 _("failed in parent after forking child to read '%s'"),
                                 path);
            goto parent_cleanup;
        }
        /* caller gets the read side of the pipe */
        fd = pipefd[0];
        pipefd[0] = -1;
parent_cleanup:
        if (pipefd[0] != -1)
            close(pipefd[0]);
        if (pipefd[1] != -1)
            close(pipefd[1]);
        if ((fd < 0) && (*child_pid > 0)) {
            /* a child process was started and subsequently an error
               occurred in the parent, so we need to wait for it to
               exit, but its status is inconsequential. */
            while ((waitpid(*child_pid, NULL, 0) == -1)
                   && (errno == EINTR)) {
                /* empty */
            }
            *child_pid = -1;
        }
        return fd;
    }

    /* child */

    /* setuid to the qemu user, then open the file, read it,
       and stuff it into the pipe for the parent process to
       read */
    int exit_code;
    char *buf = NULL;
    size_t bufsize = 1024 * 1024;
    int bytesread;
6612
    struct passwd pwd, *pwd_result;
6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624

    /* child doesn't need the read side of the pipe */
    close(pipefd[0]);

    if (forkRet < 0) {
        exit_code = errno;
        virReportSystemError(errno,
                             _("failed in child after forking to read '%s'"),
                             path);
        goto child_cleanup;
    }

6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644
    if (VIR_ALLOC_N(buf, bufsize) < 0) {
        exit_code = ENOMEM;
        virReportOOMError();
        goto child_cleanup;
    }

    exit_code = getpwuid_r(uid, &pwd, buf, bufsize, &pwd_result);
    if (pwd_result == NULL) {
        virReportSystemError(errno,
                             _("cannot getpwuid_r(%d) to read '%s'"),
                             uid, path);
        goto child_cleanup;
    }
    if (initgroups(pwd.pw_name, pwd.pw_gid) != 0) {
        exit_code = errno;
        virReportSystemError(errno,
                             _("cannot initgroups(\"%s\", %d) to read '%s'"),
                             pwd.pw_name, pwd.pw_gid, path);
        goto child_cleanup;
    }
6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686
    if (setuid(uid) != 0) {
        exit_code = errno;
        virReportSystemError(errno,
                             _("cannot setuid(%d) to read '%s'"),
                             uid, path);
        goto child_cleanup;
    }
    if ((fd = open(path, O_RDONLY)) < 0) {
        exit_code = errno;
        virReportSystemError(errno,
                             _("cannot open '%s' as uid %d"),
                             path, uid);
        goto child_cleanup;
    }

    /* read from fd and write to pipefd[1] until EOF */
    do {
        if ((bytesread = saferead(fd, buf, bufsize)) < 0) {
            exit_code = errno;
            virReportSystemError(errno,
                                 _("child failed reading from '%s'"),
                                 path);
            goto child_cleanup;
        }
        if (safewrite(pipefd[1], buf, bytesread) != bytesread) {
            exit_code = errno;
            virReportSystemError(errno, "%s",
                                 _("child failed writing to pipe"));
            goto child_cleanup;
        }
    } while (bytesread > 0);
    exit_code = 0;

child_cleanup:
    VIR_FREE(buf);
    if (fd != -1)
        close(fd);
    if (pipefd[1] != -1)
        close(pipefd[1]);
    _exit(exit_code);
}

J
Jiri Denemark 已提交
6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714
static int qemudDomainSaveImageClose(int fd, pid_t read_pid, int *status)
{
    int ret = 0;

    if (fd != -1)
        close(fd);

    if (read_pid != -1) {
        /* reap the process that read the file */
        while ((ret = waitpid(read_pid, status, 0)) == -1
               && errno == EINTR) {
            /* empty */
        }
    } else if (status) {
        *status = 0;
    }

    return ret;
}

static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5)
qemudDomainSaveImageOpen(struct qemud_driver *driver,
                                    const char *path,
                                    virDomainDefPtr *ret_def,
                                    struct qemud_save_header *ret_header,
                                    pid_t *ret_read_pid)
{
    int fd;
6715
    pid_t read_pid = -1;
6716
    struct qemud_save_header header;
J
Jiri Denemark 已提交
6717 6718
    char *xml = NULL;
    virDomainDefPtr def = NULL;
6719 6720

    if ((fd = open(path, O_RDONLY)) < 0) {
6721 6722 6723
        if ((driver->user == 0) || (getuid() != 0)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot read domain image"));
J
Jiri Denemark 已提交
6724
            goto error;
6725 6726 6727 6728 6729 6730 6731 6732
        }

        /* Opening as root failed, but qemu runs as a different user
           that might have better luck. Create a pipe, then fork a
           child process to run as the qemu user, which will hopefully
           have the necessary authority to read the file. */
        if ((fd = qemudOpenAsUID(path, driver->user, &read_pid)) < 0) {
            /* error already reported */
J
Jiri Denemark 已提交
6733
            goto error;
6734
        }
6735 6736 6737
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
6738 6739
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read qemu header"));
J
Jiri Denemark 已提交
6740
        goto error;
6741 6742 6743
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
6744 6745
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("image magic is incorrect"));
J
Jiri Denemark 已提交
6746
        goto error;
6747 6748 6749
    }

    if (header.version > QEMUD_SAVE_VERSION) {
6750 6751 6752
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("image version is not supported (%d > %d)"),
                        header.version, QEMUD_SAVE_VERSION);
J
Jiri Denemark 已提交
6753
        goto error;
6754 6755
    }

6756 6757 6758
    if (header.xml_len <= 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("invalid XML length: %d"), header.xml_len);
J
Jiri Denemark 已提交
6759
        goto error;
6760 6761
    }

6762 6763
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
        virReportOOMError();
J
Jiri Denemark 已提交
6764
        goto error;
6765 6766 6767
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
6768 6769
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to read XML"));
J
Jiri Denemark 已提交
6770
        goto error;
6771 6772 6773
    }

    /* Create a domain from this XML */
6774
    if (!(def = virDomainDefParseString(driver->caps, xml,
6775
                                        VIR_DOMAIN_XML_INACTIVE))) {
6776 6777
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to parse XML"));
J
Jiri Denemark 已提交
6778
        goto error;
6779 6780
    }

J
Jiri Denemark 已提交
6781
    VIR_FREE(xml);
6782

J
Jiri Denemark 已提交
6783 6784 6785
    *ret_def = def;
    *ret_header = header;
    *ret_read_pid = read_pid;
6786

J
Jiri Denemark 已提交
6787
    return fd;
6788

J
Jiri Denemark 已提交
6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814
error:
    virDomainDefFree(def);
    VIR_FREE(xml);
    qemudDomainSaveImageClose(fd, read_pid, NULL);

    return -1;
}

static int ATTRIBUTE_NONNULL(6)
qemudDomainSaveImageStartVM(virConnectPtr conn,
                            struct qemud_driver *driver,
                            virDomainObjPtr vm,
                            int fd,
                            pid_t read_pid,
                            const struct qemud_save_header *header,
                            const char *path)
{
    int ret = -1;
    virDomainEventPtr event;
    int intermediatefd = -1;
    pid_t intermediate_pid = -1;
    int childstat;
    int wait_ret;
    int status;

    if (header->version == 2) {
6815
        const char *intermediate_argv[3] = { NULL, "-dc", NULL };
J
Jiri Denemark 已提交
6816
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
6817
        if (prog == NULL) {
6818 6819
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("Invalid compressed save format %d"),
J
Jiri Denemark 已提交
6820 6821
                            header->compressed);
            goto out;
6822
        }
6823

J
Jiri Denemark 已提交
6824
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
6825
            intermediate_argv[0] = prog;
6826 6827
            intermediatefd = fd;
            fd = -1;
6828
            if (virExec(intermediate_argv, NULL, NULL,
6829
                        &intermediate_pid, intermediatefd, &fd, NULL, 0) < 0) {
6830 6831 6832
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Failed to start decompression binary %s"),
                                intermediate_argv[0]);
J
Jiri Denemark 已提交
6833
                goto out;
6834 6835 6836
            }
        }
    }
J
Jiri Denemark 已提交
6837

6838
    /* Set the migration source and start it up. */
6839
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio", true, fd, path);
J
Jiri Denemark 已提交
6840

6841 6842 6843
    if (intermediate_pid != -1) {
        /* Wait for intermediate process to exit */
        while (waitpid(intermediate_pid, &childstat, 0) == -1 &&
J
Jiri Denemark 已提交
6844 6845 6846
               errno == EINTR) {
            /* empty */
        }
6847 6848 6849
    }
    if (intermediatefd != -1)
        close(intermediatefd);
J
Jiri Denemark 已提交
6850 6851

    wait_ret = qemudDomainSaveImageClose(fd, read_pid, &status);
6852
    fd = -1;
6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873
    if (read_pid != -1) {
        if (wait_ret == -1) {
            virReportSystemError(errno,
                                 _("failed to wait for process reading '%s'"),
                                 path);
            ret = -1;
        } else if (!WIFEXITED(status)) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("child process exited abnormally reading '%s'"),
                            path);
            ret = -1;
        } else {
            int exit_status = WEXITSTATUS(status);
            if (exit_status != 0) {
                virReportSystemError(exit_status,
                                     _("child process returned error reading '%s'"),
                                     path);
                ret = -1;
            }
        }
    }
J
Jiri Denemark 已提交
6874

6875 6876
    if (ret < 0) {
        qemuDomainStartAudit(vm, "restored", false);
J
Jiri Denemark 已提交
6877
        goto out;
6878
    }
6879

6880 6881 6882
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
6883
    qemuDomainStartAudit(vm, "restored", true);
J
Jiri Denemark 已提交
6884 6885 6886
    if (event)
        qemuDomainEventQueue(driver, event);

6887

6888
    /* If it was running before, resume it now. */
J
Jiri Denemark 已提交
6889
    if (header->was_running) {
6890
        qemuDomainObjPrivatePtr priv = vm->privateData;
6891
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
6892
        if (qemuMonitorStartCPUs(priv->mon, conn) < 0) {
6893
            if (virGetLastError() == NULL)
6894 6895
                qemuReportError(VIR_ERR_OPERATION_FAILED,
                                "%s", _("failed to resume domain"));
6896
            qemuDomainObjExitMonitorWithDriver(driver,vm);
J
Jiri Denemark 已提交
6897
            goto out;
6898
        }
6899
        qemuDomainObjExitMonitorWithDriver(driver, vm);
6900
        vm->state = VIR_DOMAIN_RUNNING;
6901 6902
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
J
Jiri Denemark 已提交
6903
            goto out;
6904
        }
6905
    }
J
Jiri Denemark 已提交
6906

6907
    ret = 0;
6908

J
Jiri Denemark 已提交
6909
out:
6910 6911
    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSavedStateLabel &&
6912 6913
        driver->securityDriver->domainRestoreSavedStateLabel(driver->securityDriver,
                                                             vm, path) == -1)
6914 6915
        VIR_WARN("failed to restore save state label on %s", path);

J
Jiri Denemark 已提交
6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940
    return ret;
}

static int qemudDomainRestore(virConnectPtr conn,
                              const char *path) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    int fd = -1;
    pid_t read_pid = -1;
    int ret = -1;
    struct qemud_save_header header;

    qemuDriverLock(driver);

    fd = qemudDomainSaveImageOpen(driver, path, &def, &header, &read_pid);
    if (fd < 0)
        goto cleanup;

    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
        goto cleanup;

    if (!(vm = virDomainAssignDef(driver->caps,
                                  &driver->domains,
                                  def, true))) {
6941
        /* virDomainAssignDef already set the error */
J
Jiri Denemark 已提交
6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952
        goto cleanup;
    }
    def = NULL;

    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

    ret = qemudDomainSaveImageStartVM(conn, driver, vm, fd,
                                      read_pid, &header, path);

    if (qemuDomainObjEndJob(vm) == 0)
6953
        vm = NULL;
J
Jiri Denemark 已提交
6954 6955 6956 6957
    else if (ret < 0 && !vm->persistent) {
        virDomainRemoveInactive(&driver->domains, vm);
        vm = NULL;
    }
6958

6959 6960
cleanup:
    virDomainDefFree(def);
J
Jiri Denemark 已提交
6961
    qemudDomainSaveImageClose(fd, read_pid, NULL);
6962 6963 6964
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
6965
    return ret;
D
Daniel P. Berrange 已提交
6966 6967
}

J
Jiri Denemark 已提交
6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008
static int qemudDomainObjRestore(virConnectPtr conn,
                                 struct qemud_driver *driver,
                                 virDomainObjPtr vm,
                                 const char *path)
{
    virDomainDefPtr def = NULL;
    int fd = -1;
    pid_t read_pid = -1;
    int ret = -1;
    struct qemud_save_header header;

    fd = qemudDomainSaveImageOpen(driver, path, &def, &header, &read_pid);
    if (fd < 0)
        goto cleanup;

    if (STRNEQ(vm->def->name, def->name) ||
        memcmp(vm->def->uuid, def->uuid, VIR_UUID_BUFLEN)) {
        char vm_uuidstr[VIR_UUID_STRING_BUFLEN];
        char def_uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(vm->def->uuid, vm_uuidstr);
        virUUIDFormat(def->uuid, def_uuidstr);
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("cannot restore domain '%s' uuid %s from a file"
                          " which belongs to domain '%s' uuid %s"),
                        vm->def->name, vm_uuidstr,
                        def->name, def_uuidstr);
        goto cleanup;
    }

    virDomainObjAssignDef(vm, def, true);
    def = NULL;

    ret = qemudDomainSaveImageStartVM(conn, driver, vm, fd,
                                      read_pid, &header, path);

cleanup:
    virDomainDefFree(def);
    qemudDomainSaveImageClose(fd, read_pid, NULL);
    return ret;
}

D
Daniel P. Berrange 已提交
7009

7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047
static char *qemudVMDumpXML(struct qemud_driver *driver,
                            virDomainObjPtr vm,
                            int flags)
{
    char *ret = NULL;
    virCPUDefPtr cpu = NULL;
    virDomainDefPtr def;
    virCPUDefPtr def_cpu;

    if ((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef)
        def = vm->newDef;
    else
        def = vm->def;
    def_cpu = def->cpu;

    /* Update guest CPU requirements according to host CPU */
    if ((flags & VIR_DOMAIN_XML_UPDATE_CPU) && def_cpu && def_cpu->model) {
        if (!driver->caps || !driver->caps->host.cpu) {
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            "%s", _("cannot get host CPU capabilities"));
            goto cleanup;
        }

        if (!(cpu = virCPUDefCopy(def_cpu))
            || cpuUpdate(cpu, driver->caps->host.cpu))
            goto cleanup;
        def->cpu = cpu;
    }

    ret = virDomainDefFormat(def, flags);

cleanup:
    def->cpu = def_cpu;
    virCPUDefFree(cpu);
    return ret;
}


7048
static char *qemudDomainDumpXML(virDomainPtr dom,
7049
                                int flags) {
7050 7051 7052
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
7053 7054
    unsigned long balloon;
    int err;
7055

7056
    qemuDriverLock(driver);
7057
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7058

D
Daniel P. Berrange 已提交
7059
    if (!vm) {
7060 7061
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7062 7063
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7064
        goto cleanup;
D
Daniel P. Berrange 已提交
7065 7066
    }

7067 7068 7069 7070
    /* Refresh current memory based on balloon info if supported */
    if ((vm->def->memballoon != NULL) &&
        (vm->def->memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_NONE) &&
        (virDomainObjIsActive(vm))) {
7071
        qemuDomainObjPrivatePtr priv = vm->privateData;
7072 7073 7074
        /* Don't delay if someone's using the monitor, just use
         * existing most recent data instead */
        if (!priv->jobActive) {
7075
            if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
7076 7077
                goto cleanup;

7078
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
7079
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
7080
            qemuDomainObjExitMonitorWithDriver(driver, vm);
7081 7082 7083 7084
            if (qemuDomainObjEndJob(vm) == 0) {
                vm = NULL;
                goto cleanup;
            }
7085 7086 7087
            if (err < 0)
                goto cleanup;
            if (err > 0)
7088
                vm->def->mem.cur_balloon = balloon;
7089 7090
            /* err == 0 indicates no balloon support, so ignore it */
        }
7091
    }
7092

7093
    ret = qemudVMDumpXML(driver, vm, flags);
7094 7095

cleanup:
7096 7097
    if (vm)
        virDomainObjUnlock(vm);
7098
    qemuDriverUnlock(driver);
7099
    return ret;
D
Daniel P. Berrange 已提交
7100 7101 7102
}


7103 7104 7105 7106
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
                                     unsigned int flags ATTRIBUTE_UNUSED) {
7107
    struct qemud_driver *driver = conn->privateData;
7108 7109 7110 7111
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
7112 7113
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
7114 7115 7116
        goto cleanup;
    }

7117
    qemuDriverLock(driver);
7118
    def = qemuParseCommandLineString(driver->caps, config);
7119
    qemuDriverUnlock(driver);
7120 7121 7122
    if (!def)
        goto cleanup;

7123
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
7124 7125 7126 7127 7128 7129

cleanup:
    virDomainDefFree(def);
    return xml;
}

7130 7131 7132 7133 7134 7135
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
                                   unsigned int flags ATTRIBUTE_UNUSED) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
7136
    virDomainChrDef monConfig;
7137
    const char *emulator;
7138
    unsigned long long qemuCmdFlags;
7139 7140 7141 7142 7143 7144 7145 7146
    struct stat sb;
    const char **retargv = NULL;
    const char **retenv = NULL;
    const char **tmp;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *ret = NULL;
    int i;

7147 7148
    qemuDriverLock(driver);

7149
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
7150 7151
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("unsupported config type %s"), format);
7152 7153 7154
        goto cleanup;
    }

7155
    def = virDomainDefParseString(driver->caps, xmlData, 0);
7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199
    if (!def)
        goto cleanup;

    /* Since we're just exporting args, we can't do bridge/network
     * setups, since libvirt will normally create TAP devices
     * directly. We convert those configs into generic 'ethernet'
     * config and assume the user has suitable 'ifup-qemu' scripts
     */
    for (i = 0 ; i < def->nnets ; i++) {
        virDomainNetDefPtr net = def->nets[i];
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            VIR_FREE(net->data.network.name);

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.dev = NULL;
            net->data.ethernet.script = NULL;
            net->data.ethernet.ipaddr = NULL;
        } else if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
            char *brname = net->data.bridge.brname;
            char *script = net->data.bridge.script;
            char *ipaddr = net->data.bridge.ipaddr;

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.dev = brname;
            net->data.ethernet.script = script;
            net->data.ethernet.ipaddr = ipaddr;
        }
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
            def->graphics[i]->data.vnc.port = 5900;
    }
    emulator = def->emulator;

    /* Make sure the binary we are about to try exec'ing exists.
     * Technically we could catch the exec() failure, but that's
     * in a sub-process so its hard to feed back a useful error
     */
    if (stat(emulator, &sb) < 0) {
7200
        virReportSystemError(errno,
7201 7202 7203 7204 7205 7206 7207 7208
                             _("Cannot find QEMU binary %s"),
                             emulator);
        goto cleanup;
    }

    if (qemudExtractVersionInfo(emulator,
                                NULL,
                                &qemuCmdFlags) < 0) {
7209 7210 7211
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot determine QEMU argv syntax %s"),
                        emulator);
7212 7213 7214
        goto cleanup;
    }

7215
    if (qemuPrepareMonitorChr(driver, &monConfig, def->name) < 0)
7216
        goto cleanup;
7217 7218

    if (qemudBuildCommandLine(conn, driver, def,
D
Daniel P. Berrange 已提交
7219
                              &monConfig, 0, qemuCmdFlags,
7220 7221
                              &retargv, &retenv,
                              NULL, NULL, /* Don't want it to create TAP devices */
C
Chris Lalancette 已提交
7222
                              NULL, NULL) < 0) {
7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238
        goto cleanup;
    }

    tmp = retenv;
    while (*tmp) {
        virBufferAdd(&buf, *tmp, strlen(*tmp));
        virBufferAddLit(&buf, " ");
        tmp++;
    }
    tmp = retargv;
    while (*tmp) {
        virBufferAdd(&buf, *tmp, strlen(*tmp));
        virBufferAddLit(&buf, " ");
        tmp++;
    }

7239 7240
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
7241
        virReportOOMError();
7242
        goto cleanup;
7243
    }
7244 7245 7246 7247

    ret = virBufferContentAndReset(&buf);

cleanup:
7248
    qemuDriverUnlock(driver);
7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261
    for (tmp = retargv ; tmp && *tmp ; tmp++)
        VIR_FREE(*tmp);
    VIR_FREE(retargv);

    for (tmp = retenv ; tmp && *tmp ; tmp++)
        VIR_FREE(*tmp);
    VIR_FREE(retenv);

    virDomainDefFree(def);
    return ret;
}


7262
static int qemudListDefinedDomains(virConnectPtr conn,
7263
                            char **const names, int nnames) {
7264
    struct qemud_driver *driver = conn->privateData;
7265
    int n;
7266

7267
    qemuDriverLock(driver);
7268
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
7269
    qemuDriverUnlock(driver);
7270
    return n;
D
Daniel P. Berrange 已提交
7271 7272
}

7273
static int qemudNumDefinedDomains(virConnectPtr conn) {
7274
    struct qemud_driver *driver = conn->privateData;
7275
    int n;
7276

7277
    qemuDriverLock(driver);
7278
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
7279
    qemuDriverUnlock(driver);
7280

7281
    return n;
D
Daniel P. Berrange 已提交
7282 7283 7284
}


J
Jiri Denemark 已提交
7285 7286
static int qemudDomainObjStart(virConnectPtr conn,
                               struct qemud_driver *driver,
7287 7288
                               virDomainObjPtr vm,
                               bool start_paused)
J
Jiri Denemark 已提交
7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308
{
    int ret = -1;
    char *managed_save;

    /*
     * If there is a managed saved state restore it instead of starting
     * from scratch. In any case the old state is removed.
     */
    managed_save = qemuDomainManagedSavePath(driver, vm);
    if ((managed_save) && (virFileExists(managed_save))) {
        ret = qemudDomainObjRestore(conn, driver, vm, managed_save);

        if (unlink(managed_save) < 0) {
            VIR_WARN("Failed to remove the managed state %s", managed_save);
        }

        if (ret == 0)
            goto cleanup;
    }

7309
    ret = qemudStartVMDaemon(conn, driver, vm, NULL, start_paused, -1, NULL);
7310 7311
    qemuDomainStartAudit(vm, "booted", ret >= 0);
    if (ret >= 0) {
J
Jiri Denemark 已提交
7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
        if (event)
            qemuDomainEventQueue(driver, event);
    }

cleanup:
    VIR_FREE(managed_save);
    return ret;
}

7325 7326 7327
static int
qemudDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
{
7328 7329 7330
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
7331

7332
    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);
7333

7334
    qemuDriverLock(driver);
7335
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7336

7337
    if (!vm) {
7338 7339
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7340 7341
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7342
        goto cleanup;
7343 7344
    }

7345 7346 7347 7348
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

    if (virDomainObjIsActive(vm)) {
7349 7350
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is already running"));
7351 7352 7353
        goto endjob;
    }

7354 7355
    ret = qemudDomainObjStart(dom->conn, driver, vm,
                              (flags & VIR_DOMAIN_START_PAUSED) != 0);
7356

7357
endjob:
7358 7359
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
7360

7361
cleanup:
7362 7363
    if (vm)
        virDomainObjUnlock(vm);
7364
    qemuDriverUnlock(driver);
7365
    return ret;
D
Daniel P. Berrange 已提交
7366 7367
}

7368 7369 7370 7371 7372 7373
static int
qemudDomainStart(virDomainPtr dom)
{
    return qemudDomainStartWithFlags(dom, 0);
}

7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388
static int
qemudCanonicalizeMachineFromInfo(virDomainDefPtr def,
                                 virCapsGuestDomainInfoPtr info,
                                 char **canonical)
{
    int i;

    *canonical = NULL;

    for (i = 0; i < info->nmachines; i++) {
        virCapsGuestMachinePtr machine = info->machines[i];

        if (!machine->canonical)
            continue;

7389
        if (STRNEQ(def->os.machine, machine->name))
7390 7391 7392
            continue;

        if (!(*canonical = strdup(machine->canonical))) {
7393
            virReportOOMError();
7394 7395 7396 7397 7398 7399 7400 7401 7402
            return -1;
        }

        break;
    }

    return 0;
}

7403 7404 7405 7406 7407 7408 7409
static int
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
{
    virCapsGuestMachinePtr *machines = NULL;
    int i, nmachines = 0;

    if (qemudProbeMachineTypes(def->emulator, &machines, &nmachines) < 0) {
7410
        virReportOOMError();
7411 7412 7413 7414 7415 7416 7417
        return -1;
    }

    for (i = 0; i < nmachines; i++) {
        if (!machines[i]->canonical)
            continue;

7418
        if (STRNEQ(def->os.machine, machines[i]->name))
7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430
            continue;

        *canonical = machines[i]->canonical;
        machines[i]->canonical = NULL;
        break;
    }

    virCapabilitiesFreeMachines(machines, nmachines);

    return 0;
}

7431 7432
int
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
7433 7434 7435 7436 7437 7438
{
    char *canonical = NULL;
    int i;

    for (i = 0; i < driver->caps->nguests; i++) {
        virCapsGuestPtr guest = driver->caps->guests[i];
7439
        virCapsGuestDomainInfoPtr info;
7440 7441 7442
        int j;

        for (j = 0; j < guest->arch.ndomains; j++) {
7443
            info = &guest->arch.domains[j]->info;
7444

7445 7446 7447 7448 7449 7450 7451 7452 7453
            if (!info->emulator || !STREQ(info->emulator, def->emulator))
                continue;

            if (!info->nmachines)
                info = &guest->arch.defaultInfo;

            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
                return -1;
            goto out;
7454 7455
        }

7456 7457 7458 7459
        info = &guest->arch.defaultInfo;

        if (info->emulator && STREQ(info->emulator, def->emulator)) {
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
7460 7461 7462 7463
                return -1;
            goto out;
        }
    }
7464 7465 7466 7467

    if (qemudCanonicalizeMachineDirect(def, &canonical) < 0)
        return -1;

7468 7469 7470 7471 7472 7473 7474
out:
    if (canonical) {
        VIR_FREE(def->os.machine);
        def->os.machine = canonical;
    }
    return 0;
}
D
Daniel P. Berrange 已提交
7475

7476
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
7477
    struct qemud_driver *driver = conn->privateData;
7478
    virDomainDefPtr def;
7479
    virDomainObjPtr vm = NULL;
7480
    virDomainPtr dom = NULL;
7481
    virDomainEventPtr event = NULL;
7482
    int dupVM;
7483

7484
    qemuDriverLock(driver);
7485
    if (!(def = virDomainDefParseString(driver->caps, xml,
7486
                                        VIR_DOMAIN_XML_INACTIVE)))
7487
        goto cleanup;
7488

7489
    if (virSecurityDriverVerify(def) < 0)
7490 7491
        goto cleanup;

7492 7493
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
        goto cleanup;
7494

7495
    if (qemudCanonicalizeMachine(driver, def) < 0)
7496 7497
        goto cleanup;

7498 7499 7500
    if (qemuAssignPCIAddresses(def) < 0)
        goto cleanup;

7501
    if (!(vm = virDomainAssignDef(driver->caps,
7502
                                  &driver->domains,
7503
                                  def, false))) {
7504
        goto cleanup;
7505
    }
7506
    def = NULL;
7507
    vm->persistent = 1;
7508

7509
    if (virDomainSaveConfig(driver->configDir,
7510
                            vm->newDef ? vm->newDef : vm->def) < 0) {
7511 7512
        virDomainRemoveInactive(&driver->domains,
                                vm);
7513
        vm = NULL;
7514
        goto cleanup;
7515 7516
    }

7517 7518
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
7519
                                     !dupVM ?
7520 7521
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
7522

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

cleanup:
7527
    virDomainDefFree(def);
7528 7529
    if (vm)
        virDomainObjUnlock(vm);
7530 7531
    if (event)
        qemuDomainEventQueue(driver, event);
7532
    qemuDriverUnlock(driver);
7533
    return dom;
D
Daniel P. Berrange 已提交
7534 7535
}

7536
static int qemudDomainUndefine(virDomainPtr dom) {
7537 7538
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
7539
    virDomainEventPtr event = NULL;
7540
    int ret = -1;
D
Daniel P. Berrange 已提交
7541

7542
    qemuDriverLock(driver);
7543
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7544

D
Daniel P. Berrange 已提交
7545
    if (!vm) {
7546 7547
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
7548 7549
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
7550
        goto cleanup;
D
Daniel P. Berrange 已提交
7551 7552
    }

D
Daniel P. Berrange 已提交
7553
    if (virDomainObjIsActive(vm)) {
7554 7555
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot delete active domain"));
7556
        goto cleanup;
D
Daniel P. Berrange 已提交
7557 7558
    }

7559
    if (!vm->persistent) {
7560 7561
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("cannot undefine transient domain"));
7562
        goto cleanup;
7563 7564
    }

7565
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
7566
        goto cleanup;
D
Daniel P. Berrange 已提交
7567

7568 7569 7570
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
7571

7572 7573
    virDomainRemoveInactive(&driver->domains,
                            vm);
7574
    vm = NULL;
7575
    ret = 0;
D
Daniel P. Berrange 已提交
7576

7577
cleanup:
7578 7579
    if (vm)
        virDomainObjUnlock(vm);
7580 7581
    if (event)
        qemuDomainEventQueue(driver, event);
7582
    qemuDriverUnlock(driver);
7583
    return ret;
D
Daniel P. Berrange 已提交
7584 7585
}

7586

7587
static int qemudDomainChangeEjectableMedia(struct qemud_driver *driver,
7588
                                           virDomainObjPtr vm,
7589 7590
                                           virDomainDiskDefPtr disk,
                                           unsigned long long qemuCmdFlags)
7591
{
7592
    virDomainDiskDefPtr origdisk = NULL;
7593
    int i;
7594
    int ret;
7595
    char *driveAlias = NULL;
7596

7597
    origdisk = NULL;
7598
    for (i = 0 ; i < vm->def->ndisks ; i++) {
7599 7600
        if (vm->def->disks[i]->bus == disk->bus &&
            STREQ(vm->def->disks[i]->dst, disk->dst)) {
7601
            origdisk = vm->def->disks[i];
7602
            break;
7603
        }
7604 7605 7606
    }

    if (!origdisk) {
7607 7608 7609 7610
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No device with bus '%s' and target '%s'"),
                        virDomainDiskBusTypeToString(disk->bus),
                        disk->dst);
7611 7612 7613
        return -1;
    }

7614
    if (!origdisk->info.alias) {
7615 7616
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), origdisk->dst);
7617 7618
        return -1;
    }
7619

7620 7621
    if (origdisk->device != VIR_DOMAIN_DISK_DEVICE_FLOPPY &&
        origdisk->device != VIR_DOMAIN_DISK_DEVICE_CDROM) {
7622 7623 7624
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Removable media not supported for %s device"),
                        virDomainDiskDeviceTypeToString(disk->device));
7625
        return -1;
7626
    }
7627

7628 7629
    if (driver->securityDriver &&
        driver->securityDriver->domainSetSecurityImageLabel &&
7630 7631
        driver->securityDriver->domainSetSecurityImageLabel(driver->securityDriver,
                                                            vm, disk) < 0)
7632 7633
        return -1;

7634 7635 7636
    if (!(driveAlias = qemuDeviceDriveHostAlias(origdisk, qemuCmdFlags)))
        goto error;

7637
    qemuDomainObjPrivatePtr priv = vm->privateData;
7638
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
7639
    if (disk->src) {
7640
        const char *format = NULL;
7641 7642 7643
        if (disk->type != VIR_DOMAIN_DISK_TYPE_DIR) {
            if (disk->driverType)
                format = disk->driverType;
7644 7645 7646
            else if (origdisk->driverType)
                format = origdisk->driverType;
        }
7647
        ret = qemuMonitorChangeMedia(priv->mon,
7648
                                     driveAlias,
7649
                                     disk->src, format);
7650
    } else {
7651
        ret = qemuMonitorEjectMedia(priv->mon, driveAlias);
7652
    }
7653
    qemuDomainObjExitMonitorWithDriver(driver, vm);
7654

7655 7656
    qemuDomainDiskAudit(vm, origdisk, disk, "update", ret >= 0);

7657 7658 7659 7660 7661
    if (ret < 0)
        goto error;

    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSecurityImageLabel &&
7662 7663
        driver->securityDriver->domainRestoreSecurityImageLabel(driver->securityDriver,
                                                                vm, origdisk) < 0)
7664 7665 7666
        VIR_WARN("Unable to restore security label on ejected image %s", origdisk->src);

    VIR_FREE(origdisk->src);
7667 7668 7669 7670
    origdisk->src = disk->src;
    disk->src = NULL;
    origdisk->type = disk->type;

7671 7672
    VIR_FREE(driveAlias);

7673
    virDomainDiskDefFree(disk);
7674

7675
    return ret;
7676 7677

error:
7678
    VIR_FREE(driveAlias);
7679 7680
    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSecurityImageLabel &&
7681 7682
        driver->securityDriver->domainRestoreSecurityImageLabel(driver->securityDriver,
                                                                vm, disk) < 0)
7683
        VIR_WARN("Unable to restore security label on new media %s", disk->src);
7684
    return -1;
7685 7686
}

7687

7688
static int qemudDomainAttachPciDiskDevice(struct qemud_driver *driver,
7689
                                          virDomainObjPtr vm,
7690
                                          virDomainDiskDefPtr disk,
7691
                                          unsigned long long qemuCmdFlags)
7692
{
7693
    int i, ret;
7694
    const char* type = virDomainDiskBusTypeToString(disk->bus);
7695
    qemuDomainObjPrivatePtr priv = vm->privateData;
7696 7697
    char *devstr = NULL;
    char *drivestr = NULL;
7698 7699

    for (i = 0 ; i < vm->def->ndisks ; i++) {
7700
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
7701 7702
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("target %s already exists"), disk->dst);
7703 7704 7705 7706
            return -1;
        }
    }

7707 7708
    if (driver->securityDriver &&
        driver->securityDriver->domainSetSecurityImageLabel &&
7709 7710
        driver->securityDriver->domainSetSecurityImageLabel(driver->securityDriver,
                                                            vm, disk) < 0)
7711 7712
        return -1;

7713
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
7714 7715
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &disk->info) < 0)
            goto error;
7716 7717
        if (qemuAssignDeviceDiskAlias(disk, qemuCmdFlags) < 0)
            goto error;
7718

7719 7720 7721
        if (!(drivestr = qemuBuildDriveStr(disk, 0, qemuCmdFlags)))
            goto error;

7722
        if (!(devstr = qemuBuildDriveDevStr(disk)))
7723 7724 7725
            goto error;
    }

7726
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
7727
        virReportOOMError();
7728
        goto error;
7729 7730
    }

7731
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
7732 7733
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        ret = qemuMonitorAddDrive(priv->mon, drivestr);
7734 7735 7736
        if (ret == 0) {
            ret = qemuMonitorAddDevice(priv->mon, devstr);
            if (ret < 0) {
7737
                VIR_WARN("qemuMonitorAddDevice failed on %s (%s)",
7738 7739 7740 7741 7742
                         drivestr, devstr);
                /* XXX should call 'drive_del' on error but this does not
                   exist yet */
            }
        }
7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753
    } else {
        virDomainDevicePCIAddress guestAddr;
        ret = qemuMonitorAddPCIDisk(priv->mon,
                                    disk->src,
                                    type,
                                    &guestAddr);
        if (ret == 0) {
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
            memcpy(&disk->info.addr.pci, &guestAddr, sizeof(guestAddr));
        }
    }
7754
    qemuDomainObjExitMonitorWithDriver(driver, vm);
7755

7756 7757
    qemuDomainDiskAudit(vm, NULL, disk, "attach", ret >= 0);

7758 7759
    if (ret < 0)
        goto error;
7760

7761
    virDomainDiskInsertPreAlloced(vm->def, disk);
7762

7763 7764 7765
    VIR_FREE(devstr);
    VIR_FREE(drivestr);

7766 7767 7768
    return 0;

error:
7769 7770 7771
    VIR_FREE(devstr);
    VIR_FREE(drivestr);

7772 7773 7774 7775 7776
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) &&
        (disk->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
        qemuDomainPCIAddressReleaseAddr(priv->pciaddrs, &disk->info) < 0)
        VIR_WARN("Unable to release PCI address on %s", disk->src);

7777 7778
    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSecurityImageLabel &&
7779 7780
        driver->securityDriver->domainRestoreSecurityImageLabel(driver->securityDriver,
                                                                vm, disk) < 0)
7781
        VIR_WARN("Unable to restore security label on %s", disk->src);
7782 7783

    return -1;
7784
}
7785

7786

7787
static int qemudDomainAttachPciControllerDevice(struct qemud_driver *driver,
7788
                                                virDomainObjPtr vm,
7789
                                                virDomainControllerDefPtr controller,
7790
                                                unsigned long long qemuCmdFlags)
7791
{
7792 7793
    int i;
    int ret = -1;
7794
    const char* type = virDomainControllerTypeToString(controller->type);
7795
    char *devstr = NULL;
7796 7797 7798
    qemuDomainObjPrivatePtr priv = vm->privateData;

    for (i = 0 ; i < vm->def->ncontrollers ; i++) {
7799 7800
        if ((vm->def->controllers[i]->type == controller->type) &&
            (vm->def->controllers[i]->idx == controller->idx)) {
7801 7802 7803
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("target %s:%d already exists"),
                            type, controller->idx);
7804 7805 7806 7807
            return -1;
        }
    }

7808 7809 7810 7811 7812 7813
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &controller->info) < 0)
            goto cleanup;
        if (qemuAssignDeviceControllerAlias(controller) < 0)
            goto cleanup;
    }
7814

7815
    if (!(devstr = qemuBuildControllerDevStr(controller))) {
7816
        virReportOOMError();
7817 7818 7819
        goto cleanup;
    }

7820
    if (VIR_REALLOC_N(vm->def->controllers, vm->def->ncontrollers+1) < 0) {
7821
        virReportOOMError();
7822
        goto cleanup;
7823 7824 7825
    }

    qemuDomainObjEnterMonitorWithDriver(driver, vm);
7826 7827 7828 7829 7830 7831 7832
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    } else {
        ret = qemuMonitorAttachPCIDiskController(priv->mon,
                                                 type,
                                                 &controller->info.addr.pci);
    }
7833 7834 7835
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    if (ret == 0) {
7836 7837
        controller->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        virDomainControllerInsertPreAlloced(vm->def, controller);
7838 7839
    }

7840
cleanup:
7841 7842 7843 7844 7845 7846
    if ((ret != 0) &&
        (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) &&
        (controller->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
        qemuDomainPCIAddressReleaseAddr(priv->pciaddrs, &controller->info) < 0)
        VIR_WARN0("Unable to release PCI address on controller");

7847
    VIR_FREE(devstr);
7848 7849 7850
    return ret;
}

7851

7852
static virDomainControllerDefPtr
7853
qemuDomainFindOrCreateSCSIDiskController(struct qemud_driver *driver,
7854
                                         virDomainObjPtr vm,
7855
                                         int controller,
7856
                                         unsigned long long qemuCmdFlags)
7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869
{
    int i;
    virDomainControllerDefPtr cont;
    for (i = 0 ; i < vm->def->ncontrollers ; i++) {
        cont = vm->def->controllers[i];

        if (cont->type != VIR_DOMAIN_CONTROLLER_TYPE_SCSI)
            continue;

        if (cont->idx == controller)
            return cont;
    }

W
Wolfgang Mauerer 已提交
7870
    /* No SCSI controller present, for backward compatibility we
7871 7872
     * now hotplug a controller */
    if (VIR_ALLOC(cont) < 0) {
7873
        virReportOOMError();
7874 7875 7876 7877
        return NULL;
    }
    cont->type = VIR_DOMAIN_CONTROLLER_TYPE_SCSI;
    cont->idx = 0;
7878
    cont->model = -1;
7879 7880

    VIR_INFO0("No SCSI controller present, hotplugging one");
7881
    if (qemudDomainAttachPciControllerDevice(driver,
7882
                                             vm, cont, qemuCmdFlags) < 0) {
7883 7884 7885
        VIR_FREE(cont);
        return NULL;
    }
7886 7887 7888 7889 7890 7891 7892 7893 7894

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("guest unexpectedly quit"));
        /* cont doesn't need freeing here, since the reference
         * now held in def->controllers */
        return NULL;
    }

7895 7896 7897
    return cont;
}

7898

7899
static int qemudDomainAttachSCSIDisk(struct qemud_driver *driver,
7900
                                     virDomainObjPtr vm,
7901
                                     virDomainDiskDefPtr disk,
7902
                                     unsigned long long qemuCmdFlags)
7903 7904 7905
{
    int i;
    qemuDomainObjPrivatePtr priv = vm->privateData;
7906
    virDomainControllerDefPtr cont = NULL;
7907
    char *drivestr = NULL;
7908
    char *devstr = NULL;
7909 7910 7911
    int ret = -1;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
7912
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
7913 7914
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("target %s already exists"), disk->dst);
7915
            return -1;
7916 7917 7918
        }
    }

7919 7920 7921

    if (driver->securityDriver &&
        driver->securityDriver->domainSetSecurityImageLabel &&
7922 7923
        driver->securityDriver->domainSetSecurityImageLabel(driver->securityDriver,
                                                            vm, disk) < 0)
7924 7925
        return -1;

7926
    /* We should have an address already, so make sure */
7927
    if (disk->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE) {
7928 7929 7930
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unexpected disk address type %s"),
                        virDomainDeviceAddressTypeToString(disk->info.type));
7931
        goto error;
7932 7933
    }

7934 7935 7936
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (qemuAssignDeviceDiskAlias(disk, qemuCmdFlags) < 0)
            goto error;
7937
        if (!(devstr = qemuBuildDriveDevStr(disk)))
7938 7939 7940 7941 7942 7943
            goto error;
    }

    if (!(drivestr = qemuBuildDriveStr(disk, 0, qemuCmdFlags)))
        goto error;

7944
    for (i = 0 ; i <= disk->info.addr.drive.controller ; i++) {
7945
        cont = qemuDomainFindOrCreateSCSIDiskController(driver, vm, i, qemuCmdFlags);
7946
        if (!cont)
7947
            goto error;
7948 7949
    }

7950 7951 7952 7953 7954
    /* Tell clang that "cont" is non-NULL.
       This is because disk->info.addr.driver.controller is unsigned,
       and hence the above loop must iterate at least once.  */
    sa_assert (cont);

7955
    if (cont->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
7956 7957
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("SCSI controller %d was missing its PCI address"), cont->idx);
7958
        goto error;
7959 7960 7961
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
7962
        virReportOOMError();
7963
        goto error;
7964 7965 7966
    }

    qemuDomainObjEnterMonitorWithDriver(driver, vm);
7967
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
7968 7969 7970 7971
        ret = qemuMonitorAddDrive(priv->mon, drivestr);
        if (ret == 0) {
            ret = qemuMonitorAddDevice(priv->mon, devstr);
            if (ret < 0) {
7972
                VIR_WARN("qemuMonitorAddDevice failed on %s (%s)",
7973 7974 7975 7976 7977
                         drivestr, devstr);
                /* XXX should call 'drive_del' on error but this does not
                   exist yet */
            }
        }
7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990
    } else {
        virDomainDeviceDriveAddress driveAddr;
        ret = qemuMonitorAttachDrive(priv->mon,
                                     drivestr,
                                     &cont->info.addr.pci,
                                     &driveAddr);
        if (ret == 0) {
            /* XXX we should probably validate that the addr matches
             * our existing defined addr instead of overwriting */
            disk->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DRIVE;
            memcpy(&disk->info.addr.drive, &driveAddr, sizeof(driveAddr));
        }
    }
7991 7992
    qemuDomainObjExitMonitorWithDriver(driver, vm);

7993 7994
    qemuDomainDiskAudit(vm, NULL, disk, "attach", ret >= 0);

7995 7996
    if (ret < 0)
        goto error;
7997

7998
    virDomainDiskInsertPreAlloced(vm->def, disk);
7999 8000

    VIR_FREE(devstr);
8001
    VIR_FREE(drivestr);
8002 8003 8004 8005

    return 0;

error:
8006
    VIR_FREE(devstr);
8007
    VIR_FREE(drivestr);
8008

8009 8010
    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSecurityImageLabel &&
8011 8012
        driver->securityDriver->domainRestoreSecurityImageLabel(driver->securityDriver,
                                                                vm, disk) < 0)
8013
        VIR_WARN("Unable to restore security label on %s", disk->src);
8014 8015

    return -1;
8016 8017
}

8018

8019
static int qemudDomainAttachUsbMassstorageDevice(struct qemud_driver *driver,
8020
                                                 virDomainObjPtr vm,
8021
                                                 virDomainDiskDefPtr disk,
8022
                                                 unsigned long long qemuCmdFlags)
8023
{
8024
    qemuDomainObjPrivatePtr priv = vm->privateData;
8025
    int i, ret;
8026 8027
    char *drivestr = NULL;
    char *devstr = NULL;
8028

8029
    for (i = 0 ; i < vm->def->ndisks ; i++) {
8030
        if (STREQ(vm->def->disks[i]->dst, disk->dst)) {
8031 8032
            qemuReportError(VIR_ERR_OPERATION_FAILED,
                            _("target %s already exists"), disk->dst);
8033 8034 8035 8036
            return -1;
        }
    }

8037 8038
    if (driver->securityDriver &&
        driver->securityDriver->domainSetSecurityImageLabel &&
8039 8040
        driver->securityDriver->domainSetSecurityImageLabel(driver->securityDriver,
                                                            vm, disk) < 0)
8041 8042
        return -1;

8043
    if (!disk->src) {
8044 8045
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("disk source path is missing"));
8046
        goto error;
8047 8048
    }

8049
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
8050 8051
        if (qemuAssignDeviceDiskAlias(disk, qemuCmdFlags) < 0)
            goto error;
8052 8053
        if (!(drivestr = qemuBuildDriveStr(disk, 0, qemuCmdFlags)))
            goto error;
8054
        if (!(devstr = qemuBuildDriveDevStr(disk)))
8055 8056 8057
            goto error;
    }

8058
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
8059
        virReportOOMError();
8060
        goto error;
8061 8062
    }

8063
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8064
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
8065 8066 8067 8068
        ret = qemuMonitorAddDrive(priv->mon, drivestr);
        if (ret == 0) {
            ret = qemuMonitorAddDevice(priv->mon, devstr);
            if (ret < 0) {
8069
                VIR_WARN("qemuMonitorAddDevice failed on %s (%s)",
8070 8071 8072 8073 8074
                         drivestr, devstr);
                /* XXX should call 'drive_del' on error but this does not
                   exist yet */
            }
        }
8075 8076 8077
    } else {
        ret = qemuMonitorAddUSBDisk(priv->mon, disk->src);
    }
8078
    qemuDomainObjExitMonitorWithDriver(driver, vm);
8079

8080 8081
    qemuDomainDiskAudit(vm, NULL, disk, "attach", ret >= 0);

8082 8083 8084
    if (ret < 0)
        goto error;

8085
    virDomainDiskInsertPreAlloced(vm->def, disk);
8086

8087 8088 8089
    VIR_FREE(devstr);
    VIR_FREE(drivestr);

8090 8091 8092
    return 0;

error:
8093 8094 8095
    VIR_FREE(devstr);
    VIR_FREE(drivestr);

8096 8097
    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSecurityImageLabel &&
8098 8099
        driver->securityDriver->domainRestoreSecurityImageLabel(driver->securityDriver,
                                                                vm, disk) < 0)
8100
        VIR_WARN("Unable to restore security label on %s", disk->src);
8101 8102

    return -1;
8103 8104
}

8105

8106
/* XXX conn required for network -> bridge resolution */
M
Mark McLoughlin 已提交
8107
static int qemudDomainAttachNetDevice(virConnectPtr conn,
8108
                                      struct qemud_driver *driver,
M
Mark McLoughlin 已提交
8109
                                      virDomainObjPtr vm,
8110
                                      virDomainNetDefPtr net,
8111
                                      unsigned long long qemuCmdFlags)
M
Mark McLoughlin 已提交
8112
{
8113
    qemuDomainObjPrivatePtr priv = vm->privateData;
8114
    char *tapfd_name = NULL;
8115
    int tapfd = -1;
8116
    char *nicstr = NULL;
8117
    char *netstr = NULL;
8118
    int ret = -1;
8119
    virDomainDevicePCIAddress guestAddr;
8120
    int vlan;
M
Mark McLoughlin 已提交
8121 8122

    if (!(qemuCmdFlags & QEMUD_CMD_FLAG_HOST_NET_ADD)) {
8123
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8124
                        _("installed qemu version does not support host_net_add"));
M
Mark McLoughlin 已提交
8125 8126 8127 8128 8129
        return -1;
    }

    if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
        net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
8130
        if (priv->monConfig->type != VIR_DOMAIN_CHR_TYPE_UNIX) {
8131
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8132 8133 8134
                            _("network device type '%s' cannot be attached: "
                              "qemu is not using a unix socket monitor"),
                            virDomainNetTypeToString(net->type));
8135 8136 8137 8138 8139
            return -1;
        }

        if ((tapfd = qemudNetworkIfaceConnect(conn, driver, net, qemuCmdFlags)) < 0)
            return -1;
8140 8141
    } else if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
        if (priv->monConfig->type != VIR_DOMAIN_CHR_TYPE_UNIX) {
8142
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8143 8144 8145 8146 8147 8148
                            _("network device type '%s' cannot be attached: "
                            "qemu is not using a unix socket monitor"),
                            virDomainNetTypeToString(net->type));
            return -1;
        }

S
Stefan Berger 已提交
8149
        if ((tapfd = qemudPhysIfaceConnect(conn, driver, net,
8150 8151
                                           qemuCmdFlags,
                                           vm->def->uuid)) < 0)
8152
            return -1;
M
Mark McLoughlin 已提交
8153 8154
    }

8155 8156
    if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets+1) < 0)
        goto no_memory;
M
Mark McLoughlin 已提交
8157

8158 8159 8160 8161 8162
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_NET_NAME) ||
        (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
        if (qemuAssignDeviceNetAlias(vm->def, net, -1) < 0)
            goto cleanup;
    }
M
Mark McLoughlin 已提交
8163

8164 8165 8166 8167
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) &&
        qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &net->info) < 0)
        goto cleanup;

8168 8169 8170 8171 8172
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_NETDEV) &&
        (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
        vlan = -1;
    } else {
        vlan = qemuDomainNetVLAN(net);
M
Mark McLoughlin 已提交
8173

8174
        if (vlan < 0) {
8175
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
8176 8177 8178
                            _("Unable to attach network devices without vlan"));
            goto cleanup;
        }
8179 8180
    }

8181
    if (tapfd != -1) {
8182
        if (virAsprintf(&tapfd_name, "fd-%s", net->info.alias) < 0)
8183 8184
            goto no_memory;

8185
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
8186
        if (qemuMonitorSendFileHandle(priv->mon, tapfd_name, tapfd) < 0) {
8187
            qemuDomainObjExitMonitorWithDriver(driver, vm);
8188
            goto cleanup;
8189
        }
8190
        qemuDomainObjExitMonitorWithDriver(driver, vm);
8191 8192 8193 8194 8195 8196

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto cleanup;
        }
8197 8198
    }

8199
    /* FIXME - need to support vhost-net here (5th arg) */
8200 8201 8202 8203 8204 8205 8206 8207 8208 8209
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_NETDEV) &&
        (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
        if (!(netstr = qemuBuildHostNetStr(net, ',',
                                           -1, tapfd_name, 0)))
            goto try_tapfd_close;
    } else {
        if (!(netstr = qemuBuildHostNetStr(net, ' ',
                                           vlan, tapfd_name, 0)))
            goto try_tapfd_close;
    }
M
Mark McLoughlin 已提交
8210

8211
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8212 8213 8214 8215
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_NETDEV) &&
        (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
        if (qemuMonitorAddNetdev(priv->mon, netstr) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
8216
            qemuDomainNetAudit(vm, NULL, net, "attach", false);
8217 8218 8219 8220 8221
            goto try_tapfd_close;
        }
    } else {
        if (qemuMonitorAddHostNetwork(priv->mon, netstr) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
8222
            qemuDomainNetAudit(vm, NULL, net, "attach", false);
8223 8224
            goto try_tapfd_close;
        }
8225
    }
8226
    qemuDomainObjExitMonitorWithDriver(driver, vm);
M
Mark McLoughlin 已提交
8227

8228 8229 8230
    if (tapfd != -1)
        close(tapfd);
    tapfd = -1;
M
Mark McLoughlin 已提交
8231

8232 8233 8234 8235 8236 8237
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("guest unexpectedly quit"));
        goto cleanup;
    }

8238 8239 8240 8241 8242 8243 8244
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (!(nicstr = qemuBuildNicDevStr(net, vlan)))
            goto try_remove;
    } else {
        if (!(nicstr = qemuBuildNicStr(net, NULL, vlan)))
            goto try_remove;
    }
M
Mark McLoughlin 已提交
8245

8246
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8247 8248 8249
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (qemuMonitorAddDevice(priv->mon, nicstr) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
8250
            qemuDomainNetAudit(vm, NULL, net, "attach", false);
8251 8252 8253 8254 8255 8256
            goto try_remove;
        }
    } else {
        if (qemuMonitorAddPCINetwork(priv->mon, nicstr,
                                     &guestAddr) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
8257
            qemuDomainNetAudit(vm, NULL, net, "attach", false);
8258 8259 8260 8261
            goto try_remove;
        }
        net->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        memcpy(&net->info.addr.pci, &guestAddr, sizeof(guestAddr));
8262
    }
8263
    qemuDomainObjExitMonitorWithDriver(driver, vm);
8264

8265 8266
    qemuDomainNetAudit(vm, NULL, net, "attach", true);

8267
    ret = 0;
M
Mark McLoughlin 已提交
8268 8269 8270

    vm->def->nets[vm->def->nnets++] = net;

8271
cleanup:
8272 8273 8274 8275 8276 8277
    if ((ret != 0) &&
        (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) &&
        (net->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
        qemuDomainPCIAddressReleaseAddr(priv->pciaddrs, &net->info) < 0)
        VIR_WARN0("Unable to release PCI address on NIC");

8278
    if (ret != 0)
8279
        virDomainConfNWFilterTeardown(net);
S
Stefan Berger 已提交
8280

8281 8282 8283 8284 8285
    VIR_FREE(nicstr);
    VIR_FREE(netstr);
    VIR_FREE(tapfd_name);
    if (tapfd != -1)
        close(tapfd);
8286

8287
    return ret;
8288

8289
try_remove:
8290
    if (!virDomainObjIsActive(vm))
8291 8292
        goto cleanup;

8293
    if (vlan < 0) {
8294 8295 8296 8297 8298 8299 8300
        if ((qemuCmdFlags & QEMUD_CMD_FLAG_NETDEV) &&
            (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
            char *netdev_name;
            if (virAsprintf(&netdev_name, "host%s", net->info.alias) < 0)
                goto no_memory;
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            if (qemuMonitorRemoveNetdev(priv->mon, netdev_name) < 0)
8301
                VIR_WARN("Failed to remove network backend for netdev %s",
8302 8303 8304 8305
                         netdev_name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            VIR_FREE(netdev_name);
        } else {
8306
            VIR_WARN0("Unable to remove network backend");
8307
        }
8308 8309 8310 8311
    } else {
        char *hostnet_name;
        if (virAsprintf(&hostnet_name, "host%s", net->info.alias) < 0)
            goto no_memory;
8312
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
8313
        if (qemuMonitorRemoveHostNetwork(priv->mon, vlan, hostnet_name) < 0)
8314
            VIR_WARN("Failed to remove network backend for vlan %d, net %s",
8315
                     vlan, hostnet_name);
8316
        qemuDomainObjExitMonitorWithDriver(driver, vm);
8317
        VIR_FREE(hostnet_name);
8318
    }
8319
    goto cleanup;
8320

8321
try_tapfd_close:
8322
    if (!virDomainObjIsActive(vm))
8323 8324
        goto cleanup;

8325
    if (tapfd_name) {
8326
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
8327
        if (qemuMonitorCloseFileHandle(priv->mon, tapfd_name) < 0)
8328
            VIR_WARN("Failed to close tapfd with '%s'", tapfd_name);
8329
        qemuDomainObjExitMonitorWithDriver(driver, vm);
8330
    }
8331

8332 8333
    goto cleanup;

8334
no_memory:
8335
    virReportOOMError();
8336
    goto cleanup;
M
Mark McLoughlin 已提交
8337 8338
}

8339

8340
static int qemudDomainAttachHostPciDevice(struct qemud_driver *driver,
8341
                                          virDomainObjPtr vm,
8342
                                          virDomainHostdevDefPtr hostdev,
8343
                                          unsigned long long qemuCmdFlags)
8344
{
8345
    qemuDomainObjPrivatePtr priv = vm->privateData;
8346
    int ret;
8347
    char *devstr = NULL;
8348 8349
    int configfd = -1;
    char *configfd_name = NULL;
8350 8351

    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
8352
        virReportOOMError();
8353 8354 8355
        return -1;
    }

8356
    if (qemuPrepareHostdevPCIDevices(driver, &hostdev, 1) < 0)
8357
        return -1;
8358

8359
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
8360 8361
        if (qemuAssignDeviceHostdevAlias(vm->def, hostdev, -1) < 0)
            goto error;
8362 8363
        if (qemuDomainPCIAddressEnsureAddr(priv->pciaddrs, &hostdev->info) < 0)
            goto error;
8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387
        if (qemuCmdFlags & QEMUD_CMD_FLAG_PCI_CONFIGFD) {
            configfd = qemudOpenPCIConfig(hostdev);
            if (configfd >= 0) {
                if (virAsprintf(&configfd_name, "fd-%s",
                                hostdev->info.alias) < 0) {
                    virReportOOMError();
                    goto error;
                }

                qemuDomainObjEnterMonitorWithDriver(driver, vm);
                if (qemuMonitorSendFileHandle(priv->mon, configfd_name,
                                              configfd) < 0) {
                    qemuDomainObjExitMonitorWithDriver(driver, vm);
                    goto error;
                }
                qemuDomainObjExitMonitorWithDriver(driver, vm);
            }
        }

        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit during hotplug"));
            goto error;
        }
8388

8389
        if (!(devstr = qemuBuildPCIHostdevDevStr(hostdev, configfd_name)))
8390
            goto error;
8391

8392
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
8393
        ret = qemuMonitorAddDevice(priv->mon, devstr);
8394 8395 8396 8397 8398
        qemuDomainObjExitMonitorWithDriver(driver, vm);
    } else {
        virDomainDevicePCIAddress guestAddr;

        qemuDomainObjEnterMonitorWithDriver(driver, vm);
8399 8400 8401
        ret = qemuMonitorAddPCIHostDevice(priv->mon,
                                          &hostdev->source.subsys.u.pci,
                                          &guestAddr);
8402 8403 8404 8405 8406
        qemuDomainObjExitMonitorWithDriver(driver, vm);

        hostdev->info.type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
        memcpy(&hostdev->info.addr.pci, &guestAddr, sizeof(guestAddr));
    }
8407
    if (ret < 0)
8408
        goto error;
8409 8410 8411

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

8412
    VIR_FREE(devstr);
8413 8414 8415
    VIR_FREE(configfd_name);
    if (configfd >= 0)
        close(configfd);
8416

8417
    return 0;
8418 8419

error:
8420 8421 8422 8423 8424
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) &&
        (hostdev->info.type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) &&
        qemuDomainPCIAddressReleaseAddr(priv->pciaddrs, &hostdev->info) < 0)
        VIR_WARN0("Unable to release PCI address on host device");

8425
    qemuDomainReAttachHostdevDevices(driver, &hostdev, 1);
8426 8427

    VIR_FREE(devstr);
8428 8429 8430
    VIR_FREE(configfd_name);
    if (configfd >= 0)
        close(configfd);
8431 8432

    return -1;
8433 8434
}

8435

8436
static int qemudDomainAttachHostUsbDevice(struct qemud_driver *driver,
M
Mark McLoughlin 已提交
8437
                                          virDomainObjPtr vm,
8438
                                          virDomainHostdevDefPtr hostdev,
8439
                                          unsigned long long qemuCmdFlags)
8440 8441
{
    int ret;
8442
    qemuDomainObjPrivatePtr priv = vm->privateData;
8443 8444
    char *devstr = NULL;

8445 8446 8447 8448 8449 8450
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (qemuAssignDeviceHostdevAlias(vm->def, hostdev, -1) < 0)
            goto error;
        if (!(devstr = qemuBuildUSBHostdevDevStr(hostdev)))
            goto error;
    }
8451

8452
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
8453
        virReportOOMError();
8454
        goto error;
8455
    }
8456

8457
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8458 8459 8460
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)
        ret = qemuMonitorAddDevice(priv->mon, devstr);
    else
8461
        ret = qemuMonitorAddUSBDeviceExact(priv->mon,
8462 8463
                                           hostdev->source.subsys.u.usb.bus,
                                           hostdev->source.subsys.u.usb.device);
8464
    qemuDomainObjExitMonitorWithDriver(driver, vm);
8465 8466 8467 8468
    if (ret < 0)
        goto error;

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

8470
    VIR_FREE(devstr);
8471

8472 8473 8474 8475 8476
    return 0;

error:
    VIR_FREE(devstr);
    return -1;
8477 8478
}

8479

8480
static int qemudDomainAttachHostDevice(struct qemud_driver *driver,
M
Mark McLoughlin 已提交
8481
                                       virDomainObjPtr vm,
8482
                                       virDomainHostdevDefPtr hostdev,
8483
                                       unsigned long long qemuCmdFlags)
M
Mark McLoughlin 已提交
8484 8485
{
    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
8486
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8487 8488
                        _("hostdev mode '%s' not supported"),
                        virDomainHostdevModeTypeToString(hostdev->mode));
M
Mark McLoughlin 已提交
8489 8490 8491
        return -1;
    }

8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508
    /* Resolve USB product/vendor to bus/device */
    if (hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB &&
        hostdev->source.subsys.u.usb.vendor) {
        usbDevice *usb
            = usbFindDevice(hostdev->source.subsys.u.usb.vendor,
                            hostdev->source.subsys.u.usb.product);

        if (!usb)
            return -1;

        hostdev->source.subsys.u.usb.bus = usbDeviceGetBus(usb);
        hostdev->source.subsys.u.usb.device = usbDeviceGetDevno(usb);

        usbFreeDevice(usb);
    }


8509
    if (driver->securityDriver &&
8510
        driver->securityDriver->domainSetSecurityHostdevLabel &&
8511 8512
        driver->securityDriver->domainSetSecurityHostdevLabel(driver->securityDriver,
                                                              vm, hostdev) < 0)
8513
        return -1;
M
Mark McLoughlin 已提交
8514 8515

    switch (hostdev->source.subsys.type) {
8516
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
8517
        if (qemudDomainAttachHostPciDevice(driver, vm,
8518
                                           hostdev, qemuCmdFlags) < 0)
8519 8520 8521
            goto error;
        break;

M
Mark McLoughlin 已提交
8522
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
8523
        if (qemudDomainAttachHostUsbDevice(driver, vm,
8524
                                           hostdev, qemuCmdFlags) < 0)
8525 8526 8527
            goto error;
        break;

M
Mark McLoughlin 已提交
8528
    default:
8529
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8530 8531
                        _("hostdev subsys type '%s' not supported"),
                        virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
8532
        goto error;
M
Mark McLoughlin 已提交
8533
    }
8534 8535 8536 8537 8538 8539

    return 0;

error:
    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSecurityHostdevLabel &&
8540 8541
        driver->securityDriver->domainRestoreSecurityHostdevLabel(driver->securityDriver,
                                                                  vm, hostdev) < 0)
8542 8543 8544
        VIR_WARN0("Unable to restore host device labelling on hotplug fail");

    return -1;
M
Mark McLoughlin 已提交
8545 8546
}

8547

8548
static int qemudDomainAttachDevice(virDomainPtr dom,
8549 8550
                                   const char *xml)
{
8551 8552 8553
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
8554
    unsigned long long qemuCmdFlags;
8555
    virCgroupPtr cgroup = NULL;
8556
    int ret = -1;
8557

8558
    qemuDriverLock(driver);
8559
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
8560
    if (!vm) {
8561 8562
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
8563 8564
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
8565
        goto cleanup;
8566 8567
    }

8568 8569 8570
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
8571
    if (!virDomainObjIsActive(vm)) {
8572 8573
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot attach device on inactive domain"));
8574
        goto endjob;
8575 8576
    }

8577
    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
8578
                                  VIR_DOMAIN_XML_INACTIVE);
8579
    if (dev == NULL)
8580
        goto endjob;
8581

8582 8583 8584
    if (qemudExtractVersionInfo(vm->def->emulator,
                                NULL,
                                &qemuCmdFlags) < 0)
8585
        goto endjob;
8586

8587
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
8588
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
8589
            if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) !=0 ) {
8590 8591 8592
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Unable to find cgroup for %s\n"),
                                vm->def->name);
8593
                goto endjob;
8594
            }
8595
            if (qemuSetupDiskCgroup(driver, cgroup, dev->data.disk) < 0)
8596
                goto endjob;
8597 8598
        }

8599
        switch (dev->data.disk->device) {
8600 8601
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
8602 8603 8604
            ret = qemudDomainChangeEjectableMedia(driver, vm,
                                                  dev->data.disk,
                                                  qemuCmdFlags);
8605 8606
            if (ret == 0)
                dev->data.disk = NULL;
8607
            break;
8608

8609 8610
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
8611
                ret = qemudDomainAttachUsbMassstorageDevice(driver, vm,
8612
                                                            dev->data.disk, qemuCmdFlags);
8613 8614
                if (ret == 0)
                    dev->data.disk = NULL;
8615
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
8616
                ret = qemudDomainAttachPciDiskDevice(driver, vm,
8617
                                                     dev->data.disk, qemuCmdFlags);
8618 8619
                if (ret == 0)
                    dev->data.disk = NULL;
8620
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
8621
                ret = qemudDomainAttachSCSIDisk(driver, vm,
8622
                                                dev->data.disk, qemuCmdFlags);
8623 8624
                if (ret == 0)
                    dev->data.disk = NULL;
8625
            } else {
8626
                qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8627 8628
                                _("disk bus '%s' cannot be hotplugged."),
                                virDomainDiskBusTypeToString(dev->data.disk->bus));
8629
                /* fallthrough */
8630 8631
            }
            break;
8632

8633
        default:
8634
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8635 8636
                            _("disk device type '%s' cannot be hotplugged"),
                            virDomainDiskDeviceTypeToString(dev->data.disk->device));
8637 8638
            /* Fallthrough */
        }
8639
        if (ret != 0 && cgroup) {
8640
            if (qemuTeardownDiskCgroup(driver, cgroup, dev->data.disk) < 0)
8641 8642
                VIR_WARN("Failed to teardown cgroup for disk path %s",
                         NULLSTR(dev->data.disk->src));
8643
        }
8644 8645
    } else if (dev->type == VIR_DOMAIN_DEVICE_CONTROLLER) {
        if (dev->data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
8646
            ret = qemudDomainAttachPciControllerDevice(driver, vm,
8647
                                                       dev->data.controller, qemuCmdFlags);
8648 8649
            if (ret == 0)
                dev->data.controller = NULL;
8650
        } else {
8651
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8652 8653
                            _("disk controller bus '%s' cannot be hotplugged."),
                            virDomainControllerTypeToString(dev->data.controller->type));
8654 8655
            /* fallthrough */
        }
M
Mark McLoughlin 已提交
8656
    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
8657 8658
        ret = qemudDomainAttachNetDevice(dom->conn, driver, vm,
                                         dev->data.net, qemuCmdFlags);
8659 8660
        if (ret == 0)
            dev->data.net = NULL;
M
Mark McLoughlin 已提交
8661
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
8662
        ret = qemudDomainAttachHostDevice(driver, vm,
8663
                                          dev->data.hostdev, qemuCmdFlags);
8664 8665
        if (ret == 0)
            dev->data.hostdev = NULL;
8666
    } else {
8667
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8668 8669
                        _("device type '%s' cannot be attached"),
                        virDomainDeviceTypeToString(dev->type));
8670
        goto endjob;
8671 8672
    }

8673
    if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
8674 8675
        ret = -1;

8676
endjob:
8677 8678
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
8679

8680
cleanup:
8681 8682 8683
    if (cgroup)
        virCgroupFree(&cgroup);

8684
    virDomainDeviceDefFree(dev);
8685 8686
    if (vm)
        virDomainObjUnlock(vm);
8687
    qemuDriverUnlock(driver);
8688 8689 8690
    return ret;
}

8691 8692 8693 8694
static int qemudDomainAttachDeviceFlags(virDomainPtr dom,
                                        const char *xml,
                                        unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
8695 8696
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify the persistent configuration of a domain"));
8697 8698 8699 8700 8701 8702
        return -1;
    }

    return qemudDomainAttachDevice(dom, xml);
}

8703

8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780
static virDomainGraphicsDefPtr qemuDomainFindGraphics(virDomainObjPtr vm,
                                                      virDomainGraphicsDefPtr dev)
{
    int i;

    for (i = 0 ; i < vm->def->ngraphics ; i++) {
        if (vm->def->graphics[i]->type == dev->type)
            return vm->def->graphics[i];
    }

    return NULL;
}


static int
qemuDomainChangeGraphics(struct qemud_driver *driver,
                         virDomainObjPtr vm,
                         virDomainGraphicsDefPtr dev)
{
    virDomainGraphicsDefPtr olddev = qemuDomainFindGraphics(vm, dev);
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = -1;

    if (!olddev) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cannot find existing graphics device to modify"));
        return -1;
    }

    switch (dev->type) {
    case VIR_DOMAIN_GRAPHICS_TYPE_VNC:
        if ((olddev->data.vnc.autoport != dev->data.vnc.autoport) ||
            (!dev->data.vnc.autoport && (olddev->data.vnc.port != dev->data.vnc.port))) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("cannot change port settings on vnc graphics"));
            return -1;
        }
        if (STRNEQ_NULLABLE(olddev->data.vnc.listenAddr, dev->data.vnc.listenAddr)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("cannot change listen address setting on vnc graphics"));
            return -1;
        }
        if (STRNEQ_NULLABLE(olddev->data.vnc.keymap, dev->data.vnc.keymap)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("cannot change keymap setting on vnc graphics"));
            return -1;
        }

        if (STRNEQ_NULLABLE(olddev->data.vnc.passwd, dev->data.vnc.passwd)) {
            VIR_DEBUG("Updating password on VNC server %p %p", dev->data.vnc.passwd, driver->vncPassword);
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            ret = qemuMonitorSetVNCPassword(priv->mon,
                                            dev->data.vnc.passwd ?
                                            dev->data.vnc.passwd :
                                            driver->vncPassword);
            qemuDomainObjExitMonitorWithDriver(driver, vm);

            /* Steal the new dev's  char * reference */
            VIR_FREE(olddev->data.vnc.passwd);
            olddev->data.vnc.passwd = dev->data.vnc.passwd;
            dev->data.vnc.passwd = NULL;
        } else {
            ret = 0;
        }
        break;

    default:
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("unable to change config on '%s' graphics type"),
                        virDomainGraphicsTypeToString(dev->type));
        break;
    }

    return ret;
}


8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
                                       const char *xml,
                                       unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    unsigned long long qemuCmdFlags;
    virCgroupPtr cgroup = NULL;
    int ret = -1;

8792 8793 8794 8795
    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_CURRENT |
                  VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot attach device on inactive domain"));
        goto endjob;
    }

    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL)
        goto endjob;

    if (qemudExtractVersionInfo(vm->def->emulator,
                                NULL,
                                &qemuCmdFlags) < 0)
        goto endjob;

    switch (dev->type) {
    case VIR_DOMAIN_DEVICE_DISK:
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
            if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) !=0 ) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                _("Unable to find cgroup for %s\n"),
                                vm->def->name);
                goto endjob;
            }
8840
            if (qemuSetupDiskCgroup(driver, cgroup, dev->data.disk) < 0)
8841 8842 8843 8844 8845 8846
                goto endjob;
        }

        switch (dev->data.disk->device) {
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
8847 8848 8849
            ret = qemudDomainChangeEjectableMedia(driver, vm,
                                                  dev->data.disk,
                                                  qemuCmdFlags);
8850 8851 8852 8853 8854 8855
            if (ret == 0)
                dev->data.disk = NULL;
            break;


        default:
8856
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8857 8858 8859 8860 8861 8862
                            _("disk bus '%s' cannot be updated."),
                            virDomainDiskBusTypeToString(dev->data.disk->bus));
            break;
        }

        if (ret != 0 && cgroup) {
8863
            if (qemuTeardownDiskCgroup(driver, cgroup, dev->data.disk) < 0)
8864 8865
                VIR_WARN("Failed to teardown cgroup for disk path %s",
                         NULLSTR(dev->data.disk->src));
8866 8867 8868
        }
        break;

8869 8870 8871 8872
    case VIR_DOMAIN_DEVICE_GRAPHICS:
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
        break;

8873
    default:
8874
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898
                        _("disk device type '%s' cannot be updated"),
                        virDomainDiskDeviceTypeToString(dev->data.disk->device));
        break;
    }

    if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
        ret = -1;

endjob:
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

cleanup:
    if (cgroup)
        virCgroupFree(&cgroup);

    virDomainDeviceDefFree(dev);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}


E
Eric Blake 已提交
8899
static inline int qemudFindDisk(virDomainDefPtr def, const char *dst)
W
Wolfgang Mauerer 已提交
8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912
{
    int i;

    for (i = 0 ; i < def->ndisks ; i++) {
        if (STREQ(def->disks[i]->dst, dst)) {
            return i;
        }
    }

    return -1;
}


8913
static int qemudDomainDetachPciDiskDevice(struct qemud_driver *driver,
8914
                                          virDomainObjPtr vm,
8915 8916
                                          virDomainDeviceDefPtr dev,
                                          unsigned long long qemuCmdFlags)
8917 8918 8919
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
8920
    qemuDomainObjPrivatePtr priv = vm->privateData;
8921
    virCgroupPtr cgroup = NULL;
8922

W
Wolfgang Mauerer 已提交
8923
    i = qemudFindDisk(vm->def, dev->data.disk->dst);
8924

W
Wolfgang Mauerer 已提交
8925
    if (i < 0) {
8926 8927
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("disk %s not found"), dev->data.disk->dst);
8928
        goto cleanup;
8929 8930
    }

W
Wolfgang Mauerer 已提交
8931 8932
    detach = vm->def->disks[i];

8933 8934 8935 8936 8937 8938 8939 8940 8941
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Unable to find cgroup for %s\n"),
                            vm->def->name);
            goto cleanup;
        }
    }

8942 8943
    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
8944 8945
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("device cannot be detached without a PCI address"));
8946
        goto cleanup;
8947 8948
    }

8949
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
            qemuDomainObjExitMonitor(vm);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
            qemuDomainObjExitMonitor(vm);
            goto cleanup;
        }
8961
    }
8962
    qemuDomainObjExitMonitorWithDriver(driver, vm);
8963

8964 8965
    qemuDomainDiskAudit(vm, detach, NULL, "detach", ret >= 0);

8966 8967 8968 8969
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) &&
        qemuDomainPCIAddressReleaseAddr(priv->pciaddrs, &detach->info) < 0)
        VIR_WARN("Unable to release PCI address on %s", dev->data.disk->src);

8970
    virDomainDiskRemove(vm->def, i);
W
Wolfgang Mauerer 已提交
8971

8972 8973
    virDomainDiskDefFree(detach);

8974 8975
    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSecurityImageLabel &&
8976 8977
        driver->securityDriver->domainRestoreSecurityImageLabel(driver->securityDriver,
                                                                vm, dev->data.disk) < 0)
8978 8979
        VIR_WARN("Unable to restore security label on %s", dev->data.disk->src);

8980
    if (cgroup != NULL) {
8981
        if (qemuTeardownDiskCgroup(driver, cgroup, dev->data.disk) < 0)
8982 8983 8984 8985
            VIR_WARN("Failed to teardown cgroup for disk path %s",
                     NULLSTR(dev->data.disk->src));
    }

8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999
    ret = 0;

cleanup:
    return ret;
}

static int qemudDomainDetachSCSIDiskDevice(struct qemud_driver *driver,
                                           virDomainObjPtr vm,
                                           virDomainDeviceDefPtr dev,
                                           unsigned long long qemuCmdFlags)
{
    int i, ret = -1;
    virDomainDiskDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
9000
    virCgroupPtr cgroup = NULL;
9001 9002 9003 9004 9005 9006 9007 9008 9009 9010

    i = qemudFindDisk(vm->def, dev->data.disk->dst);

    if (i < 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("disk %s not found"), dev->data.disk->dst);
        goto cleanup;
    }

    if (!(qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
9011
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
9012 9013 9014 9015 9016 9017
                        _("Underlying qemu does not support SCSI disk removal"));
        goto cleanup;
    }

    detach = vm->def->disks[i];

9018 9019 9020 9021 9022 9023 9024 9025 9026
    if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("Unable to find cgroup for %s\n"),
                            vm->def->name);
            goto cleanup;
        }
    }

9027 9028 9029 9030 9031 9032 9033
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
        qemuDomainObjExitMonitor(vm);
        goto cleanup;
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

9034 9035
    qemuDomainDiskAudit(vm, detach, NULL, "detach", ret >= 0);

9036
    virDomainDiskRemove(vm->def, i);
9037

9038
    virDomainDiskDefFree(detach);
9039

9040 9041
    if (driver->securityDriver &&
        driver->securityDriver->domainRestoreSecurityImageLabel &&
9042 9043
        driver->securityDriver->domainRestoreSecurityImageLabel(driver->securityDriver,
                                                                vm, dev->data.disk) < 0)
9044 9045
        VIR_WARN("Unable to restore security label on %s", dev->data.disk->src);

9046
    if (cgroup != NULL) {
9047
        if (qemuTeardownDiskCgroup(driver, cgroup, dev->data.disk) < 0)
9048 9049 9050 9051
            VIR_WARN("Failed to teardown cgroup for disk path %s",
                     NULLSTR(dev->data.disk->src));
    }

9052
    ret = 0;
9053 9054

cleanup:
9055
    virCgroupFree(&cgroup);
9056 9057 9058
    return ret;
}

9059
static int qemudDomainDetachPciControllerDevice(struct qemud_driver *driver,
9060
                                                virDomainObjPtr vm,
9061 9062
                                                virDomainDeviceDefPtr dev,
                                                unsigned long long qemuCmdFlags)
9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076
{
    int i, ret = -1;
    virDomainControllerDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;

    for (i = 0 ; i < vm->def->ncontrollers ; i++) {
        if ((vm->def->controllers[i]->type == dev->data.controller->type) &&
            (vm->def->controllers[i]->idx == dev->data.controller->idx)) {
            detach = vm->def->controllers[i];
            break;
        }
    }

    if (!detach) {
9077 9078 9079 9080
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("disk controller %s:%d not found"),
                        virDomainControllerTypeToString(dev->data.controller->type),
                        dev->data.controller->idx);
9081 9082 9083 9084 9085
        goto cleanup;
    }

    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
9086 9087
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("device cannot be detached without a PCI address"));
9088 9089 9090
        goto cleanup;
    }

9091 9092 9093 9094 9095
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (qemuAssignDeviceControllerAlias(detach) < 0)
            goto cleanup;
    }

9096
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias)) {
            qemuDomainObjExitMonitor(vm);
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
            qemuDomainObjExitMonitor(vm);
            goto cleanup;
        }
9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    if (vm->def->ncontrollers > 1) {
        memmove(vm->def->controllers + i,
                vm->def->controllers + i + 1,
                sizeof(*vm->def->controllers) *
                (vm->def->ncontrollers - (i + 1)));
        vm->def->ncontrollers--;
        if (VIR_REALLOC_N(vm->def->controllers, vm->def->ncontrollers) < 0) {
            /* ignore, harmless */
        }
    } else {
        VIR_FREE(vm->def->controllers);
        vm->def->ncontrollers = 0;
    }
9124

9125 9126
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) &&
        qemuDomainPCIAddressReleaseAddr(priv->pciaddrs, &detach->info) < 0)
9127 9128
        VIR_WARN0("Unable to release PCI address on controller");

9129 9130 9131 9132 9133 9134 9135 9136
    virDomainControllerDefFree(detach);

    ret = 0;

cleanup:
    return ret;
}

9137
static int
9138
qemudDomainDetachNetDevice(struct qemud_driver *driver,
9139
                           virDomainObjPtr vm,
9140 9141
                           virDomainDeviceDefPtr dev,
                           unsigned long long qemuCmdFlags)
9142 9143 9144
{
    int i, ret = -1;
    virDomainNetDefPtr detach = NULL;
9145
    qemuDomainObjPrivatePtr priv = vm->privateData;
9146 9147
    int vlan;
    char *hostnet_name = NULL;
9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158

    for (i = 0 ; i < vm->def->nnets ; i++) {
        virDomainNetDefPtr net = vm->def->nets[i];

        if (!memcmp(net->mac, dev->data.net->mac,  sizeof(net->mac))) {
            detach = net;
            break;
        }
    }

    if (!detach) {
9159 9160 9161 9162 9163
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("network device %02x:%02x:%02x:%02x:%02x:%02x not found"),
                        dev->data.net->mac[0], dev->data.net->mac[1],
                        dev->data.net->mac[2], dev->data.net->mac[3],
                        dev->data.net->mac[4], dev->data.net->mac[5]);
9164 9165 9166
        goto cleanup;
    }

9167 9168
    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
9169 9170
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("device cannot be detached without a PCI address"));
9171 9172 9173
        goto cleanup;
    }

9174
    if ((vlan = qemuDomainNetVLAN(detach)) < 0) {
9175 9176
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("unable to determine original VLAN"));
9177 9178 9179 9180
        goto cleanup;
    }

    if (virAsprintf(&hostnet_name, "host%s", detach->info.alias) < 0) {
9181
        virReportOOMError();
9182 9183 9184
        goto cleanup;
    }

9185
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
9186 9187 9188
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
            qemuDomainObjExitMonitor(vm);
9189
            qemuDomainNetAudit(vm, detach, NULL, "detach", false);
9190 9191 9192 9193 9194 9195
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
9196
            qemuDomainNetAudit(vm, detach, NULL, "detach", false);
9197 9198
            goto cleanup;
        }
9199
    }
9200

9201 9202 9203 9204
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_NETDEV) &&
        (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
        if (qemuMonitorRemoveNetdev(priv->mon, hostnet_name) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
9205
            qemuDomainNetAudit(vm, detach, NULL, "detach", false);
9206 9207 9208 9209 9210
            goto cleanup;
        }
    } else {
        if (qemuMonitorRemoveHostNetwork(priv->mon, vlan, hostnet_name) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
9211
            qemuDomainNetAudit(vm, detach, NULL, "detach", false);
9212 9213
            goto cleanup;
        }
9214
    }
9215
    qemuDomainObjExitMonitorWithDriver(driver, vm);
9216

9217 9218
    qemuDomainNetAudit(vm, detach, NULL, "detach", true);

9219 9220 9221 9222
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) &&
        qemuDomainPCIAddressReleaseAddr(priv->pciaddrs, &detach->info) < 0)
        VIR_WARN0("Unable to release PCI address on NIC");

9223
    virDomainConfNWFilterTeardown(detach);
9224

9225
#if WITH_MACVTAP
9226
    if (detach->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
9227
        delMacvtap(detach->ifname, detach->mac, detach->data.direct.linkdev,
9228
                   &detach->data.direct.virtPortProfile);
9229 9230
        VIR_FREE(detach->ifname);
    }
9231 9232
#endif

9233
    if ((driver->macFilter) && (detach->ifname != NULL)) {
9234
        if ((errno = networkDisallowMacOnPort(driver,
9235 9236
                                              detach->ifname,
                                              detach->mac))) {
9237
            virReportSystemError(errno,
9238 9239 9240 9241 9242
             _("failed to remove ebtables rule on  '%s'"),
                                 detach->ifname);
        }
    }

9243 9244 9245 9246 9247 9248 9249 9250 9251 9252
    if (vm->def->nnets > 1) {
        memmove(vm->def->nets + i,
                vm->def->nets + i + 1,
                sizeof(*vm->def->nets) *
                (vm->def->nnets - (i + 1)));
        vm->def->nnets--;
        if (VIR_REALLOC_N(vm->def->nets, vm->def->nnets) < 0) {
            /* ignore, harmless */
        }
    } else {
9253
        VIR_FREE(vm->def->nets);
9254
        vm->def->nnets = 0;
9255
    }
9256
    virDomainNetDefFree(detach);
9257

9258 9259 9260
    ret = 0;

cleanup:
9261
    VIR_FREE(hostnet_name);
9262 9263 9264
    return ret;
}

9265
static int qemudDomainDetachHostPciDevice(struct qemud_driver *driver,
9266
                                          virDomainObjPtr vm,
9267 9268
                                          virDomainDeviceDefPtr dev,
                                          unsigned long long qemuCmdFlags)
9269
{
9270
    virDomainHostdevDefPtr detach = NULL;
9271
    qemuDomainObjPrivatePtr priv = vm->privateData;
9272
    int i, ret;
9273
    pciDevice *pci;
9274 9275

    for (i = 0 ; i < vm->def->nhostdevs ; i++) {
9276 9277 9278 9279
        if (vm->def->hostdevs[i]->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
            vm->def->hostdevs[i]->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
            continue;

9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294
        unsigned domain   = vm->def->hostdevs[i]->source.subsys.u.pci.domain;
        unsigned bus      = vm->def->hostdevs[i]->source.subsys.u.pci.bus;
        unsigned slot     = vm->def->hostdevs[i]->source.subsys.u.pci.slot;
        unsigned function = vm->def->hostdevs[i]->source.subsys.u.pci.function;

        if (dev->data.hostdev->source.subsys.u.pci.domain   == domain &&
            dev->data.hostdev->source.subsys.u.pci.bus      == bus &&
            dev->data.hostdev->source.subsys.u.pci.slot     == slot &&
            dev->data.hostdev->source.subsys.u.pci.function == function) {
            detach = vm->def->hostdevs[i];
            break;
        }
    }

    if (!detach) {
9295 9296 9297 9298 9299 9300
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("host pci device %.4x:%.2x:%.2x.%.1x not found"),
                        dev->data.hostdev->source.subsys.u.pci.domain,
                        dev->data.hostdev->source.subsys.u.pci.bus,
                        dev->data.hostdev->source.subsys.u.pci.slot,
                        dev->data.hostdev->source.subsys.u.pci.function);
9301 9302 9303
        return -1;
    }

9304 9305
    if (!virDomainDeviceAddressIsValid(&detach->info,
                                       VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI)) {
9306 9307
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("device cannot be detached without a PCI address"));
9308 9309 9310
        return -1;
    }

9311
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
        if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
            qemuDomainObjExitMonitor(vm);
            return -1;
        }
    } else {
        if (qemuMonitorRemovePCIDevice(priv->mon,
                                       &detach->info.addr.pci) < 0) {
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            return -1;
        }
9323
    }
9324
    qemuDomainObjExitMonitorWithDriver(driver, vm);
9325 9326 9327

    ret = 0;

9328
    pci = pciGetDevice(detach->source.subsys.u.pci.domain,
9329 9330 9331 9332 9333 9334
                       detach->source.subsys.u.pci.bus,
                       detach->source.subsys.u.pci.slot,
                       detach->source.subsys.u.pci.function);
    if (!pci)
        ret = -1;
    else {
9335
        pciDeviceSetManaged(pci, detach->managed);
9336
        pciDeviceListDel(driver->activePciHostdevs, pci);
9337
        if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
9338
            ret = -1;
9339
        qemudReattachPciDevice(pci, driver);
9340
        pciFreeDevice(pci);
9341 9342
    }

9343 9344
    if ((qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) &&
        qemuDomainPCIAddressReleaseAddr(priv->pciaddrs, &detach->info) < 0)
9345
        VIR_WARN0("Unable to release PCI address on host device");
9346

9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358
    if (vm->def->nhostdevs > 1) {
        memmove(vm->def->hostdevs + i,
                vm->def->hostdevs + i + 1,
                sizeof(*vm->def->hostdevs) *
                (vm->def->nhostdevs - (i + 1)));
        vm->def->nhostdevs--;
        if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs) < 0) {
            /* ignore, harmless */
        }
    } else {
        VIR_FREE(vm->def->hostdevs);
        vm->def->nhostdevs = 0;
9359
    }
9360
    virDomainHostdevDefFree(detach);
9361 9362 9363 9364

    return ret;
}

9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380
static int qemudDomainDetachHostUsbDevice(struct qemud_driver *driver,
                                          virDomainObjPtr vm,
                                          virDomainDeviceDefPtr dev,
                                          unsigned long long qemuCmdFlags)
{
    virDomainHostdevDefPtr detach = NULL;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int i, ret;

    for (i = 0 ; i < vm->def->nhostdevs ; i++) {
        if (vm->def->hostdevs[i]->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
            vm->def->hostdevs[i]->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
            continue;

        unsigned bus = vm->def->hostdevs[i]->source.subsys.u.usb.bus;
        unsigned device = vm->def->hostdevs[i]->source.subsys.u.usb.device;
9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396
        unsigned product = vm->def->hostdevs[i]->source.subsys.u.usb.product;
        unsigned vendor = vm->def->hostdevs[i]->source.subsys.u.usb.vendor;

        if (dev->data.hostdev->source.subsys.u.usb.bus &&
            dev->data.hostdev->source.subsys.u.usb.device) {
            if (dev->data.hostdev->source.subsys.u.usb.bus == bus &&
                dev->data.hostdev->source.subsys.u.usb.device == device) {
                detach = vm->def->hostdevs[i];
                break;
            }
        } else {
            if (dev->data.hostdev->source.subsys.u.usb.product == product &&
                dev->data.hostdev->source.subsys.u.usb.vendor == vendor) {
                detach = vm->def->hostdevs[i];
                break;
            }
9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446
        }
    }

    if (!detach) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("host usb device %03d.%03d not found"),
                        dev->data.hostdev->source.subsys.u.usb.bus,
                        dev->data.hostdev->source.subsys.u.usb.device);
        return -1;
    }

    if (!detach->info.alias) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("device cannot be detached without a device alias"));
        return -1;
    }

    if (!(qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("device cannot be detached with this QEMU version"));
        return -1;
    }

    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    if (qemuMonitorDelDevice(priv->mon, detach->info.alias) < 0) {
        qemuDomainObjExitMonitorWithDriver(driver, vm);
        return -1;
    }
    qemuDomainObjExitMonitorWithDriver(driver, vm);

    ret = 0;

    if (vm->def->nhostdevs > 1) {
        memmove(vm->def->hostdevs + i,
                vm->def->hostdevs + i + 1,
                sizeof(*vm->def->hostdevs) *
                (vm->def->nhostdevs - (i + 1)));
        vm->def->nhostdevs--;
        if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs) < 0) {
            /* ignore, harmless */
        }
    } else {
        VIR_FREE(vm->def->hostdevs);
        vm->def->nhostdevs = 0;
    }
    virDomainHostdevDefFree(detach);

    return ret;
}

9447
static int qemudDomainDetachHostDevice(struct qemud_driver *driver,
9448
                                       virDomainObjPtr vm,
9449 9450
                                       virDomainDeviceDefPtr dev,
                                       unsigned long long qemuCmdFlags)
9451 9452 9453 9454 9455
{
    virDomainHostdevDefPtr hostdev = dev->data.hostdev;
    int ret;

    if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
9456
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9457 9458
                        _("hostdev mode '%s' not supported"),
                        virDomainHostdevModeTypeToString(hostdev->mode));
9459 9460 9461 9462 9463
        return -1;
    }

    switch (hostdev->source.subsys.type) {
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI:
9464
        ret = qemudDomainDetachHostPciDevice(driver, vm, dev, qemuCmdFlags);
9465
        break;
9466 9467 9468
    case VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB:
        ret = qemudDomainDetachHostUsbDevice(driver, vm, dev, qemuCmdFlags);
        break;
9469
    default:
9470
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9471 9472
                        _("hostdev subsys type '%s' not supported"),
                        virDomainHostdevSubsysTypeToString(hostdev->source.subsys.type));
9473 9474 9475
        return -1;
    }

9476
    if (driver->securityDriver &&
9477
        driver->securityDriver->domainRestoreSecurityHostdevLabel &&
9478 9479
        driver->securityDriver->domainRestoreSecurityHostdevLabel(driver->securityDriver,
                                                                  vm, dev->data.hostdev) < 0)
9480
        VIR_WARN0("Failed to restore host device labelling");
9481

9482 9483 9484
    return ret;
}

9485 9486
static int qemudDomainDetachDevice(virDomainPtr dom,
                                   const char *xml) {
9487 9488
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
9489
    unsigned long long qemuCmdFlags;
9490 9491
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
9492

9493
    qemuDriverLock(driver);
9494
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9495
    if (!vm) {
9496 9497
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
9498 9499
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
9500
        goto cleanup;
9501 9502
    }

9503 9504 9505
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
9506
    if (!virDomainObjIsActive(vm)) {
9507 9508
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot detach device on inactive domain"));
9509
        goto endjob;
9510 9511
    }

9512
    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
9513
                                  VIR_DOMAIN_XML_INACTIVE);
9514
    if (dev == NULL)
9515
        goto endjob;
9516

9517 9518 9519 9520
    if (qemudExtractVersionInfo(vm->def->emulator,
                                NULL,
                                &qemuCmdFlags) < 0)
        goto endjob;
9521 9522

    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
9523 9524 9525 9526 9527 9528 9529 9530 9531
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
        if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
            ret = qemudDomainDetachPciDiskDevice(driver, vm, dev, qemuCmdFlags);
        }
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
            ret = qemudDomainDetachSCSIDiskDevice(driver, vm, dev,
                                                  qemuCmdFlags);
        }
        else {
9532
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
9533 9534
                            _("This type of disk cannot be hot unplugged"));
        }
9535
    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
9536
        ret = qemudDomainDetachNetDevice(driver, vm, dev, qemuCmdFlags);
9537 9538
    } else if (dev->type == VIR_DOMAIN_DEVICE_CONTROLLER) {
        if (dev->data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
9539 9540
            ret = qemudDomainDetachPciControllerDevice(driver, vm, dev,
                                                       qemuCmdFlags);
9541
        } else {
9542
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9543 9544
                            _("disk controller bus '%s' cannot be hotunplugged."),
                            virDomainControllerTypeToString(dev->data.controller->type));
9545 9546
            /* fallthrough */
        }
9547
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
9548
        ret = qemudDomainDetachHostDevice(driver, vm, dev, qemuCmdFlags);
9549
    } else {
9550
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
9551
                        "%s", _("This type of device cannot be hot unplugged"));
9552
    }
9553

9554
    if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
9555 9556
        ret = -1;

9557
endjob:
9558 9559
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
9560

9561 9562
cleanup:
    virDomainDeviceDefFree(dev);
9563 9564
    if (vm)
        virDomainObjUnlock(vm);
9565
    qemuDriverUnlock(driver);
9566 9567 9568
    return ret;
}

9569 9570 9571 9572
static int qemudDomainDetachDeviceFlags(virDomainPtr dom,
                                        const char *xml,
                                        unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
9573 9574
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("cannot modify the persistent configuration of a domain"));
9575 9576 9577 9578 9579 9580
        return -1;
    }

    return qemudDomainDetachDevice(dom, xml);
}

9581
static int qemudDomainGetAutostart(virDomainPtr dom,
9582
                                   int *autostart) {
9583 9584 9585
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
9586

9587
    qemuDriverLock(driver);
9588
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9589 9590
    qemuDriverUnlock(driver);

9591
    if (!vm) {
9592 9593
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
9594 9595
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
9596
        goto cleanup;
9597 9598 9599
    }

    *autostart = vm->autostart;
9600
    ret = 0;
9601

9602
cleanup:
9603 9604
    if (vm)
        virDomainObjUnlock(vm);
9605
    return ret;
9606 9607
}

9608
static int qemudDomainSetAutostart(virDomainPtr dom,
9609
                                   int autostart) {
9610 9611
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
9612 9613
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
9614

9615
    qemuDriverLock(driver);
9616
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9617

9618
    if (!vm) {
9619 9620
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
9621 9622
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
9623
        goto cleanup;
9624 9625
    }

9626
    if (!vm->persistent) {
9627 9628
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("cannot set autostart for transient domain"));
9629
        goto cleanup;
9630 9631
    }

9632 9633
    autostart = (autostart != 0);

9634
    if (vm->autostart != autostart) {
9635
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
9636
            goto cleanup;
9637
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
9638
            goto cleanup;
9639

9640 9641
        if (autostart) {
            int err;
9642

9643
            if ((err = virFileMakePath(driver->autostartDir))) {
9644
                virReportSystemError(err,
9645 9646
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
9647 9648
                goto cleanup;
            }
9649

9650
            if (symlink(configFile, autostartLink) < 0) {
9651
                virReportSystemError(errno,
9652 9653
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
9654 9655 9656 9657
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
9658
                virReportSystemError(errno,
9659 9660
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
9661 9662
                goto cleanup;
            }
9663 9664
        }

9665
        vm->autostart = autostart;
9666
    }
9667
    ret = 0;
9668

9669 9670 9671
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
9672 9673
    if (vm)
        virDomainObjUnlock(vm);
9674
    qemuDriverUnlock(driver);
9675
    return ret;
9676 9677
}

9678 9679 9680 9681 9682

static char *qemuGetSchedulerType(virDomainPtr dom,
                                  int *nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
9683
    char *ret = NULL;
9684

9685
    qemuDriverLock(driver);
9686
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
9687 9688
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        __FUNCTION__);
9689
        goto cleanup;
9690 9691 9692 9693 9694 9695 9696
    }

    if (nparams)
        *nparams = 1;

    ret = strdup("posix");
    if (!ret)
9697
        virReportOOMError();
9698 9699 9700

cleanup:
    qemuDriverUnlock(driver);
9701 9702 9703
    return ret;
}

9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770

static int qemuDomainSetMemoryParameters(virDomainPtr dom,
                                         virMemoryParameterPtr params,
                                         int nparams,
                                         unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;

    qemuDriverLock(driver);
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        __FUNCTION__);
        goto cleanup;
    }

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
        goto cleanup;
    }

    ret = 0;
    for (i = 0; i < nparams; i++) {
        virMemoryParameterPtr param = &params[i];

        if (STREQ(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT)) {
            int rc;
            if (param->type != VIR_DOMAIN_MEMORY_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

            rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to set memory hard_limit tunable"));
                ret = -1;
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
            int rc;
            if (param->type != VIR_DOMAIN_MEMORY_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for memory soft_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

            rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to set memory soft_limit tunable"));
                ret = -1;
            }
9771
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804
            int rc;
            if (param->type != VIR_DOMAIN_MEMORY_PARAM_ULLONG) {
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
                ret = -1;
                continue;
            }

            rc = virCgroupSetSwapHardLimit(group, params[i].value.ul);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to set swap_hard_limit tunable"));
                ret = -1;
            }
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Memory tunable `%s' not implemented"), param->field);
            ret = -1;
        } else {
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Parameter `%s' not supported"), param->field);
            ret = -1;
        }
    }

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
                                         virMemoryParameterPtr params,
                                         int *nparams,
                                         unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    unsigned long val;
    int ret = -1;
    int rc;

    qemuDriverLock(driver);

    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        __FUNCTION__);
        goto cleanup;
    }

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
        goto cleanup;
    }

    if ((*nparams) == 0) {
        /* Current number of memory parameters supported by cgroups */
        *nparams = QEMU_NB_MEM_PARAM;
        ret = 0;
        goto cleanup;
    }

    if ((*nparams) != QEMU_NB_MEM_PARAM) {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
        goto cleanup;
    }

    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
        goto cleanup;
    }

    for (i = 0; i < *nparams; i++) {
        virMemoryParameterPtr param = &params[i];
        val = 0;
        param->value.ul = 0;
        param->type = VIR_DOMAIN_MEMORY_PARAM_ULLONG;

        switch(i) {
        case 0: /* fill memory hard limit here */
            rc = virCgroupGetMemoryHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory hard limit"));
9865
                goto cleanup;
9866 9867 9868 9869
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory hard limit too long for destination"));
9870
                goto cleanup;
9871 9872 9873 9874 9875 9876 9877 9878 9879
            }
            param->value.ul = val;
            break;

        case 1: /* fill memory soft limit here */
            rc = virCgroupGetMemorySoftLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get memory soft limit"));
9880
                goto cleanup;
9881 9882 9883 9884
            }
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field memory soft limit too long for destination"));
9885
                goto cleanup;
9886 9887 9888 9889 9890 9891 9892 9893 9894
            }
            param->value.ul = val;
            break;

        case 2: /* fill swap hard limit here */
            rc = virCgroupGetSwapHardLimit(group, &val);
            if (rc != 0) {
                virReportSystemError(-rc, "%s",
                                     _("unable to get swap hard limit"));
9895
                goto cleanup;
9896
            }
9897
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
9898 9899
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                "%s", _("Field swap hard limit too long for destination"));
9900
                goto cleanup;
9901 9902 9903 9904 9905 9906 9907 9908 9909 9910
            }
            param->value.ul = val;
            break;

        default:
            break;
            /* should not hit here */
        }
    }

9911 9912
    ret = 0;

9913 9914 9915 9916 9917 9918 9919 9920 9921
cleanup:
    if (group)
        virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

9922 9923 9924 9925 9926 9927 9928 9929 9930 9931
static int qemuSetSchedulerParameters(virDomainPtr dom,
                                      virSchedParameterPtr params,
                                      int nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
    int i;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    int ret = -1;

9932
    qemuDriverLock(driver);
9933
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
9934 9935
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        __FUNCTION__);
9936
        goto cleanup;
9937 9938 9939 9940 9941
    }

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
9942 9943
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
9944 9945 9946 9947
        goto cleanup;
    }

    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
9948 9949
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
9950 9951 9952 9953 9954 9955 9956 9957 9958
        goto cleanup;
    }

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

        if (STREQ(param->field, "cpu_shares")) {
            int rc;
            if (param->type != VIR_DOMAIN_SCHED_FIELD_ULLONG) {
9959 9960
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
9961 9962 9963 9964 9965
                goto cleanup;
            }

            rc = virCgroupSetCpuShares(group, params[i].value.ul);
            if (rc != 0) {
9966
                virReportSystemError(-rc, "%s",
9967 9968 9969 9970
                                     _("unable to set cpu shares tunable"));
                goto cleanup;
            }
        } else {
9971 9972
            qemuReportError(VIR_ERR_INVALID_ARG,
                            _("Invalid parameter `%s'"), param->field);
9973 9974 9975 9976 9977 9978 9979 9980 9981
            goto cleanup;
        }
    }
    ret = 0;

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
9982
    qemuDriverUnlock(driver);
9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996
    return ret;
}

static int qemuGetSchedulerParameters(virDomainPtr dom,
                                      virSchedParameterPtr params,
                                      int *nparams)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virCgroupPtr group = NULL;
    virDomainObjPtr vm = NULL;
    unsigned long long val;
    int ret = -1;
    int rc;

9997
    qemuDriverLock(driver);
9998
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
9999 10000
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        __FUNCTION__);
10001
        goto cleanup;
10002 10003 10004
    }

    if ((*nparams) != 1) {
10005 10006
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("Invalid parameter count"));
10007
        goto cleanup;
10008 10009 10010 10011 10012
    }

    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (vm == NULL) {
10013 10014
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("No such domain %s"), dom->uuid);
10015 10016 10017 10018
        goto cleanup;
    }

    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
10019 10020
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot find cgroup for domain %s"), vm->def->name);
10021 10022 10023 10024 10025
        goto cleanup;
    }

    rc = virCgroupGetCpuShares(group, &val);
    if (rc != 0) {
10026
        virReportSystemError(-rc, "%s",
10027 10028 10029 10030 10031
                             _("unable to get cpu shares tunable"));
        goto cleanup;
    }
    params[0].value.ul = val;
    params[0].type = VIR_DOMAIN_SCHED_FIELD_ULLONG;
C
Chris Lalancette 已提交
10032
    if (virStrcpyStatic(params[0].field, "cpu_shares") == NULL) {
10033 10034
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Field cpu_shares too long for destination"));
C
Chris Lalancette 已提交
10035 10036
        goto cleanup;
    }
10037 10038 10039 10040 10041 10042 10043

    ret = 0;

cleanup:
    virCgroupFree(&group);
    if (vm)
        virDomainObjUnlock(vm);
10044
    qemuDriverUnlock(driver);
10045 10046 10047 10048
    return ret;
}


10049 10050 10051 10052 10053 10054 10055 10056 10057
/* This uses the 'info blockstats' monitor command which was
 * integrated into both qemu & kvm in late 2007.  If the command is
 * not supported we detect this and return the appropriate error.
 */
static int
qemudDomainBlockStats (virDomainPtr dom,
                       const char *path,
                       struct _virDomainBlockStats *stats)
{
10058
    struct qemud_driver *driver = dom->conn->privateData;
10059
    int i, ret = -1;
10060
    virDomainObjPtr vm;
10061
    virDomainDiskDefPtr disk = NULL;
10062

10063
    qemuDriverLock(driver);
10064
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
10065
    qemuDriverUnlock(driver);
10066
    if (!vm) {
10067 10068
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
10069 10070
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
10071
        goto cleanup;
10072
    }
10073 10074 10075 10076

    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
10077
    if (!virDomainObjIsActive (vm)) {
10078 10079
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
10080
        goto endjob;
10081 10082
    }

10083 10084 10085 10086 10087 10088 10089 10090
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
10091 10092
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path: %s"), path);
10093
        goto endjob;
10094 10095
    }

10096
    if (!disk->info.alias) {
10097 10098
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("missing disk device alias name for %s"), disk->dst);
10099
        goto endjob;
10100
    }
10101

10102
    qemuDomainObjPrivatePtr priv = vm->privateData;
10103 10104
    qemuDomainObjEnterMonitor(vm);
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
10105
                                       disk->info.alias,
10106 10107 10108 10109 10110 10111
                                       &stats->rd_req,
                                       &stats->rd_bytes,
                                       &stats->wr_req,
                                       &stats->wr_bytes,
                                       &stats->errs);
    qemuDomainObjExitMonitor(vm);
10112

10113
endjob:
10114 10115
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
10116

10117
cleanup:
10118 10119
    if (vm)
        virDomainObjUnlock(vm);
10120
    return ret;
10121 10122
}

10123
#ifdef __linux__
10124 10125 10126 10127 10128
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
10129 10130
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
10131
    int i;
10132
    int ret = -1;
10133

10134
    qemuDriverLock(driver);
10135
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
10136 10137
    qemuDriverUnlock(driver);

10138
    if (!vm) {
10139 10140
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
10141 10142
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
10143
        goto cleanup;
10144 10145
    }

D
Daniel P. Berrange 已提交
10146
    if (!virDomainObjIsActive(vm)) {
10147 10148
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
10149
        goto cleanup;
10150 10151 10152
    }

    /* Check the path is one of the domain's network interfaces. */
10153 10154
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
10155 10156 10157 10158
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
10159 10160
    }

10161
    if (ret == 0)
10162
        ret = linuxDomainInterfaceStats(path, stats);
10163
    else
10164 10165
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path, '%s' is not a known interface"), path);
10166

10167
cleanup:
10168 10169
    if (vm)
        virDomainObjUnlock(vm);
10170 10171
    return ret;
}
10172
#else
10173 10174 10175 10176
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
10177 10178
    qemuReportError(VIR_ERR_NO_SUPPORT,
                    "%s", __FUNCTION__);
10179 10180
    return -1;
}
10181
#endif
10182

10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198
static int
qemudDomainMemoryStats (virDomainPtr dom,
                        struct _virDomainMemoryStat *stats,
                        unsigned int nr_stats)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned int ret = -1;

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
10199 10200
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
10201 10202 10203
        goto cleanup;
    }

10204 10205 10206
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

10207 10208 10209
    if (virDomainObjIsActive(vm)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
        qemuDomainObjEnterMonitor(vm);
10210
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
10211 10212
        qemuDomainObjExitMonitor(vm);
    } else {
10213 10214
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
10215 10216
    }

10217 10218 10219
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

10220 10221 10222 10223 10224 10225
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}

10226 10227 10228 10229 10230 10231 10232
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
10233 10234 10235
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
10236

10237
    qemuDriverLock(driver);
10238
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
10239 10240
    qemuDriverUnlock(driver);

10241
    if (!vm) {
10242 10243
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
10244 10245
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
10246
        goto cleanup;
10247 10248 10249
    }

    if (!path || path[0] == '\0') {
10250 10251
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
10252
        goto cleanup;
10253 10254 10255
    }

    /* Check the path belongs to this domain. */
10256 10257
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
10258 10259 10260 10261
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
10262 10263
    }

10264 10265 10266 10267 10268
    if (ret == 0) {
        ret = -1;
        /* The path is correct, now try to open it and get its size. */
        fd = open (path, O_RDONLY);
        if (fd == -1) {
10269 10270
            virReportSystemError(errno,
                                 _("%s: failed to open"), path);
10271 10272
            goto cleanup;
        }
10273

10274 10275 10276 10277 10278 10279
        /* Seek and read. */
        /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
         * be 64 bits on all platforms.
         */
        if (lseek (fd, offset, SEEK_SET) == (off_t) -1 ||
            saferead (fd, buffer, size) == (ssize_t) -1) {
10280 10281
            virReportSystemError(errno,
                                 _("%s: failed to seek or read"), path);
10282 10283 10284 10285 10286
            goto cleanup;
        }

        ret = 0;
    } else {
10287 10288
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("invalid path"));
10289 10290
    }

10291 10292 10293
cleanup:
    if (fd >= 0)
        close (fd);
10294 10295
    if (vm)
        virDomainObjUnlock(vm);
10296 10297 10298
    return ret;
}

R
Richard W.M. Jones 已提交
10299 10300 10301 10302 10303 10304
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
10305 10306
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
10307
    char *tmp = NULL;
R
Richard W.M. Jones 已提交
10308 10309
    int fd = -1, ret = -1;

10310
    qemuDriverLock(driver);
10311
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
10312
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
10313 10314

    if (!vm) {
10315 10316
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
10317 10318
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
10319 10320 10321
        goto cleanup;
    }

10322
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
10323 10324
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
10325
        goto cleanup;
R
Richard W.M. Jones 已提交
10326 10327
    }

10328 10329 10330
    if (qemuDomainObjBeginJob(vm) < 0)
        goto cleanup;

D
Daniel P. Berrange 已提交
10331
    if (!virDomainObjIsActive(vm)) {
10332 10333
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
10334
        goto endjob;
R
Richard W.M. Jones 已提交
10335 10336
    }

10337
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
10338
        virReportOOMError();
10339
        goto endjob;
10340 10341
    }

R
Richard W.M. Jones 已提交
10342 10343
    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
10344 10345
        virReportSystemError(errno,
                             _("mkstemp(\"%s\") failed"), tmp);
10346
        goto endjob;
R
Richard W.M. Jones 已提交
10347 10348
    }

10349
    qemuDomainObjPrivatePtr priv = vm->privateData;
10350
    qemuDomainObjEnterMonitor(vm);
10351
    if (flags == VIR_MEMORY_VIRTUAL) {
10352 10353
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
            qemuDomainObjExitMonitor(vm);
10354
            goto endjob;
10355
        }
10356
    } else {
10357 10358
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
            qemuDomainObjExitMonitor(vm);
10359
            goto endjob;
10360
        }
R
Richard W.M. Jones 已提交
10361
    }
10362
    qemuDomainObjExitMonitor(vm);
R
Richard W.M. Jones 已提交
10363 10364 10365

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
10366 10367 10368
        virReportSystemError(errno,
                             _("failed to read temporary file "
                               "created with template %s"), tmp);
10369
        goto endjob;
R
Richard W.M. Jones 已提交
10370 10371 10372
    }

    ret = 0;
10373

10374
endjob:
10375 10376
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
10377

10378
cleanup:
10379
    VIR_FREE(tmp);
R
Richard W.M. Jones 已提交
10380 10381
    if (fd >= 0) close (fd);
    unlink (tmp);
10382 10383
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
10384 10385 10386
    return ret;
}

10387

10388 10389 10390 10391 10392 10393 10394 10395 10396 10397
static int qemuDomainGetBlockInfo(virDomainPtr dom,
                                  const char *path,
                                  virDomainBlockInfoPtr info,
                                  unsigned int flags) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    int fd = -1;
    off_t end;
    virStorageFileMetadata meta;
10398
    virDomainDiskDefPtr disk = NULL;
10399 10400
    struct stat sb;
    int i;
10401
    int format;
10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!path || path[0] == '\0') {
        qemuReportError(VIR_ERR_INVALID_ARG,
                        "%s", _("NULL or empty path"));
        goto cleanup;
    }

    /* Check the path belongs to this domain. */
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
            STREQ (vm->def->disks[i]->src, path)) {
10426
            disk = vm->def->disks[i];
10427 10428 10429 10430
            break;
        }
    }

10431
    if (!disk) {
10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("invalid path %s not assigned to domain"), path);
        goto cleanup;
    }

    /* The path is correct, now try to open it and get its size. */
    fd = open (path, O_RDONLY);
    if (fd == -1) {
        virReportSystemError(errno,
                             _("failed to open path '%s'"), path);
        goto cleanup;
    }

    /* Probe for magic formats */
10446 10447 10448 10449 10450 10451 10452 10453
    if (disk->driverType) {
        if ((format = virStorageFileFormatTypeFromString(disk->driverType)) < 0) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("unknown disk format %s for %s"),
                            disk->driverType, disk->src);
            goto cleanup;
        }
    } else {
10454 10455 10456 10457 10458 10459 10460
        if (driver->allowDiskFormatProbing) {
            if ((format = virStorageFileProbeFormat(disk->src)) < 0)
                goto cleanup;
        } else {
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
                            _("no disk format for %s and probing is disabled"),
                            disk->src);
10461
            goto cleanup;
10462
        }
10463 10464 10465 10466 10467
    }

    if (virStorageFileGetMetadataFromFD(path, fd,
                                        format,
                                        &meta) < 0)
10468 10469 10470 10471 10472 10473 10474 10475 10476 10477
        goto cleanup;

    /* Get info for normal formats */
    if (fstat(fd, &sb) < 0) {
        virReportSystemError(errno,
                             _("cannot stat file '%s'"), path);
        goto cleanup;
    }

    if (S_ISREG(sb.st_mode)) {
10478
#ifndef WIN32
10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506
        info->physical = (unsigned long long)sb.st_blocks *
            (unsigned long long)DEV_BSIZE;
#else
        info->physical = sb.st_size;
#endif
        /* Regular files may be sparse, so logical size (capacity) is not same
         * as actual physical above
         */
        info->capacity = sb.st_size;
    } else {
        /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
         * be 64 bits on all platforms.
         */
        end = lseek (fd, 0, SEEK_END);
        if (end == (off_t)-1) {
            virReportSystemError(errno,
                                 _("failed to seek to end of %s"), path);
            goto cleanup;
        }
        info->physical = end;
        info->capacity = end;
    }

    /* If the file we probed has a capacity set, then override
     * what we calculated from file/block extents */
    if (meta.capacity)
        info->capacity = meta.capacity;

10507
    /* Set default value .. */
10508 10509
    info->allocation = info->physical;

10510 10511 10512 10513 10514
    /* ..but if guest is running & not using raw
       disk format and on a block device, then query
       highest allocated extent from QEMU */
    if (virDomainObjIsActive(vm) &&
        disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
10515
        format != VIR_STORAGE_FILE_RAW &&
10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531
        S_ISBLK(sb.st_mode)) {
        qemuDomainObjPrivatePtr priv = vm->privateData;
        if (qemuDomainObjBeginJob(vm) < 0)
            goto cleanup;

        qemuDomainObjEnterMonitor(vm);
        ret = qemuMonitorGetBlockExtent(priv->mon,
                                        disk->info.alias,
                                        &info->allocation);
        qemuDomainObjExitMonitor(vm);

        if (qemuDomainObjEndJob(vm) == 0)
            vm = NULL;
    } else {
        ret = 0;
    }
10532 10533 10534 10535 10536 10537 10538 10539 10540 10541

cleanup:
    if (fd != -1)
        close(fd);
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


10542
static int
10543 10544 10545 10546
qemuDomainEventRegister(virConnectPtr conn,
                        virConnectDomainEventCallback callback,
                        void *opaque,
                        virFreeCallback freecb)
10547
{
10548 10549 10550
    struct qemud_driver *driver = conn->privateData;
    int ret;

10551
    qemuDriverLock(driver);
10552 10553
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                        callback, opaque, freecb);
10554
    qemuDriverUnlock(driver);
10555

10556
    return ret;
10557 10558
}

10559

10560
static int
10561 10562
qemuDomainEventDeregister(virConnectPtr conn,
                          virConnectDomainEventCallback callback)
10563
{
10564 10565 10566
    struct qemud_driver *driver = conn->privateData;
    int ret;

10567
    qemuDriverLock(driver);
10568 10569 10570 10571 10572 10573
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                               callback);
10574
    qemuDriverUnlock(driver);
10575

10576
    return ret;
10577 10578
}

10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621

static int
qemuDomainEventRegisterAny(virConnectPtr conn,
                           virDomainPtr dom,
                           int eventID,
                           virConnectDomainEventGenericCallback callback,
                           void *opaque,
                           virFreeCallback freecb)
{
    struct qemud_driver *driver = conn->privateData;
    int ret;

    qemuDriverLock(driver);
    ret = virDomainEventCallbackListAddID(conn,
                                          driver->domainEventCallbacks,
                                          dom, eventID,
                                          callback, opaque, freecb);
    qemuDriverUnlock(driver);

    return ret;
}


static int
qemuDomainEventDeregisterAny(virConnectPtr conn,
                             int callbackID)
{
    struct qemud_driver *driver = conn->privateData;
    int ret;

    qemuDriverLock(driver);
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDeleteID(conn, driver->domainEventCallbacks,
                                                     callbackID);
    else
        ret = virDomainEventCallbackListRemoveID(conn, driver->domainEventCallbacks,
                                                 callbackID);
    qemuDriverUnlock(driver);

    return ret;
}


10622 10623
static void qemuDomainEventDispatchFunc(virConnectPtr conn,
                                        virDomainEventPtr event,
10624
                                        virConnectDomainEventGenericCallback cb,
10625 10626
                                        void *cbopaque,
                                        void *opaque)
10627
{
10628
    struct qemud_driver *driver = opaque;
10629

10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673
    /* Drop the lock whle dispatching, for sake of re-entrancy */
    qemuDriverUnlock(driver);
    virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
    qemuDriverLock(driver);
}

static void qemuDomainEventFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    struct qemud_driver *driver = opaque;
    virDomainEventQueue tempQueue;

    qemuDriverLock(driver);

    driver->domainEventDispatching = 1;

    /* Copy the queue, so we're reentrant safe */
    tempQueue.count = driver->domainEventQueue->count;
    tempQueue.events = driver->domainEventQueue->events;
    driver->domainEventQueue->count = 0;
    driver->domainEventQueue->events = NULL;

    virEventUpdateTimeout(driver->domainEventTimer, -1);
    virDomainEventQueueDispatch(&tempQueue,
                                driver->domainEventCallbacks,
                                qemuDomainEventDispatchFunc,
                                driver);

    /* Purge any deleted callbacks */
    virDomainEventCallbackListPurgeMarked(driver->domainEventCallbacks);

    driver->domainEventDispatching = 0;
    qemuDriverUnlock(driver);
}


/* driver must be locked before calling */
static void qemuDomainEventQueue(struct qemud_driver *driver,
                                 virDomainEventPtr event)
{
    if (virDomainEventQueuePush(driver->domainEventQueue,
                                event) < 0)
        virDomainEventFree(event);
    if (qemu_driver->domainEventQueue->count == 1)
        virEventUpdateTimeout(driver->domainEventTimer, 0);
10674 10675
}

D
Daniel Veillard 已提交
10676 10677
/* Migration support. */

10678 10679 10680 10681 10682
static bool ATTRIBUTE_NONNULL(1)
qemuDomainIsMigratable(virDomainDefPtr def)
{
    if (def->nhostdevs > 0) {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
10683
            "%s", _("Domain with assigned host devices cannot be migrated"));
10684 10685 10686 10687 10688 10689 10690
        return false;
    }

    return true;
}


C
Chris Lalancette 已提交
10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709
/* Tunnelled migration stream support */
struct qemuStreamMigFile {
    int fd;

    int watch;
    unsigned int cbRemoved;
    unsigned int dispatching;
    virStreamEventCallback cb;
    void *opaque;
    virFreeCallback ff;
};

static int qemuStreamMigRemoveCallback(virStreamPtr stream)
{
    struct qemud_driver *driver = stream->conn->privateData;
    struct qemuStreamMigFile *qemust = stream->privateData;
    int ret = -1;

    if (!qemust) {
10710 10711
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("stream is not open"));
C
Chris Lalancette 已提交
10712 10713 10714 10715 10716
        return -1;
    }

    qemuDriverLock(driver);
    if (qemust->watch == 0) {
10717 10718
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("stream does not have a callback registered"));
C
Chris Lalancette 已提交
10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746
        goto cleanup;
    }

    virEventRemoveHandle(qemust->watch);
    if (qemust->dispatching)
        qemust->cbRemoved = 1;
    else if (qemust->ff)
        (qemust->ff)(qemust->opaque);

    qemust->watch = 0;
    qemust->ff = NULL;
    qemust->cb = NULL;
    qemust->opaque = NULL;

    ret = 0;

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}

static int qemuStreamMigUpdateCallback(virStreamPtr stream, int events)
{
    struct qemud_driver *driver = stream->conn->privateData;
    struct qemuStreamMigFile *qemust = stream->privateData;
    int ret = -1;

    if (!qemust) {
10747 10748
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("stream is not open"));
C
Chris Lalancette 已提交
10749 10750 10751 10752 10753
        return -1;
    }

    qemuDriverLock(driver);
    if (qemust->watch == 0) {
10754 10755
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("stream does not have a callback registered"));
C
Chris Lalancette 已提交
10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812
        goto cleanup;
    }

    virEventUpdateHandle(qemust->watch, events);

    ret = 0;

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}

static void qemuStreamMigEvent(int watch ATTRIBUTE_UNUSED,
                               int fd ATTRIBUTE_UNUSED,
                               int events,
                               void *opaque)
{
    virStreamPtr stream = opaque;
    struct qemud_driver *driver = stream->conn->privateData;
    struct qemuStreamMigFile *qemust = stream->privateData;
    virStreamEventCallback cb;
    void *cbopaque;
    virFreeCallback ff;

    qemuDriverLock(driver);
    if (!qemust || !qemust->cb) {
        qemuDriverUnlock(driver);
        return;
    }

    cb = qemust->cb;
    cbopaque = qemust->opaque;
    ff = qemust->ff;
    qemust->dispatching = 1;
    qemuDriverUnlock(driver);

    cb(stream, events, cbopaque);

    qemuDriverLock(driver);
    qemust->dispatching = 0;
    if (qemust->cbRemoved && ff)
        (ff)(cbopaque);
    qemuDriverUnlock(driver);
}

static int
qemuStreamMigAddCallback(virStreamPtr st,
                         int events,
                         virStreamEventCallback cb,
                         void *opaque,
                         virFreeCallback ff)
{
    struct qemud_driver *driver = st->conn->privateData;
    struct qemuStreamMigFile *qemust = st->privateData;
    int ret = -1;

    if (!qemust) {
10813 10814
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("stream is not open"));
C
Chris Lalancette 已提交
10815 10816 10817 10818 10819
        return -1;
    }

    qemuDriverLock(driver);
    if (qemust->watch != 0) {
10820 10821
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("stream already has a callback registered"));
C
Chris Lalancette 已提交
10822 10823 10824 10825 10826 10827 10828 10829
        goto cleanup;
    }

    if ((qemust->watch = virEventAddHandle(qemust->fd,
                                           events,
                                           qemuStreamMigEvent,
                                           st,
                                           NULL)) < 0) {
10830 10831
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("cannot register file watch on stream"));
C
Chris Lalancette 已提交
10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863
        goto cleanup;
    }

    qemust->cbRemoved = 0;
    qemust->cb = cb;
    qemust->opaque = opaque;
    qemust->ff = ff;
    virStreamRef(st);

    ret = 0;

cleanup:
    qemuDriverUnlock(driver);
    return ret;
}

static void qemuStreamMigFree(struct qemuStreamMigFile *qemust)
{
    if (qemust->fd != -1)
        close(qemust->fd);
    VIR_FREE(qemust);
}

static struct qemuStreamMigFile *qemuStreamMigOpen(virStreamPtr st,
                                                   const char *unixfile)
{
    struct qemuStreamMigFile *qemust = NULL;
    struct sockaddr_un sa_qemu;
    int i = 0;
    int timeout = 3;
    int ret;

10864
    if (VIR_ALLOC(qemust) < 0) {
10865
        virReportOOMError();
C
Chris Lalancette 已提交
10866
        return NULL;
10867
    }
C
Chris Lalancette 已提交
10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928

    qemust->fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (qemust->fd < 0)
        goto cleanup;

    memset(&sa_qemu, 0, sizeof(sa_qemu));
    sa_qemu.sun_family = AF_UNIX;
    if (virStrcpy(sa_qemu.sun_path, unixfile, sizeof(sa_qemu.sun_path)) == NULL)
        goto cleanup;

    do {
        ret = connect(qemust->fd, (struct sockaddr *)&sa_qemu, sizeof(sa_qemu));
        if (ret == 0)
            break;

        if (errno == ENOENT || errno == ECONNREFUSED) {
            /* ENOENT       : Socket may not have shown up yet
             * ECONNREFUSED : Leftover socket hasn't been removed yet */
            continue;
        }

        goto cleanup;
    } while ((++i <= timeout*5) && (usleep(.2 * 1000000) <= 0));

    if ((st->flags & VIR_STREAM_NONBLOCK) && virSetNonBlock(qemust->fd) < 0)
        goto cleanup;

    return qemust;

cleanup:
    qemuStreamMigFree(qemust);
    return NULL;
}

static int
qemuStreamMigClose(virStreamPtr st)
{
    struct qemud_driver *driver = st->conn->privateData;
    struct qemuStreamMigFile *qemust = st->privateData;

    if (!qemust)
        return 0;

    qemuDriverLock(driver);

    qemuStreamMigFree(qemust);

    st->privateData = NULL;

    qemuDriverUnlock(driver);

    return 0;
}

static int qemuStreamMigWrite(virStreamPtr st, const char *bytes, size_t nbytes)
{
    struct qemud_driver *driver = st->conn->privateData;
    struct qemuStreamMigFile *qemust = st->privateData;
    int ret;

    if (!qemust) {
10929 10930
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("stream is not open"));
C
Chris Lalancette 已提交
10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944
        return -1;
    }

    qemuDriverLock(driver);

retry:
    ret = write(qemust->fd, bytes, nbytes);
    if (ret < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            ret = -2;
        } else if (errno == EINTR) {
            goto retry;
        } else {
            ret = -1;
10945
            virReportSystemError(errno, "%s",
C
Chris Lalancette 已提交
10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983
                                 _("cannot write to stream"));
        }
    }

    qemuDriverUnlock(driver);
    return ret;
}

static virStreamDriver qemuStreamMigDrv = {
    .streamSend = qemuStreamMigWrite,
    .streamFinish = qemuStreamMigClose,
    .streamAbort = qemuStreamMigClose,
    .streamAddCallback = qemuStreamMigAddCallback,
    .streamUpdateCallback = qemuStreamMigUpdateCallback,
    .streamRemoveCallback = qemuStreamMigRemoveCallback
};

/* Prepare is the first step, and it runs on the destination host.
 *
 * This version starts an empty VM listening on a localhost TCP port, and
 * sets up the corresponding virStream to handle the incoming data.
 */
static int
qemudDomainMigratePrepareTunnel(virConnectPtr dconn,
                                virStreamPtr st,
                                unsigned long flags,
                                const char *dname,
                                unsigned long resource ATTRIBUTE_UNUSED,
                                const char *dom_xml)
{
    struct qemud_driver *driver = dconn->privateData;
    virDomainDefPtr def = NULL;
    virDomainObjPtr vm = NULL;
    char *migrateFrom;
    virDomainEventPtr event = NULL;
    int ret = -1;
    int internalret;
    char *unixfile = NULL;
10984
    unsigned long long qemuCmdFlags;
C
Chris Lalancette 已提交
10985
    struct qemuStreamMigFile *qemust = NULL;
10986 10987 10988 10989 10990 10991 10992 10993
    qemuDomainObjPrivatePtr priv = NULL;
    struct timeval now;

    if (gettimeofday(&now, NULL) < 0) {
        virReportSystemError(errno, "%s",
                             _("cannot get time of day"));
        return -1;
    }
C
Chris Lalancette 已提交
10994 10995 10996

    qemuDriverLock(driver);
    if (!dom_xml) {
10997 10998
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
C
Chris Lalancette 已提交
10999 11000 11001
        goto cleanup;
    }
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
11002
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
11003 11004 11005 11006
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
        goto cleanup;
    }
    if (st == NULL) {
11007 11008
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("tunnelled migration requested but NULL stream passed"));
C
Chris Lalancette 已提交
11009 11010 11011 11012
        goto cleanup;
    }

    /* Parse the domain XML. */
11013
    if (!(def = virDomainDefParseString(driver->caps, dom_xml,
C
Chris Lalancette 已提交
11014
                                        VIR_DOMAIN_XML_INACTIVE))) {
11015 11016
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to parse XML"));
C
Chris Lalancette 已提交
11017 11018 11019
        goto cleanup;
    }

11020 11021 11022
    if (!qemuDomainIsMigratable(def))
        goto cleanup;

C
Chris Lalancette 已提交
11023
    /* Target domain name, maybe renamed. */
11024 11025 11026 11027 11028 11029
    if (dname) {
        VIR_FREE(def->name);
        def->name = strdup(dname);
        if (def->name == NULL)
            goto cleanup;
    }
C
Chris Lalancette 已提交
11030

11031 11032
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
        goto cleanup;
C
Chris Lalancette 已提交
11033

11034
    if (!(vm = virDomainAssignDef(driver->caps,
C
Chris Lalancette 已提交
11035
                                  &driver->domains,
11036
                                  def, true))) {
11037
        /* virDomainAssignDef already set the error */
C
Chris Lalancette 已提交
11038 11039 11040
        goto cleanup;
    }
    def = NULL;
11041
    priv = vm->privateData;
C
Chris Lalancette 已提交
11042

11043 11044
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
11045
    priv->jobActive = QEMU_JOB_MIGRATION_OUT;
11046

C
Chris Lalancette 已提交
11047 11048 11049 11050
    /* Domain starts inactive, even if the domain XML had an id field. */
    vm->def->id = -1;

    if (virAsprintf(&unixfile, "%s/qemu.tunnelmigrate.dest.%s",
11051
                    driver->libDir, vm->def->name) < 0) {
11052
        virReportOOMError();
11053
        goto endjob;
C
Chris Lalancette 已提交
11054 11055 11056 11057 11058
    }
    unlink(unixfile);

    /* check that this qemu version supports the interactive exec */
    if (qemudExtractVersionInfo(vm->def->emulator, NULL, &qemuCmdFlags) < 0) {
11059 11060 11061
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot determine QEMU argv syntax %s"),
                        vm->def->emulator);
11062
        goto endjob;
C
Chris Lalancette 已提交
11063 11064 11065 11066 11067 11068
    }
    if (qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_UNIX)
        internalret = virAsprintf(&migrateFrom, "unix:%s", unixfile);
    else if (qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_EXEC)
        internalret = virAsprintf(&migrateFrom, "exec:nc -U -l %s", unixfile);
    else {
11069 11070
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("Destination qemu is too old to support tunnelled migration"));
11071
        goto endjob;
C
Chris Lalancette 已提交
11072 11073
    }
    if (internalret < 0) {
11074
        virReportOOMError();
11075
        goto endjob;
C
Chris Lalancette 已提交
11076 11077 11078 11079
    }
    /* Start the QEMU daemon, with the same command-line arguments plus
     * -incoming unix:/path/to/file or exec:nc -U /path/to/file
     */
11080 11081
    internalret = qemudStartVMDaemon(dconn, driver, vm, migrateFrom, true,
                                     -1, NULL);
C
Chris Lalancette 已提交
11082 11083
    VIR_FREE(migrateFrom);
    if (internalret < 0) {
11084
        qemuDomainStartAudit(vm, "migrated", false);
C
Chris Lalancette 已提交
11085 11086 11087 11088 11089 11090 11091
        /* Note that we don't set an error here because qemudStartVMDaemon
         * should have already done that.
         */
        if (!vm->persistent) {
            virDomainRemoveInactive(&driver->domains, vm);
            vm = NULL;
        }
11092
        goto endjob;
C
Chris Lalancette 已提交
11093 11094 11095 11096
    }

    qemust = qemuStreamMigOpen(st, unixfile);
    if (qemust == NULL) {
11097
        qemuDomainStartAudit(vm, "migrated", false);
11098
        qemudShutdownVMDaemon(driver, vm, 0);
11099
        if (!vm->persistent) {
11100 11101
            if (qemuDomainObjEndJob(vm) > 0)
                virDomainRemoveInactive(&driver->domains, vm);
11102 11103
            vm = NULL;
        }
11104
        virReportSystemError(errno,
C
Chris Lalancette 已提交
11105 11106
                             _("cannot open unix socket '%s' for tunnelled migration"),
                             unixfile);
11107
        goto endjob;
C
Chris Lalancette 已提交
11108 11109 11110 11111 11112
    }

    st->driver = &qemuStreamMigDrv;
    st->privateData = qemust;

11113
    qemuDomainStartAudit(vm, "migrated", true);
C
Chris Lalancette 已提交
11114 11115 11116 11117 11118
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_MIGRATED);
    ret = 0;

11119
endjob:
11120 11121 11122
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
11123

11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135
    /* We set a fake job active which is held across
     * API calls until the finish() call. This prevents
     * any other APIs being invoked while incoming
     * migration is taking place
     */
    if (vm &&
        virDomainObjIsActive(vm)) {
        priv->jobActive = QEMU_JOB_MIGRATION_IN;
        priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
        priv->jobStart = (now.tv_sec * 1000ull) + (now.tv_usec / 1000);
    }

C
Chris Lalancette 已提交
11136 11137
cleanup:
    virDomainDefFree(def);
11138 11139
    if (unixfile)
        unlink(unixfile);
C
Chris Lalancette 已提交
11140 11141 11142 11143 11144 11145 11146 11147 11148
    VIR_FREE(unixfile);
    if (vm)
        virDomainObjUnlock(vm);
    if (event)
        qemuDomainEventQueue(driver, event);
    qemuDriverUnlock(driver);
    return ret;
}

D
Daniel Veillard 已提交
11149 11150 11151 11152
/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
11153
static int ATTRIBUTE_NONNULL (5)
D
Daniel Veillard 已提交
11154 11155 11156 11157 11158
qemudDomainMigratePrepare2 (virConnectPtr dconn,
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
                            const char *uri_in,
                            char **uri_out,
C
Chris Lalancette 已提交
11159
                            unsigned long flags,
D
Daniel Veillard 已提交
11160 11161 11162 11163 11164
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
    static int port = 0;
11165 11166
    struct qemud_driver *driver = dconn->privateData;
    virDomainDefPtr def = NULL;
D
Daniel Veillard 已提交
11167 11168
    virDomainObjPtr vm = NULL;
    int this_port;
C
Chris Lalancette 已提交
11169
    char *hostname = NULL;
D
Daniel Veillard 已提交
11170 11171
    char migrateFrom [64];
    const char *p;
11172
    virDomainEventPtr event = NULL;
11173
    int ret = -1;
11174
    int internalret;
11175 11176 11177 11178 11179 11180 11181 11182
    qemuDomainObjPrivatePtr priv = NULL;
    struct timeval now;

    if (gettimeofday(&now, NULL) < 0) {
        virReportSystemError(errno, "%s",
                             _("cannot get time of day"));
        return -1;
    }
11183

C
Chris Lalancette 已提交
11184 11185 11186 11187 11188 11189 11190 11191 11192
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

11193
    *uri_out = NULL;
D
Daniel Veillard 已提交
11194

11195
    qemuDriverLock(driver);
C
Chris Lalancette 已提交
11196 11197 11198 11199
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /* this is a logical error; we never should have gotten here with
         * VIR_MIGRATE_TUNNELLED set
         */
11200 11201
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
C
Chris Lalancette 已提交
11202 11203 11204
        goto cleanup;
    }

D
Daniel Veillard 已提交
11205
    if (!dom_xml) {
11206 11207
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("no domain XML passed"));
11208
        goto cleanup;
D
Daniel Veillard 已提交
11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225
    }

    /* The URI passed in may be NULL or a string "tcp://somehostname:port".
     *
     * If the URI passed in is NULL then we allocate a port number
     * from our pool of port numbers and return a URI of
     * "tcp://ourhostname:port".
     *
     * If the URI passed in is not NULL then we try to parse out the
     * port number and use that (note that the hostname is assumed
     * to be a correct hostname which refers to the target machine).
     */
    if (uri_in == NULL) {
        this_port = QEMUD_MIGRATION_FIRST_PORT + port++;
        if (port == QEMUD_MIGRATION_NUM_PORTS) port = 0;

        /* Get hostname */
C
Chris Lalancette 已提交
11226
        if ((hostname = virGetHostname(NULL)) == NULL)
11227
            goto cleanup;
D
Daniel Veillard 已提交
11228

C
Chris Lalancette 已提交
11229 11230 11231 11232 11233 11234
        if (STRPREFIX(hostname, "localhost")) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("hostname on destination resolved to localhost, but migration requires an FQDN"));
            goto cleanup;
        }

11235 11236 11237 11238 11239
        /* XXX this really should have been a properly well-formed
         * URI, but we can't add in tcp:// now without breaking
         * compatability with old targets. We at least make the
         * new targets accept both syntaxes though.
         */
D
Daniel Veillard 已提交
11240
        /* Caller frees */
11241 11242
        internalret = virAsprintf(uri_out, "tcp:%s:%d", hostname, this_port);
        if (internalret < 0) {
11243
            virReportOOMError();
11244
            goto cleanup;
D
Daniel Veillard 已提交
11245 11246 11247 11248 11249 11250
        }
    } else {
        /* Check the URI starts with "tcp:".  We will escape the
         * URI when passing it to the qemu monitor, so bad
         * characters in hostname part don't matter.
         */
11251
        if (!STRPREFIX (uri_in, "tcp:")) {
11252 11253
            qemuReportError (VIR_ERR_INVALID_ARG,
                             "%s", _("only tcp URIs are supported for KVM/QEMU migrations"));
11254
            goto cleanup;
D
Daniel Veillard 已提交
11255 11256 11257 11258
        }

        /* Get the port number. */
        p = strrchr (uri_in, ':');
11259 11260 11261 11262 11263 11264 11265 11266
        if (p == strchr(uri_in, ':')) {
            /* Generate a port */
            this_port = QEMUD_MIGRATION_FIRST_PORT + port++;
            if (port == QEMUD_MIGRATION_NUM_PORTS)
                port = 0;

            /* Caller frees */
            if (virAsprintf(uri_out, "%s:%d", uri_in, this_port) < 0) {
11267
                virReportOOMError();
11268 11269 11270 11271 11272 11273 11274
                goto cleanup;
            }

        } else {
            p++; /* definitely has a ':' in it, see above */
            this_port = virParseNumber (&p);
            if (this_port == -1 || p-uri_in != strlen (uri_in)) {
11275 11276
                qemuReportError(VIR_ERR_INVALID_ARG,
                                "%s", _("URI ended with incorrect ':port'"));
11277 11278
                goto cleanup;
            }
D
Daniel Veillard 已提交
11279 11280 11281
        }
    }

11282
    if (*uri_out)
11283 11284
        VIR_DEBUG("Generated uri_out=%s", *uri_out);

D
Daniel Veillard 已提交
11285
    /* Parse the domain XML. */
11286
    if (!(def = virDomainDefParseString(driver->caps, dom_xml,
11287
                                        VIR_DOMAIN_XML_INACTIVE))) {
11288 11289
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to parse XML"));
11290
        goto cleanup;
D
Daniel Veillard 已提交
11291 11292
    }

11293 11294 11295
    if (!qemuDomainIsMigratable(def))
        goto cleanup;

D
Daniel Veillard 已提交
11296
    /* Target domain name, maybe renamed. */
11297 11298 11299 11300 11301 11302
    if (dname) {
        VIR_FREE(def->name);
        def->name = strdup(dname);
        if (def->name == NULL)
            goto cleanup;
    }
D
Daniel Veillard 已提交
11303

11304 11305
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
        goto cleanup;
D
Daniel Veillard 已提交
11306

11307
    if (!(vm = virDomainAssignDef(driver->caps,
D
Daniel Veillard 已提交
11308
                                  &driver->domains,
11309
                                  def, true))) {
11310
        /* virDomainAssignDef already set the error */
11311
        goto cleanup;
D
Daniel Veillard 已提交
11312
    }
11313
    def = NULL;
11314
    priv = vm->privateData;
D
Daniel Veillard 已提交
11315

11316 11317
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
11318
    priv->jobActive = QEMU_JOB_MIGRATION_OUT;
11319

D
Daniel Veillard 已提交
11320 11321 11322 11323 11324 11325 11326
    /* Domain starts inactive, even if the domain XML had an id field. */
    vm->def->id = -1;

    /* Start the QEMU daemon, with the same command-line arguments plus
     * -incoming tcp:0.0.0.0:port
     */
    snprintf (migrateFrom, sizeof (migrateFrom), "tcp:0.0.0.0:%d", this_port);
11327 11328
    if (qemudStartVMDaemon (dconn, driver, vm, migrateFrom, true,
                            -1, NULL) < 0) {
11329
        qemuDomainStartAudit(vm, "migrated", false);
11330 11331 11332
        /* Note that we don't set an error here because qemudStartVMDaemon
         * should have already done that.
         */
11333
        if (!vm->persistent) {
11334 11335
            if (qemuDomainObjEndJob(vm) > 0)
                virDomainRemoveInactive(&driver->domains, vm);
11336 11337
            vm = NULL;
        }
11338
        goto endjob;
D
Daniel Veillard 已提交
11339
    }
11340

11341
    qemuDomainStartAudit(vm, "migrated", true);
11342 11343 11344
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_MIGRATED);
11345
    ret = 0;
D
Daniel Veillard 已提交
11346

11347
endjob:
11348 11349 11350
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
11351

11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363
    /* We set a fake job active which is held across
     * API calls until the finish() call. This prevents
     * any other APIs being invoked while incoming
     * migration is taking place
     */
    if (vm &&
        virDomainObjIsActive(vm)) {
        priv->jobActive = QEMU_JOB_MIGRATION_IN;
        priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
        priv->jobStart = (now.tv_sec * 1000ull) + (now.tv_usec / 1000);
    }

11364
cleanup:
C
Chris Lalancette 已提交
11365
    VIR_FREE(hostname);
11366
    virDomainDefFree(def);
C
Chris Lalancette 已提交
11367
    if (ret != 0)
11368
        VIR_FREE(*uri_out);
11369 11370
    if (vm)
        virDomainObjUnlock(vm);
11371 11372
    if (event)
        qemuDomainEventQueue(driver, event);
11373
    qemuDriverUnlock(driver);
11374
    return ret;
C
Chris Lalancette 已提交
11375 11376 11377

}

11378 11379 11380 11381

/* Perform migration using QEMU's native TCP migrate support,
 * not encrypted obviously
 */
11382
static int doNativeMigrate(struct qemud_driver *driver,
11383 11384
                           virDomainObjPtr vm,
                           const char *uri,
11385
                           unsigned int flags,
11386 11387 11388 11389
                           const char *dname ATTRIBUTE_UNUSED,
                           unsigned long resource)
{
    int ret = -1;
11390
    xmlURIPtr uribits = NULL;
11391
    qemuDomainObjPrivatePtr priv = vm->privateData;
11392
    unsigned int background_flags = QEMU_MONITOR_MIGRATE_BACKGROUND;
11393

11394 11395 11396 11397 11398
    /* Issue the migrate command. */
    if (STRPREFIX(uri, "tcp:") && !STRPREFIX(uri, "tcp://")) {
        /* HACK: source host generates bogus URIs, so fix them up */
        char *tmpuri;
        if (virAsprintf(&tmpuri, "tcp://%s", uri + strlen("tcp:")) < 0) {
11399
            virReportOOMError();
11400 11401 11402 11403 11404 11405 11406 11407
            goto cleanup;
        }
        uribits = xmlParseURI(tmpuri);
        VIR_FREE(tmpuri);
    } else {
        uribits = xmlParseURI(uri);
    }
    if (!uribits) {
11408 11409
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot parse URI %s"), uri);
11410 11411 11412
        goto cleanup;
    }

11413
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
11414
    if (resource > 0 &&
11415
        qemuMonitorSetMigrationSpeed(priv->mon, resource) < 0) {
11416
        qemuDomainObjExitMonitorWithDriver(driver, vm);
11417
        goto cleanup;
11418
    }
11419

11420 11421 11422 11423 11424 11425 11426 11427
    if (flags & VIR_MIGRATE_NON_SHARED_DISK)
        background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_DISK;

    if (flags & VIR_MIGRATE_NON_SHARED_INC)
        background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_INC;

    if (qemuMonitorMigrateToHost(priv->mon, background_flags, uribits->server,
                                 uribits->port) < 0) {
11428
        qemuDomainObjExitMonitorWithDriver(driver, vm);
11429 11430
        goto cleanup;
    }
11431
    qemuDomainObjExitMonitorWithDriver(driver, vm);
11432

11433
    if (qemuDomainWaitForMigrationComplete(driver, vm) < 0)
11434 11435 11436 11437 11438 11439 11440 11441 11442 11443
        goto cleanup;

    ret = 0;

cleanup:
    xmlFreeURI(uribits);
    return ret;
}


11444 11445
#define TUNNEL_SEND_BUF_SIZE 65536

11446
static int doTunnelSendAll(virStreamPtr st,
11447 11448
                           int sock)
{
11449 11450 11451 11452 11453 11454 11455 11456
    char *buffer;
    int nbytes = TUNNEL_SEND_BUF_SIZE;

    if (VIR_ALLOC_N(buffer, TUNNEL_SEND_BUF_SIZE) < 0) {
        virReportOOMError();
        virStreamAbort(st);
        return -1;
    }
11457 11458 11459 11460 11461

    /* XXX should honour the 'resource' parameter here */
    for (;;) {
        nbytes = saferead(sock, buffer, nbytes);
        if (nbytes < 0) {
11462
            virReportSystemError(errno, "%s",
11463
                                 _("tunnelled migration failed to read from qemu"));
11464 11465
            virStreamAbort(st);
            VIR_FREE(buffer);
11466 11467 11468 11469 11470 11471 11472
            return -1;
        }
        else if (nbytes == 0)
            /* EOF; get out of here */
            break;

        if (virStreamSend(st, buffer, nbytes) < 0) {
11473 11474
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                            _("Failed to write migration data to remote libvirtd"));
11475
            VIR_FREE(buffer);
11476 11477 11478 11479
            return -1;
        }
    }

11480 11481
    VIR_FREE(buffer);

11482 11483 11484 11485 11486 11487 11488
    if (virStreamFinish(st) < 0)
        /* virStreamFinish set the error for us */
        return -1;

    return 0;
}

C
Chris Lalancette 已提交
11489
static int doTunnelMigrate(virDomainPtr dom,
11490
                           struct qemud_driver *driver,
11491
                           virConnectPtr dconn,
C
Chris Lalancette 已提交
11492
                           virDomainObjPtr vm,
11493
                           const char *dom_xml,
C
Chris Lalancette 已提交
11494 11495 11496 11497 11498
                           const char *uri,
                           unsigned long flags,
                           const char *dname,
                           unsigned long resource)
{
11499
    qemuDomainObjPrivatePtr priv = vm->privateData;
11500 11501
    int client_sock = -1;
    int qemu_sock = -1;
C
Chris Lalancette 已提交
11502 11503
    struct sockaddr_un sa_qemu, sa_client;
    socklen_t addrlen;
11504
    virDomainPtr ddomain = NULL;
C
Chris Lalancette 已提交
11505
    int retval = -1;
11506
    virStreamPtr st = NULL;
C
Chris Lalancette 已提交
11507 11508
    char *unixfile = NULL;
    int internalret;
11509
    unsigned long long qemuCmdFlags;
C
Chris Lalancette 已提交
11510 11511
    int status;
    unsigned long long transferred, remaining, total;
11512
    unsigned int background_flags = QEMU_MONITOR_MIGRATE_BACKGROUND;
C
Chris Lalancette 已提交
11513

11514 11515 11516 11517 11518 11519 11520 11521
    /*
     * The order of operations is important here to avoid touching
     * the source VM until we are very sure we can successfully
     * start the migration operation.
     *
     *   1. setup local support infrastructure (eg sockets)
     *   2. setup destination fully
     *   3. start migration on source
C
Chris Lalancette 已提交
11522 11523
     */

11524

11525
    /* Stage 1. setup local support infrastructure */
C
Chris Lalancette 已提交
11526 11527

    if (virAsprintf(&unixfile, "%s/qemu.tunnelmigrate.src.%s",
11528
                    driver->libDir, vm->def->name) < 0) {
11529
        virReportOOMError();
11530
        goto cleanup;
C
Chris Lalancette 已提交
11531 11532 11533 11534
    }

    qemu_sock = socket(AF_UNIX, SOCK_STREAM, 0);
    if (qemu_sock < 0) {
11535
        virReportSystemError(errno, "%s",
C
Chris Lalancette 已提交
11536
                             _("cannot open tunnelled migration socket"));
11537
        goto cleanup;
C
Chris Lalancette 已提交
11538 11539 11540 11541 11542
    }
    memset(&sa_qemu, 0, sizeof(sa_qemu));
    sa_qemu.sun_family = AF_UNIX;
    if (virStrcpy(sa_qemu.sun_path, unixfile,
                  sizeof(sa_qemu.sun_path)) == NULL) {
11543 11544 11545
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Unix socket '%s' too big for destination"),
                        unixfile);
11546
        goto cleanup;
C
Chris Lalancette 已提交
11547 11548 11549
    }
    unlink(unixfile);
    if (bind(qemu_sock, (struct sockaddr *)&sa_qemu, sizeof(sa_qemu)) < 0) {
11550
        virReportSystemError(errno,
C
Chris Lalancette 已提交
11551 11552
                             _("Cannot bind to unix socket '%s' for tunnelled migration"),
                             unixfile);
11553
        goto cleanup;
C
Chris Lalancette 已提交
11554 11555
    }
    if (listen(qemu_sock, 1) < 0) {
11556
        virReportSystemError(errno,
C
Chris Lalancette 已提交
11557 11558
                             _("Cannot listen on unix socket '%s' for tunnelled migration"),
                             unixfile);
11559
        goto cleanup;
C
Chris Lalancette 已提交
11560 11561
    }

11562 11563 11564 11565 11566 11567 11568
    if (chown(unixfile, qemu_driver->user, qemu_driver->group) < 0) {
        virReportSystemError(errno,
                             _("Cannot change unix socket '%s' owner"),
                             unixfile);
        goto cleanup;
    }

C
Chris Lalancette 已提交
11569 11570
    /* check that this qemu version supports the unix migration */
    if (qemudExtractVersionInfo(vm->def->emulator, NULL, &qemuCmdFlags) < 0) {
11571 11572 11573
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        _("Cannot extract Qemu version from '%s'"),
                        vm->def->emulator);
11574 11575 11576 11577 11578
        goto cleanup;
    }

    if (!(qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_UNIX) &&
        !(qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_EXEC)) {
11579 11580
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("Source qemu is too old to support tunnelled migration"));
11581
        goto cleanup;
C
Chris Lalancette 已提交
11582
    }
11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594


    /* Stage 2. setup destination fully
     *
     * Once stage 2 has completed successfully, we *must* call finish
     * to cleanup the target whether we succeed or fail
     */
    st = virStreamNew(dconn, 0);
    if (st == NULL)
        /* virStreamNew only fails on OOM, and it reports the error itself */
        goto cleanup;

11595
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
11596 11597 11598
    internalret = dconn->driver->domainMigratePrepareTunnel(dconn, st,
                                                            flags, dname,
                                                            resource, dom_xml);
11599
    qemuDomainObjExitRemoteWithDriver(driver, vm);
11600 11601 11602 11603 11604

    if (internalret < 0)
        /* domainMigratePrepareTunnel sets the error for us */
        goto cleanup;

11605 11606 11607 11608 11609 11610 11611 11612 11613
    /* the domain may have shutdown or crashed while we had the locks dropped
     * in qemuDomainObjEnterRemoteWithDriver, so check again
     */
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("guest unexpectedly quit"));
        goto cleanup;
    }

11614
    /*   3. start migration on source */
11615
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
11616 11617 11618 11619 11620 11621 11622 11623
    if (flags & VIR_MIGRATE_NON_SHARED_DISK)
        background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_DISK;
    if (flags & VIR_MIGRATE_NON_SHARED_INC)
        background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_INC;
    if (qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_UNIX){
        internalret = qemuMonitorMigrateToUnix(priv->mon, background_flags,
                                               unixfile);
    }
C
Chris Lalancette 已提交
11624 11625
    else if (qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_EXEC) {
        const char *args[] = { "nc", "-U", unixfile, NULL };
11626
        internalret = qemuMonitorMigrateToCommand(priv->mon, QEMU_MONITOR_MIGRATE_BACKGROUND, args);
11627 11628
    } else {
        internalret = -1;
C
Chris Lalancette 已提交
11629
    }
11630
    qemuDomainObjExitMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
11631
    if (internalret < 0) {
11632 11633
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("tunnelled migration monitor command failed"));
11634
        goto finish;
C
Chris Lalancette 已提交
11635 11636
    }

11637 11638 11639 11640 11641 11642
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("guest unexpectedly quit"));
        goto cleanup;
    }

11643 11644 11645
    /* From this point onwards we *must* call cancel to abort the
     * migration on source if anything goes wrong */

C
Chris Lalancette 已提交
11646 11647 11648
    /* it is also possible that the migrate didn't fail initially, but
     * rather failed later on.  Check the output of "info migrate"
     */
11649
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
11650 11651
    if (qemuMonitorGetMigrationStatus(priv->mon,
                                      &status,
C
Chris Lalancette 已提交
11652 11653 11654
                                      &transferred,
                                      &remaining,
                                      &total) < 0) {
11655
        qemuDomainObjExitMonitorWithDriver(driver, vm);
11656
        goto cancel;
C
Chris Lalancette 已提交
11657
    }
11658
    qemuDomainObjExitMonitorWithDriver(driver, vm);
C
Chris Lalancette 已提交
11659 11660

    if (status == QEMU_MONITOR_MIGRATION_STATUS_ERROR) {
11661 11662
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s",_("migrate failed"));
11663
        goto cancel;
C
Chris Lalancette 已提交
11664 11665 11666 11667 11668 11669
    }

    addrlen = sizeof(sa_client);
    while ((client_sock = accept(qemu_sock, (struct sockaddr *)&sa_client, &addrlen)) < 0) {
        if (errno == EAGAIN || errno == EINTR)
            continue;
11670
        virReportSystemError(errno, "%s",
C
Chris Lalancette 已提交
11671
                             _("tunnelled migration failed to accept from qemu"));
11672
        goto cancel;
C
Chris Lalancette 已提交
11673 11674
    }

11675
    retval = doTunnelSendAll(st, client_sock);
11676

11677
cancel:
11678
    if (retval != 0 && virDomainObjIsActive(vm)) {
11679
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
11680
        qemuMonitorMigrateCancel(priv->mon);
11681
        qemuDomainObjExitMonitorWithDriver(driver, vm);
11682
    }
C
Chris Lalancette 已提交
11683

11684
finish:
C
Chris Lalancette 已提交
11685
    dname = dname ? dname : dom->name;
11686
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
C
Chris Lalancette 已提交
11687 11688
    ddomain = dconn->driver->domainMigrateFinish2
        (dconn, dname, NULL, 0, uri, flags, retval);
11689
    qemuDomainObjExitRemoteWithDriver(driver, vm);
11690 11691 11692 11693 11694 11695 11696

cleanup:
    if (client_sock != -1)
        close(client_sock);
    if (qemu_sock != -1)
        close(qemu_sock);

C
Chris Lalancette 已提交
11697 11698 11699
    if (ddomain)
        virUnrefDomain(ddomain);

11700 11701 11702 11703
    if (unixfile) {
        unlink(unixfile);
        VIR_FREE(unixfile);
    }
C
Chris Lalancette 已提交
11704

11705 11706 11707
    if (st)
        /* don't call virStreamFree(), because that resets any pending errors */
        virUnrefStream(st);
11708 11709 11710 11711
    return retval;
}


11712 11713 11714 11715
/* This is essentially a simplified re-impl of
 * virDomainMigrateVersion2 from libvirt.c, but running in source
 * libvirtd context, instead of client app context */
static int doNonTunnelMigrate(virDomainPtr dom,
11716
                              struct qemud_driver *driver,
11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727
                              virConnectPtr dconn,
                              virDomainObjPtr vm,
                              const char *dom_xml,
                              const char *uri ATTRIBUTE_UNUSED,
                              unsigned long flags,
                              const char *dname,
                              unsigned long resource)
{
    virDomainPtr ddomain = NULL;
    int retval = -1;
    char *uri_out = NULL;
11728
    int rc;
11729

11730
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
11731 11732
    /* NB we don't pass 'uri' into this, since that's the libvirtd
     * URI in this context - so we let dest pick it */
11733 11734 11735 11736 11737 11738 11739 11740 11741
    rc = dconn->driver->domainMigratePrepare2(dconn,
                                              NULL, /* cookie */
                                              0, /* cookielen */
                                              NULL, /* uri */
                                              &uri_out,
                                              flags, dname,
                                              resource, dom_xml);
    qemuDomainObjExitRemoteWithDriver(driver, vm);
    if (rc < 0)
11742 11743 11744
        /* domainMigratePrepare2 sets the error for us */
        goto cleanup;

11745 11746 11747 11748 11749 11750 11751 11752 11753
    /* the domain may have shutdown or crashed while we had the locks dropped
     * in qemuDomainObjEnterRemoteWithDriver, so check again
     */
    if (!virDomainObjIsActive(vm)) {
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("guest unexpectedly quit"));
        goto cleanup;
    }

11754
    if (uri_out == NULL) {
11755 11756
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("domainMigratePrepare2 did not set uri"));
11757
        goto cleanup;
11758 11759
    }

11760
    if (doNativeMigrate(driver, vm, uri_out, flags, dname, resource) < 0)
11761 11762 11763 11764 11765 11766
        goto finish;

    retval = 0;

finish:
    dname = dname ? dname : dom->name;
11767
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
11768 11769
    ddomain = dconn->driver->domainMigrateFinish2
        (dconn, dname, NULL, 0, uri_out, flags, retval);
11770
    qemuDomainObjExitRemoteWithDriver(driver, vm);
11771 11772 11773 11774 11775 11776 11777 11778 11779

    if (ddomain)
        virUnrefDomain(ddomain);

cleanup:
    return retval;
}


11780
static int doPeer2PeerMigrate(virDomainPtr dom,
11781
                              struct qemud_driver *driver,
11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797
                              virDomainObjPtr vm,
                              const char *uri,
                              unsigned long flags,
                              const char *dname,
                              unsigned long resource)
{
    int ret = -1;
    virConnectPtr dconn = NULL;
    char *dom_xml;

    /* the order of operations is important here; we make sure the
     * destination side is completely setup before we touch the source
     */

    dconn = virConnectOpen(uri);
    if (dconn == NULL) {
11798 11799
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("Failed to connect to remote libvirt URI %s"), uri);
11800 11801 11802
        return -1;
    }
    if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
11803
                                  VIR_DRV_FEATURE_MIGRATION_P2P)) {
11804 11805
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
                        _("Destination libvirt does not support peer-to-peer migration protocol"));
11806 11807 11808
        goto cleanup;
    }

11809 11810 11811
    dom_xml = qemudVMDumpXML(driver, vm,
                             VIR_DOMAIN_XML_SECURE |
                             VIR_DOMAIN_XML_UPDATE_CPU);
11812
    if (!dom_xml) {
11813 11814
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        "%s", _("failed to get domain xml"));
11815 11816 11817
        goto cleanup;
    }

11818
    if (flags & VIR_MIGRATE_TUNNELLED)
11819
        ret = doTunnelMigrate(dom, driver, dconn, vm, dom_xml, uri, flags, dname, resource);
11820
    else
11821
        ret = doNonTunnelMigrate(dom, driver, dconn, vm, dom_xml, uri, flags, dname, resource);
11822 11823 11824

cleanup:
    VIR_FREE(dom_xml);
C
Chris Lalancette 已提交
11825 11826 11827
    /* don't call virConnectClose(), because that resets any pending errors */
    virUnrefConnect(dconn);

11828
    return ret;
D
Daniel Veillard 已提交
11829 11830
}

11831

D
Daniel Veillard 已提交
11832 11833 11834 11835 11836 11837
/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
                           const char *cookie ATTRIBUTE_UNUSED,
                           int cookielen ATTRIBUTE_UNUSED,
                           const char *uri,
11838
                           unsigned long flags,
11839
                           const char *dname,
D
Daniel Veillard 已提交
11840 11841
                           unsigned long resource)
{
11842 11843
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
11844
    virDomainEventPtr event = NULL;
11845
    int ret = -1;
11846
    int resume = 0;
11847
    qemuDomainObjPrivatePtr priv;
D
Daniel Veillard 已提交
11848

C
Chris Lalancette 已提交
11849 11850 11851 11852 11853 11854 11855 11856 11857
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, -1);

11858
    qemuDriverLock(driver);
11859
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
11860
    if (!vm) {
11861 11862
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
11863 11864
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
11865
        goto cleanup;
D
Daniel Veillard 已提交
11866
    }
11867
    priv = vm->privateData;
D
Daniel Veillard 已提交
11868

11869 11870
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
11871
    priv->jobActive = QEMU_JOB_MIGRATION_OUT;
11872

D
Daniel P. Berrange 已提交
11873
    if (!virDomainObjIsActive(vm)) {
11874 11875
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
11876
        goto endjob;
D
Daniel Veillard 已提交
11877 11878
    }

11879 11880 11881
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
    priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;

11882
    resume = vm->state == VIR_DOMAIN_RUNNING;
11883
    if (!(flags & VIR_MIGRATE_LIVE) && vm->state == VIR_DOMAIN_RUNNING) {
11884
        if (qemuDomainMigrateOffline(driver, vm) < 0)
11885
            goto endjob;
11886 11887
    }

11888
    if ((flags & (VIR_MIGRATE_TUNNELLED | VIR_MIGRATE_PEER2PEER))) {
11889
        if (doPeer2PeerMigrate(dom, driver, vm, uri, flags, dname, resource) < 0)
11890
            /* doPeer2PeerMigrate already set the error, so just get out */
11891
            goto endjob;
11892
    } else {
11893
        if (doNativeMigrate(driver, vm, uri, flags, dname, resource) < 0)
11894
            goto endjob;
11895 11896
    }

D
Daniel Veillard 已提交
11897
    /* Clean up the source domain. */
11898
    qemudShutdownVMDaemon(driver, vm, 1);
11899
    qemuDomainStopAudit(vm, "migrated");
11900
    resume = 0;
11901 11902 11903 11904

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
C
Chris Lalancette 已提交
11905
    if (!vm->persistent || (flags & VIR_MIGRATE_UNDEFINE_SOURCE)) {
11906
        virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm);
11907 11908
        if (qemuDomainObjEndJob(vm) > 0)
            virDomainRemoveInactive(&driver->domains, vm);
11909 11910
        vm = NULL;
    }
11911
    ret = 0;
D
Daniel Veillard 已提交
11912

11913
endjob:
11914
    if (resume && vm->state == VIR_DOMAIN_PAUSED) {
11915
        /* we got here through some sort of failure; start the domain again */
11916
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
11917
        if (qemuMonitorStartCPUs(priv->mon, dom->conn) < 0) {
11918 11919 11920 11921
            /* Hm, we already know we are in error here.  We don't want to
             * overwrite the previous error, though, so we just throw something
             * to the logs and hope for the best
             */
11922
            VIR_ERROR(_("Failed to resume guest %s after failure"),
11923
                      vm->def->name);
11924
        }
11925
        qemuDomainObjExitMonitorWithDriver(driver, vm);
11926

11927
        vm->state = VIR_DOMAIN_RUNNING;
11928 11929 11930 11931
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
    }
11932 11933 11934
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
11935

11936
cleanup:
11937 11938
    if (vm)
        virDomainObjUnlock(vm);
11939 11940
    if (event)
        qemuDomainEventQueue(driver, event);
11941
    qemuDriverUnlock(driver);
11942
    return ret;
D
Daniel Veillard 已提交
11943 11944 11945 11946 11947 11948 11949 11950 11951
}

/* Finish is the third and final step, and it runs on the destination host. */
static virDomainPtr
qemudDomainMigrateFinish2 (virConnectPtr dconn,
                           const char *dname,
                           const char *cookie ATTRIBUTE_UNUSED,
                           int cookielen ATTRIBUTE_UNUSED,
                           const char *uri ATTRIBUTE_UNUSED,
C
Chris Lalancette 已提交
11952
                           unsigned long flags,
D
Daniel Veillard 已提交
11953 11954
                           int retcode)
{
11955 11956 11957
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
11958
    virDomainEventPtr event = NULL;
11959
    virErrorPtr orig_err;
C
Chris Lalancette 已提交
11960
    int newVM = 1;
11961
    qemuDomainObjPrivatePtr priv = NULL;
D
Daniel Veillard 已提交
11962

C
Chris Lalancette 已提交
11963 11964 11965 11966 11967 11968 11969 11970 11971
    virCheckFlags(VIR_MIGRATE_LIVE |
                  VIR_MIGRATE_PEER2PEER |
                  VIR_MIGRATE_TUNNELLED |
                  VIR_MIGRATE_PERSIST_DEST |
                  VIR_MIGRATE_UNDEFINE_SOURCE |
                  VIR_MIGRATE_PAUSED |
                  VIR_MIGRATE_NON_SHARED_DISK |
                  VIR_MIGRATE_NON_SHARED_INC, NULL);

11972 11973 11974
    /* Migration failed. Save the current error so nothing squashes it */
    orig_err = virSaveLastError();

11975
    qemuDriverLock(driver);
11976
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
11977
    if (!vm) {
11978 11979
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching name '%s'"), dname);
11980
        goto cleanup;
D
Daniel Veillard 已提交
11981 11982
    }

11983 11984 11985 11986 11987 11988 11989 11990 11991
    priv = vm->privateData;
    if (priv->jobActive != QEMU_JOB_MIGRATION_IN) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("domain '%s' is not processing incoming migration"), dname);
        goto cleanup;
    }
    priv->jobActive = QEMU_JOB_NONE;
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));

11992 11993 11994
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

D
Daniel Veillard 已提交
11995 11996 11997 11998
    /* Did the migration go as planned?  If yes, return the domain
     * object, but if no, clean up the empty qemu process.
     */
    if (retcode == 0) {
11999 12000 12001 12002 12003 12004
        if (!virDomainObjIsActive(vm)) {
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("guest unexpectedly quit"));
            goto cleanup;
        }

C
Chris Lalancette 已提交
12005 12006 12007 12008 12009
        if (flags & VIR_MIGRATE_PERSIST_DEST) {
            if (vm->persistent)
                newVM = 0;
            vm->persistent = 1;

12010
            if (virDomainSaveConfig(driver->configDir, vm->def) < 0) {
C
Chris Lalancette 已提交
12011 12012 12013 12014 12015 12016 12017 12018 12019 12020
                /* Hmpf.  Migration was successful, but making it persistent
                 * was not.  If we report successful, then when this domain
                 * shuts down, management tools are in for a surprise.  On the
                 * other hand, if we report failure, then the management tools
                 * might try to restart the domain on the source side, even
                 * though the domain is actually running on the destination.
                 * Return a NULL dom pointer, and hope that this is a rare
                 * situation and management tools are smart.
                 */
                vm = NULL;
12021
                goto endjob;
C
Chris Lalancette 已提交
12022 12023 12024 12025 12026 12027 12028 12029 12030
            }

            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_DEFINED,
                                             newVM ?
                                             VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                             VIR_DOMAIN_EVENT_DEFINED_UPDATED);
            if (event)
                qemuDomainEventQueue(driver, event);
12031
            event = NULL;
C
Chris Lalancette 已提交
12032 12033

        }
D
Daniel Veillard 已提交
12034
        dom = virGetDomain (dconn, vm->def->name, vm->def->uuid);
12035

12036 12037 12038 12039 12040 12041 12042 12043
        if (!(flags & VIR_MIGRATE_PAUSED)) {
            /* run 'cont' on the destination, which allows migration on qemu
             * >= 0.10.6 to work properly.  This isn't strictly necessary on
             * older qemu's, but it also doesn't hurt anything there
             */
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            if (qemuMonitorStartCPUs(priv->mon, dconn) < 0) {
                if (virGetLastError() == NULL)
12044 12045
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
                                    "%s", _("resume operation failed"));
12046 12047 12048
                qemuDomainObjExitMonitorWithDriver(driver, vm);
                goto endjob;
            }
12049
            qemuDomainObjExitMonitorWithDriver(driver, vm);
12050 12051

            vm->state = VIR_DOMAIN_RUNNING;
12052 12053
        }

12054 12055 12056
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
12057 12058 12059 12060 12061 12062
        if (vm->state == VIR_DOMAIN_PAUSED) {
            qemuDomainEventQueue(driver, event);
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_SUSPENDED,
                                             VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
        }
12063 12064 12065 12066
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
            goto endjob;
        }
D
Daniel Veillard 已提交
12067
    } else {
12068
        qemudShutdownVMDaemon(driver, vm, 1);
12069
        qemuDomainStopAudit(vm, "failed");
12070 12071 12072
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
12073
        if (!vm->persistent) {
12074 12075
            if (qemuDomainObjEndJob(vm) > 0)
                virDomainRemoveInactive(&driver->domains, vm);
12076 12077
            vm = NULL;
        }
D
Daniel Veillard 已提交
12078
    }
12079

12080
endjob:
12081 12082 12083
    if (vm &&
        qemuDomainObjEndJob(vm) == 0)
        vm = NULL;
12084

12085
cleanup:
12086 12087 12088 12089
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
12090 12091
    if (vm)
        virDomainObjUnlock(vm);
12092 12093
    if (event)
        qemuDomainEventQueue(driver, event);
12094
    qemuDriverUnlock(driver);
12095
    return dom;
D
Daniel Veillard 已提交
12096 12097
}

12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113
static int
qemudNodeDeviceGetPciInfo (virNodeDevicePtr dev,
                           unsigned *domain,
                           unsigned *bus,
                           unsigned *slot,
                           unsigned *function)
{
    virNodeDeviceDefPtr def = NULL;
    virNodeDevCapsDefPtr cap;
    char *xml = NULL;
    int ret = -1;

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

12114
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131
    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) {
12132 12133
        qemuReportError(VIR_ERR_INVALID_ARG,
                        _("device %s is not a PCI device"), dev->name);
12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146
        goto out;
    }

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

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
12147
    struct qemud_driver *driver = dev->conn->privateData;
12148 12149 12150 12151 12152 12153 12154
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

12155
    pci = pciGetDevice(domain, bus, slot, function);
12156 12157 12158
    if (!pci)
        return -1;

12159 12160
    qemuDriverLock(driver);
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
12161 12162 12163 12164
        goto out;

    ret = 0;
out:
12165
    qemuDriverUnlock(driver);
12166
    pciFreeDevice(pci);
12167 12168 12169 12170 12171 12172
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
12173
    struct qemud_driver *driver = dev->conn->privateData;
12174 12175 12176 12177 12178 12179 12180
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

12181
    pci = pciGetDevice(domain, bus, slot, function);
12182 12183 12184
    if (!pci)
        return -1;

12185 12186
    qemuDriverLock(driver);
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
12187 12188 12189 12190
        goto out;

    ret = 0;
out:
12191
    qemuDriverUnlock(driver);
12192
    pciFreeDevice(pci);
12193 12194 12195 12196 12197 12198
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
12199
    struct qemud_driver *driver = dev->conn->privateData;
12200 12201 12202 12203 12204 12205 12206
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

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

12207
    pci = pciGetDevice(domain, bus, slot, function);
12208 12209 12210
    if (!pci)
        return -1;

12211 12212
    qemuDriverLock(driver);

12213
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
12214 12215 12216 12217
        goto out;

    ret = 0;
out:
12218
    qemuDriverUnlock(driver);
12219
    pciFreeDevice(pci);
12220 12221 12222
    return ret;
}

12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233
static int
qemuCPUCompare(virConnectPtr conn,
               const char *xmlDesc,
               unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = conn->privateData;
    int ret = VIR_CPU_COMPARE_ERROR;

    qemuDriverLock(driver);

    if (!driver->caps || !driver->caps->host.cpu) {
12234 12235
        qemuReportError(VIR_ERR_NO_SUPPORT,
                        "%s", _("cannot get host CPU capabilities"));
12236 12237
    }
    else
12238
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
12239 12240 12241 12242 12243 12244

    qemuDriverUnlock(driver);

    return ret;
}

12245

12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258
static char *
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
                const char **xmlCPUs,
                unsigned int ncpus,
                unsigned int flags ATTRIBUTE_UNUSED)
{
    char *cpu;

    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);

    return cpu;
}

12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281

static int qemuDomainGetJobInfo(virDomainPtr dom,
                                virDomainJobInfoPtr info) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    priv = vm->privateData;

    if (virDomainObjIsActive(vm)) {
        if (priv->jobActive) {
12282 12283
            struct timeval now;

12284
            memcpy(info, &priv->jobInfo, sizeof(*info));
12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298

            /* Refresh elapsed time again just to ensure it
             * is fully updated. This is primarily for benefit
             * of incoming migration which we don't currently
             * monitor actively in the background thread
             */
            if (gettimeofday(&now, NULL) < 0) {
                virReportSystemError(errno, "%s",
                                     _("cannot get time of day"));
                goto cleanup;
            }
            info->timeElapsed =
                ((now.tv_sec * 1000ull) + (now.tv_usec / 1000)) -
                priv->jobStart;
12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317
        } else {
            memset(info, 0, sizeof(*info));
            info->type = VIR_DOMAIN_JOB_NONE;
        }
    } else {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339
static int qemuDomainAbortJob(virDomainPtr dom) {
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    qemuDriverUnlock(driver);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    priv = vm->privateData;

    if (virDomainObjIsActive(vm)) {
        if (priv->jobActive) {
            VIR_DEBUG("Requesting cancellation of job on vm %s", vm->def->name);
12340
            priv->jobSignals |= QEMU_JOB_SIGNAL_CANCEL;
12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360
        } else {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
                            "%s", _("no job is active on the domain"));
            goto cleanup;
        }
    } else {
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not running"));
        goto cleanup;
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    return ret;
}


12361 12362 12363 12364 12365 12366 12367 12368 12369 12370
static int
qemuDomainMigrateSetMaxDowntime(virDomainPtr dom,
                                unsigned long long downtime,
                                unsigned int flags)
{
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    qemuDomainObjPrivatePtr priv;
    int ret = -1;

12371
    virCheckFlags(0, -1);
12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

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

    priv = vm->privateData;

12392
    if (priv->jobActive != QEMU_JOB_MIGRATION_OUT) {
12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409
        qemuReportError(VIR_ERR_OPERATION_INVALID,
                        "%s", _("domain is not being migrated"));
        goto cleanup;
    }

    VIR_DEBUG("Requesting migration downtime change to %llums", downtime);
    priv->jobSignals |= QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME;
    priv->jobSignalsData.migrateDowntime = downtime;
    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

C
Chris Lalancette 已提交
12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518
static char *qemuFindQemuImgBinary(void)
{
    char *ret;

    ret = virFindFileInPath("kvm-img");
    if (ret == NULL)
        ret = virFindFileInPath("qemu-img");
    if (ret == NULL)
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
                        "%s", _("unable to find kvm-img or qemu-img"));

    return ret;
}

static int qemuDomainSnapshotWriteSnapshotMetadata(virDomainObjPtr vm,
                                                   char *snapshotDir)
{
    int fd = -1;
    char *newxml = NULL;
    int ret = -1;
    char *snapDir = NULL;
    char *snapFile = NULL;
    int err;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(vm->def->uuid, uuidstr);
    newxml = virDomainSnapshotDefFormat(uuidstr, vm->current_snapshot->def, 1);
    if (newxml == NULL) {
        virReportOOMError();
        return -1;
    }

    if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    err = virFileMakePath(snapDir);
    if (err < 0) {
        virReportSystemError(err, _("cannot create snapshot directory '%s'"),
                             snapDir);
        goto cleanup;
    }

    if (virAsprintf(&snapFile, "%s/%s.xml", snapDir,
                    vm->current_snapshot->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    fd = open(snapFile, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR);
    if (fd < 0) {
        qemuReportError(VIR_ERR_OPERATION_FAILED,
                        _("failed to create snapshot file '%s'"), snapFile);
        goto cleanup;
    }
    if (safewrite(fd, newxml, strlen(newxml)) != strlen(newxml)) {
        virReportSystemError(errno, _("Failed to write snapshot data to %s"),
                             snapFile);
        goto cleanup;
    }

    ret = 0;

cleanup:
    VIR_FREE(snapFile);
    VIR_FREE(snapDir);
    VIR_FREE(newxml);
    if (fd != -1)
        close(fd);
    return ret;
}

static int qemuDomainSnapshotSetActive(virDomainObjPtr vm,
                                       char *snapshotDir)
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 1;

        return qemuDomainSnapshotWriteSnapshotMetadata(vm, snapshotDir);
    }

    return 0;
}

static int qemuDomainSnapshotSetInactive(virDomainObjPtr vm,
                                         char *snapshotDir)
{
    if (vm->current_snapshot) {
        vm->current_snapshot->def->active = 0;

        return qemuDomainSnapshotWriteSnapshotMetadata(vm, snapshotDir);
    }

    return 0;
}


static int qemuDomainSnapshotIsAllowed(virDomainObjPtr vm)
{
    int i;

    /* FIXME: we need to figure out what else here might succeed; in
     * particular, if it's a raw device but on LVM, we could probably make
     * that succeed as well
     */
    for (i = 0; i < vm->def->ndisks; i++) {
        if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
            (!vm->def->disks[i]->driverType ||
             STRNEQ(vm->def->disks[i]->driverType, "qcow2"))) {
            qemuReportError(VIR_ERR_OPERATION_INVALID,
12519 12520
                            _("Disk '%s' does not support snapshotting"),
                            vm->def->disks[i]->src);
C
Chris Lalancette 已提交
12521 12522 12523 12524 12525 12526 12527 12528 12529
            return 0;
        }
    }

    return 1;
}

static virDomainSnapshotPtr qemuDomainSnapshotCreateXML(virDomainPtr domain,
                                                        const char *xmlDesc,
12530
                                                        unsigned int flags)
C
Chris Lalancette 已提交
12531 12532 12533 12534 12535 12536 12537 12538 12539 12540
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainSnapshotDefPtr def;
    const char *qemuimgarg[] = { NULL, "snapshot", "-c", NULL, NULL, NULL };
    int i;

12541 12542
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603
    qemuDriverLock(driver);
    virUUIDFormat(domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    /* in a perfect world, we would allow qemu to tell us this.  The problem
     * is that qemu only does this check device-by-device; so if you had a
     * domain that booted from a large qcow2 device, but had a secondary raw
     * device attached, you wouldn't find out that you can't snapshot your
     * guest until *after* it had spent the time to snapshot the boot device.
     * This is probably a bug in qemu, but we'll work around it here for now.
     */
    if (!qemuDomainSnapshotIsAllowed(vm))
        goto cleanup;

    if (!(def = virDomainSnapshotDefParseString(xmlDesc, 1)))
        goto cleanup;

    if (!(snap = virDomainSnapshotAssignDef(&vm->snapshots, def)))
        goto cleanup;

    /* actually do the snapshot */
    if (!virDomainObjIsActive(vm)) {
        qemuimgarg[0] = qemuFindQemuImgBinary();
        if (qemuimgarg[0] == NULL)
            /* qemuFindQemuImgBinary set the error */
            goto cleanup;

        qemuimgarg[3] = snap->def->name;

        for (i = 0; i < vm->def->ndisks; i++) {
            /* FIXME: we also need to handle LVM here */
            /* FIXME: if we fail halfway through this loop, we are in an
             * inconsistent state.  I'm not quite sure what to do about that
             */
            if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                if (!vm->def->disks[i]->driverType ||
                    STRNEQ(vm->def->disks[i]->driverType, "qcow2")) {
                    qemuReportError(VIR_ERR_OPERATION_INVALID,
                                    _("Disk device '%s' does not support snapshotting"),
                                    vm->def->disks[i]->info.alias);
                    goto cleanup;
                }

                qemuimgarg[4] = vm->def->disks[i]->src;

                if (virRun(qemuimgarg, NULL) < 0) {
                    virReportSystemError(errno,
                                         _("Failed to run '%s' to create snapshot '%s' from disk '%s'"),
                                         qemuimgarg[0], snap->def->name,
                                         vm->def->disks[i]->src);
                    goto cleanup;
                }
            }
        }
    }
    else {
12604 12605 12606 12607 12608
        qemuDomainObjPrivatePtr priv;
        int ret;

        if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
            goto cleanup;
C
Chris Lalancette 已提交
12609 12610
        priv = vm->privateData;
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
12611
        ret = qemuMonitorCreateSnapshot(priv->mon, def->name);
C
Chris Lalancette 已提交
12612
        qemuDomainObjExitMonitorWithDriver(driver, vm);
12613
        if (qemuDomainObjEndJob(vm) == 0) {
12614
            vm = NULL;
12615 12616
            goto cleanup;
        }
12617 12618
        if (ret < 0)
            goto cleanup;
C
Chris Lalancette 已提交
12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654
    }

    snap->def->state = vm->state;

    /* FIXME: if we fail after this point, there's not a whole lot we can
     * do; we've successfully taken the snapshot, and we are now running
     * on it, so we have to go forward the best we can
     */

    if (vm->current_snapshot) {
        def->parent = strdup(vm->current_snapshot->def->name);
        if (def->parent == NULL) {
            virReportOOMError();
            goto cleanup;
        }
    }

    /* Now we set the new current_snapshot for the domain */
    vm->current_snapshot = snap;

    if (qemuDomainSnapshotWriteSnapshotMetadata(vm, driver->snapshotDir) < 0)
        /* qemuDomainSnapshotWriteSnapshotMetadata set the error */
        goto cleanup;

    snapshot = virGetDomainSnapshot(domain, snap->def->name);

cleanup:
    VIR_FREE(qemuimgarg[0]);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return snapshot;
}

static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
                                       int nameslen,
12655
                                       unsigned int flags)
C
Chris Lalancette 已提交
12656 12657 12658 12659 12660
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

12661 12662
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    n = virDomainSnapshotObjListGetNames(&vm->snapshots, names, nameslen);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return n;
}

static int qemuDomainSnapshotNum(virDomainPtr domain,
12683
                                 unsigned int flags)
C
Chris Lalancette 已提交
12684 12685 12686 12687 12688
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int n = -1;

12689 12690
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    n = virDomainSnapshotObjListNum(&vm->snapshots);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return n;
}

static virDomainSnapshotPtr qemuDomainSnapshotLookupByName(virDomainPtr domain,
                                                           const char *name,
12712
                                                           unsigned int flags)
C
Chris Lalancette 已提交
12713 12714 12715 12716 12717 12718
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotObjPtr snap = NULL;
    virDomainSnapshotPtr snapshot = NULL;

12719 12720
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no snapshot with matching name '%s'"), name);
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, snap->def->name);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return snapshot;
}

static int qemuDomainHasCurrentSnapshot(virDomainPtr domain,
12748
                                        unsigned int flags)
C
Chris Lalancette 已提交
12749 12750 12751 12752 12753
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

12754 12755
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    ret = (vm->current_snapshot != NULL);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

static virDomainSnapshotPtr qemuDomainSnapshotCurrent(virDomainPtr domain,
12776
                                                      unsigned int flags)
C
Chris Lalancette 已提交
12777 12778 12779 12780 12781
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm;
    virDomainSnapshotPtr snapshot = NULL;

12782 12783
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809
    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    if (!vm->current_snapshot) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
                        _("the domain does not have a current snapshot"));
        goto cleanup;
    }

    snapshot = virGetDomainSnapshot(domain, vm->current_snapshot->def->name);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return snapshot;
}

static char *qemuDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
12810
                                       unsigned int flags)
C
Chris Lalancette 已提交
12811 12812 12813 12814 12815 12816 12817
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    char *xml = NULL;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

12818 12819
    virCheckFlags(0, NULL);

C
Chris Lalancette 已提交
12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

    xml = virDomainSnapshotDefFormat(uuidstr, snap->def, 0);

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return xml;
}

static int qemuDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
12847
                                      unsigned int flags)
C
Chris Lalancette 已提交
12848 12849 12850 12851 12852 12853 12854 12855 12856 12857
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainEventPtr event = NULL;
    qemuDomainObjPrivatePtr priv;
    int rc;

12858 12859
    virCheckFlags(0, -1);

C
Chris Lalancette 已提交
12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

    vm->current_snapshot = snap;

    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

    if (snap->def->state == VIR_DOMAIN_RUNNING
        || snap->def->state == VIR_DOMAIN_PAUSED) {

        if (virDomainObjIsActive(vm)) {
            priv = vm->privateData;
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
            if (rc < 0)
12891
                goto endjob;
C
Chris Lalancette 已提交
12892 12893 12894
        }
        else {
            if (qemuDomainSnapshotSetActive(vm, driver->snapshotDir) < 0)
12895
                goto endjob;
C
Chris Lalancette 已提交
12896 12897

            rc = qemudStartVMDaemon(snapshot->domain->conn, driver, vm, NULL,
12898
                                    false, -1, NULL);
12899
            qemuDomainStartAudit(vm, "from-snapshot", rc >= 0);
C
Chris Lalancette 已提交
12900
            if (qemuDomainSnapshotSetInactive(vm, driver->snapshotDir) < 0)
12901
                goto endjob;
C
Chris Lalancette 已提交
12902
            if (rc < 0)
12903
                goto endjob;
C
Chris Lalancette 已提交
12904 12905 12906 12907 12908 12909
        }

        if (snap->def->state == VIR_DOMAIN_PAUSED) {
            /* qemu unconditionally starts the domain running again after
             * loadvm, so let's pause it to keep consistency
             */
12910
            int state = vm->state;
C
Chris Lalancette 已提交
12911
            priv = vm->privateData;
12912
            vm->state = VIR_DOMAIN_PAUSED;
C
Chris Lalancette 已提交
12913 12914 12915
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
            rc = qemuMonitorStopCPUs(priv->mon);
            qemuDomainObjExitMonitorWithDriver(driver, vm);
12916 12917
            if (rc < 0) {
                vm->state = state;
12918
                goto endjob;
12919
            }
C
Chris Lalancette 已提交
12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937
        }

        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT);
    }
    else {
        /* qemu is a little funny with running guests and the restoration
         * of snapshots.  If the snapshot was taken online,
         * then after a "loadvm" monitor command, the VM is set running
         * again.  If the snapshot was taken offline, then after a "loadvm"
         * monitor command the VM is left paused.  Unpausing it leads to
         * the memory state *before* the loadvm with the disk *after* the
         * loadvm, which obviously is bound to corrupt something.
         * Therefore we destroy the domain and set it to "off" in this case.
         */

        if (virDomainObjIsActive(vm)) {
12938
            qemudShutdownVMDaemon(driver, vm, 0);
12939
            qemuDomainStopAudit(vm, "from-snapshot");
C
Chris Lalancette 已提交
12940 12941 12942
            event = virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STOPPED,
                                             VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
12943 12944 12945 12946
            if (!vm->persistent) {
                if (qemuDomainObjEndJob(vm) > 0)
                    virDomainRemoveInactive(&driver->domains, vm);
                vm = NULL;
12947
                goto cleanup;
12948
            }
C
Chris Lalancette 已提交
12949 12950 12951
        }

        if (qemuDomainSnapshotSetActive(vm, driver->snapshotDir) < 0)
12952
            goto endjob;
C
Chris Lalancette 已提交
12953 12954 12955 12956 12957 12958
    }

    vm->state = snap->def->state;

    ret = 0;

12959
endjob:
C
Chris Lalancette 已提交
12960 12961 12962
    if (vm && qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

12963
cleanup:
C
Chris Lalancette 已提交
12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097
    if (event)
        qemuDomainEventQueue(driver, event);
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);

    return ret;
}

static int qemuDomainSnapshotDiscard(struct qemud_driver *driver,
                                     virDomainObjPtr vm,
                                     virDomainSnapshotObjPtr snap)
{
    const char *qemuimgarg[] = { NULL, "snapshot", "-d", NULL, NULL, NULL };
    char *snapFile = NULL;
    int ret = -1;
    int i;
    qemuDomainObjPrivatePtr priv;
    virDomainSnapshotObjPtr parentsnap;

    if (!virDomainObjIsActive(vm)) {
        qemuimgarg[0] = qemuFindQemuImgBinary();
        if (qemuimgarg[0] == NULL)
            /* qemuFindQemuImgBinary set the error */
            goto cleanup;

        qemuimgarg[3] = snap->def->name;

        for (i = 0; i < vm->def->ndisks; i++) {
            /* FIXME: we also need to handle LVM here */
            if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                if (!vm->def->disks[i]->driverType ||
                    STRNEQ(vm->def->disks[i]->driverType, "qcow2")) {
                    /* we continue on even in the face of error, since other
                     * disks in this VM may have this snapshot in place
                     */
                    continue;
                }

                qemuimgarg[4] = vm->def->disks[i]->src;

                if (virRun(qemuimgarg, NULL) < 0) {
                    /* we continue on even in the face of error, since other
                     * disks in this VM may have this snapshot in place
                     */
                    continue;
                }
            }
        }
    }
    else {
        priv = vm->privateData;
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
        /* we continue on even in the face of error */
        qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
        qemuDomainObjExitMonitorWithDriver(driver, vm);
    }

    if (snap == vm->current_snapshot) {
        if (snap->def->parent) {
            parentsnap = virDomainSnapshotFindByName(&vm->snapshots,
                                                     snap->def->parent);
            if (!parentsnap) {
                qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                                _("no domain snapshot parent with matching name '%s'"),
                                snap->def->parent);
                goto cleanup;
            }

            /* Now we set the new current_snapshot for the domain */
            vm->current_snapshot = parentsnap;
        }
        else
            vm->current_snapshot = NULL;
    }

    if (virAsprintf(&snapFile, "%s/%s/%s.xml", driver->snapshotDir,
                    vm->def->name, snap->def->name) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    unlink(snapFile);

    virDomainSnapshotObjListRemove(&vm->snapshots, snap);

    ret = 0;

cleanup:
    VIR_FREE(snapFile);
    VIR_FREE(qemuimgarg[0]);

    return ret;
}

struct snap_remove {
    struct qemud_driver *driver;
    virDomainObjPtr vm;
    char *parent;
    int err;
};

static void qemuDomainSnapshotDiscardChildren(void *payload,
                                              const char *name ATTRIBUTE_UNUSED,
                                              void *data)
{
    virDomainSnapshotObjPtr snap = payload;
    struct snap_remove *curr = data;
    struct snap_remove this;

    if (snap->def->parent && STREQ(snap->def->parent, curr->parent)) {
        this.driver = curr->driver;
        this.vm = curr->vm;
        this.parent = snap->def->name;
        this.err = 0;
        virHashForEach(curr->vm->snapshots.objs,
                       qemuDomainSnapshotDiscardChildren, &this);

        if (this.err)
            curr->err = this.err;
        else
            this.err = qemuDomainSnapshotDiscard(curr->driver, curr->vm, snap);
    }
}

static int qemuDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                                    unsigned int flags)
{
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    virDomainSnapshotObjPtr snap = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    struct snap_remove rem;

13098 13099
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

C
Chris Lalancette 已提交
13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116
    qemuDriverLock(driver);
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
    if (!vm) {
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
    if (!snap) {
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                        _("no domain snapshot with matching name '%s'"),
                        snapshot->name);
        goto cleanup;
    }

13117 13118 13119
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;

C
Chris Lalancette 已提交
13120 13121 13122 13123 13124 13125 13126 13127
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN) {
        rem.driver = driver;
        rem.vm = vm;
        rem.parent = snap->def->name;
        rem.err = 0;
        virHashForEach(vm->snapshots.objs, qemuDomainSnapshotDiscardChildren,
                       &rem);
        if (rem.err < 0)
13128
            goto endjob;
C
Chris Lalancette 已提交
13129 13130 13131 13132
    }

    ret = qemuDomainSnapshotDiscard(driver, vm, snap);

13133 13134 13135 13136
endjob:
    if (qemuDomainObjEndJob(vm) == 0)
        vm = NULL;

C
Chris Lalancette 已提交
13137 13138 13139 13140 13141 13142
cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}
13143

13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194
static int qemuDomainMonitorCommand(virDomainPtr domain, const char *cmd,
                                    char **result, unsigned int flags)
{
    struct qemud_driver *driver = domain->conn->privateData;
    virDomainObjPtr vm = NULL;
    int ret = -1;
    qemuDomainObjPrivatePtr priv;

    virCheckFlags(0, -1);

    qemuDriverLock(driver);
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(domain->uuid, uuidstr);
        qemuReportError(VIR_ERR_NO_DOMAIN,
                        _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

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

    priv = vm->privateData;

    if (!priv->monitor_warned) {
        VIR_INFO("Qemu monitor command '%s' executed; libvirt results may be unpredictable!",
                 cmd);
        priv->monitor_warned = 1;
    }

    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
        goto cleanup;
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result);
    qemuDomainObjExitMonitorWithDriver(driver, vm);
    if (qemuDomainObjEndJob(vm) == 0) {
        vm = NULL;
        goto cleanup;
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
    return ret;
}

13195 13196 13197 13198 13199
static virDriver qemuDriver = {
    VIR_DRV_QEMU,
    "QEMU",
    qemudOpen, /* open */
    qemudClose, /* close */
D
Daniel Veillard 已提交
13200
    qemudSupportsFeature, /* supports_feature */
13201 13202
    qemudGetType, /* type */
    qemudGetVersion, /* version */
13203
    NULL, /* libvirtVersion (impl. in libvirt.c) */
13204
    virGetHostname, /* getHostname */
13205
    qemudGetMaxVCPUs, /* getMaxVcpus */
13206
    nodeGetInfo, /* nodeGetInfo */
13207 13208 13209
    qemudGetCapabilities, /* getCapabilities */
    qemudListDomains, /* listDomains */
    qemudNumDomains, /* numOfDomains */
13210
    qemudDomainCreate, /* domainCreateXML */
13211 13212 13213 13214 13215
    qemudDomainLookupByID, /* domainLookupByID */
    qemudDomainLookupByUUID, /* domainLookupByUUID */
    qemudDomainLookupByName, /* domainLookupByName */
    qemudDomainSuspend, /* domainSuspend */
    qemudDomainResume, /* domainResume */
13216
    qemudDomainShutdown, /* domainShutdown */
13217 13218 13219
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */
    qemudDomainGetOSType, /* domainGetOSType */
13220
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
13221
    NULL, /* domainSetMaxMemory */
13222
    qemudDomainSetMemory, /* domainSetMemory */
13223 13224 13225
    qemudDomainGetInfo, /* domainGetInfo */
    qemudDomainSave, /* domainSave */
    qemudDomainRestore, /* domainRestore */
P
Paolo Bonzini 已提交
13226
    qemudDomainCoreDump, /* domainCoreDump */
13227
    qemudDomainSetVcpus, /* domainSetVcpus */
13228 13229
    qemudDomainSetVcpusFlags, /* domainSetVcpusFlags */
    qemudDomainGetVcpusFlags, /* domainGetVcpusFlags */
13230 13231
    qemudDomainPinVcpu, /* domainPinVcpu */
    qemudDomainGetVcpus, /* domainGetVcpus */
13232
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
13233 13234
    qemudDomainGetSecurityLabel, /* domainGetSecurityLabel */
    qemudNodeGetSecurityModel, /* nodeGetSecurityModel */
13235
    qemudDomainDumpXML, /* domainDumpXML */
13236
    qemuDomainXMLFromNative, /* domainXmlFromNative */
13237
    qemuDomainXMLToNative, /* domainXMLToNative */
13238 13239
    qemudListDefinedDomains, /* listDefinedDomains */
    qemudNumDefinedDomains, /* numOfDefinedDomains */
13240
    qemudDomainStart, /* domainCreate */
13241
    qemudDomainStartWithFlags, /* domainCreateWithFlags */
13242 13243
    qemudDomainDefine, /* domainDefineXML */
    qemudDomainUndefine, /* domainUndefine */
13244
    qemudDomainAttachDevice, /* domainAttachDevice */
13245
    qemudDomainAttachDeviceFlags, /* domainAttachDeviceFlags */
13246
    qemudDomainDetachDevice, /* domainDetachDevice */
13247
    qemudDomainDetachDeviceFlags, /* domainDetachDeviceFlags */
13248
    qemuDomainUpdateDeviceFlags, /* domainUpdateDeviceFlags */
13249 13250
    qemudDomainGetAutostart, /* domainGetAutostart */
    qemudDomainSetAutostart, /* domainSetAutostart */
13251 13252 13253
    qemuGetSchedulerType, /* domainGetSchedulerType */
    qemuGetSchedulerParameters, /* domainGetSchedulerParameters */
    qemuSetSchedulerParameters, /* domainSetSchedulerParameters */
D
Daniel Veillard 已提交
13254 13255
    NULL, /* domainMigratePrepare (v1) */
    qemudDomainMigratePerform, /* domainMigratePerform */
13256
    NULL, /* domainMigrateFinish */
13257
    qemudDomainBlockStats, /* domainBlockStats */
13258
    qemudDomainInterfaceStats, /* domainInterfaceStats */
13259
    qemudDomainMemoryStats, /* domainMemoryStats */
13260
    qemudDomainBlockPeek, /* domainBlockPeek */
R
Richard W.M. Jones 已提交
13261
    qemudDomainMemoryPeek, /* domainMemoryPeek */
13262
    qemuDomainGetBlockInfo, /* domainGetBlockInfo */
13263 13264
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
13265 13266
    qemuDomainEventRegister, /* domainEventRegister */
    qemuDomainEventDeregister, /* domainEventDeregister */
D
Daniel Veillard 已提交
13267 13268
    qemudDomainMigratePrepare2, /* domainMigratePrepare2 */
    qemudDomainMigrateFinish2, /* domainMigrateFinish2 */
13269 13270 13271
    qemudNodeDeviceDettach, /* nodeDeviceDettach */
    qemudNodeDeviceReAttach, /* nodeDeviceReAttach */
    qemudNodeDeviceReset, /* nodeDeviceReset */
C
Chris Lalancette 已提交
13272
    qemudDomainMigratePrepareTunnel, /* domainMigratePrepareTunnel */
13273 13274 13275 13276
    qemuIsEncrypted, /* isEncrypted */
    qemuIsSecure, /* isSecure */
    qemuDomainIsActive, /* domainIsActive */
    qemuDomainIsPersistent, /* domainIsPersistent */
13277
    qemuCPUCompare, /* cpuCompare */
13278
    qemuCPUBaseline, /* cpuBaseline */
13279
    qemuDomainGetJobInfo, /* domainGetJobInfo */
13280
    qemuDomainAbortJob, /* domainAbortJob */
13281
    qemuDomainMigrateSetMaxDowntime, /* domainMigrateSetMaxDowntime */
13282 13283
    qemuDomainEventRegisterAny, /* domainEventRegisterAny */
    qemuDomainEventDeregisterAny, /* domainEventDeregisterAny */
13284 13285 13286
    qemuDomainManagedSave, /* domainManagedSave */
    qemuDomainHasManagedSaveImage, /* domainHasManagedSaveImage */
    qemuDomainManagedSaveRemove, /* domainManagedSaveRemove */
C
Chris Lalancette 已提交
13287 13288 13289 13290 13291 13292 13293 13294 13295
    qemuDomainSnapshotCreateXML, /* domainSnapshotCreateXML */
    qemuDomainSnapshotDumpXML, /* domainSnapshotDumpXML */
    qemuDomainSnapshotNum, /* domainSnapshotNum */
    qemuDomainSnapshotListNames, /* domainSnapshotListNames */
    qemuDomainSnapshotLookupByName, /* domainSnapshotLookupByName */
    qemuDomainHasCurrentSnapshot, /* domainHasCurrentSnapshot */
    qemuDomainSnapshotCurrent, /* domainSnapshotCurrent */
    qemuDomainRevertToSnapshot, /* domainRevertToSnapshot */
    qemuDomainSnapshotDelete, /* domainSnapshotDelete */
13296
    qemuDomainMonitorCommand, /* qemuDomainMonitorCommand */
13297
    qemuDomainSetMemoryParameters, /* domainSetMemoryParameters */
13298
    qemuDomainGetMemoryParameters, /* domainGetMemoryParameters */
13299 13300 13301
};


13302
static virStateDriver qemuStateDriver = {
13303
    .name = "QEMU",
13304 13305 13306 13307
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
13308
};
13309

S
Stefan Berger 已提交
13310
static int
13311
qemudVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
S
Stefan Berger 已提交
13312 13313 13314
                     virHashIterator iter, void *data)
{
    virHashForEach(qemu_driver->domains.objs, iter, data);
13315

S
Stefan Berger 已提交
13316 13317 13318
    return 0;
}

13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340
static int
qemudVMFiltersInstantiate(virConnectPtr conn,
                          virDomainDefPtr def)
{
    int err = 0;
    int i;

    if (!conn)
        return 1;

    for (i = 0 ; i < def->nnets ; i++) {
        virDomainNetDefPtr net = def->nets[i];
        if ((net->filter) && (net->ifname)) {
           if (virDomainConfNWFilterInstantiate(conn, net)) {
                err = 1;
                break;
            }
        }
    }

    return err;
}
S
Stefan Berger 已提交
13341

13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354

static void
qemudVMDriverLock(void) {
    qemuDriverLock(qemu_driver);
};


static void
qemudVMDriverUnlock(void) {
    qemuDriverUnlock(qemu_driver);
};


S
Stefan Berger 已提交
13355 13356 13357
static virNWFilterCallbackDriver qemuCallbackDriver = {
    .name = "QEMU",
    .vmFilterRebuild = qemudVMFilterRebuild,
13358 13359
    .vmDriverLock = qemudVMDriverLock,
    .vmDriverUnlock = qemudVMDriverUnlock,
S
Stefan Berger 已提交
13360 13361
};

13362
int qemuRegister(void) {
13363 13364
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
S
Stefan Berger 已提交
13365
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
13366 13367
    return 0;
}