qemu_driver.c 127.5 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 virDomainObjPtr vm,
140 141
                                const char *cmd,
                                char **reply);
142

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


146 147 148
static void
qemudAutostartConfigs(struct qemud_driver *driver) {
    unsigned int i;
149 150 151 152 153 154 155 156 157
    /* XXX: Figure out a better way todo this. The domain
     * startup code needs a connection handle in order
     * to lookup the bridge associated with a virtual
     * network
     */
    virConnectPtr conn = virConnectOpen(getuid() ?
                                        "qemu:///session" :
                                        "qemu:///system");
    /* Ignoring NULL conn which is mostly harmless here */
158 159

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

    virConnectClose(conn);
183 184
}

185 186 187 188 189 190 191
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
qemudStartup(void) {
192 193 194
    uid_t uid = geteuid();
    struct passwd *pw;
    char *base = NULL;
D
Daniel P. Berrange 已提交
195
    char driverConf[PATH_MAX];
196

197
    if (VIR_ALLOC(qemu_driver) < 0)
198 199
        return -1;

200 201 202
    pthread_mutex_init(&qemu_driver->lock, NULL);
    qemuDriverLock(qemu_driver);

203 204 205
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;

206 207
    /* Init callback list */
    if(VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
208
        goto out_of_memory;
209 210 211 212 213 214
    if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
        goto out_of_memory;

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

216
    if (!uid) {
217 218 219
        if (asprintf(&qemu_driver->logDir,
                     "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
220

D
Daniel P. Berrange 已提交
221
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
222 223 224
            goto out_of_memory;
    } else {
        if (!(pw = getpwuid(uid))) {
225
            qemudLog(QEMUD_ERR, _("Failed to find user record for uid '%d': %s\n"),
226
                     uid, strerror(errno));
227
            goto error;
228 229
        }

230 231 232
        if (asprintf(&qemu_driver->logDir,
                     "%s/.libvirt/qemu/log", pw->pw_dir) == -1)
            goto out_of_memory;
233

234
        if (asprintf (&base, "%s/.libvirt", pw->pw_dir) == -1)
235 236 237 238 239 240
            goto out_of_memory;
    }

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

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

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

251
    VIR_FREE(base);
252 253 254

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

    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
257
        goto error;
D
Daniel P. Berrange 已提交
258 259
    }

260 261 262 263
    if (virDomainLoadAllConfigs(NULL,
                                qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
264
                                qemu_driver->autostartDir,
265 266
                                NULL, NULL) < 0)
        goto error;
267 268
    qemudAutostartConfigs(qemu_driver);

269 270
    qemuDriverUnlock(qemu_driver);

271 272
    return 0;

273
out_of_memory:
J
Jim Meyering 已提交
274
    qemudLog (QEMUD_ERR,
275
              "%s", _("qemudStartup: out of memory\n"));
276 277 278
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
279
    VIR_FREE(base);
280
    qemudShutdown();
281 282 283
    return -1;
}

284 285 286 287
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;

288 289 290 291 292 293 294 295
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
    }
296 297
}

298 299 300 301 302 303 304 305
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
306 307 308
    if (!qemu_driver)
        return 0;

309
    qemuDriverLock(qemu_driver);
310 311 312 313
    virDomainLoadAllConfigs(NULL,
                            qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
314 315
                            qemu_driver->autostartDir,
                            qemudNotifyLoadDomain, qemu_driver);
316

317
    qemudAutostartConfigs(qemu_driver);
318
    qemuDriverUnlock(qemu_driver);
319 320

    return 0;
321 322
}

323 324 325 326 327 328 329 330 331 332
/**
 * 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) {
333
    unsigned int i;
334
    int active = 0;
335

336 337 338
    if (!qemu_driver)
        return 0;

339 340 341 342 343 344 345 346
    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);
    }
347

348 349
    qemuDriverUnlock(qemu_driver);
    return active;
350 351
}

352 353 354 355 356 357 358
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
359
    unsigned int i;
360

361
    if (!qemu_driver)
362
        return -1;
363

364
    qemuDriverLock(qemu_driver);
365 366
    virCapabilitiesFree(qemu_driver->caps);

367
    /* shutdown active VMs */
