qemu_driver.c 128.1 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 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 28 29 30 31 32 33 34 35 36
#include <sys/types.h>
#include <sys/poll.h>
#include <dirent.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <strings.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
37
#include <sys/utsname.h>
38 39 40 41
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
42 43
#include <pwd.h>
#include <stdio.h>
44
#include <sys/wait.h>
45
#include <sys/ioctl.h>
D
Daniel P. Berrange 已提交
46

47
#if HAVE_NUMACTL
48
#define NUMA_VERSION1_COMPATIBILITY 1
49 50 51
#include <numa.h>
#endif

52 53 54 55
#if HAVE_SCHED_H
#include <sched.h>
#endif

56
#include "virterror_internal.h"
57
#include "logging.h"
58
#include "datatypes.h"
59 60
#include "qemu_driver.h"
#include "qemu_conf.h"
J
Jim Meyering 已提交
61
#include "c-ctype.h"
62
#include "event.h"
63
#include "buf.h"
64
#include "util.h"
65
#include "nodeinfo.h"
66
#include "stats_linux.h"
67
#include "capabilities.h"
68
#include "memory.h"
69
#include "uuid.h"
70
#include "domain_conf.h"
71

R
Richard W.M. Jones 已提交
72 73 74
/* For storing short-lived temporary files. */
#define TEMPDIR LOCAL_STATE_DIR "/cache/libvirt"

75 76
static int qemudShutdown(void);

77 78
#define qemudLog(level, msg...) fprintf(stderr, msg)

79 80 81 82 83 84 85 86 87
static void qemuDriverLock(struct qemud_driver *driver)
{
    pthread_mutex_lock(&driver->lock);
}
static void qemuDriverUnlock(struct qemud_driver *driver)
{
    pthread_mutex_unlock(&driver->lock);
}

88 89 90 91 92 93 94 95 96
static int qemudSetCloseExec(int fd) {
    int flags;
    if ((flags = fcntl(fd, F_GETFD)) < 0)
        goto error;
    flags |= FD_CLOEXEC;
    if ((fcntl(fd, F_SETFD, flags)) < 0)
        goto error;
    return 0;
 error:
J
Jim Meyering 已提交
97
    qemudLog(QEMUD_ERR,
98
             "%s", _("Failed to set close-on-exec file descriptor flag\n"));
99 100 101 102 103 104 105 106 107 108 109 110 111
    return -1;
}


static int qemudSetNonBlock(int fd) {
    int flags;
    if ((flags = fcntl(fd, F_GETFL)) < 0)
        goto error;
    flags |= O_NONBLOCK;
    if ((fcntl(fd, F_SETFL, flags)) < 0)
        goto error;
    return 0;
 error:
J
Jim Meyering 已提交
112
    qemudLog(QEMUD_ERR,
113
             "%s", _("Failed to set non-blocking file descriptor flag\n"));
114 115 116 117
    return -1;
}


118 119 120 121

static void qemuDomainEventFlush(int timer, void *opaque);
static void qemuDomainEventQueue(struct qemud_driver *driver,
                                 virDomainEventPtr event);
122

123 124
static void qemudDispatchVMEvent(int watch,
                                 int fd,
125 126 127
                                 int events,
                                 void *opaque);

128 129
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
130 131
                              virDomainObjPtr vm,
                              const char *migrateFrom);
132

133 134
static void qemudShutdownVMDaemon(virConnectPtr conn,
                                  struct qemud_driver *driver,
135
                                  virDomainObjPtr vm);
136

137
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
138

139
static int qemudMonitorCommand (const struct qemud_driver *driver,
140
                                const virDomainObjPtr vm,
141 142
                                const char *cmd,
                                char **reply);
143

J
Jim Meyering 已提交
144
static struct qemud_driver *qemu_driver = NULL;
145 146


147 148 149 150 151
static void
qemudAutostartConfigs(struct qemud_driver *driver) {
    unsigned int i;

    for (i = 0 ; i < driver->domains.count ; i++) {
152
        virDomainObjPtr vm = driver->domains.objs[i];
153
        virDomainObjLock(vm);
154 155 156 157 158 159 160 161 162
        if (vm->autostart &&
            !virDomainIsActive(vm)) {
            int ret = qemudStartVMDaemon(NULL, driver, vm, NULL);
            if (ret < 0) {
                virErrorPtr err = virGetLastError();
                qemudLog(QEMUD_ERR, _("Failed to autostart VM '%s': %s\n"),
                         vm->def->name,
                         err ? err->message : NULL);
            } else {
163 164 165 166 167 168
                virDomainEventPtr event =
                    virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             VIR_DOMAIN_EVENT_STARTED_BOOTED);
                if (event)
                    qemuDomainEventQueue(driver, event);
169
            }
170
        }
171
        virDomainObjUnlock(vm);
172
    }
173 174
}

175 176 177 178 179 180 181
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
qemudStartup(void) {
182 183 184
    uid_t uid = geteuid();
    struct passwd *pw;
    char *base = NULL;
D
Daniel P. Berrange 已提交
185
    char driverConf[PATH_MAX];
186

187
    if (VIR_ALLOC(qemu_driver) < 0)
188 189
        return -1;

190 191 192
    pthread_mutex_init(&qemu_driver->lock, NULL);
    qemuDriverLock(qemu_driver);

193 194 195
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;

196 197
    /* Init callback list */
    if(VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
198
        goto out_of_memory;
199 200 201 202 203 204
    if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
        goto out_of_memory;

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

206
    if (!uid) {
207 208 209
        if (asprintf(&qemu_driver->logDir,
                     "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
210

D
Daniel P. Berrange 已提交
211
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
212 213 214
            goto out_of_memory;
    } else {
        if (!(pw = getpwuid(uid))) {
215
            qemudLog(QEMUD_ERR, _("Failed to find user record for uid '%d': %s\n"),
216
                     uid, strerror(errno));
217
            goto error;
218 219
        }

220 221 222
        if (asprintf(&qemu_driver->logDir,
                     "%s/.libvirt/qemu/log", pw->pw_dir) == -1)
            goto out_of_memory;
223

224
        if (asprintf (&base, "%s/.libvirt", pw->pw_dir) == -1)
225 226 227 228 229 230
            goto out_of_memory;
    }

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

D
Daniel P. Berrange 已提交
235
    if (asprintf (&qemu_driver->configDir, "%s/qemu", base) == -1)
236 237
        goto out_of_memory;

D
Daniel P. Berrange 已提交
238
    if (asprintf (&qemu_driver->autostartDir, "%s/qemu/autostart", base) == -1)
239 240
        goto out_of_memory;

241
    VIR_FREE(base);
242 243 244

    if ((qemu_driver->caps = qemudCapsInit()) == NULL)
        goto out_of_memory;
D
Daniel P. Berrange 已提交
245 246

    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
247
        goto error;
D
Daniel P. Berrange 已提交
248 249
    }

250 251 252 253
    if (virDomainLoadAllConfigs(NULL,
                                qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
254
                                qemu_driver->autostartDir,
255 256
                                NULL, NULL) < 0)
        goto error;
257 258
    qemudAutostartConfigs(qemu_driver);

259 260
    qemuDriverUnlock(qemu_driver);

261 262
    return 0;

263
out_of_memory:
J
Jim Meyering 已提交
264
    qemudLog (QEMUD_ERR,
265
              "%s", _("qemudStartup: out of memory\n"));
266 267 268
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
269
    VIR_FREE(base);
270
    qemudShutdown();
271 272 273
    return -1;
}

274 275 276 277
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;

278 279 280 281 282 283 284 285
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
    }
286 287
}

288 289 290 291 292 293 294 295
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
296 297 298
    if (!qemu_driver)
        return 0;

299
    qemuDriverLock(qemu_driver);
300 301 302 303
    virDomainLoadAllConfigs(NULL,
                            qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
304 305
                            qemu_driver->autostartDir,
                            qemudNotifyLoadDomain, qemu_driver);
306

307
    qemudAutostartConfigs(qemu_driver);
308
    qemuDriverUnlock(qemu_driver);
309 310

    return 0;
311 312
}

313 314 315 316 317 318 319 320 321 322
/**
 * 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) {
323
    unsigned int i;
324
    int active = 0;
325

326 327 328
    if (!qemu_driver)
        return 0;

329 330 331 332 333 334 335 336
    qemuDriverLock(qemu_driver);
    for (i = 0 ; i < qemu_driver->domains.count ; i++) {
        virDomainObjPtr vm = qemu_driver->domains.objs[i];
        virDomainObjLock(vm);
        if (virDomainIsActive(vm))
            active = 1;
        virDomainObjUnlock(vm);
    }
337

338 339
    qemuDriverUnlock(qemu_driver);
    return active;
340 341
}

342 343 344 345 346 347 348
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
349
    unsigned int i;
350

351
    if (!qemu_driver)
352
        return -1;
353

354
    qemuDriverLock(qemu_driver);
355 356
    virCapabilitiesFree(qemu_driver->caps);

357
    /* shutdown active VMs */
358 359
    for (i = 0 ; i < qemu_driver->domains.count ; i++) {
        virDomainObjPtr dom = qemu_driver->domains.objs[i];
360
        virDomainObjLock(dom);
361 362
        if (virDomainIsActive(dom))
            qemudShutdownVMDaemon(NULL, qemu_driver, dom);
363
        virDomainObjUnlock(dom);
364
    }
365

366
    virDomainObjListFree(&qemu_driver->domains);
367

368
    VIR_FREE(qemu_driver->logDir);
369 370 371
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
    VIR_FREE(qemu_driver->vncTLSx509certdir);
J
Jim Meyering 已提交
372
    VIR_FREE(qemu_driver->vncListen);
D
Daniel P. Berrange 已提交
373

374 375
    /* Free domain callback list */
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
376 377 378 379
    virDomainEventQueueFree(qemu_driver->domainEventQueue);

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

381 382 383
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);

384
    qemuDriverUnlock(qemu_driver);
385
    VIR_FREE(qemu_driver);
386 387

    return 0;
388 389 390
}

/* Return -1 for error, 1 to continue reading and 0 for success */
391 392
typedef int qemudHandlerMonitorOutput(virConnectPtr conn,
                                      struct qemud_driver *driver,
393
                                      virDomainObjPtr vm,
394 395 396 397
                                      const char *output,
                                      int fd);

static int
398 399
qemudReadMonitorOutput(virConnectPtr conn,
                       struct qemud_driver *driver,
400
                       virDomainObjPtr vm,
401 402 403 404
                       int fd,
                       char *buf,
                       int buflen,
                       qemudHandlerMonitorOutput func,
405 406
                       const char *what,
                       int timeout)
407 408 409 410 411 412 413 414 415 416
{
    int got = 0;
    buf[0] = '\0';

   /* Consume & discard the initial greeting */
    while (got < (buflen-1)) {
        int ret;

        ret = read(fd, buf+got, buflen-got-1);
        if (ret == 0) {
417
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
418
                             _("QEMU quit during %s startup\n%s"), what, buf);
419 420 421 422 423 424 425 426
            return -1;
        }
        if (ret < 0) {
            struct pollfd pfd = { .fd = fd, .events = POLLIN };
            if (errno == EINTR)
                continue;

            if (errno != EAGAIN) {
427
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
428
                                 _("Failure while reading %s startup output: %s"),
429 430 431 432
                                 what, strerror(errno));
                return -1;
            }

433
            ret = poll(&pfd, 1, timeout);
434
            if (ret == 0) {
435
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
436
                                 _("Timed out while reading %s startup output"), what);
437 438 439
                return -1;
            } else if (ret == -1) {
                if (errno != EINTR) {
440
                    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
441
                                     _("Failure while reading %s startup output: %s"),
442 443 444 445 446 447 448 449 450
                                     what, strerror(errno));
                    return -1;
                }
            } else {
                /* Make sure we continue loop & read any further data
                   available before dealing with EOF */
                if (pfd.revents & (POLLIN | POLLHUP))
                    continue;

451
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
452
                                 _("Failure while reading %s startup output"), what);
453 454 455 456 457
                return -1;
            }
        } else {
            got += ret;
            buf[got] = '\0';
458
            if ((ret = func(conn, driver, vm, buf, fd)) != 1)
459 460 461 462
                return ret;
        }
    }

463
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
464
                     _("Out of space while reading %s startup output"), what);
465 466 467 468 469
    return -1;

}

static int
470 471
qemudCheckMonitorPrompt(virConnectPtr conn ATTRIBUTE_UNUSED,
                        struct qemud_driver *driver ATTRIBUTE_UNUSED,
472
                        virDomainObjPtr vm,
473 474 475 476 477 478 479 480 481 482 483
                        const char *output,
                        int fd)
{
    if (strstr(output, "(qemu) ") == NULL)
        return 1; /* keep reading */

    vm->monitor = fd;

    return 0;
}

484 485
static int qemudOpenMonitor(virConnectPtr conn,
                            struct qemud_driver *driver,
486
                            virDomainObjPtr vm,
487
                            const char *monitor) {
488 489 490 491
    int monfd;
    char buf[1024];
    int ret = -1;

D
Daniel Veillard 已提交
492
    if ((monfd = open(monitor, O_RDWR)) < 0) {
493
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
494
                         _("Unable to open monitor path %s"), monitor);
495 496 497
        return -1;
    }
    if (qemudSetCloseExec(monfd) < 0) {
498
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
499
                         "%s", _("Unable to set monitor close-on-exec flag"));
500 501 502
        goto error;
    }
    if (qemudSetNonBlock(monfd) < 0) {
503
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
504
                         "%s", _("Unable to put monitor into non-blocking mode"));
505 506 507
        goto error;
    }

508 509
    ret = qemudReadMonitorOutput(conn,
                                 driver, vm, monfd,
510 511
                                 buf, sizeof(buf),
                                 qemudCheckMonitorPrompt,
512
                                 "monitor", 10000);
513 514 515 516 517

    /* Keep monitor open upon success */
    if (ret == 0)
        return ret;

518 519 520 521 522
 error:
    close(monfd);
    return ret;
}

523 524
static int qemudExtractMonitorPath(virConnectPtr conn,
                                   const char *haystack,
525
                                   size_t *offset,
526
                                   char **path) {
527
    static const char needle[] = "char device redirected to";
528
    char *tmp, *dev;
529

530
    VIR_FREE(*path);
531
    /* First look for our magic string */
532 533 534 535 536
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
537

538 539 540 541 542
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
543
        if (c_isspace(*tmp)) {
544 545 546 547 548 549 550
            if (VIR_ALLOC_N(*path, (tmp-dev)+1) < 0) {
                qemudReportError(conn, NULL, NULL,
                                 VIR_ERR_NO_MEMORY, NULL);
                return -1;
            }
            strncpy(*path, dev, (tmp-dev));
            (*path)[(tmp-dev)] = '\0';
551
            /* ... now further update offset till we get EOL */
552
            *offset = tmp - haystack;
553 554
            return 0;
        }
555
        tmp++;
556 557 558 559 560
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
561 562
     * least see a \n - indicate that we want to carry
     * on trying again
563
     */
564
    return 1;
565 566 567
}

static int
568 569
qemudFindCharDevicePTYs(virConnectPtr conn,
                        struct qemud_driver *driver,
570
                        virDomainObjPtr vm,
571 572
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
573
{
574
    char *monitor = NULL;
575
    size_t offset = 0;
576
    int ret, i;
577 578 579 580 581

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

583
    /* So first comes the monitor device */
584 585
    if ((ret = qemudExtractMonitorPath(conn, output, &offset, &monitor)) != 0)
        goto cleanup;
586

587
    /* then the serial devices */
588 589
    for (i = 0 ; i < vm->def->nserials ; i++) {
        virDomainChrDefPtr chr = vm->def->serials[i];
590 591 592 593
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
594 595 596 597
        }
    }

    /* and finally the parallel devices */
598 599
    for (i = 0 ; i < vm->def->nparallels ; i++) {
        virDomainChrDefPtr chr = vm->def->parallels[i];
600 601 602 603
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
604 605 606 607
        }
    }

    /* Got them all, so now open the monitor console */
608 609 610 611 612
    ret = qemudOpenMonitor(conn, driver, vm, monitor);

cleanup:
    VIR_FREE(monitor);
    return ret;
613 614
}

615 616
static int qemudWaitForMonitor(virConnectPtr conn,
                               struct qemud_driver *driver,
617
                               virDomainObjPtr vm) {
618
    char buf[1024]; /* Plenty of space to get startup greeting */
619
    int ret = qemudReadMonitorOutput(conn,
620
                                     driver, vm, vm->stderr_fd,
621
                                     buf, sizeof(buf),
622
                                     qemudFindCharDevicePTYs,
623
                                     "console", 3000);
624 625

    buf[sizeof(buf)-1] = '\0';
626 627

    if (safewrite(vm->logfile, buf, strlen(buf)) < 0) {
628
        /* Log, but ignore failures to write logfile for VM */
629
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
630 631 632 633 634
                 strerror(errno));
    }
    return ret;
}

635 636 637
static int
qemudDetectVcpuPIDs(virConnectPtr conn,
                    struct qemud_driver *driver,
638
                    virDomainObjPtr vm) {
639 640 641 642 643 644
    char *qemucpus = NULL;
    char *line;
    int lastVcpu = -1;

    /* Only KVM has seperate threads for CPUs,
       others just use main QEMU process for CPU */
645
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM)
646 647 648 649 650 651 652 653 654 655
        vm->nvcpupids = 1;
    else
        vm->nvcpupids = vm->def->vcpus;

    if (VIR_ALLOC_N(vm->vcpupids, vm->nvcpupids) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("allocate cpumap"));
        return -1;
    }

656
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
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 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
        vm->vcpupids[0] = vm->pid;
        return 0;
    }

    if (qemudMonitorCommand(driver, vm, "info cpus", &qemucpus) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot run monitor command to fetch CPU thread info"));
        VIR_FREE(vm->vcpupids);
        vm->nvcpupids = 0;
        return -1;
    }

    /*
     * This is the gross format we're about to parse :-{
     *
     * (qemu) info cpus
     * * CPU #0: pc=0x00000000000f0c4a thread_id=30019
     *   CPU #1: pc=0x00000000fffffff0 thread_id=30020
     *   CPU #2: pc=0x00000000fffffff0 thread_id=30021
     *
     */
    line = qemucpus;
    do {
        char *offset = strchr(line, '#');
        char *end = NULL;
        int vcpu = 0, tid = 0;

        /* See if we're all done */
        if (offset == NULL)
            break;

        /* Extract VCPU number */
        if (virStrToLong_i(offset + 1, &end, 10, &vcpu) < 0)
            goto error;
        if (end == NULL || *end != ':')
            goto error;

        /* Extract host Thread ID */
        if ((offset = strstr(line, "thread_id=")) == NULL)
            goto error;
        if (virStrToLong_i(offset + strlen("thread_id="), &end, 10, &tid) < 0)
            goto error;
        if (end == NULL || !c_isspace(*end))
            goto error;

        /* Validate the VCPU is in expected range & order */
        if (vcpu > vm->nvcpupids ||
            vcpu != (lastVcpu + 1))
            goto error;

        lastVcpu = vcpu;
        vm->vcpupids[vcpu] = tid;

        /* Skip to next data line */
        line = strchr(offset, '\r');
        if (line == NULL)
            line = strchr(offset, '\n');
    } while (line != NULL);

    /* Validate we got data for all VCPUs we expected */
    if (lastVcpu != (vm->def->vcpus - 1))
        goto error;

720
    VIR_FREE(qemucpus);
721 722 723 724
    return 0;

error:
    VIR_FREE(vm->vcpupids);
725 726
    vm->nvcpupids = 0;
    VIR_FREE(qemucpus);
727 728 729 730 731 732 733 734

    /* Explicitly return success, not error. Older KVM does
       not have vCPU -> Thread mapping info and we don't
       want to break its use. This merely disables ability
       to pin vCPUS with libvirt */
    return 0;
}

735 736 737
static int
qemudInitCpus(virConnectPtr conn,
              struct qemud_driver *driver,
D
Daniel Veillard 已提交
738 739
              virDomainObjPtr vm,
              const char *migrateFrom) {
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
    char *info = NULL;
#if HAVE_SCHED_GETAFFINITY
    cpu_set_t mask;
    int i, maxcpu = QEMUD_CPUMASK_LEN;
    virNodeInfo nodeinfo;

    if (virNodeInfoPopulate(conn, &nodeinfo) < 0)
        return -1;

    /* setaffinity fails if you set bits for CPUs which
     * aren't present, so we have to limit ourselves */
    if (maxcpu > nodeinfo.cpus)
        maxcpu = nodeinfo.cpus;

    CPU_ZERO(&mask);
D
Daniel P. Berrange 已提交
755 756 757 758 759 760
    if (vm->def->cpumask) {
        for (i = 0 ; i < maxcpu ; i++)
            if (vm->def->cpumask[i])
                CPU_SET(i, &mask);
    } else {
        for (i = 0 ; i < maxcpu ; i++)
761
            CPU_SET(i, &mask);
D
Daniel P. Berrange 已提交
762
    }
763 764 765 766 767 768 769 770 771 772 773 774

    for (i = 0 ; i < vm->nvcpupids ; i++) {
        if (sched_setaffinity(vm->vcpupids[i],
                              sizeof(mask), &mask) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("failed to set CPU affinity %s"),
                             strerror(errno));
            return -1;
        }
    }
#endif /* HAVE_SCHED_GETAFFINITY */

D
Daniel Veillard 已提交
775 776 777 778 779 780 781 782
    if (migrateFrom == NULL) {
        /* Allow the CPUS to start executing */
        if (qemudMonitorCommand(driver, vm, "cont", &info) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("resume operation failed"));
            return -1;
        }
        VIR_FREE(info);
783 784 785 786 787 788
    }

    return 0;
}


789
static int qemudNextFreeVNCPort(struct qemud_driver *driver ATTRIBUTE_UNUSED) {
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
    int i;

    for (i = 5900 ; i < 6000 ; i++) {
        int fd;
        int reuse = 1;
        struct sockaddr_in addr;
        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);
            return i;
        }
        close(fd);

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

825 826 827
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
                                            const char *name);

828 829
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
830 831
                              virDomainObjPtr vm,
                              const char *migrateFrom) {
832
    const char **argv = NULL, **tmp;
833
    const char **progenv = NULL;
834
    int i, ret;
835
    char logfile[PATH_MAX];
836
    struct stat sb;
837 838
    int *tapfds = NULL;
    int ntapfds = 0;
839
    unsigned int qemuCmdFlags;
840
    fd_set keepfd;
841
    const char *emulator;
842 843

    FD_ZERO(&keepfd);
844

845
    if (virDomainIsActive(vm)) {
846
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
847
                         "%s", _("VM is already active"));
848 849 850
        return -1;
    }

851 852 853
    if (vm->def->graphics &&
        vm->def->graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics->data.vnc.autoport) {
854
        int port = qemudNextFreeVNCPort(driver);
855
        if (port < 0) {
856
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
857
                             "%s", _("Unable to find an unused VNC port"));
858 859
            return -1;
        }
860 861
        vm->def->graphics->data.vnc.port = port;
    }
862

863
    if ((strlen(driver->logDir) + /* path */
864 865 866 867
         1 + /* Separator */
         strlen(vm->def->name) + /* basename */
         4 + /* suffix .log */
         1 /* NULL */) > PATH_MAX) {
868
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
869
                         _("config file path too long: %s/%s.log"),
870
                         driver->logDir, vm->def->name);
871 872
        return -1;
    }
873
    strcpy(logfile, driver->logDir);
874 875 876 877
    strcat(logfile, "/");
    strcat(logfile, vm->def->name);
    strcat(logfile, ".log");

878
    if (virFileMakePath(driver->logDir) < 0) {
879
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
880
                         _("cannot create log directory %s: %s"),
881
                         driver->logDir, strerror(errno));
882 883 884 885 886
        return -1;
    }

    if ((vm->logfile = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                            S_IRUSR | S_IWUSR)) < 0) {
887
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
888
                         _("failed to create logfile %s: %s"),
889 890 891
                         logfile, strerror(errno));
        return -1;
    }
892 893
    if (qemudSetCloseExec(vm->logfile) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
894
                         _("Unable to set VM logfile close-on-exec flag %s"),
895 896 897 898 899
                         strerror(errno));
        close(vm->logfile);
        vm->logfile = -1;
        return -1;
    }
900

901 902 903 904 905 906
    emulator = vm->def->emulator;
    if (!emulator)
        emulator = virDomainDefDefaultEmulator(conn, vm->def, driver->caps);
    if (!emulator)
        return -1;

907 908 909 910
    /* 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
     */
911
    if (stat(emulator, &sb) < 0) {
912 913
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot find QEMU binary %s: %s"),
914
                         emulator,
915 916 917 918
                         strerror(errno));
        return -1;
    }

919
    if (qemudExtractVersionInfo(emulator,
920 921 922 923
                                NULL,
                                &qemuCmdFlags) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot determine QEMU argv syntax %s"),
924
                         emulator);
925 926
        return -1;
    }
927

928
    vm->def->id = driver->nextvmid++;
929
    if (qemudBuildCommandLine(conn, driver, vm,
930
                              qemuCmdFlags, &argv, &progenv,
931
                              &tapfds, &ntapfds, migrateFrom) < 0) {
932
        close(vm->logfile);
933
        vm->def->id = -1;
934 935 936 937
        vm->logfile = -1;
        return -1;
    }

938 939 940 941 942 943 944 945 946 947
    tmp = progenv;
    while (*tmp) {
        if (safewrite(vm->logfile, *tmp, strlen(*tmp)) < 0)
            qemudLog(QEMUD_WARN, _("Unable to write envv to logfile %d: %s\n"),
                     errno, strerror(errno));
        if (safewrite(vm->logfile, " ", 1) < 0)
            qemudLog(QEMUD_WARN, _("Unable to write envv to logfile %d: %s\n"),
                     errno, strerror(errno));
        tmp++;
    }
948 949
    tmp = argv;
    while (*tmp) {
950
        if (safewrite(vm->logfile, *tmp, strlen(*tmp)) < 0)
951
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
952
                     errno, strerror(errno));
953
        if (safewrite(vm->logfile, " ", 1) < 0)
954
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
955 956 957
                     errno, strerror(errno));
        tmp++;
    }
958
    if (safewrite(vm->logfile, "\n", 1) < 0)
959
        qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
960 961
                 errno, strerror(errno));

962 963 964
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;

965 966 967
    for (i = 0 ; i < ntapfds ; i++)
        FD_SET(tapfds[i], &keepfd);

968
    ret = virExec(conn, argv, progenv, &keepfd, &vm->pid,
969 970
                  vm->stdin_fd, &vm->stdout_fd, &vm->stderr_fd,
                  VIR_EXEC_NONBLOCK);
971
    if (ret == 0)
972
        vm->state = migrateFrom ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
973 974
    else
        vm->def->id = -1;
975

976
    for (i = 0 ; argv[i] ; i++)
977 978
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
979

980 981 982 983
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

984 985 986
    if (tapfds) {
        for (i = 0 ; i < ntapfds ; i++) {
            close(tapfds[i]);
987
        }
988
        VIR_FREE(tapfds);
989 990
    }

991
    if (ret == 0) {
992
        if (((vm->stdout_watch = virEventAddHandle(vm->stdout_fd,
993 994 995 996 997
                                                   VIR_EVENT_HANDLE_READABLE |
                                                   VIR_EVENT_HANDLE_ERROR |
                                                   VIR_EVENT_HANDLE_HANGUP,
                                                   qemudDispatchVMEvent,
                                                   driver, NULL)) < 0) ||
998 999 1000 1001 1002
            ((vm->stderr_watch = virEventAddHandle(vm->stderr_fd,
                                                   VIR_EVENT_HANDLE_READABLE |
                                                   VIR_EVENT_HANDLE_ERROR |
                                                   VIR_EVENT_HANDLE_HANGUP,
                                                   qemudDispatchVMEvent,
1003
                                                   driver, NULL)) < 0) ||
1004 1005
            (qemudWaitForMonitor(conn, driver, vm) < 0) ||
            (qemudDetectVcpuPIDs(conn, driver, vm) < 0) ||
D
Daniel Veillard 已提交
1006
            (qemudInitCpus(conn, driver, vm, migrateFrom) < 0)) {
1007 1008 1009
            qemudShutdownVMDaemon(conn, driver, vm);
            return -1;
        }
1010 1011
    }

1012
    return ret;
1013 1014
}

1015
static int qemudVMData(struct qemud_driver *driver ATTRIBUTE_UNUSED,
1016
                       virDomainObjPtr vm, int fd) {
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    char buf[4096];
    if (vm->pid < 0)
        return 0;

    for (;;) {
        int ret = read(fd, buf, sizeof(buf)-1);
        if (ret < 0) {
            if (errno == EAGAIN)
                return 0;
            return -1;
        }
        if (ret == 0) {
            return 0;
        }
        buf[ret] = '\0';

1033
        if (safewrite(vm->logfile, buf, ret) < 0) {
1034
            /* Log, but ignore failures to write logfile for VM */
1035
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1036 1037 1038 1039 1040 1041
                     strerror(errno));
        }
    }
}