368 369
    for (i = 0 ; i < qemu_driver->domains.count ; i++) {
        virDomainObjPtr dom = qemu_driver->domains.objs[i];
370
        virDomainObjLock(dom);
371 372
        if (virDomainIsActive(dom))
            qemudShutdownVMDaemon(NULL, qemu_driver, dom);
373
        virDomainObjUnlock(dom);
374
    }
375

376
    virDomainObjListFree(&qemu_driver->domains);
377

378
    VIR_FREE(qemu_driver->logDir);
379 380 381
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
    VIR_FREE(qemu_driver->vncTLSx509certdir);
J
Jim Meyering 已提交
382
    VIR_FREE(qemu_driver->vncListen);
D
Daniel P. Berrange 已提交
383

384 385
    /* Free domain callback list */
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
386 387 388 389
    virDomainEventQueueFree(qemu_driver->domainEventQueue);

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

391 392 393
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);

394
    qemuDriverUnlock(qemu_driver);
395
    VIR_FREE(qemu_driver);
396 397

    return 0;
398 399 400
}

/* Return -1 for error, 1 to continue reading and 0 for success */
401
typedef int qemudHandlerMonitorOutput(virConnectPtr conn,
402
                                      virDomainObjPtr vm,
403 404 405 406
                                      const char *output,
                                      int fd);

static int
407
qemudReadMonitorOutput(virConnectPtr conn,
408
                       virDomainObjPtr vm,
409 410 411 412
                       int fd,
                       char *buf,
                       int buflen,
                       qemudHandlerMonitorOutput func,
413 414
                       const char *what,
                       int timeout)
415 416 417 418 419 420 421 422 423 424
{
    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) {
425
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
426
                             _("QEMU quit during %s startup\n%s"), what, buf);
427 428 429 430 431 432 433 434
            return -1;
        }
        if (ret < 0) {
            struct pollfd pfd = { .fd = fd, .events = POLLIN };
            if (errno == EINTR)
                continue;

            if (errno != EAGAIN) {
435
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
436
                                 _("Failure while reading %s startup output: %s"),
437 438 439 440
                                 what, strerror(errno));
                return -1;
            }

441
            ret = poll(&pfd, 1, timeout);
442
            if (ret == 0) {
443
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
444
                                 _("Timed out while reading %s startup output"), what);
445 446 447
                return -1;
            } else if (ret == -1) {
                if (errno != EINTR) {
448
                    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
449
                                     _("Failure while reading %s startup output: %s"),
450 451 452 453 454 455 456 457 458
                                     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;

459
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
460
                                 _("Failure while reading %s startup output"), what);
461 462 463 464 465
                return -1;
            }
        } else {
            got += ret;
            buf[got] = '\0';
466
            if ((ret = func(conn, vm, buf, fd)) != 1)
467 468 469 470
                return ret;
        }
    }

471
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
472
                     _("Out of space while reading %s startup output"), what);
473 474 475 476 477
    return -1;

}

static int
478
qemudCheckMonitorPrompt(virConnectPtr conn ATTRIBUTE_UNUSED,
479
                        virDomainObjPtr vm,
480 481 482 483 484 485 486 487 488 489 490
                        const char *output,
                        int fd)
{
    if (strstr(output, "(qemu) ") == NULL)
        return 1; /* keep reading */

    vm->monitor = fd;

    return 0;
}