1042
static void qemudShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
1043 1044
                                  struct qemud_driver *driver, virDomainObjPtr vm) {
    if (!virDomainIsActive(vm))
1045
        return;
1046

1047
    qemudLog(QEMUD_INFO, _("Shutting down VM '%s'\n"), vm->def->name);
1048 1049 1050

    kill(vm->pid, SIGTERM);

1051 1052
    qemudVMData(driver, vm, vm->stdout_fd);
    qemudVMData(driver, vm, vm->stderr_fd);
1053

1054 1055
    virEventRemoveHandle(vm->stdout_watch);
    virEventRemoveHandle(vm->stderr_watch);
1056 1057

    if (close(vm->logfile) < 0)
1058
        qemudLog(QEMUD_WARN, _("Unable to close logfile %d: %s\n"),
1059
                 errno, strerror(errno));
1060 1061
    close(vm->stdout_fd);
    close(vm->stderr_fd);
1062 1063 1064
    if (vm->monitor != -1)
        close(vm->monitor);
    vm->logfile = -1;
1065 1066
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;
1067 1068 1069 1070 1071
    vm->monitor = -1;

    if (waitpid(vm->pid, NULL, WNOHANG) != vm->pid) {
        kill(vm->pid, SIGKILL);
        if (waitpid(vm->pid, NULL, 0) != vm->pid) {
J
Jim Meyering 已提交
1072
            qemudLog(QEMUD_WARN,
1073
                     "%s", _("Got unexpected pid, damn\n"));
1074 1075 1076 1077
        }
    }

    vm->pid = -1;
1078
    vm->def->id = -1;
1079
    vm->state = VIR_DOMAIN_SHUTOFF;
1080
    VIR_FREE(vm->vcpupids);
1081
    vm->nvcpupids = 0;
1082 1083

    if (vm->newDef) {
1084
        virDomainDefFree(vm->def);
1085
        vm->def = vm->newDef;
1086
        vm->def->id = -1;
1087 1088 1089 1090 1091
        vm->newDef = NULL;
    }
}


1092
static void
1093
qemudDispatchVMEvent(int watch, int fd, int events, void *opaque) {
1094
    struct qemud_driver *driver = opaque;
1095
    virDomainObjPtr vm = NULL;
1096
    virDomainEventPtr event = NULL;
1097
    unsigned int i;
1098
    int quit = 0, failed = 0;
1099

1100
    qemuDriverLock(driver);
1101
    for (i = 0 ; i < driver->domains.count ; i++) {
1102 1103 1104 1105 1106 1107
        virDomainObjPtr tmpvm = driver->domains.objs[i];
        virDomainObjLock(tmpvm);
        if (virDomainIsActive(tmpvm) &&
            (tmpvm->stdout_watch == watch ||
             tmpvm->stderr_watch == watch)) {
            vm = tmpvm;
1108
            break;
1109
        }
1110
        virDomainObjUnlock(tmpvm);
1111 1112 1113
    }

    if (!vm)
1114
        goto cleanup;
1115

1116 1117
    if (vm->stdout_fd != fd &&
        vm->stderr_fd != fd) {
1118 1119 1120 1121 1122 1123 1124 1125
        failed = 1;
    } else {
        if (events & VIR_EVENT_HANDLE_READABLE) {
            if (qemudVMData(driver, vm, fd) < 0)
                failed = 1;
        } else {
            quit = 1;
        }
1126 1127
    }

1128
    if (failed || quit) {
1129 1130 1131 1132 1133
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         quit ?
                                         VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN :
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
        qemudShutdownVMDaemon(NULL, driver, vm);
        if (!vm->persistent) {
            virDomainRemoveInactive(&driver->domains,
                                    vm);
            vm = NULL;
        }
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
1145 1146
    if (event)
        qemuDomainEventQueue(driver, event);
1147
    qemuDriverUnlock(driver);
1148 1149
}

1150 1151
static int
qemudMonitorCommand (const struct qemud_driver *driver ATTRIBUTE_UNUSED,
1152
                     const virDomainObjPtr vm,
1153 1154
                     const char *cmd,
                     char **reply) {
D
Daniel P. Berrange 已提交
1155 1156
    int size = 0;
    char *buf = NULL;
1157
    size_t cmdlen = strlen(cmd);
D
Daniel P. Berrange 已提交
1158

1159 1160 1161
    if (safewrite(vm->monitor, cmd, cmdlen) != cmdlen)
        return -1;
    if (safewrite(vm->monitor, "\r", 1) != 1)
D
Daniel P. Berrange 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
        return -1;

    *reply = NULL;

    for (;;) {
        struct pollfd fd = { vm->monitor, POLLIN | POLLERR | POLLHUP, 0 };
        char *tmp;

        /* Read all the data QEMU has sent thus far */
        for (;;) {
            char data[1024];
            int got = read(vm->monitor, data, sizeof(data));
D
Daniel P. Berrange 已提交
1174

1175 1176
            if (got == 0)
                goto error;
D
Daniel P. Berrange 已提交
1177 1178 1179 1180 1181
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
1182
                goto error;
1183
            }
1184
            if (VIR_REALLOC_N(buf, size+got+1) < 0)
1185 1186
                goto error;

D
Daniel P. Berrange 已提交
1187 1188 1189 1190
            memmove(buf+size, data, got);
            buf[size+got] = '\0';
            size += got;
        }
1191

D
Daniel P. Berrange 已提交
1192
        /* Look for QEMU prompt to indicate completion */
D
Daniel P. Berrange 已提交
1193
        if (buf && ((tmp = strstr(buf, "\n(qemu) ")) != NULL)) {
D
Daniel P. Berrange 已提交
1194 1195 1196 1197 1198 1199 1200 1201
            tmp[0] = '\0';
            break;
        }
    pollagain:
        /* Need to wait for more data */
        if (poll(&fd, 1, -1) < 0) {
            if (errno == EINTR)
                goto pollagain;
1202
            goto error;
D
Daniel P. Berrange 已提交
1203 1204 1205
        }
    }

1206 1207
    /* Log, but ignore failures to write logfile for VM */
    if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1208
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1209 1210
                 strerror(errno));

D
Daniel P. Berrange 已提交
1211 1212
    *reply = buf;
    return 0;
1213 1214 1215 1216 1217

 error:
    if (buf) {
        /* Log, but ignore failures to write logfile for VM */
        if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1218
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1219
                     strerror(errno));
1220
        VIR_FREE(buf);
1221 1222
    }
    return -1;
D
Daniel P. Berrange 已提交
1223 1224
}

1225 1226 1227 1228 1229 1230
/**
 * qemudProbe:
 *
 * Probe for the availability of the qemu driver, assume the
 * presence of QEmu emulation if the binaries are installed
 */
1231
static int qemudProbe(void)
1232 1233 1234
{
    if ((virFileExists("/usr/bin/qemu")) ||
        (virFileExists("/usr/bin/qemu-kvm")) ||
G
Guido Günther 已提交
1235
        (virFileExists("/usr/bin/kvm")) ||
1236 1237 1238 1239
        (virFileExists("/usr/bin/xenner")))
        return 1;

    return 0;
1240
}
1241

1242
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
1243
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1244
                                  int flags ATTRIBUTE_UNUSED) {
1245 1246 1247
    uid_t uid = getuid();

    if (qemu_driver == NULL)
1248
        goto decline;
1249

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
    if (!qemudProbe())
        goto decline;

    if (conn->uri == NULL) {
        conn->uri = xmlParseURI(uid ? "qemu:///session" : "qemu:///system");
        if (!conn->uri) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,NULL);
            return VIR_DRV_OPEN_ERROR;
        }
    } else if (conn->uri->scheme == NULL ||
               conn->uri->path == NULL)
1261 1262
        goto decline;

1263
    if (STRNEQ (conn->uri->scheme, "qemu"))
1264 1265
        goto decline;

1266
    if (uid != 0) {
1267
        if (STRNEQ (conn->uri->path, "/session"))
1268
            goto decline;
1269
    } else { /* root */
1270 1271
        if (STRNEQ (conn->uri->path, "/system") &&
            STRNEQ (conn->uri->path, "/session"))
1272
            goto decline;
1273 1274 1275 1276 1277
    }

    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
1278 1279

 decline:
1280
    return VIR_DRV_OPEN_DECLINED;
1281 1282 1283
}

static int qemudClose(virConnectPtr conn) {
1284
    struct qemud_driver *driver = conn->privateData;
1285 1286 1287

    /* Get rid of callbacks registered for this conn */
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
1288 1289 1290 1291 1292 1293

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
/* Which features are supported by this driver? */
static int
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
{
    switch (feature) {
    case VIR_DRV_FEATURE_MIGRATION_V2: return 1;
    default: return 0;
    }
}

1304
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1305
    return "QEMU";
1306 1307
}

1308 1309 1310 1311 1312

static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
1313

1314 1315
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
1316
        qemudLog(QEMUD_WARN, _("Unable to open %s: %s\n"), KVM_DEVICE, strerror(errno));
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
        return maxvcpus;
    }

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

    close(fd);
    return maxvcpus;
}


1329
static int qemudGetMaxVCPUs(virConnectPtr conn, const char *type) {
1330 1331 1332
    if (!type)
        return 16;

1333
    if (STRCASEEQ(type, "qemu"))
1334 1335 1336 1337
        return 16;

    /* XXX future KVM will support SMP. Need to probe
       kernel to figure out KVM module version i guess */
1338
    if (STRCASEEQ(type, "kvm"))
1339
        return kvmGetMaxVCPUs();
1340

1341
    if (STRCASEEQ(type, "kqemu"))
1342
        return 1;
1343 1344 1345

    qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                     _("unknown type '%s'"), type);
1346 1347 1348
    return -1;
}

1349 1350 1351
static int qemudGetNodeInfo(virConnectPtr conn,
                            virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
1352 1353 1354
}


1355
static char *qemudGetCapabilities(virConnectPtr conn) {
1356
    struct qemud_driver *driver = conn->privateData;
1357
    char *xml;
1358

1359
    qemuDriverLock(driver);
1360
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1361 1362
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                 "%s", _("failed to allocate space for capabilities support"));
1363
    qemuDriverUnlock(driver);
1364

1365
    return xml;
1366 1367 1368
}


1369 1370 1371 1372 1373 1374 1375 1376
#if HAVE_NUMACTL
static int
qemudNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;
1377
    int ret = -1;
1378 1379 1380 1381

    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1382
        goto cleanup;
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    }
    lastCell = startCell + maxCells - 1;
    if (lastCell > numa_max_node())
        lastCell = numa_max_node();

    for (numCells = 0, n = startCell ; n <= lastCell ; n++) {
        long long mem;
        if (numa_node_size64(n, &mem) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("Failed to query NUMA free memory"));
1393
            goto cleanup;
1394 1395 1396
        }
        freeMems[numCells++] = mem;
    }
1397 1398 1399 1400
    ret = numCells;

cleanup:
    return ret;
1401 1402 1403 1404 1405
}

static unsigned long long
qemudNodeGetFreeMemory (virConnectPtr conn)
{
1406
    unsigned long long freeMem = -1;
1407
    int n;
1408

1409 1410 1411
    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1412
        goto cleanup;
1413 1414 1415 1416 1417 1418 1419
    }

    for (n = 0 ; n <= numa_max_node() ; n++) {
        long long mem;
        if (numa_node_size64(n, &mem) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("Failed to query NUMA free memory"));
1420
            goto cleanup;
1421 1422 1423 1424
        }
        freeMem += mem;
    }

1425
cleanup:
1426 1427 1428 1429
    return freeMem;
}

#endif
1430

D
Daniel P. Berrange 已提交
1431 1432 1433
static int qemudGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
1434
    unsigned long long usertime, systime;
D
Daniel P. Berrange 已提交
1435 1436 1437 1438 1439 1440

    if (snprintf(proc, sizeof(proc), "/proc/%d/stat", pid) >= (int)sizeof(proc)) {
        return -1;
    }

    if (!(pidinfo = fopen(proc, "r"))) {
1441
        /*printf("cannot read pid info");*/
D
Daniel P. Berrange 已提交
1442 1443 1444 1445 1446
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
        return 0;
    }

1447
    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
1448
        qemudDebug("not enough arg");
D
Daniel P. Berrange 已提交
1449 1450 1451 1452 1453 1454 1455 1456
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1457
    *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
D
Daniel P. Berrange 已提交
1458

1459
    qemudDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);
D
Daniel P. Berrange 已提交
1460 1461 1462 1463 1464 1465 1466

    fclose(pidinfo);

    return 0;
}


1467
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1468
                                          int id) {
1469 1470 1471 1472
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1473
    qemuDriverLock(driver);
1474
    vm  = virDomainFindByID(&driver->domains, id);
1475
    qemuDriverUnlock(driver);
1476 1477

    if (!vm) {
1478
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1479
        goto cleanup;
1480 1481
    }

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

cleanup:
1486 1487
    if (vm)
        virDomainObjUnlock(vm);
1488 1489
    return dom;
}
1490

1491
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1492
                                            const unsigned char *uuid) {
1493 1494 1495
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1496

1497
    qemuDriverLock(driver);
1498
    vm = virDomainFindByUUID(&driver->domains, uuid);
1499 1500
    qemuDriverUnlock(driver);

1501
    if (!vm) {
1502
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1503
        goto cleanup;
1504 1505
    }

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

cleanup:
1510 1511
    if (vm)
        virDomainObjUnlock(vm);
1512 1513
    return dom;
}
1514

1515
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1516
                                            const char *name) {
1517 1518 1519
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1520

1521
    qemuDriverLock(driver);
1522
    vm = virDomainFindByName(&driver->domains, name);
1523 1524
    qemuDriverUnlock(driver);

1525
    if (!vm) {
1526
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1527
        goto cleanup;
1528 1529
    }

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

cleanup:
1534 1535
    if (vm)
        virDomainObjUnlock(vm);
1536 1537 1538
    return dom;
}

1539
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1540 1541 1542
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1543
    qemuDriverLock(driver);
1544
    if (qemudExtractVersion(conn, driver) < 0)
1545
        goto cleanup;
1546

1547
    *version = qemu_driver->qemuVersion;
1548 1549 1550
    ret = 0;

cleanup:
1551
    qemuDriverUnlock(driver);
1552
    return ret;
D
Daniel P. Berrange 已提交
1553 1554
}

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
static char *
qemudGetHostname (virConnectPtr conn)
{
    int r;
    char hostname[HOST_NAME_MAX+1], *str;

    r = gethostname (hostname, HOST_NAME_MAX+1);
    if (r == -1) {
        qemudReportError (conn, NULL, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
        return NULL;
    }
    /* Caller frees this string. */
    str = strdup (hostname);
    if (str == NULL) {
        qemudReportError (conn, NULL, NULL, VIR_ERR_SYSTEM_ERROR,
                         "%s", strerror (errno));
        return NULL;
    }
    return str;
}

1577
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1578
    struct qemud_driver *driver = conn->privateData;
1579 1580
    int got = 0, i;

1581 1582 1583
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count && got < nids ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1584 1585
        if (virDomainIsActive(driver->domains.objs[i]))
            ids[got++] = driver->domains.objs[i]->def->id;
1586 1587 1588
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1589

D
Daniel P. Berrange 已提交
1590 1591
    return got;
}
1592

1593
static int qemudNumDomains(virConnectPtr conn) {
1594
    struct qemud_driver *driver = conn->privateData;
1595 1596
    int n = 0, i;

1597 1598 1599
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1600
        if (virDomainIsActive(driver->domains.objs[i]))
1601
            n++;
1602 1603 1604
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1605

1606
    return n;
D
Daniel P. Berrange 已提交
1607
}
1608

1609
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1610
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1611
    struct qemud_driver *driver = conn->privateData;
1612
    virDomainDefPtr def;
1613
    virDomainObjPtr vm = NULL;
1614
    virDomainPtr dom = NULL;
1615
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
1616

1617
    qemuDriverLock(driver);
1618
    if (!(def = virDomainDefParseString(conn, driver->caps, xml)))
1619
        goto cleanup;
1620

1621
    vm = virDomainFindByName(&driver->domains, def->name);
1622
    if (vm) {
1623
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1624
                         _("domain '%s' is already defined"),
1625
                         def->name);
1626
        goto cleanup;
1627
    }
1628
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
1629 1630 1631 1632 1633
    if (vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(def->uuid, uuidstr);
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1634
                         _("domain with uuid '%s' is already defined"),
1635
                         uuidstr);
1636
        goto cleanup;
1637
    }
1638

1639 1640
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
1641 1642 1643 1644
                                  def)))
        goto cleanup;

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

1646 1647 1648
    if (qemudStartVMDaemon(conn, driver, vm, NULL) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1649
        vm = NULL;
1650
        goto cleanup;
D
Daniel P. Berrange 已提交
1651
    }
1652 1653 1654 1655

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
D
Daniel P. Berrange 已提交
1656

1657
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1658
    if (dom) dom->id = vm->def->id;
1659 1660 1661

cleanup:
    virDomainDefFree(def);
1662 1663
    if (vm)
        virDomainObjUnlock(vm);
1664 1665
    if (event)
        qemuDomainEventQueue(driver, event);
1666
    qemuDriverUnlock(driver);
1667
    return dom;
D
Daniel P. Berrange 已提交
1668 1669 1670
}


1671
static int qemudDomainSuspend(virDomainPtr dom) {
1672
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1673
    char *info;
1674 1675
    virDomainObjPtr vm;
    int ret = -1;
1676
    virDomainEventPtr event = NULL;
1677

1678
    qemuDriverLock(driver);
1679
    vm = virDomainFindByID(&driver->domains, dom->id);
1680 1681
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
1682
    if (!vm) {
1683
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN, _("no domain with matching id %d"), dom->id);
1684
        goto cleanup;
D
Daniel P. Berrange 已提交
1685
    }
1686
    if (!virDomainIsActive(vm)) {
1687 1688
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
1689
        goto cleanup;
D
Daniel P. Berrange 已提交
1690
    }
1691 1692 1693 1694 1695 1696 1697 1698
    if (vm->state != VIR_DOMAIN_PAUSED) {
        if (qemudMonitorCommand(driver, vm, "stop", &info) < 0) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("suspend operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_PAUSED;
        qemudDebug("Reply %s", info);
1699 1700 1701
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
1702
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
1703
    }
1704 1705 1706
    ret = 0;

cleanup:
1707 1708
    if (vm)
        virDomainObjUnlock(vm);
1709 1710 1711 1712 1713 1714

    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
1715
    return ret;
D
Daniel P. Berrange 已提交
1716 1717 1718
}


1719
static int qemudDomainResume(virDomainPtr dom) {
1720
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1721
    char *info;
1722 1723
    virDomainObjPtr vm;
    int ret = -1;
1724
    virDomainEventPtr event = NULL;
1725

1726
    qemuDriverLock(driver);
1727
    vm = virDomainFindByID(&driver->domains, dom->id);
1728 1729
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
1730
    if (!vm) {
1731 1732
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
1733
        goto cleanup;
D
Daniel P. Berrange 已提交
1734
    }
1735
    if (!virDomainIsActive(vm)) {
1736 1737
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
1738
        goto cleanup;
D
Daniel P. Berrange 已提交
1739
    }
1740 1741 1742 1743 1744 1745 1746 1747
    if (vm->state == VIR_DOMAIN_PAUSED) {
        if (qemudMonitorCommand(driver, vm, "cont", &info) < 0) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("resume operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_RUNNING;
        qemudDebug("Reply %s", info);
1748 1749 1750
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
1751
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
1752
    }
1753 1754 1755
    ret = 0;

cleanup:
1756 1757
    if (vm)
        virDomainObjUnlock(vm);
1758 1759 1760 1761 1762
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
1763
    return ret;
D
Daniel P. Berrange 已提交
1764 1765 1766
}


1767
static int qemudDomainShutdown(virDomainPtr dom) {
1768 1769
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1770
    char* info;
1771
    int ret = -1;
1772

1773
    qemuDriverLock(driver);
1774
    vm = virDomainFindByID(&driver->domains, dom->id);
1775 1776
    qemuDriverUnlock(driver);

1777 1778
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1779
                         _("no domain with matching id %d"), dom->id);
1780
        goto cleanup;
1781 1782 1783 1784
    }

    if (qemudMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1785
                         "%s", _("shutdown operation failed"));
1786
        goto cleanup;
1787
    }
D
Daniel Veillard 已提交
1788
    VIR_FREE(info);
1789 1790 1791
    ret = 0;

cleanup:
1792 1793
    if (vm)
        virDomainObjUnlock(vm);
1794
    return ret;
1795 1796 1797
}


1798
static int qemudDomainDestroy(virDomainPtr dom) {
1799 1800 1801
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1802
    virDomainEventPtr event = NULL;
1803

1804
    qemuDriverLock(driver);
1805
    vm  = virDomainFindByID(&driver->domains, dom->id);
D
Daniel P. Berrange 已提交
1806
    if (!vm) {
1807
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1808
                         _("no domain with matching id %d"), dom->id);
1809
        goto cleanup;
D
Daniel P. Berrange 已提交
1810
    }
1811

1812
    qemudShutdownVMDaemon(dom->conn, driver, vm);
1813 1814 1815
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1816
    if (!vm->persistent) {
1817 1818
        virDomainRemoveInactive(&driver->domains,
                                vm);
1819 1820
        vm = NULL;
    }
1821 1822 1823
    ret = 0;

cleanup:
1824 1825
    if (vm)
        virDomainObjUnlock(vm);
1826 1827
    if (event)
        qemuDomainEventQueue(driver, event);
1828
    qemuDriverUnlock(driver);
1829
    return ret;
D
Daniel P. Berrange 已提交
1830 1831 1832
}


1833
static char *qemudDomainGetOSType(virDomainPtr dom) {
1834 1835 1836
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1837

1838
    qemuDriverLock(driver);
1839
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1840
    qemuDriverUnlock(driver);
1841 1842
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1843
                         "%s", _("no domain with matching uuid"));
1844
        goto cleanup;
1845 1846
    }

1847
    if (!(type = strdup(vm->def->os.type)))
1848 1849
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for ostype"));
1850 1851

cleanup:
1852 1853
    if (vm)
        virDomainObjUnlock(vm);
1854 1855 1856
    return type;
}

1857 1858
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1859 1860 1861
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1862

1863
    qemuDriverLock(driver);
1864
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1865 1866
    qemuDriverUnlock(driver);

1867
    if (!vm) {
1868 1869 1870
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1871
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1872
                         _("no domain with matching uuid '%s'"), uuidstr);
1873
        goto cleanup;
1874 1875
    }

1876 1877 1878
    ret = vm->def->maxmem;

cleanup:
1879 1880
    if (vm)
        virDomainObjUnlock(vm);
1881
    return ret;
1882 1883 1884
}

static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1885 1886 1887
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1888

1889
    qemuDriverLock(driver);
1890
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1891 1892
    qemuDriverUnlock(driver);

1893
    if (!vm) {
1894 1895 1896
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1897
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1898
                         _("no domain with matching uuid '%s'"), uuidstr);
1899
        goto cleanup;
1900 1901 1902 1903
    }

    if (newmax < vm->def->memory) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
1904
                         "%s", _("cannot set max memory lower than current memory"));
1905
        goto cleanup;;
1906 1907 1908
    }

    vm->def->maxmem = newmax;
1909 1910 1911
    ret = 0;

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

static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
1918 1919 1920
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1921

1922
    qemuDriverLock(driver);
1923
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1924
    qemuDriverUnlock(driver);
1925
    if (!vm) {
1926 1927 1928
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1929
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1930
                         _("no domain with matching uuid '%s'"), uuidstr);
1931
        goto cleanup;
1932 1933
    }

1934
    if (virDomainIsActive(vm)) {
1935
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
1936
                         "%s", _("cannot set memory of an active domain"));
1937
        goto cleanup;
1938 1939 1940 1941
    }

    if (newmem > vm->def->maxmem) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
1942
                         "%s", _("cannot set memory higher than max memory"));
1943
        goto cleanup;
1944 1945 1946
    }

    vm->def->memory = newmem;
1947 1948 1949
    ret = 0;

cleanup:
1950 1951
    if (vm)
        virDomainObjUnlock(vm);
1952
    return ret;
1953 1954
}

1955
static int qemudDomainGetInfo(virDomainPtr dom,
1956
                              virDomainInfoPtr info) {
1957 1958 1959 1960
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

1961
    qemuDriverLock(driver);
1962
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1963
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
1964
    if (!vm) {
1965 1966
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
1967
        goto cleanup;
D
Daniel P. Berrange 已提交
1968 1969
    }

1970
    info->state = vm->state;
D
Daniel P. Berrange 已提交
1971

1972
    if (!virDomainIsActive(vm)) {
1973
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
1974
    } else {
1975
        if (qemudGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1976
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED, ("cannot read cputime for domain"));
1977
            goto cleanup;
D
Daniel P. Berrange 已提交
1978 1979 1980
        }
    }

1981 1982 1983
    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
1984 1985 1986
    ret = 0;

cleanup:
1987 1988
    if (vm)
        virDomainObjUnlock(vm);
1989
    return ret;
D
Daniel P. Berrange 已提交
1990 1991 1992
}


D
Daniel P. Berrange 已提交
1993
static char *qemudEscape(const char *in, int shell)
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
{
    int len = 0;
    int i, j;
    char *out;

    /* To pass through the QEMU monitor, we need to use escape
       sequences: \r, \n, \", \\

       To pass through both QEMU + the shell, we need to escape
       the single character ' as the five characters '\\''
    */

    for (i = 0; in[i] != '\0'; i++) {
        switch(in[i]) {
        case '\r':
        case '\n':
        case '"':
        case '\\':
            len += 2;
            break;
        case '\'':
D
Daniel P. Berrange 已提交
2015 2016 2017 2018
            if (shell)
                len += 5;
            else
                len += 1;
2019 2020 2021 2022 2023 2024 2025
            break;
        default:
            len += 1;
            break;
        }
    }

2026
    if (VIR_ALLOC_N(out, len + 1) < 0)
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
        return NULL;

    for (i = j = 0; in[i] != '\0'; i++) {
        switch(in[i]) {
        case '\r':
            out[j++] = '\\';
            out[j++] = 'r';
            break;
        case '\n':
            out[j++] = '\\';
            out[j++] = 'n';
            break;
        case '"':
        case '\\':
            out[j++] = '\\';
            out[j++] = in[i];
            break;
        case '\'':
D
Daniel P. Berrange 已提交
2045 2046 2047 2048 2049 2050 2051 2052 2053
            if (shell) {
                out[j++] = '\'';
                out[j++] = '\\';
                out[j++] = '\\';
                out[j++] = '\'';
                out[j++] = '\'';
            } else {
                out[j++] = in[i];
            }
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

2065 2066 2067 2068 2069
static char *qemudEscapeMonitorArg(const char *in)
{
    return qemudEscape(in, 0);
}

D
Daniel P. Berrange 已提交
2070 2071 2072 2073
static char *qemudEscapeShellArg(const char *in)
{
    return qemudEscape(in, 1);
}
2074

2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
#define QEMUD_SAVE_VERSION 1

struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
    int version;
    int xml_len;
    int was_running;
    int unused[16];
};

2086
static int qemudDomainSave(virDomainPtr dom,
2087
                           const char *path) {
2088 2089 2090 2091 2092 2093 2094
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *command = NULL;
    char *info = NULL;
    int fd = -1;
    char *safe_path = NULL;
    char *xml = NULL;
2095
    struct qemud_save_header header;
2096
    int ret = -1;
2097
    virDomainEventPtr event = NULL;
2098 2099 2100 2101 2102

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

2103
    qemuDriverLock(driver);
2104 2105
    vm = virDomainFindByID(&driver->domains, dom->id);

D
Daniel P. Berrange 已提交
2106
    if (!vm) {
2107
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2108
                         _("no domain with matching id %d"), dom->id);
2109
        goto cleanup;
D
Daniel P. Berrange 已提交
2110
    }
2111

2112
    if (!virDomainIsActive(vm)) {
2113
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2114
                         "%s", _("domain is not running"));
2115
        goto cleanup;
D
Daniel P. Berrange 已提交
2116
    }
2117 2118 2119 2120 2121 2122

    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
        if (qemudDomainSuspend(dom) != 0) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2123
                             "%s", _("failed to pause domain"));
2124
            goto cleanup;
2125 2126 2127 2128
        }
    }

    /* Get XML for the domain */
2129
    xml = virDomainDefFormat(dom->conn, vm->def, VIR_DOMAIN_XML_SECURE);
2130 2131
    if (!xml) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2132
                         "%s", _("failed to get domain xml"));
2133
        goto cleanup;