491
static int qemudOpenMonitor(virConnectPtr conn,
492
                            virDomainObjPtr vm,
493
                            const char *monitor) {
494 495 496 497
    int monfd;
    char buf[1024];
    int ret = -1;

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

514
    ret = qemudReadMonitorOutput(conn,
515
                                 vm, monfd,
516 517
                                 buf, sizeof(buf),
                                 qemudCheckMonitorPrompt,
518
                                 "monitor", 10000);
519 520 521 522 523

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

524 525 526 527 528
 error:
    close(monfd);
    return ret;
}

529 530
static int qemudExtractMonitorPath(virConnectPtr conn,
                                   const char *haystack,
531
                                   size_t *offset,
532
                                   char **path) {
533
    static const char needle[] = "char device redirected to";
534
    char *tmp, *dev;
535

536
    VIR_FREE(*path);
537
    /* First look for our magic string */
538 539 540 541 542
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
543

544 545 546 547 548
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
549
        if (c_isspace(*tmp)) {
550 551 552 553 554 555 556
            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';
557
            /* ... now further update offset till we get EOL */
558
            *offset = tmp - haystack;
559 560
            return 0;
        }
561
        tmp++;
562 563 564 565 566
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
567 568
     * least see a \n - indicate that we want to carry
     * on trying again
569
     */
570
    return 1;
571 572 573
}

static int
574
qemudFindCharDevicePTYs(virConnectPtr conn,
575
                        virDomainObjPtr vm,
576 577
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
578
{
579
    char *monitor = NULL;
580
    size_t offset = 0;
581
    int ret, i;
582 583 584 585 586

    /* 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.... */
587

588
    /* So first comes the monitor device */
589 590
    if ((ret = qemudExtractMonitorPath(conn, output, &offset, &monitor)) != 0)
        goto cleanup;
591

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

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

    /* Got them all, so now open the monitor console */
613
    ret = qemudOpenMonitor(conn, vm, monitor);
614 615 616 617

cleanup:
    VIR_FREE(monitor);
    return ret;
618 619
}

620
static int qemudWaitForMonitor(virConnectPtr conn,
621
                               virDomainObjPtr vm) {
622
    char buf[1024]; /* Plenty of space to get startup greeting */
623
    int ret = qemudReadMonitorOutput(conn,
624
                                     vm, vm->stderr_fd,
625
                                     buf, sizeof(buf),
626
                                     qemudFindCharDevicePTYs,
627
                                     "console", 3000);
628 629

    buf[sizeof(buf)-1] = '\0';
630 631

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

639 640
static int
qemudDetectVcpuPIDs(virConnectPtr conn,
641
                    virDomainObjPtr vm) {
642 643 644 645 646 647
    char *qemucpus = NULL;
    char *line;
    int lastVcpu = -1;

    /* Only KVM has seperate threads for CPUs,
       others just use main QEMU process for CPU */
648
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM)
649 650 651 652 653 654 655 656 657 658
        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;
    }

659
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
660 661 662 663
        vm->vcpupids[0] = vm->pid;
        return 0;
    }

664
    if (qemudMonitorCommand(vm, "info cpus", &qemucpus) < 0) {
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 720 721 722
        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;

723
    VIR_FREE(qemucpus);
724 725 726 727
    return 0;

error:
    VIR_FREE(vm->vcpupids);
728 729
    vm->nvcpupids = 0;
    VIR_FREE(qemucpus);
730 731 732 733 734 735 736 737

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

738 739
static int
qemudInitCpus(virConnectPtr conn,
D
Daniel Veillard 已提交
740 741
              virDomainObjPtr vm,
              const char *migrateFrom) {
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
    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 已提交
757 758 759 760 761 762
    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++)
763
            CPU_SET(i, &mask);
D
Daniel P. Berrange 已提交
764
    }
765 766 767 768 769 770 771 772 773 774 775 776

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

    return 0;
}


791
static int qemudNextFreeVNCPort(struct qemud_driver *driver ATTRIBUTE_UNUSED) {
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 825 826
    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;
}

827 828 829
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
                                            const char *name);

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

    FD_ZERO(&keepfd);