2134 2135 2136 2137 2138 2139
    }
    header.xml_len = strlen(xml) + 1;

    /* Write header to file, followed by XML */
    if ((fd = open(path, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR)) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2140
                         _("failed to create '%s'"), path);
2141
        goto cleanup;
2142 2143 2144 2145
    }

    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2146
                         "%s", _("failed to write save header"));
2147
        goto cleanup;
2148 2149 2150 2151
    }

    if (safewrite(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2152
                         "%s", _("failed to write xml"));
2153
        goto cleanup;
2154 2155
    }

2156 2157 2158 2159 2160 2161 2162
    if (close(fd) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         _("unable to save file %s %s"),
                         path, strerror(errno));
        goto cleanup;
    }
    fd = -1;
2163 2164 2165 2166 2167

    /* Migrate to file */
    safe_path = qemudEscapeShellArg(path);
    if (!safe_path) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2168
                         "%s", _("out of memory"));
2169
        goto cleanup;
2170 2171 2172
    }
    if (asprintf (&command, "migrate \"exec:"
                  "dd of='%s' oflag=append conv=notrunc 2>/dev/null"
2173
                  "\"", safe_path) == -1) {
2174
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2175
                         "%s", _("out of memory"));
2176 2177
        command = NULL;
        goto cleanup;
2178 2179 2180 2181
    }

    if (qemudMonitorCommand(driver, vm, command, &info) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2182
                         "%s", _("migrate operation failed"));
2183
        goto cleanup;
2184 2185
    }

2186 2187 2188 2189 2190 2191 2192 2193
    DEBUG ("migrate reply: %s", info);

    /* If the command isn't supported then qemu prints:
     * unknown command: migrate" */
    if (strstr(info, "unknown command:")) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'migrate' not supported by this qemu"));
2194
        goto cleanup;
2195 2196
    }

2197 2198
    /* Shut it down */
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2199 2200 2201
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2202
    if (!vm->persistent) {
2203 2204
        virDomainRemoveInactive(&driver->domains,
                                vm);
2205 2206
        vm = NULL;
    }
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
    ret = 0;

cleanup:
    if (fd != -1)
        close(fd);
    VIR_FREE(xml);
    VIR_FREE(safe_path);
    VIR_FREE(command);
    VIR_FREE(info);
    if (ret != 0)
        unlink(path);
2218 2219
    if (vm)
        virDomainObjUnlock(vm);
2220 2221
    if (event)
        qemuDomainEventQueue(driver, event);
2222
    qemuDriverUnlock(driver);
2223
    return ret;
D
Daniel P. Berrange 已提交
2224 2225 2226
}


2227
static int qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
2228 2229
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2230
    int max;
2231
    int ret = -1;
2232

2233
    qemuDriverLock(driver);
2234
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2235 2236
    qemuDriverUnlock(driver);

2237
    if (!vm) {
2238 2239 2240
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2241
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2242
                         _("no domain with matching uuid '%s'"), uuidstr);
2243
        goto cleanup;
2244 2245
    }

2246
    if (virDomainIsActive(vm)) {
2247
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT, "%s",
2248
                         _("cannot change vcpu count of an active domain"));
2249
        goto cleanup;
2250 2251 2252 2253 2254
    }

    if ((max = qemudDomainGetMaxVcpus(dom)) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                         _("could not determine max vcpus for the domain"));
2255
        goto cleanup;
2256 2257 2258 2259 2260 2261
    }

    if (nvcpus > max) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         _("requested vcpus is greater than max allowable"
                           " vcpus for the domain: %d > %d"), nvcpus, max);
2262
        goto cleanup;
2263 2264 2265
    }

    vm->def->vcpus = nvcpus;
2266 2267 2268
    ret = 0;

cleanup:
2269 2270
    if (vm)
        virDomainObjUnlock(vm);
2271
    return ret;
2272 2273
}

2274 2275 2276 2277 2278 2279 2280

#if HAVE_SCHED_GETAFFINITY
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
2281 2282
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2283 2284 2285
    cpu_set_t mask;
    int i, maxcpu;
    virNodeInfo nodeinfo;
2286
    int ret = -1;
2287

2288
    qemuDriverLock(driver);
2289
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2290 2291
    qemuDriverUnlock(driver);

2292
    if (!virDomainIsActive(vm)) {
2293 2294
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2295
        goto cleanup;
2296 2297 2298 2299 2300 2301
    }

    if (vcpu > (vm->nvcpupids-1)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         _("vcpu number out of range %d > %d"),
                         vcpu, vm->nvcpupids);
2302
        goto cleanup;
2303 2304 2305
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2306
        goto cleanup;
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321

    maxcpu = maplen * 8;
    if (maxcpu > nodeinfo.cpus)
        maxcpu = nodeinfo.cpus;

    CPU_ZERO(&mask);
    for (i = 0 ; i < maxcpu ; i++) {
        if ((cpumap[i/8] >> (i % 8)) & 1)
            CPU_SET(i, &mask);
    }

    if (vm->vcpupids != NULL) {
        if (sched_setaffinity(vm->vcpupids[vcpu], sizeof(mask), &mask) < 0) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                             _("cannot set affinity: %s"), strerror(errno));
2322
            goto cleanup;
2323 2324 2325 2326
        }
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cpu affinity is not supported"));
2327
        goto cleanup;
2328
    }
2329
    ret = 0;
2330

2331
cleanup:
2332 2333
    if (vm)
        virDomainObjUnlock(vm);
2334
    return ret;
2335 2336 2337 2338 2339 2340 2341 2342
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
2343 2344
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2345 2346
    virNodeInfo nodeinfo;
    int i, v, maxcpu;
2347
    int ret = -1;
2348

2349
    qemuDriverLock(driver);
2350
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2351 2352
    qemuDriverUnlock(driver);

2353
    if (!virDomainIsActive(vm)) {
2354 2355
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2356
        goto cleanup;
2357 2358 2359
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2360
        goto cleanup;
2361 2362 2363 2364 2365 2366 2367 2368 2369

    maxcpu = maplen * 8;
    if (maxcpu > nodeinfo.cpus)
        maxcpu = nodeinfo.cpus;

    /* Clamp to actual number of vcpus */
    if (maxinfo > vm->nvcpupids)
        maxinfo = vm->nvcpupids;

2370 2371 2372 2373 2374 2375 2376 2377
    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;
                /* XXX cpu time, current pCPU mapping */
            }
2378 2379
        }

2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
            if (vm->vcpupids != NULL) {
                for (v = 0 ; v < maxinfo ; v++) {
                    cpu_set_t mask;
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);
                    CPU_ZERO(&mask);

                    if (sched_getaffinity(vm->vcpupids[v], sizeof(mask), &mask) < 0) {
                        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                                         _("cannot get affinity: %s"), strerror(errno));
                        goto cleanup;
                    }

                    for (i = 0 ; i < maxcpu ; i++)
                        if (CPU_ISSET(i, &mask))
                            VIR_USE_CPU(cpumap, i);
2397
                }
2398 2399 2400 2401
            } else {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                                 "%s", _("cpu affinity is not available"));
                goto cleanup;
2402 2403 2404
            }
        }
    }
2405
    ret = maxinfo;
2406

2407
cleanup:
2408 2409
    if (vm)
        virDomainObjUnlock(vm);
2410
    return ret;
2411 2412 2413 2414
}
#endif /* HAVE_SCHED_GETAFFINITY */


2415
static int qemudDomainGetMaxVcpus(virDomainPtr dom) {
2416 2417
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2418
    const char *type;
2419
    int ret = -1;
2420

2421
    qemuDriverLock(driver);
2422
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2423 2424
    qemuDriverUnlock(driver);

2425
    if (!vm) {
2426 2427 2428
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2429
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2430
                         _("no domain with matching uuid '%s'"), uuidstr);
2431
        goto cleanup;
2432 2433
    }

2434
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
2435 2436 2437
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unknown virt type in domain definition '%d'"),
                         vm->def->virtType);
2438
        goto cleanup;
2439 2440
    }

2441
    ret = qemudGetMaxVCPUs(dom->conn, type);
2442

2443
cleanup:
2444 2445
    if (vm)
        virDomainObjUnlock(vm);
2446 2447 2448 2449
    return ret;
}


2450
static int qemudDomainRestore(virConnectPtr conn,
2451 2452 2453
                              const char *path) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
2454
    virDomainObjPtr vm = NULL;
2455 2456 2457
    int fd = -1;
    int ret = -1;
    char *xml = NULL;
2458
    struct qemud_save_header header;
2459
    virDomainEventPtr event = NULL;
2460

2461
    qemuDriverLock(driver);
2462 2463 2464
    /* Verify the header and read the XML */
    if ((fd = open(path, O_RDONLY)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2465
                         "%s", _("cannot read domain image"));
2466
        goto cleanup;
2467 2468 2469 2470
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2471
                         "%s", _("failed to read qemu header"));
2472
        goto cleanup;
2473 2474 2475 2476
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2477
                         "%s", _("image magic is incorrect"));
2478
        goto cleanup;
2479 2480 2481 2482
    }

    if (header.version > QEMUD_SAVE_VERSION) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2483
                         _("image version is not supported (%d > %d)"),
2484
                         header.version, QEMUD_SAVE_VERSION);
2485
        goto cleanup;
2486 2487
    }

2488
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
2489
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2490
                         "%s", _("out of memory"));
2491
        goto cleanup;
2492 2493 2494 2495
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2496
                         "%s", _("failed to read XML"));
2497
        goto cleanup;
2498 2499 2500
    }

    /* Create a domain from this XML */
2501
    if (!(def = virDomainDefParseString(conn, driver->caps, xml))) {
2502
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2503
                         "%s", _("failed to parse XML"));
2504
        goto cleanup;
2505 2506 2507
    }

    /* Ensure the name and UUID don't already exist in an active VM */
2508
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
2509
    if (!vm)
2510
        vm = virDomainFindByName(&driver->domains, def->name);
2511
    if (vm && virDomainIsActive(vm)) {
2512
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2513
                         _("domain is already active as '%s'"), vm->def->name);
2514
        goto cleanup;
2515 2516
    }

2517 2518 2519
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
2520
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2521
                         "%s", _("failed to assign new VM"));
2522
        goto cleanup;
2523
    }
2524
    def = NULL;
2525 2526

    /* Set the migration source and start it up. */
2527
    vm->stdin_fd = fd;
2528
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio");
2529
    close(fd);
2530
    fd = -1;
2531
    vm->stdin_fd = -1;
2532
    if (ret < 0) {
2533
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2534
                         "%s", _("failed to start VM"));
2535
        if (!vm->persistent) {
2536 2537
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2538 2539
            vm = NULL;
        }
2540
        goto cleanup;
2541 2542
    }

2543 2544 2545
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
2546

2547 2548 2549
    /* If it was running before, resume it now. */
    if (header.was_running) {
        char *info;
2550
        if (qemudMonitorCommand(driver, vm, "cont", &info) < 0) {
2551
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2552
                             "%s", _("failed to resume domain"));
2553
            goto cleanup;
2554
        }
2555
        VIR_FREE(info);
2556 2557
        vm->state = VIR_DOMAIN_RUNNING;
    }
2558
    ret = 0;
2559

2560 2561 2562 2563 2564
cleanup:
    virDomainDefFree(def);
    VIR_FREE(xml);
    if (fd != -1)
        close(fd);
2565 2566
    if (vm)
        virDomainObjUnlock(vm);
2567 2568
    if (event)
        qemuDomainEventQueue(driver, event);
2569
    qemuDriverUnlock(driver);
2570
    return ret;
D
Daniel P. Berrange 已提交
2571 2572 2573
}


2574
static char *qemudDomainDumpXML(virDomainPtr dom,
2575
                                int flags ATTRIBUTE_UNUSED) {
2576 2577 2578 2579
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

2580
    qemuDriverLock(driver);
2581
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2582 2583
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
2584
    if (!vm) {
2585 2586
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2587
        goto cleanup;
D
Daniel P. Berrange 已提交
2588 2589
    }

2590 2591 2592 2593 2594 2595
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                             vm->newDef : vm->def,
                             flags);

cleanup:
2596 2597
    if (vm)
        virDomainObjUnlock(vm);
2598
    return ret;
D
Daniel P. Berrange 已提交
2599 2600 2601
}


2602
static int qemudListDefinedDomains(virConnectPtr conn,
2603
                            char **const names, int nnames) {
2604
    struct qemud_driver *driver = conn->privateData;
2605
    int got = 0, i;
2606

2607
    qemuDriverLock(driver);
2608
    for (i = 0 ; i < driver->domains.count && got < nnames ; i++) {
2609
        virDomainObjLock(driver->domains.objs[i]);
2610 2611
        if (!virDomainIsActive(driver->domains.objs[i])) {
            if (!(names[got++] = strdup(driver->domains.objs[i]->def->name))) {
2612
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
2613
                                 "%s", _("failed to allocate space for VM name string"));
2614
                virDomainObjUnlock(driver->domains.objs[i]);
2615 2616
                goto cleanup;
            }
2617
        }
2618
        virDomainObjUnlock(driver->domains.objs[i]);
D
Daniel P. Berrange 已提交
2619
    }
2620

2621
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2622
    return got;
2623 2624 2625

 cleanup:
    for (i = 0 ; i < got ; i++)
2626
        VIR_FREE(names[i]);
2627
    qemuDriverUnlock(driver);
2628
    return -1;
D
Daniel P. Berrange 已提交
2629 2630
}

2631
static int qemudNumDefinedDomains(virConnectPtr conn) {
2632
    struct qemud_driver *driver = conn->privateData;
2633 2634
    int n = 0, i;

2635
    qemuDriverLock(driver);
2636 2637
    for (i = 0 ; i < driver->domains.count ; i++)
        if (!virDomainIsActive(driver->domains.objs[i]))
2638
            n++;
2639
    qemuDriverUnlock(driver);
2640

2641
    return n;
D
Daniel P. Berrange 已提交
2642 2643 2644
}


2645
static int qemudDomainStart(virDomainPtr dom) {
2646 2647 2648
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2649
    virDomainEventPtr event = NULL;
2650

2651
    qemuDriverLock(driver);
2652
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2653 2654
    qemuDriverUnlock(driver);

2655
    if (!vm) {
2656
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2657
                         "%s", _("no domain with matching uuid"));
2658
        goto cleanup;
2659 2660
    }

2661
    ret = qemudStartVMDaemon(dom->conn, driver, vm, NULL);
2662
    if (ret != -1)
2663 2664 2665
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
2666 2667

cleanup:
2668 2669
    if (vm)
        virDomainObjUnlock(vm);
2670 2671 2672 2673 2674
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
2675
    return ret;