846

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

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

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

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

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

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

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

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

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

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

964 965 966
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;

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

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

978
    for (i = 0 ; argv[i] ; i++)
979 980
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
981

982 983 984 985
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

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

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

1014
    return ret;
1015 1016
}

1017
static int qemudVMData(struct qemud_driver *driver ATTRIBUTE_UNUSED,
1018
                       virDomainObjPtr vm, int fd) {
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    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';

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


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

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

    kill(vm->pid, SIGTERM);

1053 1054
    qemudVMData(driver, vm, vm->stdout_fd);
    qemudVMData(driver, vm, vm->stderr_fd);
1055

1056 1057
    virEventRemoveHandle(vm->stdout_watch);
    virEventRemoveHandle(vm->stderr_watch);
1058 1059

    if (close(vm->logfile) < 0)
1060
        qemudLog(QEMUD_WARN, _("Unable to close logfile %d: %s\n"),
1061
                 errno, strerror(errno));
1062 1063
    close(vm->stdout_fd);
    close(vm->stderr_fd);
1064 1065 1066
    if (vm->monitor != -1)
        close(vm->monitor);
    vm->logfile = -1;
1067 1068
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;
1069 1070 1071 1072 1073
    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 已提交
1074
            qemudLog(QEMUD_WARN,
1075
                     "%s", _("Got unexpected pid, damn\n"));
1076 1077 1078 1079
        }
    }

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

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


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

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

    if (!vm)
1116
        goto cleanup;
1117

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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
1241
}
1242

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

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

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    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)
1262 1263
        goto decline;

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

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

    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
1279 1280

 decline:
1281
    return VIR_DRV_OPEN_DECLINED;
1282 1283 1284
}

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

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

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
/* 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;
    }
}

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

1309 1310 1311 1312 1313

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

    int r, fd;
1314

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

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

    close(fd);
    return maxvcpus;
}


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

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

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

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

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

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


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

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

1366
    return xml;
1367 1368 1369
}


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

    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1383
        goto cleanup;
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
    }
    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"));
1394
            goto cleanup;
1395 1396 1397
        }
        freeMems[numCells++] = mem;
    }
1398 1399 1400 1401
    ret = numCells;

cleanup:
    return ret;
1402 1403 1404 1405 1406
}

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

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

    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"));
1421
            goto cleanup;
1422 1423 1424 1425
        }
        freeMem += mem;
    }

1426
cleanup:
1427 1428 1429 1430
    return freeMem;
}

#endif
1431

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

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

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

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

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

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

    fclose(pidinfo);

    return 0;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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


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

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

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

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


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

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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


D
Daniel P. Berrange 已提交
1994
static char *qemudEscape(const char *in, int shell)
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
{
    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 已提交
2016 2017 2018 2019
            if (shell)
                len += 5;
            else
                len += 1;
2020 2021 2022 2023 2024 2025 2026
            break;
        default:
            len += 1;
            break;
        }
    }

2027
    if (VIR_ALLOC_N(out, len + 1) < 0)
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
        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 已提交
2046 2047 2048 2049 2050 2051 2052 2053 2054
            if (shell) {
                out[j++] = '\'';
                out[j++] = '\\';
                out[j++] = '\\';
                out[j++] = '\'';
                out[j++] = '\'';
            } else {
                out[j++] = in[i];
            }
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

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

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

2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
#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];
};

2087
static int qemudDomainSave(virDomainPtr dom,
2088
                           const char *path) {
2089 2090 2091 2092 2093 2094 2095
    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;
2096
    struct qemud_save_header header;
2097
    int ret = -1;
2098
    virDomainEventPtr event = NULL;
2099 2100 2101 2102 2103

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

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

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

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

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

    /* Get XML for the domain */
2130
    xml = virDomainDefFormat(dom->conn, vm->def, VIR_DOMAIN_XML_SECURE);
2131 2132
    if (!xml) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2133
                         "%s", _("failed to get domain xml"));
2134
        goto cleanup;
2135 2136 2137 2138 2139 2140
    }
    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,
2141
                         _("failed to create '%s'"), path);
2142
        goto cleanup;
2143 2144 2145 2146
    }

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

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

2157 2158 2159 2160 2161 2162 2163
    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;
2164 2165 2166 2167 2168

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

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

2187 2188 2189 2190 2191 2192 2193 2194
    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"));
2195
        goto cleanup;
2196 2197
    }

2198 2199
    /* Shut it down */
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2200 2201 2202
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2203
    if (!vm->persistent) {
2204 2205
        virDomainRemoveInactive(&driver->domains,
                                vm);
2206 2207
        vm = NULL;
    }
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
    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);
2219 2220
    if (vm)
        virDomainObjUnlock(vm);
2221 2222
    if (event)
        qemuDomainEventQueue(driver, event);
2223
    qemuDriverUnlock(driver);
2224
    return ret;
D
Daniel P. Berrange 已提交
2225 2226 2227
}


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

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

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

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

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

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

    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);
2263
        goto cleanup;
2264 2265 2266
    }

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

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

2275 2276 2277 2278 2279 2280 2281

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

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

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

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

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

    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));
2323
            goto cleanup;
2324 2325 2326 2327
        }
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cpu affinity is not supported"));
2328
        goto cleanup;
2329
    }
2330
    ret = 0;
2331

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

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

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

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

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

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

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

2371 2372 2373 2374 2375 2376 2377 2378
    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 */
            }
2379 2380
        }

2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
        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);
2398
                }
2399 2400 2401 2402
            } else {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                                 "%s", _("cpu affinity is not available"));
                goto cleanup;
2403 2404 2405
            }
        }
    }
2406
    ret = maxinfo;
2407

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


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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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


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

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

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

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

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

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

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


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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
2798 2799 2800 2801
            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);
2802 2803
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
2804 2805 2806 2807
            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);
2808 2809 2810 2811 2812 2813 2814 2815
            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:
2816
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
2817 2818 2819 2820 2821 2822
                             _("Unsupported disk name mapping for bus '%s'"),
                             virDomainDiskBusTypeToString(disk->bus));
            return NULL;
    }

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

    return devname;
}

2830 2831
static int qemudDomainChangeEjectableMedia(virConnectPtr conn,
                                           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(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
static int qemudDomainAttachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm,
                                          virDomainDeviceDefPtr dev)
2945 2946
{
    int ret, i;
2947
    char *cmd, *reply, *s;
2948 2949 2950 2951 2952
    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)) {
2953
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2954 2955 2956 2957 2958 2959
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

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

    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
2966
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2967 2968 2969 2970 2971 2972 2973 2974
                         "%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) {
2975
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
2976 2977 2978
        return ret;
    }

2979
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
2980
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2981 2982 2983 2984 2985 2986 2987 2988
                         _("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... */
2989 2990 2991 2992 2993 2994
#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 已提交
2995
            qemudLog(QEMUD_WARN, "%s", _("Unable to parse slot number\n"));
2996
    } else {
2997
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
                          _("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;
}
3012

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

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

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

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

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

3048
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3049
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3050
                         "%s", _("cannot attach usb disk"));
3051 3052 3053 3054 3055 3056 3057 3058
        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 ")) {
3059
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3060
                          "%s",
3061
                          _("adding usb disk failed"));
3062 3063 3064 3065
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3066

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

3071 3072 3073 3074 3075
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}

3076 3077 3078
static int qemudDomainAttachHostDevice(virConnectPtr conn,
                                       virDomainObjPtr vm,
                                       virDomainDeviceDefPtr dev)
3079 3080 3081 3082
{
    int ret;
    char *cmd, *reply;

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

    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) {
3098
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3099 3100 3101
        return -1;
    }