D
Daniel P. Berrange 已提交
2676 2677 2678
}


2679
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
2680
    struct qemud_driver *driver = conn->privateData;
2681
    virDomainDefPtr def;
2682
    virDomainObjPtr vm = NULL;
2683
    virDomainPtr dom = NULL;
2684
    virDomainEventPtr event = NULL;
2685
    int newVM = 1;
2686

2687
    qemuDriverLock(driver);
2688
    if (!(def = virDomainDefParseString(conn, driver->caps, xml)))
2689
        goto cleanup;
2690

2691
    vm = virDomainFindByName(&driver->domains, def->name);
2692 2693
    if (vm) {
        virDomainObjUnlock(vm);
2694
        newVM = 0;
2695
    }
2696

2697 2698 2699 2700
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
        virDomainDefFree(def);
2701
        goto cleanup;
2702
    }
2703
    vm->persistent = 1;
2704

2705 2706
    if (virDomainSaveConfig(conn,
                            driver->configDir,
2707
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2708 2709
        virDomainRemoveInactive(&driver->domains,
                                vm);
2710
        vm = NULL;
2711
        goto cleanup;
2712 2713
    }

2714 2715 2716 2717 2718
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     newVM ?
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
2719

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

cleanup:
2724 2725
    if (vm)
        virDomainObjUnlock(vm);
2726 2727
    if (event)
        qemuDomainEventQueue(driver, event);
2728
    qemuDriverUnlock(driver);
2729
    return dom;
D
Daniel P. Berrange 已提交
2730 2731
}

2732
static int qemudDomainUndefine(virDomainPtr dom) {
2733 2734
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2735
    virDomainEventPtr event = NULL;
2736
    int ret = -1;
D
Daniel P. Berrange 已提交
2737

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

D
Daniel P. Berrange 已提交
2741
    if (!vm) {
2742 2743
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2744
        goto cleanup;
D
Daniel P. Berrange 已提交
2745 2746
    }

2747
    if (virDomainIsActive(vm)) {
2748 2749
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
2750
        goto cleanup;
D
Daniel P. Berrange 已提交
2751 2752
    }

2753 2754 2755
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
2756
        goto cleanup;
2757 2758 2759
    }

    if (virDomainDeleteConfig(dom->conn, driver->configDir, driver->autostartDir, vm) < 0)
2760
        goto cleanup;
D
Daniel P. Berrange 已提交
2761

2762 2763 2764
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
2765

2766 2767
    virDomainRemoveInactive(&driver->domains,
                            vm);
2768
    vm = NULL;
2769
    ret = 0;
D
Daniel P. Berrange 已提交
2770

2771
cleanup:
2772 2773
    if (vm)
        virDomainObjUnlock(vm);
2774 2775
    if (event)
        qemuDomainEventQueue(driver, event);
2776
    qemuDriverUnlock(driver);
2777
    return ret;
D
Daniel P. Berrange 已提交
2778 2779
}

2780
/* Return the disks name for use in monitor commands */
2781
static char *qemudDiskDeviceName(const virConnectPtr conn,
2782
                                 const virDomainDiskDefPtr disk) {
2783 2784 2785 2786 2787 2788

    int busid, devid;
    int ret;
    char *devname;

    if (virDiskNameToBusDeviceIndex(disk, &busid, &devid) < 0) {
2789
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2790 2791 2792 2793 2794 2795 2796
                         _("cannot convert disk '%s' to bus/device index"),
                         disk->dst);
        return NULL;
    }

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
2797 2798 2799 2800
            if (disk->device== VIR_DOMAIN_DISK_DEVICE_DISK)
                ret = asprintf(&devname, "ide%d-hd%d", busid, devid);
            else
                ret = asprintf(&devname, "ide%d-cd%d", busid, devid);
2801 2802
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
2803 2804 2805 2806
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
                ret = asprintf(&devname, "scsi%d-hd%d", busid, devid);
            else
                ret = asprintf(&devname, "scsi%d-cd%d", busid, devid);
2807 2808 2809 2810 2811 2812 2813 2814
            break;
        case VIR_DOMAIN_DISK_BUS_FDC:
            ret = asprintf(&devname, "floppy%d", devid);
            break;
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
            ret = asprintf(&devname, "virtio%d", devid);
            break;
        default:
2815
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
2816 2817 2818 2819 2820 2821
                             _("Unsupported disk name mapping for bus '%s'"),
                             virDomainDiskBusTypeToString(disk->bus));
            return NULL;
    }

    if (ret == -1) {
2822
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
2823 2824 2825 2826 2827 2828
        return NULL;
    }

    return devname;
}

2829 2830 2831
static int qemudDomainChangeEjectableMedia(virConnectPtr conn,
                                           struct qemud_driver *driver,
                                           virDomainObjPtr vm,
2832 2833
                                           virDomainDeviceDefPtr dev)
{
2834
    virDomainDiskDefPtr origdisk = NULL, newdisk;
2835
    char *cmd, *reply, *safe_path;
2836
    char *devname = NULL;
2837
    unsigned int qemuCmdFlags;
2838
    int i;
2839

2840
    origdisk = NULL;
2841
    newdisk = dev->data.disk;
2842 2843 2844 2845
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->bus == newdisk->bus &&
            STREQ(vm->def->disks[i]->dst, newdisk->dst)) {
            origdisk = vm->def->disks[i];
2846
            break;
2847
        }
2848 2849 2850
    }

    if (!origdisk) {
2851
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2852 2853 2854 2855 2856 2857 2858 2859 2860
                         _("No device with bus '%s' and target '%s'"),
                         virDomainDiskBusTypeToString(newdisk->bus),
                         newdisk->dst);
        return -1;
    }

    if (qemudExtractVersionInfo(vm->def->emulator,
                                NULL,
                                &qemuCmdFlags) < 0) {
2861
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2862 2863 2864 2865 2866 2867
                         _("Cannot determine QEMU argv syntax %s"),
                         vm->def->emulator);
        return -1;
    }

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
2868
        if (!(devname = qemudDiskDeviceName(conn, newdisk)))
2869 2870 2871 2872 2873 2874 2875 2876 2877
            return -1;
    } else {
        /* Back compat for no -drive option */
        if (newdisk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)
            devname = strdup(newdisk->dst);
        else if (newdisk->device == VIR_DOMAIN_DISK_DEVICE_CDROM &&
                 STREQ(newdisk->dst, "hdc"))
            devname = strdup("cdrom");
        else {
2878
            qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2879 2880 2881 2882 2883 2884 2885 2886
                             _("Emulator version does not support removable "
                               "media for device '%s' and target '%s'"),
                               virDomainDiskDeviceTypeToString(newdisk->device),
                               newdisk->dst);
            return -1;
        }

        if (!devname) {
2887
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
2888 2889 2890
            return -1;
        }
    }
2891

2892
    if (newdisk->src) {
2893 2894
        safe_path = qemudEscapeMonitorArg(newdisk->src);
        if (!safe_path) {
2895
            qemudReportError(conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
2896
            VIR_FREE(devname);
2897 2898
            return -1;
        }
2899
        if (asprintf (&cmd, "change %s \"%s\"", devname, safe_path) == -1) {
2900
            qemudReportError(conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
2901
            VIR_FREE(safe_path);
2902
            VIR_FREE(devname);
2903 2904
            return -1;
        }
2905
        VIR_FREE(safe_path);
2906

2907
    } else if (asprintf(&cmd, "eject %s", devname) == -1) {
2908
        qemudReportError(conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
2909
        VIR_FREE(devname);
2910 2911
        return -1;
    }
2912
    VIR_FREE(devname);
2913 2914

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
2915
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2916
                         "%s", _("cannot change cdrom media"));
2917
        VIR_FREE(cmd);
2918 2919
        return -1;
    }
2920 2921 2922 2923

    /* If the command failed qemu prints:
     * device not found, device is locked ...
     * No message is printed on success it seems */
2924
    DEBUG ("ejectable media change reply: %s", reply);
2925
    if (strstr(reply, "\ndevice ")) {
2926
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2927 2928 2929 2930 2931
                          "%s", _("changing cdrom media failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
2932 2933
    VIR_FREE(reply);
    VIR_FREE(cmd);
2934

2935 2936
    VIR_FREE(origdisk->src);
    origdisk->src = newdisk->src;
2937
    newdisk->src = NULL;
2938
    origdisk->type = newdisk->type;
2939 2940 2941
    return 0;
}

2942 2943 2944 2945
static int qemudDomainAttachPciDiskDevice(virConnectPtr conn,
                                          struct qemud_driver *driver,
                                          virDomainObjPtr vm,
                                          virDomainDeviceDefPtr dev)
2946 2947
{
    int ret, i;
2948
    char *cmd, *reply, *s;
2949 2950 2951 2952 2953
    char *safe_path;
    const char* type = virDomainDiskBusTypeToString(dev->data.disk->bus);

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
2954
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2955 2956 2957 2958 2959 2960
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
2961
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
2962 2963 2964 2965 2966
        return -1;
    }

    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
2967
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2968 2969 2970 2971 2972 2973 2974 2975
                         "%s", _("out of memory"));
        return -1;
    }

    ret = asprintf(&cmd, "pci_add 0 storage file=%s,if=%s",
                         safe_path, type);
    VIR_FREE(safe_path);
    if (ret == -1) {
2976
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
2977 2978 2979 2980
        return ret;
    }

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
2981
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2982 2983 2984 2985 2986 2987 2988 2989
                         _("cannot attach %s disk"), type);
        VIR_FREE(cmd);
        return -1;
    }

    DEBUG ("pci_add reply: %s", reply);
    /* If the command succeeds qemu prints:
     * OK bus 0... */
2990 2991 2992 2993 2994 2995
#define PCI_ATTACH_OK_MSG "OK bus 0, slot "
    if ((s=strstr(reply, PCI_ATTACH_OK_MSG))) {
        char* dummy = s;
        s += strlen(PCI_ATTACH_OK_MSG);

        if (virStrToLong_i ((const char*)s, &dummy, 10, &dev->data.disk->slotnum) == -1)
J
Jim Meyering 已提交
2996
            qemudLog(QEMUD_WARN, "%s", _("Unable to parse slot number\n"));
2997
    } else {
2998
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012
                          _("adding %s disk failed"), type);
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }

    vm->def->disks[vm->def->ndisks++] = dev->data.disk;
    qsort(vm->def->disks, vm->def->ndisks, sizeof(*vm->def->disks),
          virDomainDiskQSort);

    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}
3013

3014 3015 3016 3017
static int qemudDomainAttachUsbMassstorageDevice(virConnectPtr conn,
                                                 struct qemud_driver *driver,
                                                 virDomainObjPtr vm,
                                                 virDomainDeviceDefPtr dev)
3018
{
3019 3020
    int ret, i;
    char *safe_path;
3021 3022
    char *cmd, *reply;

3023 3024
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
3025
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3026 3027 3028 3029 3030
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

3031
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3032
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3033
        return -1;
3034 3035
    }

3036 3037
    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3038
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3039 3040 3041 3042 3043 3044
                         "%s", _("out of memory"));
        return -1;
    }

    ret = asprintf(&cmd, "usb_add disk:%s", safe_path);
    VIR_FREE(safe_path);
3045
    if (ret == -1) {
3046
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3047 3048 3049 3050
        return ret;
    }

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
3051
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3052
                         "%s", _("cannot attach usb disk"));
3053 3054 3055 3056 3057 3058 3059 3060
        VIR_FREE(cmd);
        return -1;
    }

    DEBUG ("attach_usb reply: %s", reply);
    /* If the command failed qemu prints:
     * Could not add ... */
    if (strstr(reply, "Could not add ")) {
3061
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3062
                          "%s",
3063
                          _("adding usb disk failed"));
3064 3065 3066 3067
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3068

3069 3070 3071
    vm->def->disks[vm->def->ndisks++] = dev->data.disk;
    qsort(vm->def->disks, vm->def->ndisks, sizeof(*vm->def->disks),
          virDomainDiskQSort);
3072

3073 3074 3075 3076 3077
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}

3078 3079 3080 3081
static int qemudDomainAttachHostDevice(virConnectPtr conn,
                                       struct qemud_driver *driver,
                                       virDomainObjPtr vm,
                                       virDomainDeviceDefPtr dev)
3082 3083 3084 3085
{
    int ret;
    char *cmd, *reply;

3086
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
3087
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3088 3089
        return -1;
    }
3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100

    if (dev->data.hostdev->source.subsys.usb.vendor) {
        ret = asprintf(&cmd, "usb_add host:%.4x:%.4x",
                       dev->data.hostdev->source.subsys.usb.vendor,
                       dev->data.hostdev->source.subsys.usb.product);
    } else {
        ret = asprintf(&cmd, "usb_add host:%.3d.%.3d",
                       dev->data.hostdev->source.subsys.usb.bus,
                       dev->data.hostdev->source.subsys.usb.device);
    }
    if (ret == -1) {
3101
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3102 3103 3104 3105
        return -1;
    }

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
3106
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3107 3108 3109 3110 3111 3112 3113 3114 3115
                         "%s", _("cannot attach usb device"));
        VIR_FREE(cmd);
        return -1;
    }

    DEBUG ("attach_usb reply: %s", reply);
    /* If the command failed qemu prints:
     * Could not add ... */
    if (strstr(reply, "Could not add ")) {
3116
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3117 3118 3119 3120 3121 3122
                          "%s",
                          _("adding usb device failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3123

3124
    vm->def->hostdevs[vm->def->nhostdevs++] = dev->data.hostdev;
3125

3126 3127
    VIR_FREE(reply);
    VIR_FREE(cmd);
3128 3129 3130
    return 0;
}

3131 3132
static int qemudDomainAttachDevice(virDomainPtr dom,
                                   const char *xml) {
3133 3134 3135 3136
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3137

3138
    qemuDriverLock(driver);
3139
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3140 3141 3142
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3143
        goto cleanup;
3144 3145 3146 3147 3148
    }

    if (!virDomainIsActive(vm)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot attach device on inactive domain"));
3149
        goto cleanup;
3150 3151
    }

3152 3153 3154
    dev = virDomainDeviceDefParse(dom->conn,
                                  driver->caps,
                                  vm->def, xml);
3155 3156 3157
    if (dev == NULL)
        goto cleanup;

3158

3159 3160
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        switch (dev->data.disk->device) {
3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
            ret = qemudDomainChangeEjectableMedia(dom->conn, driver, vm, dev);
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
                ret = qemudDomainAttachUsbMassstorageDevice(dom->conn, driver, vm, dev);
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                       dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
                ret = qemudDomainAttachPciDiskDevice(dom->conn, driver, vm, dev);
            }
            break;
        default:
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             "%s", _("this disk device type cannot be attached"));
            goto cleanup;
3177
        }
3178
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
3179 3180 3181 3182
               dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
               dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
        ret = qemudDomainAttachHostDevice(dom->conn, driver, vm, dev);
    } else {
3183
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
3184
                         "%s", _("this device type cannot be attached"));
3185
        goto cleanup;
3186 3187
    }

3188 3189
cleanup:
    virDomainDeviceDefFree(dev);
3190 3191 3192
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
3193 3194 3195
    return ret;
}

3196 3197 3198
static int qemudDomainDetachPciDiskDevice(virConnectPtr conn,
                                          struct qemud_driver *driver,
                                          virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3199 3200
{
    int i, ret = -1;
3201 3202
    char *cmd = NULL;
    char *reply = NULL;
3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
    virDomainDiskDefPtr detach = NULL;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
            detach = vm->def->disks[i];
            break;
        }
    }

    if (!detach) {
3213
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3214
                         _("disk %s not found"), dev->data.disk->dst);
3215
        goto cleanup;
3216 3217 3218
    }

    if (detach->slotnum < 1) {
3219
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3220
                         _("disk %s cannot be detached - invalid slot number %d"),
3221
                           detach->dst, detach->slotnum);
3222
        goto cleanup;
3223 3224
    }

3225 3226 3227 3228
    if (asprintf(&cmd, "pci_del 0 %d", detach->slotnum) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        cmd = NULL;
        goto cleanup;
3229 3230 3231
    }

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
3232
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3233
                          _("failed to execute detach disk %s command"), detach->dst);
3234
        goto cleanup;
3235 3236 3237 3238 3239 3240
    }

    DEBUG ("pci_del reply: %s", reply);
    /* If the command fails due to a wrong slot qemu prints: invalid slot,
     * nothing is printed on success */
    if (strstr(reply, "invalid slot")) {
3241
        qemudReportError (conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3242
                          _("failed to detach disk %s: invalid slot %d"),
3243 3244
                          detach->dst, detach->slotnum);
        goto cleanup;
3245 3246 3247 3248 3249
    }

    if (vm->def->ndisks > 1) {
        vm->def->disks[i] = vm->def->disks[--vm->def->ndisks];
        if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks) < 0) {
3250 3251
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
            goto cleanup;
3252 3253 3254 3255 3256 3257 3258 3259
        }
        qsort(vm->def->disks, vm->def->ndisks, sizeof(*vm->def->disks),
              virDomainDiskQSort);
    } else {
        VIR_FREE(vm->def->disks[0]);
        vm->def->ndisks = 0;
    }
    ret = 0;
3260 3261

cleanup:
3262 3263 3264 3265 3266 3267 3268
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return ret;
}

static int qemudDomainDetachDevice(virDomainPtr dom,
                                   const char *xml) {
3269 3270 3271 3272
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3273

3274
    qemuDriverLock(driver);
3275
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3276 3277 3278
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3279
        goto cleanup;
3280 3281 3282 3283 3284
    }

    if (!virDomainIsActive(vm)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot attach device on inactive domain"));
3285
        goto cleanup;
3286 3287 3288
    }

    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml);
3289 3290 3291
    if (dev == NULL)
        goto cleanup;

3292 3293 3294 3295 3296

    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
        (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
         dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO))
3297 3298
        ret = qemudDomainDetachPciDiskDevice(dom->conn, driver, vm, dev);
    else
3299 3300 3301
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("only SCSI or virtio disk device can be detached dynamically"));

3302 3303
cleanup:
    virDomainDeviceDefFree(dev);
3304 3305 3306
    if (vm)
        virDomainObjUnlock(vm);
    qemuDriverUnlock(driver);
3307 3308 3309
    return ret;
}

3310
static int qemudDomainGetAutostart(virDomainPtr dom,
3311
                                   int *autostart) {
3312 3313 3314
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
3315

3316
    qemuDriverLock(driver);
3317
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3318 3319
    qemuDriverUnlock(driver);

3320
    if (!vm) {
3321 3322
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3323
        goto cleanup;
3324 3325 3326
    }

    *autostart = vm->autostart;
3327
    ret = 0;
3328

3329
cleanup:
3330 3331
    if (vm)
        virDomainObjUnlock(vm);
3332
    return ret;
3333 3334
}

3335
static int qemudDomainSetAutostart(virDomainPtr dom,
3336
                                   int autostart) {
3337 3338
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3339 3340
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
3341

3342
    qemuDriverLock(driver);
3343
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3344 3345
    qemuDriverUnlock(driver);

3346
    if (!vm) {
3347 3348
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3349
        goto cleanup;
3350 3351
    }

3352 3353 3354
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
3355
        goto cleanup;
3356 3357
    }

3358 3359
    autostart = (autostart != 0);

3360 3361 3362 3363 3364
    if (vm->autostart != autostart) {
        if ((configFile = virDomainConfigFile(dom->conn, driver->configDir, vm->def->name)) == NULL)
            goto cleanup;
        if ((autostartLink = virDomainConfigFile(dom->conn, driver->autostartDir, vm->def->name)) == NULL)
            goto cleanup;
3365

3366 3367
        if (autostart) {
            int err;
3368

3369 3370 3371 3372 3373 3374
            if ((err = virFileMakePath(driver->autostartDir))) {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("cannot create autostart directory %s: %s"),
                                 driver->autostartDir, strerror(err));
                goto cleanup;
            }
3375

3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
            if (symlink(configFile, autostartLink) < 0) {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("Failed to create symlink '%s to '%s': %s"),
                                 autostartLink, configFile, strerror(errno));
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("Failed to delete symlink '%s': %s"),
                                 autostartLink, strerror(errno));
                goto cleanup;
            }
3389 3390
        }

3391
        vm->autostart = autostart;
3392
    }
3393
    ret = 0;
3394

3395 3396 3397
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
3398 3399
    if (vm)
        virDomainObjUnlock(vm);
3400
    return ret;
3401 3402
}

3403 3404 3405 3406 3407 3408 3409 3410 3411
/* 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)
{
3412
    struct qemud_driver *driver = dom->conn->privateData;
3413
    char *dummy, *info = NULL;
3414
    const char *p, *eol;
3415
    const char *qemu_dev_name = NULL;
3416
    size_t len;
3417
    int i, ret = -1;
3418
    virDomainObjPtr vm;
3419
    virDomainDiskDefPtr disk = NULL;
3420

3421
    qemuDriverLock(driver);
3422
    vm = virDomainFindByID(&driver->domains, dom->id);
3423
    qemuDriverUnlock(driver);
3424 3425 3426
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3427
        goto cleanup;
3428
    }
3429
    if (!virDomainIsActive (vm)) {
3430 3431
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("domain is not running"));
3432
        goto cleanup;
3433 3434
    }

3435 3436 3437 3438 3439 3440 3441 3442
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
3443 3444
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path: %s"), path);
3445
        goto cleanup;
3446 3447
    }

3448
    qemu_dev_name = qemudDiskDeviceName(dom->conn, disk);
3449
    if (!qemu_dev_name)
3450
        goto cleanup;
3451 3452 3453 3454 3455
    len = strlen (qemu_dev_name);

    if (qemudMonitorCommand (driver, vm, "info blockstats", &info) < 0) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("'info blockstats' command failed"));
3456
        goto cleanup;
3457 3458 3459 3460 3461 3462 3463 3464
    }
    DEBUG ("info blockstats reply: %s", info);

    /* If the command isn't supported then qemu prints the supported
     * info commands, so the output starts "info ".  Since this is
     * unlikely to be the name of a block device, we can use this
     * to detect if qemu supports the command.
     */
3465
    if (STRPREFIX (info, "info ")) {
3466 3467 3468
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'info blockstats' not supported by this qemu"));
3469
        goto cleanup;
3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495
    }

    stats->rd_req = -1;
    stats->rd_bytes = -1;
    stats->wr_req = -1;
    stats->wr_bytes = -1;
    stats->errs = -1;

    /* The output format for both qemu & KVM is:
     *   blockdevice: rd_bytes=% wr_bytes=% rd_operations=% wr_operations=%
     *   (repeated for each block device)
     * where '%' is a 64 bit number.
     */
    p = info;

    while (*p) {
        if (STREQLEN (p, qemu_dev_name, len)
            && p[len] == ':' && p[len+1] == ' ') {

            eol = strchr (p, '\n');
            if (!eol)
                eol = p + strlen (p);

            p += len+2;         /* Skip to first label. */

            while (*p) {
3496
                if (STRPREFIX (p, "rd_bytes=")) {
3497 3498 3499
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_bytes) == -1)
                        DEBUG ("error reading rd_bytes: %s", p);
3500
                } else if (STRPREFIX (p, "wr_bytes=")) {
3501 3502 3503
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_bytes) == -1)
                        DEBUG ("error reading wr_bytes: %s", p);
3504
                } else if (STRPREFIX (p, "rd_operations=")) {
3505 3506 3507
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_req) == -1)
                        DEBUG ("error reading rd_req: %s", p);
3508
                } else if (STRPREFIX (p, "wr_operations=")) {
3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_req) == -1)
                        DEBUG ("error reading wr_req: %s", p);
                } else
                    DEBUG ("unknown block stat near %s", p);

                /* Skip to next label. */
                p = strchr (p, ' ');
                if (!p || p >= eol) break;
                p++;
            }
3520
            ret = 0;
3521
            goto cleanup;
3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532
        }

        /* Skip to next line. */
        p = strchr (p, '\n');
        if (!p) break;
        p++;
    }

    /* If we reach here then the device was not found. */
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                      _("device not found: %s (%s)"), path, qemu_dev_name);
3533
 cleanup:
3534 3535
    VIR_FREE(qemu_dev_name);
    VIR_FREE(info);
3536 3537
    if (vm)
        virDomainObjUnlock(vm);
3538
    return ret;
3539 3540
}

3541
#ifdef __linux__
3542 3543 3544 3545 3546
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
3547 3548
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3549
    int i;
3550
    int ret = -1;
3551

3552
    qemuDriverLock(driver);
3553
    vm = virDomainFindByID(&driver->domains, dom->id);
3554 3555
    qemuDriverUnlock(driver);

3556 3557
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
3558
                          _("no domain with matching id %d"), dom->id);
3559
        goto cleanup;
3560 3561
    }

3562
    if (!virDomainIsActive(vm)) {
3563
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3564
                         "%s", _("domain is not running"));
3565
        goto cleanup;
3566 3567 3568 3569
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
3570
                         "%s", _("NULL or empty path"));
3571
        goto cleanup;
3572 3573 3574
    }

    /* Check the path is one of the domain's network interfaces. */
3575 3576
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
3577 3578 3579 3580
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
3581 3582
    }

3583 3584 3585 3586 3587
    if (ret == 0)
        ret = linuxDomainInterfaceStats (dom->conn, path, stats);
    else
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path, '%s' is not a known interface"), path);
3588

3589
cleanup:
3590 3591
    if (vm)
        virDomainObjUnlock(vm);
3592 3593
    return ret;
}
3594
#else
3595 3596 3597 3598
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
3599 3600 3601 3602
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                      "%s", __FUNCTION__);
    return -1;
}
3603
#endif
3604

3605 3606 3607 3608 3609 3610 3611
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
3612 3613 3614
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
3615

3616
    qemuDriverLock(driver);
3617
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3618 3619
    qemuDriverUnlock(driver);

3620 3621
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
3622
                          "%s", _("no domain with matching uuid"));
3623
        goto cleanup;
3624 3625 3626 3627
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
3628
                         "%s", _("NULL or empty path"));
3629
        goto cleanup;
3630 3631 3632
    }

    /* Check the path belongs to this domain. */
3633 3634
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
3635 3636 3637 3638
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
3639 3640
    }

3641 3642 3643 3644 3645 3646 3647 3648 3649
    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) {
            qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                              "%s", strerror (errno));
            goto cleanup;
        }
3650

3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665
        /* 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) {
            qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                              "%s", strerror (errno));
            goto cleanup;
        }

        ret = 0;
    } else {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          "%s", _("invalid path"));
3666 3667
    }

3668 3669 3670
cleanup:
    if (fd >= 0)
        close (fd);
3671 3672
    if (vm)
        virDomainObjUnlock(vm);
3673 3674 3675
    return ret;
}

R
Richard W.M. Jones 已提交
3676 3677 3678 3679 3680 3681
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
3682 3683 3684
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char cmd[256], *info = NULL;
R
Richard W.M. Jones 已提交
3685 3686 3687
    char tmp[] = TEMPDIR "/qemu.mem.XXXXXX";
    int fd = -1, ret = -1;

3688
    qemuDriverLock(driver);
3689
    vm = virDomainFindByID(&driver->domains, dom->id);
3690
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
3691 3692 3693 3694

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3695 3696 3697 3698 3699 3700 3701
        goto cleanup;
    }

    if (flags != VIR_MEMORY_VIRTUAL) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          "%s", _("QEMU driver only supports virtual memory addrs"));
        goto cleanup;
R
Richard W.M. Jones 已提交
3702 3703
    }

3704
    if (!virDomainIsActive(vm)) {
R
Richard W.M. Jones 已提交
3705 3706
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
3707
        goto cleanup;
R
Richard W.M. Jones 已提交
3708 3709 3710 3711 3712 3713
    }

    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
3714
        goto cleanup;
R
Richard W.M. Jones 已提交
3715 3716 3717 3718 3719 3720
    }

    /* Issue the memsave command. */
    snprintf (cmd, sizeof cmd, "memsave %llu %zi \"%s\"", offset, size, tmp);
    if (qemudMonitorCommand (driver, vm, cmd, &info) < 0) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3721
                          "%s", _("'memsave' command failed"));
3722
        goto cleanup;
R
Richard W.M. Jones 已提交
3723 3724 3725 3726 3727 3728 3729 3730
    }

    DEBUG ("memsave reply: %s", info);

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
3731
        goto cleanup;
R
Richard W.M. Jones 已提交
3732 3733 3734
    }

    ret = 0;
3735 3736 3737

cleanup:
    VIR_FREE(info);
R
Richard W.M. Jones 已提交
3738 3739
    if (fd >= 0) close (fd);
    unlink (tmp);
3740 3741
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
3742 3743 3744
    return ret;
}

3745

3746 3747 3748
static int
qemudDomainEventRegister (virConnectPtr conn,
                          void *callback,
3749 3750
                          void *opaque,
                          virFreeCallback freecb)