3102
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3103
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3104 3105 3106 3107 3108 3109 3110 3111 3112
                         "%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 ")) {
3113
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3114 3115 3116 3117 3118 3119
                          "%s",
                          _("adding usb device failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3120

3121
    vm->def->hostdevs[vm->def->nhostdevs++] = dev->data.hostdev;
3122

3123 3124
    VIR_FREE(reply);
    VIR_FREE(cmd);
3125 3126 3127
    return 0;
}

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

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

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

3151 3152 3153
    dev = virDomainDeviceDefParse(dom->conn,
                                  driver->caps,
                                  vm->def, xml);
3154
    qemuDriverUnlock(driver);
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
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
3163
            ret = qemudDomainChangeEjectableMedia(dom->conn, vm, dev);
3164 3165 3166
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
3167
                ret = qemudDomainAttachUsbMassstorageDevice(dom->conn, vm, dev);
3168 3169
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                       dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
3170
                ret = qemudDomainAttachPciDiskDevice(dom->conn, vm, dev);
3171 3172 3173 3174 3175 3176
            }
            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
               dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
               dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
3181
        ret = qemudDomainAttachHostDevice(dom->conn, vm, dev);
3182
    } 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
    if (vm)
        virDomainObjUnlock(vm);
3192 3193 3194
    return ret;
}

3195 3196
static int qemudDomainDetachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3197 3198
{
    int i, ret = -1;
3199 3200
    char *cmd = NULL;
    char *reply = NULL;
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
    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) {
3211
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3212
                         _("disk %s not found"), dev->data.disk->dst);
3213
        goto cleanup;
3214 3215 3216
    }

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

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

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

    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")) {
3239
        qemudReportError (conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3240
                          _("failed to detach disk %s: invalid slot %d"),
3241 3242
                          detach->dst, detach->slotnum);
        goto cleanup;
3243 3244 3245 3246 3247
    }

    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) {
3248 3249
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
            goto cleanup;
3250 3251 3252 3253 3254 3255 3256 3257
        }
        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;
3258 3259

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

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

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

    if (!virDomainIsActive(vm)) {
3282
        qemuDriverUnlock(driver);
3283 3284
        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
    qemuDriverUnlock(driver);
3290 3291 3292
    if (dev == NULL)
        goto cleanup;

3293 3294 3295 3296 3297

    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))
3298
        ret = qemudDomainDetachPciDiskDevice(dom->conn, vm, dev);
3299
    else
3300 3301 3302
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("only SCSI or virtio disk device can be detached dynamically"));

3303 3304
cleanup:
    virDomainDeviceDefFree(dev);
3305 3306
    if (vm)
        virDomainObjUnlock(vm);
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
    len = strlen (qemu_dev_name);

3453
    if (qemudMonitorCommand (vm, "info blockstats", &info) < 0) {
3454 3455
        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
    }

    /* Issue the memsave command. */
    snprintf (cmd, sizeof cmd, "memsave %llu %zi \"%s\"", offset, size, tmp);
3719
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
R
Richard W.M. Jones 已提交
3720
        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
    if (!(flags & VIR_MIGRATE_LIVE)) {
        /* Pause domain for non-live migration */
        snprintf(cmd, sizeof cmd, "%s", "stop");
4037
        qemudMonitorCommand (vm, cmd, &info);
4038 4039 4040
        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
    if (resource > 0) {
        /* Issue migrate_set_speed command.  Don't worry if it fails. */
        snprintf (cmd, sizeof cmd, "migrate_set_speed %lum", resource);
4052
        qemudMonitorCommand (vm, cmd, &info);
D
Daniel Veillard 已提交
4053 4054 4055 4056 4057 4058 4059 4060 4061 4062

        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
    }
    snprintf (cmd, sizeof cmd, "migrate \"%s\"", safe_uri);
    VIR_FREE (safe_uri);

4068
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
D
Daniel Veillard 已提交
4069 4070
        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;
}