3751
{
3752 3753 3754
    struct qemud_driver *driver = conn->privateData;
    int ret;

3755
    qemuDriverLock(driver);
3756 3757
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                        callback, opaque, freecb);
3758
    qemuDriverUnlock(driver);
3759

3760
    return ret;
3761 3762 3763 3764 3765 3766
}

static int
qemudDomainEventDeregister (virConnectPtr conn,
                            void *callback)
{
3767 3768 3769
    struct qemud_driver *driver = conn->privateData;
    int ret;

3770
    qemuDriverLock(driver);
3771 3772 3773 3774 3775 3776
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                               callback);
3777
    qemuDriverUnlock(driver);
3778

3779
    return ret;
3780 3781
}

3782 3783 3784 3785 3786
static void qemuDomainEventDispatchFunc(virConnectPtr conn,
                                        virDomainEventPtr event,
                                        virConnectDomainEventCallback cb,
                                        void *cbopaque,
                                        void *opaque)
3787
{
3788
    struct qemud_driver *driver = opaque;
3789

3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833
    /* 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);
3834 3835
}

D
Daniel Veillard 已提交
3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853
/* Migration support. */

/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
static int
qemudDomainMigratePrepare2 (virConnectPtr dconn,
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
                            const char *uri_in,
                            char **uri_out,
                            unsigned long flags ATTRIBUTE_UNUSED,
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
    static int port = 0;
3854 3855
    struct qemud_driver *driver = dconn->privateData;
    virDomainDefPtr def = NULL;
D
Daniel Veillard 已提交
3856 3857 3858 3859 3860
    virDomainObjPtr vm = NULL;
    int this_port;
    char hostname [HOST_NAME_MAX+1];
    char migrateFrom [64];
    const char *p;
3861
    virDomainEventPtr event = NULL;
3862 3863 3864
    int ret = -1;;

    *uri_out = NULL;
D
Daniel Veillard 已提交
3865

3866
    qemuDriverLock(driver);
D
Daniel Veillard 已提交
3867 3868 3869
    if (!dom_xml) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                          "%s", _("no domain XML passed"));
3870
        goto cleanup;
D
Daniel Veillard 已提交
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890
    }

    /* 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 */
        if (gethostname (hostname, HOST_NAME_MAX+1) == -1) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_SYSTEM_ERROR,
                              "%s", strerror (errno));
3891
            goto cleanup;
D
Daniel Veillard 已提交
3892 3893 3894 3895 3896 3897
        }

        /* Caller frees */
        if (asprintf(uri_out, "tcp:%s:%d", hostname, this_port) < 0) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_NO_MEMORY,
                              "%s", strerror (errno));
3898 3899
            *uri_out = NULL;
            goto cleanup;
D
Daniel Veillard 已提交
3900 3901 3902 3903 3904 3905 3906 3907 3908
        }
    } 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.
         */
        if (!STREQLEN (uri_in, "tcp:", 6)) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_ARG,
                  "%s", _("only tcp URIs are supported for KVM migrations"));
3909
            goto cleanup;
D
Daniel Veillard 已提交
3910 3911 3912 3913 3914 3915 3916 3917 3918
        }

        /* Get the port number. */
        p = strrchr (uri_in, ':');
        p++; /* definitely has a ':' in it, see above */
        this_port = virParseNumber (&p);
        if (this_port == -1 || p-uri_in != strlen (uri_in)) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_ARG,
                              "%s", _("URI did not have ':port' at the end"));
3919
            goto cleanup;
D
Daniel Veillard 已提交
3920 3921 3922 3923 3924 3925 3926
        }
    }

    /* Parse the domain XML. */
    if (!(def = virDomainDefParseString(dconn, driver->caps, dom_xml))) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to parse XML"));
3927
        goto cleanup;
D
Daniel Veillard 已提交
3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943
    }

    /* Target domain name, maybe renamed. */
    dname = dname ? dname : def->name;

#if 1
    /* Ensure the name and UUID don't already exist in an active VM */
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
#else
    /* For TESTING ONLY you can change #if 1 -> #if 0 above and use
     * this code which lets you do localhost migrations.  You must still
     * supply a fresh 'dname' but this code assigns a random UUID.
     */
    if (virUUIDGenerate (def->uuid) == -1) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
            _("could not generate random UUID"));
3944
        goto cleanup;
D
Daniel Veillard 已提交
3945 3946 3947 3948 3949 3950 3951 3952 3953
    }
#endif

    if (!vm) vm = virDomainFindByName(&driver->domains, dname);
    if (vm) {
        if (virDomainIsActive(vm)) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                              _("domain with the same name or UUID already exists as '%s'"),
                              vm->def->name);
3954
            goto cleanup;
D
Daniel Veillard 已提交
3955 3956 3957 3958 3959 3960 3961 3962
        }
    }

    if (!(vm = virDomainAssignDef(dconn,
                                  &driver->domains,
                                  def))) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to assign new VM"));
3963
        goto cleanup;
D
Daniel Veillard 已提交
3964
    }
3965
    def = NULL;
D
Daniel Veillard 已提交
3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976

    /* 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);
    if (qemudStartVMDaemon (dconn, driver, vm, migrateFrom) < 0) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to start listening VM"));
3977
        if (!vm->persistent) {
D
Daniel Veillard 已提交
3978
            virDomainRemoveInactive(&driver->domains, vm);
3979 3980
            vm = NULL;
        }
3981
        goto cleanup;
D
Daniel Veillard 已提交
3982
    }
3983 3984 3985 3986

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_MIGRATED);
3987
    ret = 0;
D
Daniel Veillard 已提交
3988

3989 3990 3991 3992 3993
cleanup:
    virDomainDefFree(def);
    if (ret != 0) {
        VIR_FREE(*uri_out);
    }
3994 3995
    if (vm)
        virDomainObjUnlock(vm);
3996 3997
    if (event)
        qemuDomainEventQueue(driver, event);
3998
    qemuDriverUnlock(driver);
3999
    return ret;
D
Daniel Veillard 已提交
4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011
}

/* 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,
                           unsigned long flags ATTRIBUTE_UNUSED,
                           const char *dname ATTRIBUTE_UNUSED,
                           unsigned long resource)
{
4012 4013
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4014
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4015 4016
    char *safe_uri;
    char cmd[HOST_NAME_MAX+50];
4017 4018
    char *info = NULL;
    int ret = -1;
D
Daniel Veillard 已提交
4019

4020
    qemuDriverLock(driver);
4021
    vm = virDomainFindByID(&driver->domains, dom->id);
D
Daniel Veillard 已提交
4022 4023 4024
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
4025
        goto cleanup;
D
Daniel Veillard 已提交
4026 4027 4028 4029 4030
    }

    if (!virDomainIsActive(vm)) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("domain is not running"));
4031
        goto cleanup;
D
Daniel Veillard 已提交
4032 4033
    }

4034 4035 4036 4037 4038 4039 4040
    if (!(flags & VIR_MIGRATE_LIVE)) {
        /* Pause domain for non-live migration */
        snprintf(cmd, sizeof cmd, "%s", "stop");
        qemudMonitorCommand (driver, vm, cmd, &info);
        DEBUG ("stop reply: %s", info);
        VIR_FREE(info);

4041 4042 4043 4044 4045 4046
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
        if (event)
            qemuDomainEventQueue(driver, event);
        event = NULL;
4047 4048
    }

D
Daniel Veillard 已提交
4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062
    if (resource > 0) {
        /* Issue migrate_set_speed command.  Don't worry if it fails. */
        snprintf (cmd, sizeof cmd, "migrate_set_speed %lum", resource);
        qemudMonitorCommand (driver, vm, cmd, &info);

        DEBUG ("migrate_set_speed reply: %s", info);
        VIR_FREE (info);
    }

    /* Issue the migrate command. */
    safe_uri = qemudEscapeMonitorArg (uri);
    if (!safe_uri) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
4063
        goto cleanup;
D
Daniel Veillard 已提交
4064 4065 4066 4067 4068 4069 4070
    }
    snprintf (cmd, sizeof cmd, "migrate \"%s\"", safe_uri);
    VIR_FREE (safe_uri);

    if (qemudMonitorCommand (driver, vm, cmd, &info) < 0) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("migrate operation failed"));
4071
        goto cleanup;
D
Daniel Veillard 已提交
4072 4073 4074 4075 4076 4077 4078 4079
    }

    DEBUG ("migrate reply: %s", info);

    /* Now check for "fail" in the output string */
    if (strstr(info, "fail") != NULL) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          _("migrate failed: %s"), info);
4080
        goto cleanup;
D
Daniel Veillard 已提交
4081 4082 4083 4084
    }

    /* Clean up the source domain. */
    qemudShutdownVMDaemon (dom->conn, driver, vm);
4085 4086 4087 4088

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
4089
    if (!vm->persistent) {
D
Daniel Veillard 已提交
4090
        virDomainRemoveInactive(&driver->domains, vm);
4091 4092
        vm = NULL;
    }
4093
    ret = 0;
D
Daniel Veillard 已提交
4094

4095 4096
cleanup:
    VIR_FREE(info);
4097 4098
    if (vm)
        virDomainObjUnlock(vm);
4099 4100
    if (event)
        qemuDomainEventQueue(driver, event);
4101
    qemuDriverUnlock(driver);
4102
    return ret;
D
Daniel Veillard 已提交
4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114
}

/* 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,
                           unsigned long flags ATTRIBUTE_UNUSED,
                           int retcode)
{
4115 4116 4117
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
4118
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4119 4120
    char *info = NULL;

4121
    qemuDriverLock(driver);
4122
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
4123 4124 4125
    if (!vm) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching name %s"), dname);
4126
        goto cleanup;
D
Daniel Veillard 已提交
4127 4128 4129 4130 4131 4132 4133 4134 4135
    }

    /* Did the migration go as planned?  If yes, return the domain
     * object, but if no, clean up the empty qemu process.
     */
    if (retcode == 0) {
        dom = virGetDomain (dconn, vm->def->name, vm->def->uuid);
        VIR_FREE(info);
        vm->state = VIR_DOMAIN_RUNNING;
4136 4137 4138
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
D
Daniel Veillard 已提交
4139 4140
    } else {
        qemudShutdownVMDaemon (dconn, driver, vm);
4141 4142 4143
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
4144
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4145
            virDomainRemoveInactive(&driver->domains, vm);
4146 4147
            vm = NULL;
        }
D
Daniel Veillard 已提交
4148
    }
4149 4150

cleanup:
4151 4152
    if (vm)
        virDomainObjUnlock(vm);
4153 4154
    if (event)
        qemuDomainEventQueue(driver, event);
4155
    qemuDriverUnlock(driver);
4156
    return dom;
D
Daniel Veillard 已提交
4157 4158
}

4159 4160 4161 4162 4163
static virDriver qemuDriver = {
    VIR_DRV_QEMU,
    "QEMU",
    qemudOpen, /* open */
    qemudClose, /* close */
D
Daniel Veillard 已提交
4164
    qemudSupportsFeature, /* supports_feature */
4165 4166
    qemudGetType, /* type */
    qemudGetVersion, /* version */
4167
    qemudGetHostname, /* hostname */
4168
    NULL, /* URI  */
4169 4170 4171 4172 4173
    qemudGetMaxVCPUs, /* getMaxVcpus */
    qemudGetNodeInfo, /* nodeGetInfo */
    qemudGetCapabilities, /* getCapabilities */
    qemudListDomains, /* listDomains */
    qemudNumDomains, /* numOfDomains */
4174
    qemudDomainCreate, /* domainCreateXML */
4175 4176 4177 4178 4179
    qemudDomainLookupByID, /* domainLookupByID */
    qemudDomainLookupByUUID, /* domainLookupByUUID */
    qemudDomainLookupByName, /* domainLookupByName */
    qemudDomainSuspend, /* domainSuspend */
    qemudDomainResume, /* domainResume */
4180
    qemudDomainShutdown, /* domainShutdown */
4181 4182 4183
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */
    qemudDomainGetOSType, /* domainGetOSType */
4184 4185 4186
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
    qemudDomainSetMaxMemory, /* domainSetMaxMemory */
    qemudDomainSetMemory, /* domainSetMemory */
4187 4188 4189 4190
    qemudDomainGetInfo, /* domainGetInfo */
    qemudDomainSave, /* domainSave */
    qemudDomainRestore, /* domainRestore */
    NULL, /* domainCoreDump */
4191
    qemudDomainSetVcpus, /* domainSetVcpus */
4192 4193 4194 4195
#if HAVE_SCHED_GETAFFINITY
    qemudDomainPinVcpu, /* domainPinVcpu */
    qemudDomainGetVcpus, /* domainGetVcpus */
#else
4196 4197
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
4198
#endif
4199
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
4200 4201 4202 4203 4204 4205
    qemudDomainDumpXML, /* domainDumpXML */
    qemudListDefinedDomains, /* listDomains */
    qemudNumDefinedDomains, /* numOfDomains */
    qemudDomainStart, /* domainCreate */
    qemudDomainDefine, /* domainDefineXML */
    qemudDomainUndefine, /* domainUndefine */
4206
    qemudDomainAttachDevice, /* domainAttachDevice */
4207
    qemudDomainDetachDevice, /* domainDetachDevice */
4208 4209 4210 4211 4212
    qemudDomainGetAutostart, /* domainGetAutostart */
    qemudDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
D
Daniel Veillard 已提交
4213 4214
    NULL, /* domainMigratePrepare (v1) */
    qemudDomainMigratePerform, /* domainMigratePerform */
4215
    NULL, /* domainMigrateFinish */
4216
    qemudDomainBlockStats, /* domainBlockStats */
4217
    qemudDomainInterfaceStats, /* domainInterfaceStats */
4218
    qemudDomainBlockPeek, /* domainBlockPeek */
R
Richard W.M. Jones 已提交
4219
    qemudDomainMemoryPeek, /* domainMemoryPeek */
4220 4221 4222 4223
#if HAVE_NUMACTL
    qemudNodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    qemudNodeGetFreeMemory,  /* getFreeMemory */
#else
4224
    NULL, /* nodeGetCellsFreeMemory */
4225
    NULL, /* getFreeMemory */
4226
#endif
4227 4228
    qemudDomainEventRegister, /* domainEventRegister */
    qemudDomainEventDeregister, /* domainEventDeregister */
D
Daniel Veillard 已提交
4229 4230
    qemudDomainMigratePrepare2, /* domainMigratePrepare2 */
    qemudDomainMigrateFinish2, /* domainMigrateFinish2 */
4231 4232 4233
};


4234
static virStateDriver qemuStateDriver = {
4235 4236 4237 4238
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
4239
};
4240

4241
int qemuRegister(void) {
4242 4243 4244 4245 4246
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}