qemu_driver.c 106.0 KB
Newer Older
D
Daniel P. Berrange 已提交
1 2 3
/*
 * driver.c: core driver methods for managing qemu guests
 *
4
 * Copyright (C) 2006, 2007, 2008 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 48 49 50
#if HAVE_NUMACTL
#include <numa.h>
#endif

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

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

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

74 75
static int qemudShutdown(void);

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

78 79 80 81 82 83 84 85 86
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 已提交
87
    qemudLog(QEMUD_ERR,
88
             "%s", _("Failed to set close-on-exec file descriptor flag\n"));
89 90 91 92 93 94 95 96 97 98 99 100 101
    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 已提交
102
    qemudLog(QEMUD_ERR,
103
             "%s", _("Failed to set non-blocking file descriptor flag\n"));
104 105 106 107
    return -1;
}


108 109 110 111 112 113 114 115
static void qemudDomainEventDispatch (struct qemud_driver *driver,
                                      virDomainObjPtr vm,
                                      virDomainEventType evt);

static void qemudDispatchVMEvent(int fd,
                                 int events,
                                 void *opaque);

116 117
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
118 119
                              virDomainObjPtr vm,
                              const char *migrateFrom);
120

121 122
static void qemudShutdownVMDaemon(virConnectPtr conn,
                                  struct qemud_driver *driver,
123
                                  virDomainObjPtr vm);
124

125
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
126

127
static int qemudMonitorCommand (const struct qemud_driver *driver,
128
                                const virDomainObjPtr vm,
129 130
                                const char *cmd,
                                char **reply);
131

J
Jim Meyering 已提交
132
static struct qemud_driver *qemu_driver = NULL;
133 134


135 136 137 138 139 140 141 142
static void
qemudAutostartConfigs(struct qemud_driver *driver) {
    unsigned int i;

    for (i = 0 ; i < driver->domains.count ; i++) {
        if (driver->domains.objs[i]->autostart &&
            !virDomainIsActive(driver->domains.objs[i]) &&
            qemudStartVMDaemon(NULL, driver, driver->domains.objs[i], NULL) < 0) {
143
            virErrorPtr err = virGetLastError();
144
            qemudLog(QEMUD_ERR, _("Failed to autostart VM '%s': %s\n"),
145 146
                     driver->domains.objs[i]->def->name,
                     err ? err->message : NULL);
147 148
        }
    }
149 150
}

151 152 153 154 155 156 157
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
qemudStartup(void) {
158 159 160
    uid_t uid = geteuid();
    struct passwd *pw;
    char *base = NULL;
D
Daniel P. Berrange 已提交
161
    char driverConf[PATH_MAX];
162

163
    if (VIR_ALLOC(qemu_driver) < 0)
164 165 166 167 168
        return -1;

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

169 170 171 172
    /* Init callback list */
    if(VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
        return -1;

173
    if (!uid) {
174 175 176
        if (asprintf(&qemu_driver->logDir,
                     "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
177

D
Daniel P. Berrange 已提交
178
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
179 180 181
            goto out_of_memory;
    } else {
        if (!(pw = getpwuid(uid))) {
182
            qemudLog(QEMUD_ERR, _("Failed to find user record for uid '%d': %s\n"),
183
                     uid, strerror(errno));
184
            goto out_nouid;
185 186
        }

187 188 189
        if (asprintf(&qemu_driver->logDir,
                     "%s/.libvirt/qemu/log", pw->pw_dir) == -1)
            goto out_of_memory;
190

191
        if (asprintf (&base, "%s/.libvirt", pw->pw_dir) == -1)
192 193 194 195 196 197
            goto out_of_memory;
    }

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

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

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

208
    VIR_FREE(base);
209 210 211

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

    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
214
        qemudShutdown();
D
Daniel P. Berrange 已提交
215 216 217
        return -1;
    }

218 219 220 221 222
    if (virDomainLoadAllConfigs(NULL,
                                qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
                                qemu_driver->autostartDir) < 0) {
D
Daniel P. Berrange 已提交
223 224 225
        qemudShutdown();
        return -1;
    }
226 227 228 229 230
    qemudAutostartConfigs(qemu_driver);

    return 0;

 out_of_memory:
J
Jim Meyering 已提交
231
    qemudLog (QEMUD_ERR,
232
              "%s", _("qemudStartup: out of memory\n"));
233
 out_nouid:
234 235
    VIR_FREE(base);
    VIR_FREE(qemu_driver);
236 237 238
    return -1;
}

239 240 241 242 243 244 245 246
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
247 248 249
    if (!qemu_driver)
        return 0;

250 251 252 253 254 255
    virDomainLoadAllConfigs(NULL,
                            qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
                            qemu_driver->autostartDir);

256
    qemudAutostartConfigs(qemu_driver);
257 258

    return 0;
259 260
}

261 262 263 264 265 266 267 268 269 270
/**
 * 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) {
271
    unsigned int i;
272

273 274 275 276 277
    if (!qemu_driver)
        return 0;

    for (i = 0 ; i < qemu_driver->domains.count ; i++)
        if (virDomainIsActive(qemu_driver->domains.objs[i]))
278 279
            return 1;

280 281 282 283
    /* Otherwise we're happy to deal with a shutdown */
    return 0;
}

284 285 286 287 288 289 290
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
291
    unsigned int i;
292

293
    if (!qemu_driver)
294
        return -1;
295

296 297
    virCapabilitiesFree(qemu_driver->caps);

298
    /* shutdown active VMs */
299 300 301 302 303
    for (i = 0 ; i < qemu_driver->domains.count ; i++) {
        virDomainObjPtr dom = qemu_driver->domains.objs[i];
        if (virDomainIsActive(dom))
            qemudShutdownVMDaemon(NULL, qemu_driver, dom);
        if (!dom->persistent)
304
            virDomainRemoveInactive(&qemu_driver->domains,
305
                                    dom);
306
    }
307

308
    virDomainObjListFree(&qemu_driver->domains);
309

310
    VIR_FREE(qemu_driver->logDir);
311 312 313
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
    VIR_FREE(qemu_driver->vncTLSx509certdir);
J
Jim Meyering 已提交
314
    VIR_FREE(qemu_driver->vncListen);
D
Daniel P. Berrange 已提交
315

316 317 318
    /* Free domain callback list */
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);

319 320 321
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);

322
    VIR_FREE(qemu_driver);
323 324

    return 0;
325 326 327
}

/* Return -1 for error, 1 to continue reading and 0 for success */
328 329
typedef int qemudHandlerMonitorOutput(virConnectPtr conn,
                                      struct qemud_driver *driver,
330
                                      virDomainObjPtr vm,
331 332 333 334
                                      const char *output,
                                      int fd);

static int
335 336
qemudReadMonitorOutput(virConnectPtr conn,
                       struct qemud_driver *driver,
337
                       virDomainObjPtr vm,
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
                       int fd,
                       char *buf,
                       int buflen,
                       qemudHandlerMonitorOutput func,
                       const char *what)
{
#define MONITOR_TIMEOUT 3000
    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) {
354
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
355
                             _("QEMU quit during %s startup\n%s"), what, buf);
356 357 358 359 360 361 362 363
            return -1;
        }
        if (ret < 0) {
            struct pollfd pfd = { .fd = fd, .events = POLLIN };
            if (errno == EINTR)
                continue;

            if (errno != EAGAIN) {
364
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
365
                                 _("Failure while reading %s startup output: %s"),
366 367 368 369 370 371
                                 what, strerror(errno));
                return -1;
            }

            ret = poll(&pfd, 1, MONITOR_TIMEOUT);
            if (ret == 0) {
372
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
373
                                 _("Timed out while reading %s startup output"), what);
374 375 376
                return -1;
            } else if (ret == -1) {
                if (errno != EINTR) {
377
                    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
378
                                     _("Failure while reading %s startup output: %s"),
379 380 381 382 383 384 385 386 387
                                     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;

388
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
389
                                 _("Failure while reading %s startup output"), what);
390 391 392 393 394
                return -1;
            }
        } else {
            got += ret;
            buf[got] = '\0';
395
            if ((ret = func(conn, driver, vm, buf, fd)) != 1)
396 397 398 399
                return ret;
        }
    }

400
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
401
                     _("Out of space while reading %s startup output"), what);
402 403 404 405 406 407
    return -1;

#undef MONITOR_TIMEOUT
}

static int
408 409
qemudCheckMonitorPrompt(virConnectPtr conn ATTRIBUTE_UNUSED,
                        struct qemud_driver *driver ATTRIBUTE_UNUSED,
410
                        virDomainObjPtr vm,
411 412 413 414 415 416 417 418 419 420 421
                        const char *output,
                        int fd)
{
    if (strstr(output, "(qemu) ") == NULL)
        return 1; /* keep reading */

    vm->monitor = fd;

    return 0;
}

422 423
static int qemudOpenMonitor(virConnectPtr conn,
                            struct qemud_driver *driver,
424
                            virDomainObjPtr vm,
425
                            const char *monitor) {
426 427 428 429
    int monfd;
    char buf[1024];
    int ret = -1;

D
Daniel Veillard 已提交
430
    if ((monfd = open(monitor, O_RDWR)) < 0) {
431
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
432
                         _("Unable to open monitor path %s"), monitor);
433 434 435
        return -1;
    }
    if (qemudSetCloseExec(monfd) < 0) {
436
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
437
                         "%s", _("Unable to set monitor close-on-exec flag"));
438 439 440
        goto error;
    }
    if (qemudSetNonBlock(monfd) < 0) {
441
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
442
                         "%s", _("Unable to put monitor into non-blocking mode"));
443 444 445
        goto error;
    }

446 447
    ret = qemudReadMonitorOutput(conn,
                                 driver, vm, monfd,
448 449 450
                                 buf, sizeof(buf),
                                 qemudCheckMonitorPrompt,
                                 "monitor");
451 452 453 454 455

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

456 457 458 459 460
 error:
    close(monfd);
    return ret;
}

461 462
static int qemudExtractMonitorPath(virConnectPtr conn,
                                   const char *haystack,
463
                                   size_t *offset,
464
                                   char **path) {
465
    static const char needle[] = "char device redirected to";
466
    char *tmp, *dev;
467

468
    VIR_FREE(*path);
469
    /* First look for our magic string */
470 471 472 473 474
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
475

476 477 478 479 480
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
481
        if (c_isspace(*tmp)) {
482 483 484 485 486 487 488
            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';
489
            /* ... now further update offset till we get EOL */
490
            *offset = tmp - haystack;
491 492
            return 0;
        }
493
        tmp++;
494 495 496 497 498
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
499 500
     * least see a \n - indicate that we want to carry
     * on trying again
501
     */
502
    return 1;
503 504 505
}

static int
506 507
qemudFindCharDevicePTYs(virConnectPtr conn,
                        struct qemud_driver *driver,
508
                        virDomainObjPtr vm,
509 510
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
511
{
512
    char *monitor = NULL;
513
    size_t offset = 0;
514
    int ret, i;
515 516 517 518 519

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

521
    /* So first comes the monitor device */
522 523
    if ((ret = qemudExtractMonitorPath(conn, output, &offset, &monitor)) != 0)
        goto cleanup;
524

525
    /* then the serial devices */
526 527
    for (i = 0 ; i < vm->def->nserials ; i++) {
        virDomainChrDefPtr chr = vm->def->serials[i];
528 529 530 531
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
532 533 534 535
        }
    }

    /* and finally the parallel devices */
536 537
    for (i = 0 ; i < vm->def->nparallels ; i++) {
        virDomainChrDefPtr chr = vm->def->parallels[i];
538 539 540 541
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
542 543 544 545
        }
    }

    /* Got them all, so now open the monitor console */
546 547 548 549 550
    ret = qemudOpenMonitor(conn, driver, vm, monitor);

cleanup:
    VIR_FREE(monitor);
    return ret;
551 552
}

553 554
static int qemudWaitForMonitor(virConnectPtr conn,
                               struct qemud_driver *driver,
555
                               virDomainObjPtr vm) {
556
    char buf[1024]; /* Plenty of space to get startup greeting */
557
    int ret = qemudReadMonitorOutput(conn,
558
                                     driver, vm, vm->stderr_fd,
559
                                     buf, sizeof(buf),
560
                                     qemudFindCharDevicePTYs,
561 562 563
                                     "console");

    buf[sizeof(buf)-1] = '\0';
564 565

    if (safewrite(vm->logfile, buf, strlen(buf)) < 0) {
566
        /* Log, but ignore failures to write logfile for VM */
567
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
568 569 570 571 572
                 strerror(errno));
    }
    return ret;
}

573 574 575
static int
qemudDetectVcpuPIDs(virConnectPtr conn,
                    struct qemud_driver *driver,
576
                    virDomainObjPtr vm) {
577 578 579 580 581 582
    char *qemucpus = NULL;
    char *line;
    int lastVcpu = -1;

    /* Only KVM has seperate threads for CPUs,
       others just use main QEMU process for CPU */
583
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM)
584 585 586 587 588 589 590 591 592 593
        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;
    }

594
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        vm->vcpupids[0] = vm->pid;
        return 0;
    }

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

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

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

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

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

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

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

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

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

658
    VIR_FREE(qemucpus);
659 660 661 662
    return 0;

error:
    VIR_FREE(vm->vcpupids);
663 664
    vm->nvcpupids = 0;
    VIR_FREE(qemucpus);
665 666 667 668 669 670 671 672

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

673 674 675
static int
qemudInitCpus(virConnectPtr conn,
              struct qemud_driver *driver,
676
              virDomainObjPtr vm) {
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
    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 已提交
692 693 694 695 696 697
    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++)
698
            CPU_SET(i, &mask);
D
Daniel P. Berrange 已提交
699
    }
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717

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

    /* Allow the CPUS to start executing */
    if (qemudMonitorCommand(driver, vm, "cont", &info) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("resume operation failed"));
        return -1;
    }
718
    VIR_FREE(info);
719 720 721 722 723

    return 0;
}


724
static int qemudNextFreeVNCPort(struct qemud_driver *driver ATTRIBUTE_UNUSED) {
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
    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;
}

760 761 762
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
                                            const char *name);

763 764
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
765 766
                              virDomainObjPtr vm,
                              const char *migrateFrom) {
767
    const char **argv = NULL, **tmp;
768
    const char **progenv = NULL;
769
    int i, ret;
770
    char logfile[PATH_MAX];
771
    struct stat sb;
772 773
    int *tapfds = NULL;
    int ntapfds = 0;
774
    unsigned int qemuCmdFlags;
775
    fd_set keepfd;
776
    const char *emulator;
777 778

    FD_ZERO(&keepfd);
779

780
    if (virDomainIsActive(vm)) {
781
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
782
                         "%s", _("VM is already active"));
783 784 785
        return -1;
    }

786 787 788
    if (vm->def->graphics &&
        vm->def->graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics->data.vnc.autoport) {
789
        int port = qemudNextFreeVNCPort(driver);
790
        if (port < 0) {
791
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
792
                             "%s", _("Unable to find an unused VNC port"));
793 794
            return -1;
        }
795 796
        vm->def->graphics->data.vnc.port = port;
    }
797

798
    if ((strlen(driver->logDir) + /* path */
799 800 801 802
         1 + /* Separator */
         strlen(vm->def->name) + /* basename */
         4 + /* suffix .log */
         1 /* NULL */) > PATH_MAX) {
803
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
804
                         _("config file path too long: %s/%s.log"),
805
                         driver->logDir, vm->def->name);
806 807
        return -1;
    }
808
    strcpy(logfile, driver->logDir);
809 810 811 812
    strcat(logfile, "/");
    strcat(logfile, vm->def->name);
    strcat(logfile, ".log");

813
    if (virFileMakePath(driver->logDir) < 0) {
814
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
815
                         _("cannot create log directory %s: %s"),
816
                         driver->logDir, strerror(errno));
817 818 819 820 821
        return -1;
    }

    if ((vm->logfile = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                            S_IRUSR | S_IWUSR)) < 0) {
822
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
823
                         _("failed to create logfile %s: %s"),
824 825 826
                         logfile, strerror(errno));
        return -1;
    }
827 828
    if (qemudSetCloseExec(vm->logfile) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
829
                         _("Unable to set VM logfile close-on-exec flag %s"),
830 831 832 833 834
                         strerror(errno));
        close(vm->logfile);
        vm->logfile = -1;
        return -1;
    }
835

836 837 838 839 840 841
    emulator = vm->def->emulator;
    if (!emulator)
        emulator = virDomainDefDefaultEmulator(conn, vm->def, driver->caps);
    if (!emulator)
        return -1;

842 843 844 845
    /* 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
     */
846
    if (stat(emulator, &sb) < 0) {
847 848
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot find QEMU binary %s: %s"),
849
                         emulator,
850 851 852 853
                         strerror(errno));
        return -1;
    }

854
    if (qemudExtractVersionInfo(emulator,
855 856 857 858
                                NULL,
                                &qemuCmdFlags) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot determine QEMU argv syntax %s"),
859
                         emulator);
860 861
        return -1;
    }
862

863
    vm->def->id = driver->nextvmid++;
864
    if (qemudBuildCommandLine(conn, driver, vm,
865
                              qemuCmdFlags, &argv, &progenv,
866
                              &tapfds, &ntapfds, migrateFrom) < 0) {
867
        close(vm->logfile);
868
        vm->def->id = -1;
869 870 871 872
        vm->logfile = -1;
        return -1;
    }

873 874 875 876 877 878 879 880 881 882
    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++;
    }
883 884
    tmp = argv;
    while (*tmp) {
885
        if (safewrite(vm->logfile, *tmp, strlen(*tmp)) < 0)
886
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
887
                     errno, strerror(errno));
888
        if (safewrite(vm->logfile, " ", 1) < 0)
889
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
890 891 892
                     errno, strerror(errno));
        tmp++;
    }
893
    if (safewrite(vm->logfile, "\n", 1) < 0)
894
        qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
895 896
                 errno, strerror(errno));

897 898 899
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;

900 901 902
    for (i = 0 ; i < ntapfds ; i++)
        FD_SET(tapfds[i], &keepfd);

903
    ret = virExec(conn, argv, progenv, &keepfd, &vm->pid,
904 905
                  vm->stdin_fd, &vm->stdout_fd, &vm->stderr_fd,
                  VIR_EXEC_NONBLOCK);
906
    if (ret == 0)
907
        vm->state = migrateFrom ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
908 909
    else
        vm->def->id = -1;
910

911
    for (i = 0 ; argv[i] ; i++)
912 913
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
914

915 916 917 918
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

919 920 921
    if (tapfds) {
        for (i = 0 ; i < ntapfds ; i++) {
            close(tapfds[i]);
922
        }
923
        VIR_FREE(tapfds);
924 925
    }

926
    if (ret == 0) {
927
        if ((virEventAddHandle(vm->stdout_fd,
928 929 930
                               VIR_EVENT_HANDLE_READABLE |
                                   VIR_EVENT_HANDLE_ERROR |
                                   VIR_EVENT_HANDLE_HANGUP,
931 932
                               qemudDispatchVMEvent,
                               driver) < 0) ||
933
            (virEventAddHandle(vm->stderr_fd,
934 935 936
                               VIR_EVENT_HANDLE_READABLE |
                                   VIR_EVENT_HANDLE_ERROR |
                                   VIR_EVENT_HANDLE_HANGUP,
937 938 939 940 941
                               qemudDispatchVMEvent,
                               driver) < 0) ||
            (qemudWaitForMonitor(conn, driver, vm) < 0) ||
            (qemudDetectVcpuPIDs(conn, driver, vm) < 0) ||
            (qemudInitCpus(conn, driver, vm) < 0)) {
942 943 944
            qemudShutdownVMDaemon(conn, driver, vm);
            return -1;
        }
945
        qemudDomainEventDispatch(driver, vm, VIR_DOMAIN_EVENT_STARTED);
946 947
    }

948
    return ret;
949 950
}

951
static int qemudVMData(struct qemud_driver *driver ATTRIBUTE_UNUSED,
952
                       virDomainObjPtr vm, int fd) {
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
    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';

969
        if (safewrite(vm->logfile, buf, ret) < 0) {
970
            /* Log, but ignore failures to write logfile for VM */
971
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
972 973 974 975 976 977
                     strerror(errno));
        }
    }
}


978
static void qemudShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
979 980
                                  struct qemud_driver *driver, virDomainObjPtr vm) {
    if (!virDomainIsActive(vm))
981
        return;
982

983
    qemudLog(QEMUD_INFO, _("Shutting down VM '%s'\n"), vm->def->name);
984 985 986

    kill(vm->pid, SIGTERM);

987 988
    qemudVMData(driver, vm, vm->stdout_fd);
    qemudVMData(driver, vm, vm->stderr_fd);
989

990 991
    virEventRemoveHandle(vm->stdout_fd);
    virEventRemoveHandle(vm->stderr_fd);
992 993

    if (close(vm->logfile) < 0)
994
        qemudLog(QEMUD_WARN, _("Unable to close logfile %d: %s\n"),
995
                 errno, strerror(errno));
996 997
    close(vm->stdout_fd);
    close(vm->stderr_fd);
998 999 1000
    if (vm->monitor != -1)
        close(vm->monitor);
    vm->logfile = -1;
1001 1002
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;
1003 1004 1005 1006 1007
    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 已提交
1008
            qemudLog(QEMUD_WARN,
1009
                     "%s", _("Got unexpected pid, damn\n"));
1010 1011 1012 1013
        }
    }

    vm->pid = -1;
1014
    vm->def->id = -1;
1015
    vm->state = VIR_DOMAIN_SHUTOFF;
1016
    VIR_FREE(vm->vcpupids);
1017
    vm->nvcpupids = 0;
1018 1019

    if (vm->newDef) {
1020
        virDomainDefFree(vm->def);
1021
        vm->def = vm->newDef;
1022
        vm->def->id = -1;
1023 1024 1025 1026
        vm->newDef = NULL;
    }
}

1027
static int qemudDispatchVMLog(struct qemud_driver *driver, virDomainObjPtr vm, int fd) {
1028 1029
    if (qemudVMData(driver, vm, fd) < 0) {
        qemudShutdownVMDaemon(NULL, driver, vm);
1030
        if (!vm->persistent)
1031 1032
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1033
    }
1034 1035 1036
    return 0;
}

1037
static int qemudDispatchVMFailure(struct qemud_driver *driver, virDomainObjPtr vm,
1038
                                  int fd ATTRIBUTE_UNUSED) {
1039
    qemudShutdownVMDaemon(NULL, driver, vm);
1040
    qemudDomainEventDispatch(driver, vm, VIR_DOMAIN_EVENT_STOPPED);
1041
    if (!vm->persistent)
1042 1043
        virDomainRemoveInactive(&driver->domains,
                                vm);
1044 1045 1046 1047
    return 0;
}


1048 1049
static void
qemudDispatchVMEvent(int fd, int events, void *opaque) {
1050
    struct qemud_driver *driver = (struct qemud_driver *)opaque;
1051 1052 1053 1054 1055 1056 1057 1058
    virDomainObjPtr vm = NULL;
    unsigned int i;

    for (i = 0 ; i < driver->domains.count ; i++) {
        if (virDomainIsActive(driver->domains.objs[i]) &&
            (driver->domains.objs[i]->stdout_fd == fd ||
             driver->domains.objs[i]->stderr_fd == fd)) {
            vm = driver->domains.objs[i];
1059
            break;
1060
        }
1061 1062 1063 1064 1065
    }

    if (!vm)
        return;

1066
    if (events == VIR_EVENT_HANDLE_READABLE)
1067
        qemudDispatchVMLog(driver, vm, fd);
1068
    else
1069
        qemudDispatchVMFailure(driver, vm, fd);
1070 1071
}

1072 1073
static int
qemudMonitorCommand (const struct qemud_driver *driver ATTRIBUTE_UNUSED,
1074
                     const virDomainObjPtr vm,
1075 1076
                     const char *cmd,
                     char **reply) {
D
Daniel P. Berrange 已提交
1077 1078
    int size = 0;
    char *buf = NULL;
1079
    size_t cmdlen = strlen(cmd);
D
Daniel P. Berrange 已提交
1080

1081 1082 1083
    if (safewrite(vm->monitor, cmd, cmdlen) != cmdlen)
        return -1;
    if (safewrite(vm->monitor, "\r", 1) != 1)
D
Daniel P. Berrange 已提交
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
        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 已提交
1096

1097 1098
            if (got == 0)
                goto error;
D
Daniel P. Berrange 已提交
1099 1100 1101 1102 1103
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
1104
                goto error;
1105
            }
1106
            if (VIR_REALLOC_N(buf, size+got+1) < 0)
1107 1108
                goto error;

D
Daniel P. Berrange 已提交
1109 1110 1111 1112
            memmove(buf+size, data, got);
            buf[size+got] = '\0';
            size += got;
        }
1113

D
Daniel P. Berrange 已提交
1114
        /* Look for QEMU prompt to indicate completion */
D
Daniel P. Berrange 已提交
1115
        if (buf && ((tmp = strstr(buf, "\n(qemu) ")) != NULL)) {
D
Daniel P. Berrange 已提交
1116 1117 1118 1119 1120 1121 1122 1123
            tmp[0] = '\0';
            break;
        }
    pollagain:
        /* Need to wait for more data */
        if (poll(&fd, 1, -1) < 0) {
            if (errno == EINTR)
                goto pollagain;
1124
            goto error;
D
Daniel P. Berrange 已提交
1125 1126 1127
        }
    }

1128 1129
    /* Log, but ignore failures to write logfile for VM */
    if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1130
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1131 1132
                 strerror(errno));

D
Daniel P. Berrange 已提交
1133 1134
    *reply = buf;
    return 0;
1135 1136 1137 1138 1139

 error:
    if (buf) {
        /* Log, but ignore failures to write logfile for VM */
        if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1140
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1141
                     strerror(errno));
1142
        VIR_FREE(buf);
1143 1144
    }
    return -1;
D
Daniel P. Berrange 已提交
1145 1146
}

1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
/**
 * qemudProbe:
 *
 * Probe for the availability of the qemu driver, assume the
 * presence of QEmu emulation if the binaries are installed
 */
static const char *qemudProbe(void)
{
    if ((virFileExists("/usr/bin/qemu")) ||
        (virFileExists("/usr/bin/qemu-kvm")) ||
1157
        (virFileExists("/usr/bin/xenner"))) {
1158
        if (getuid() == 0) {
1159 1160 1161 1162
            return("qemu:///system");
        } else {
            return("qemu:///session");
        }
1163 1164 1165
    }
    return(NULL);
}
1166

1167
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
1168
                                  xmlURIPtr uri,
1169
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1170
                                  int flags ATTRIBUTE_UNUSED) {
1171 1172 1173
    uid_t uid = getuid();

    if (qemu_driver == NULL)
1174
        goto decline;
1175

1176 1177 1178 1179 1180 1181
    if (uri == NULL || uri->scheme == NULL || uri->path == NULL)
        goto decline;

    if (STRNEQ (uri->scheme, "qemu"))
        goto decline;

1182
    if (uid != 0) {
1183 1184
        if (STRNEQ (uri->path, "/session"))
            goto decline;
1185
    } else { /* root */
1186 1187
        if (STRNEQ (uri->path, "/system") &&
            STRNEQ (uri->path, "/session"))
1188
            goto decline;
1189 1190 1191 1192 1193
    }

    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
1194 1195

 decline:
1196
    return VIR_DRV_OPEN_DECLINED;
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
}

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

    conn->privateData = NULL;

    return 0;
}

static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1208
    return "QEMU";
1209 1210
}

1211 1212 1213 1214 1215

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

    int r, fd;
1216

1217 1218
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
1219
        qemudLog(QEMUD_WARN, _("Unable to open %s: %s\n"), KVM_DEVICE, strerror(errno));
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
        return maxvcpus;
    }

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

    close(fd);
    return maxvcpus;
}


1232
static int qemudGetMaxVCPUs(virConnectPtr conn, const char *type) {
1233 1234 1235
    if (!type)
        return 16;

1236
    if (STRCASEEQ(type, "qemu"))
1237 1238 1239 1240
        return 16;

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

1244
    if (STRCASEEQ(type, "kqemu"))
1245
        return 1;
1246 1247 1248

    qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                     _("unknown type '%s'"), type);
1249 1250 1251
    return -1;
}

1252 1253 1254
static int qemudGetNodeInfo(virConnectPtr conn,
                            virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
1255 1256 1257
}


1258 1259 1260
static char *qemudGetCapabilities(virConnectPtr conn) {
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *xml;
1261

1262
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL) {
1263 1264
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                 "%s", _("failed to allocate space for capabilities support"));
1265 1266 1267
        return NULL;
    }

1268
    return xml;
1269 1270 1271
}


1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
#if HAVE_NUMACTL
static int
qemudNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;

    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
        return -1;
    }
    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"));
            return -1;
        }
        freeMems[numCells++] = mem;
    }
    return numCells;
}

static unsigned long long
qemudNodeGetFreeMemory (virConnectPtr conn)
{
    unsigned long long freeMem = 0;
    int n;
    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
        return -1;
    }

    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"));
            return -1;
        }
        freeMem += mem;
    }

    return freeMem;
}

#endif
1327

D
Daniel P. Berrange 已提交
1328 1329 1330
static int qemudGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
1331
    unsigned long long usertime, systime;
D
Daniel P. Berrange 已提交
1332 1333 1334 1335 1336 1337

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

    if (!(pidinfo = fopen(proc, "r"))) {
1338
        /*printf("cannot read pid info");*/
D
Daniel P. Berrange 已提交
1339 1340 1341 1342 1343
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
        return 0;
    }

1344
    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
1345
        qemudDebug("not enough arg");
D
Daniel P. Berrange 已提交
1346 1347 1348 1349 1350 1351 1352 1353
        return -1;
    }

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

1356
    qemudDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);
D
Daniel P. Berrange 已提交
1357 1358 1359 1360 1361 1362 1363

    fclose(pidinfo);

    return 0;
}


1364
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1365
                                          int id) {
1366
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1367
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, id);
1368 1369 1370
    virDomainPtr dom;

    if (!vm) {
1371
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1372 1373 1374
        return NULL;
    }

1375
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1376
    if (dom) dom->id = vm->def->id;
1377 1378
    return dom;
}
1379
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1380
                                            const unsigned char *uuid) {
1381
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1382
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, uuid);
1383 1384 1385
    virDomainPtr dom;

    if (!vm) {
1386
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1387 1388 1389
        return NULL;
    }

1390
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1391
    if (dom) dom->id = vm->def->id;
1392 1393
    return dom;
}
1394
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1395
                                            const char *name) {
1396
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1397
    virDomainObjPtr vm = virDomainFindByName(&driver->domains, name);
1398 1399 1400
    virDomainPtr dom;

    if (!vm) {
1401
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1402 1403 1404
        return NULL;
    }

1405
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1406
    if (dom) dom->id = vm->def->id;
1407 1408 1409
    return dom;
}

1410
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1411
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1412
    if (qemudExtractVersion(conn, driver) < 0)
1413 1414
        return -1;

1415 1416
    *version = qemu_driver->qemuVersion;
    return 0;
D
Daniel P. Berrange 已提交
1417 1418
}

1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
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;
}

1441
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1442
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1443 1444 1445 1446 1447 1448
    int got = 0, i;

    for (i = 0 ; i < driver->domains.count && got < nids ; i++)
        if (virDomainIsActive(driver->domains.objs[i]))
            ids[got++] = driver->domains.objs[i]->def->id;

D
Daniel P. Berrange 已提交
1449 1450
    return got;
}
1451
static int qemudNumDomains(virConnectPtr conn) {
1452
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1453 1454 1455 1456
    int n = 0, i;

    for (i = 0 ; i < driver->domains.count ; i++)
        if (virDomainIsActive(driver->domains.objs[i]))
1457
            n++;
1458

1459
    return n;
D
Daniel P. Berrange 已提交
1460
}
1461
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1462
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1463 1464
    virDomainDefPtr def;
    virDomainObjPtr vm;
1465 1466
    virDomainPtr dom;
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
D
Daniel P. Berrange 已提交
1467

1468
    if (!(def = virDomainDefParseString(conn, driver->caps, xml)))
1469 1470
        return NULL;

1471
    vm = virDomainFindByName(&driver->domains, def->name);
1472
    if (vm) {
1473
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1474
                         _("domain '%s' is already defined"),
1475 1476 1477 1478
                         def->name);
        virDomainDefFree(def);
        return NULL;
    }
1479
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
1480 1481 1482 1483 1484
    if (vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(def->uuid, uuidstr);
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1485
                         _("domain with uuid '%s' is already defined"),
1486 1487 1488 1489
                         uuidstr);
        virDomainDefFree(def);
        return NULL;
    }
1490

1491 1492 1493 1494
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
        virDomainDefFree(def);
D
Daniel P. Berrange 已提交
1495 1496 1497
        return NULL;
    }

1498 1499 1500
    if (qemudStartVMDaemon(conn, driver, vm, NULL) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
D
Daniel P. Berrange 已提交
1501 1502 1503
        return NULL;
    }

1504
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1505
    if (dom) dom->id = vm->def->id;
1506
    return dom;
D
Daniel P. Berrange 已提交
1507 1508 1509
}


1510
static int qemudDomainSuspend(virDomainPtr dom) {
1511
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
D
Daniel P. Berrange 已提交
1512
    char *info;
1513
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
D
Daniel P. Berrange 已提交
1514
    if (!vm) {
1515
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN, _("no domain with matching id %d"), dom->id);
D
Daniel P. Berrange 已提交
1516 1517
        return -1;
    }
1518
    if (!virDomainIsActive(vm)) {
1519 1520
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
D
Daniel P. Berrange 已提交
1521 1522
        return -1;
    }
1523
    if (vm->state == VIR_DOMAIN_PAUSED)
D
Daniel P. Berrange 已提交
1524
        return 0;
D
Daniel P. Berrange 已提交
1525

1526
    if (qemudMonitorCommand(driver, vm, "stop", &info) < 0) {
1527 1528
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("suspend operation failed"));
D
Daniel P. Berrange 已提交
1529 1530
        return -1;
    }
1531
    vm->state = VIR_DOMAIN_PAUSED;
1532
    qemudDebug("Reply %s", info);
1533
    qemudDomainEventDispatch(driver, vm, VIR_DOMAIN_EVENT_SUSPENDED);
1534
    VIR_FREE(info);
D
Daniel P. Berrange 已提交
1535 1536 1537 1538
    return 0;
}


1539
static int qemudDomainResume(virDomainPtr dom) {
1540
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
D
Daniel P. Berrange 已提交
1541
    char *info;
1542
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
D
Daniel P. Berrange 已提交
1543
    if (!vm) {
1544 1545
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
D
Daniel P. Berrange 已提交
1546 1547
        return -1;
    }
1548
    if (!virDomainIsActive(vm)) {
1549 1550
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
D
Daniel P. Berrange 已提交
1551 1552
        return -1;
    }
1553
    if (vm->state == VIR_DOMAIN_RUNNING)
D
Daniel P. Berrange 已提交
1554
        return 0;
1555
    if (qemudMonitorCommand(driver, vm, "cont", &info) < 0) {
1556 1557
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("resume operation failed"));
D
Daniel P. Berrange 已提交
1558 1559
        return -1;
    }
1560
    vm->state = VIR_DOMAIN_RUNNING;
1561
    qemudDebug("Reply %s", info);
1562
    qemudDomainEventDispatch(driver, vm, VIR_DOMAIN_EVENT_RESUMED);
1563
    VIR_FREE(info);
D
Daniel P. Berrange 已提交
1564
    return 0;
D
Daniel P. Berrange 已提交
1565 1566 1567
}


1568 1569
static int qemudDomainShutdown(virDomainPtr dom) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1570
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
1571 1572 1573 1574
    char* info;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1575
                         _("no domain with matching id %d"), dom->id);
1576 1577 1578 1579 1580
        return -1;
    }

    if (qemudMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1581
                         "%s", _("shutdown operation failed"));
1582 1583
        return -1;
    }
D
Daniel Veillard 已提交
1584
    VIR_FREE(info);
1585 1586 1587 1588 1589
    return 0;

}


1590
static int qemudDomainDestroy(virDomainPtr dom) {
1591
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1592
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
1593

D
Daniel P. Berrange 已提交
1594
    if (!vm) {
1595
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1596
                         _("no domain with matching id %d"), dom->id);
D
Daniel P. Berrange 已提交
1597 1598
        return -1;
    }
1599

1600
    qemudShutdownVMDaemon(dom->conn, driver, vm);
1601
    qemudDomainEventDispatch(driver, vm, VIR_DOMAIN_EVENT_STOPPED);
1602
    if (!vm->persistent)
1603 1604
        virDomainRemoveInactive(&driver->domains,
                                vm);
1605
    return 0;
D
Daniel P. Berrange 已提交
1606 1607 1608
}


1609 1610
static char *qemudDomainGetOSType(virDomainPtr dom) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1611
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1612 1613 1614 1615
    char *type;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1616
                         "%s", _("no domain with matching uuid"));
1617 1618 1619 1620
        return NULL;
    }

    if (!(type = strdup(vm->def->os.type))) {
1621 1622
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for ostype"));
1623 1624 1625 1626 1627
        return NULL;
    }
    return type;
}

1628 1629 1630
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1631
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1632 1633

    if (!vm) {
1634 1635 1636
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1637
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1638
                         _("no domain with matching uuid '%s'"), uuidstr);
1639 1640 1641 1642 1643 1644 1645 1646
        return 0;
    }

    return vm->def->maxmem;
}

static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1647
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1648 1649

    if (!vm) {
1650 1651 1652
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1653
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1654
                         _("no domain with matching uuid '%s'"), uuidstr);
1655 1656 1657 1658 1659
        return -1;
    }

    if (newmax < vm->def->memory) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
1660
                         "%s", _("cannot set max memory lower than current memory"));
1661 1662 1663 1664 1665 1666 1667 1668 1669
        return -1;
    }

    vm->def->maxmem = newmax;
    return 0;
}

static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1670
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1671 1672

    if (!vm) {
1673 1674 1675
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1676
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1677
                         _("no domain with matching uuid '%s'"), uuidstr);
1678 1679 1680
        return -1;
    }

1681
    if (virDomainIsActive(vm)) {
1682
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
1683
                         "%s", _("cannot set memory of an active domain"));
1684 1685 1686 1687 1688
        return -1;
    }

    if (newmem > vm->def->maxmem) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
1689
                         "%s", _("cannot set memory higher than max memory"));
1690 1691 1692 1693 1694 1695 1696
        return -1;
    }

    vm->def->memory = newmem;
    return 0;
}

1697
static int qemudDomainGetInfo(virDomainPtr dom,
1698
                              virDomainInfoPtr info) {
1699
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1700
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
1701
    if (!vm) {
1702 1703
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
D
Daniel P. Berrange 已提交
1704 1705 1706
        return -1;
    }

1707
    info->state = vm->state;
D
Daniel P. Berrange 已提交
1708

1709
    if (!virDomainIsActive(vm)) {
1710
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
1711
    } else {
1712
        if (qemudGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1713
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED, ("cannot read cputime for domain"));
D
Daniel P. Berrange 已提交
1714 1715 1716 1717
            return -1;
        }
    }

1718 1719 1720
    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
D
Daniel P. Berrange 已提交
1721 1722 1723 1724
    return 0;
}


D
Daniel P. Berrange 已提交
1725
static char *qemudEscape(const char *in, int shell)
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
{
    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 已提交
1747 1748 1749 1750
            if (shell)
                len += 5;
            else
                len += 1;
1751 1752 1753 1754 1755 1756 1757
            break;
        default:
            len += 1;
            break;
        }
    }

1758
    if (VIR_ALLOC_N(out, len + 1) < 0)
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
        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 已提交
1777 1778 1779 1780 1781 1782 1783 1784 1785
            if (shell) {
                out[j++] = '\'';
                out[j++] = '\\';
                out[j++] = '\\';
                out[j++] = '\'';
                out[j++] = '\'';
            } else {
                out[j++] = in[i];
            }
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

1797 1798 1799 1800 1801
static char *qemudEscapeMonitorArg(const char *in)
{
    return qemudEscape(in, 0);
}

D
Daniel P. Berrange 已提交
1802 1803 1804 1805
static char *qemudEscapeShellArg(const char *in)
{
    return qemudEscape(in, 1);
}
1806

1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
#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];
};

1818
static int qemudDomainSave(virDomainPtr dom,
1819
                           const char *path) {
1820
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1821
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
    char *command, *info;
    int fd;
    char *safe_path;
    char *xml;
    struct qemud_save_header header;

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

D
Daniel P. Berrange 已提交
1832
    if (!vm) {
1833
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1834
                         _("no domain with matching id %d"), dom->id);
D
Daniel P. Berrange 已提交
1835 1836
        return -1;
    }
1837

1838
    if (!virDomainIsActive(vm)) {
1839
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1840
                         "%s", _("domain is not running"));
D
Daniel P. Berrange 已提交
1841 1842
        return -1;
    }
1843 1844 1845 1846 1847 1848

    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
        if (qemudDomainSuspend(dom) != 0) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1849
                             "%s", _("failed to pause domain"));
1850 1851 1852 1853 1854
            return -1;
        }
    }

    /* Get XML for the domain */
1855
    xml = virDomainDefFormat(dom->conn, vm->def, VIR_DOMAIN_XML_SECURE);
1856 1857
    if (!xml) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1858
                         "%s", _("failed to get domain xml"));
1859 1860 1861 1862 1863 1864 1865
        return -1;
    }
    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,
1866
                         _("failed to create '%s'"), path);
1867
        VIR_FREE(xml);
1868 1869 1870 1871 1872
        return -1;
    }

    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1873
                         "%s", _("failed to write save header"));
1874
        close(fd);
1875
        VIR_FREE(xml);
1876 1877 1878 1879 1880
        return -1;
    }

    if (safewrite(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1881
                         "%s", _("failed to write xml"));
1882
        close(fd);
1883
        VIR_FREE(xml);
1884 1885 1886 1887
        return -1;
    }

    close(fd);
1888
    VIR_FREE(xml);
1889 1890 1891 1892 1893

    /* Migrate to file */
    safe_path = qemudEscapeShellArg(path);
    if (!safe_path) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1894
                         "%s", _("out of memory"));
1895 1896 1897 1898
        return -1;
    }
    if (asprintf (&command, "migrate \"exec:"
                  "dd of='%s' oflag=append conv=notrunc 2>/dev/null"
1899
                  "\"", safe_path) == -1) {
1900
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1901
                         "%s", _("out of memory"));
1902
        VIR_FREE(safe_path);
1903 1904 1905 1906 1907 1908
        return -1;
    }
    free(safe_path);

    if (qemudMonitorCommand(driver, vm, command, &info) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1909
                         "%s", _("migrate operation failed"));
1910
        VIR_FREE(command);
1911 1912 1913
        return -1;
    }

1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
    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"));
        VIR_FREE(info);
        VIR_FREE(command);
        return -1;
    }

1927 1928
    VIR_FREE(info);
    VIR_FREE(command);
1929 1930 1931

    /* Shut it down */
    qemudShutdownVMDaemon(dom->conn, driver, vm);
1932
    if (!vm->persistent)
1933 1934
        virDomainRemoveInactive(&driver->domains,
                                vm);
1935
    qemudDomainEventDispatch(driver, vm, VIR_DOMAIN_EVENT_SAVED);
1936
    return 0;
D
Daniel P. Berrange 已提交
1937 1938 1939
}


1940
static int qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
1941 1942
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1943 1944 1945
    int max;

    if (!vm) {
1946 1947 1948
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1949
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1950
                         _("no domain with matching uuid '%s'"), uuidstr);
1951 1952 1953
        return -1;
    }

1954
    if (virDomainIsActive(vm)) {
1955
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT, "%s",
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
                         _("cannot change vcpu count of an active domain"));
        return -1;
    }

    if ((max = qemudDomainGetMaxVcpus(dom)) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                         _("could not determine max vcpus for the domain"));
        return -1;
    }

    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);
        return -1;
    }

    vm->def->vcpus = nvcpus;
    return 0;
}

1977 1978 1979 1980 1981 1982 1983 1984

#if HAVE_SCHED_GETAFFINITY
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1985
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1986 1987 1988 1989
    cpu_set_t mask;
    int i, maxcpu;
    virNodeInfo nodeinfo;

1990
    if (!virDomainIsActive(vm)) {
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
        return -1;
    }

    if (vcpu > (vm->nvcpupids-1)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         _("vcpu number out of range %d > %d"),
                         vcpu, vm->nvcpupids);
        return -1;
    }

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

    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));
            return -1;
        }
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cpu affinity is not supported"));
        return -1;
    }

    return 0;
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2038
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2039 2040 2041
    virNodeInfo nodeinfo;
    int i, v, maxcpu;

2042
    if (!virDomainIsActive(vm)) {
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
        return -1;
    }

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

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

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

    if (maxinfo < 1)
        return 0;

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

    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));
                    return -1;
                }

                for (i = 0 ; i < maxcpu ; i++)
                    if (CPU_ISSET(i, &mask))
                        VIR_USE_CPU(cpumap, i);
            }
        } else {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             "%s", _("cpu affinity is not available"));
            return -1;
        }
    }

    return maxinfo;
}
#endif /* HAVE_SCHED_GETAFFINITY */


2101 2102
static int qemudDomainGetMaxVcpus(virDomainPtr dom) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2103
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2104 2105 2106 2107
    const char *type;
    int ret;

    if (!vm) {
2108 2109 2110
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2111
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2112
                         _("no domain with matching uuid '%s'"), uuidstr);
2113 2114 2115
        return -1;
    }

2116
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unknown virt type in domain definition '%d'"),
                         vm->def->virtType);
        return -1;
    }

    if ((ret = qemudGetMaxVCPUs(dom->conn, type)) < 0) {
        return -1;
    }

    return ret;
}


2131
static int qemudDomainRestore(virConnectPtr conn,
2132 2133
                       const char *path) {
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
2134 2135
    virDomainDefPtr def;
    virDomainObjPtr vm;
2136
    int fd;
2137
    int ret;
2138 2139 2140 2141 2142 2143
    char *xml;
    struct qemud_save_header header;

    /* Verify the header and read the XML */
    if ((fd = open(path, O_RDONLY)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2144
                         "%s", _("cannot read domain image"));
2145 2146 2147 2148 2149
        return -1;
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2150
                         "%s", _("failed to read qemu header"));
2151 2152 2153 2154 2155 2156
        close(fd);
        return -1;
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2157
                         "%s", _("image magic is incorrect"));
2158 2159 2160 2161 2162 2163
        close(fd);
        return -1;
    }

    if (header.version > QEMUD_SAVE_VERSION) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2164
                         _("image version is not supported (%d > %d)"),
2165 2166 2167 2168 2169
                         header.version, QEMUD_SAVE_VERSION);
        close(fd);
        return -1;
    }

2170
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
2171
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2172
                         "%s", _("out of memory"));
2173 2174 2175 2176 2177 2178
        close(fd);
        return -1;
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2179
                         "%s", _("failed to read XML"));
2180
        close(fd);
2181
        VIR_FREE(xml);
2182 2183 2184 2185
        return -1;
    }

    /* Create a domain from this XML */
2186
    if (!(def = virDomainDefParseString(conn, driver->caps, xml))) {
2187
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2188
                         "%s", _("failed to parse XML"));
2189
        close(fd);
2190
        VIR_FREE(xml);
2191 2192
        return -1;
    }
2193
    VIR_FREE(xml);
2194 2195

    /* Ensure the name and UUID don't already exist in an active VM */
2196
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
2197
    if (!vm)
2198
        vm = virDomainFindByName(&driver->domains, def->name);
2199
    if (vm && virDomainIsActive(vm)) {
2200
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2201
                         _("domain is already active as '%s'"), vm->def->name);
2202 2203 2204 2205
        close(fd);
        return -1;
    }

2206 2207 2208
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
2209
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2210
                         "%s", _("failed to assign new VM"));
2211
        virDomainDefFree(def);
2212 2213 2214 2215 2216
        close(fd);
        return -1;
    }

    /* Set the migration source and start it up. */
2217
    vm->stdin_fd = fd;
2218
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio");
2219
    close(fd);
2220
    vm->stdin_fd = -1;
2221
    if (ret < 0) {
2222
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2223
                         "%s", _("failed to start VM"));
2224
        if (!vm->persistent)
2225 2226
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2227 2228 2229 2230 2231 2232
        return -1;
    }

    /* If it was running before, resume it now. */
    if (header.was_running) {
        char *info;
2233
        if (qemudMonitorCommand(driver, vm, "cont", &info) < 0) {
2234
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2235
                             "%s", _("failed to resume domain"));
2236 2237
            return -1;
        }
2238
        VIR_FREE(info);
2239 2240 2241
        vm->state = VIR_DOMAIN_RUNNING;
    }

2242
    qemudDomainEventDispatch(driver, vm, VIR_DOMAIN_EVENT_RESTORED);
2243
    return 0;
D
Daniel P. Berrange 已提交
2244 2245 2246
}


2247
static char *qemudDomainDumpXML(virDomainPtr dom,
2248
                                int flags ATTRIBUTE_UNUSED) {
2249
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2250
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
2251
    if (!vm) {
2252 2253
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2254
        return NULL;
D
Daniel P. Berrange 已提交
2255 2256
    }

2257 2258 2259 2260
    return virDomainDefFormat(dom->conn,
                              (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                              vm->newDef : vm->def,
                              flags);
D
Daniel P. Berrange 已提交
2261 2262 2263
}


2264
static int qemudListDefinedDomains(virConnectPtr conn,
2265 2266 2267
                            char **const names, int nnames) {
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    int got = 0, i;
2268 2269 2270 2271

    for (i = 0 ; i < driver->domains.count && got < nnames ; i++) {
        if (!virDomainIsActive(driver->domains.objs[i])) {
            if (!(names[got++] = strdup(driver->domains.objs[i]->def->name))) {
2272
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
2273
                                 "%s", _("failed to allocate space for VM name string"));
2274 2275
                goto cleanup;
            }
2276
        }
D
Daniel P. Berrange 已提交
2277
    }
2278

D
Daniel P. Berrange 已提交
2279
    return got;
2280 2281 2282

 cleanup:
    for (i = 0 ; i < got ; i++)
2283
        VIR_FREE(names[i]);
2284
    return -1;
D
Daniel P. Berrange 已提交
2285 2286
}

2287
static int qemudNumDefinedDomains(virConnectPtr conn) {
2288
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
2289 2290 2291 2292
    int n = 0, i;

    for (i = 0 ; i < driver->domains.count ; i++)
        if (!virDomainIsActive(driver->domains.objs[i]))
2293
            n++;
2294

2295
    return n;
D
Daniel P. Berrange 已提交
2296 2297 2298
}


2299
static int qemudDomainStart(virDomainPtr dom) {
2300
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2301
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2302 2303

    if (!vm) {
2304
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2305
                         "%s", _("no domain with matching uuid"));
2306
        return -1;
2307 2308
    }

2309
    return qemudStartVMDaemon(dom->conn, driver, vm, NULL);
D
Daniel P. Berrange 已提交
2310 2311 2312
}


2313
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
2314
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
2315 2316
    virDomainDefPtr def;
    virDomainObjPtr vm;
2317
    virDomainPtr dom;
2318

2319
    if (!(def = virDomainDefParseString(conn, driver->caps, xml)))
2320 2321
        return NULL;

2322 2323 2324 2325
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
        virDomainDefFree(def);
2326 2327
        return NULL;
    }
2328
    vm->persistent = 1;
2329

2330 2331
    if (virDomainSaveConfig(conn,
                            driver->configDir,
2332
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2333 2334
        virDomainRemoveInactive(&driver->domains,
                                vm);
2335 2336 2337
        return NULL;
    }

2338
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
2339
    if (dom) dom->id = vm->def->id;
2340
    return dom;
D
Daniel P. Berrange 已提交
2341 2342
}

2343
static int qemudDomainUndefine(virDomainPtr dom) {
2344
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2345
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
2346 2347

    if (!vm) {
2348 2349
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
D
Daniel P. Berrange 已提交
2350 2351 2352
        return -1;
    }

2353
    if (virDomainIsActive(vm)) {
2354 2355
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
D
Daniel P. Berrange 已提交
2356 2357 2358
        return -1;
    }

2359 2360 2361 2362 2363 2364 2365
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
        return -1;
    }

    if (virDomainDeleteConfig(dom->conn, driver->configDir, driver->autostartDir, vm) < 0)
D
Daniel P. Berrange 已提交
2366 2367
        return -1;

2368 2369
    virDomainRemoveInactive(&driver->domains,
                            vm);
D
Daniel P. Berrange 已提交
2370 2371 2372 2373

    return 0;
}

2374
/* Return the disks name for use in monitor commands */
2375 2376
static char *qemudDiskDeviceName(const virDomainPtr dom,
                                 const virDomainDiskDefPtr disk) {
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390

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

    if (virDiskNameToBusDeviceIndex(disk, &busid, &devid) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("cannot convert disk '%s' to bus/device index"),
                         disk->dst);
        return NULL;
    }

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
2391 2392 2393 2394
            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);
2395 2396
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
2397 2398 2399 2400
            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);
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
            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:
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             _("Unsupported disk name mapping for bus '%s'"),
                             virDomainDiskBusTypeToString(disk->bus));
            return NULL;
    }

    if (ret == -1) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return NULL;
    }

    return devname;
}

static int qemudDomainChangeEjectableMedia(virDomainPtr dom,
                                           virDomainDeviceDefPtr dev)
{
2426
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2427
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2428
    virDomainDiskDefPtr origdisk = NULL, newdisk;
2429
    char *cmd, *reply, *safe_path;
2430
    char *devname = NULL;
2431
    unsigned int qemuCmdFlags;
2432
    int i;
2433 2434 2435 2436 2437 2438 2439

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }

2440
    origdisk = NULL;
2441
    newdisk = dev->data.disk;
2442 2443 2444 2445
    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];
2446
            break;
2447
        }
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
    }

    if (!origdisk) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("No device with bus '%s' and target '%s'"),
                         virDomainDiskBusTypeToString(newdisk->bus),
                         newdisk->dst);
        return -1;
    }

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

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
        if (!(devname = qemudDiskDeviceName(dom, newdisk)))
            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 {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Emulator version does not support removable "
                               "media for device '%s' and target '%s'"),
                               virDomainDiskDeviceTypeToString(newdisk->device),
                               newdisk->dst);
            return -1;
        }

        if (!devname) {
            qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
            return -1;
        }
    }
2491

2492
    if (newdisk->src) {
2493 2494
        safe_path = qemudEscapeMonitorArg(newdisk->src);
        if (!safe_path) {
2495 2496
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
            VIR_FREE(devname);
2497 2498
            return -1;
        }
2499 2500
        if (asprintf (&cmd, "change %s \"%s\"", devname, safe_path) == -1) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
2501
            VIR_FREE(safe_path);
2502
            VIR_FREE(devname);
2503 2504
            return -1;
        }
2505
        VIR_FREE(safe_path);
2506

2507 2508 2509
    } else if (asprintf(&cmd, "eject %s", devname) == -1) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
        VIR_FREE(devname);
2510 2511
        return -1;
    }
2512
    VIR_FREE(devname);
2513 2514

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
2515 2516
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("cannot change cdrom media"));
2517
        VIR_FREE(cmd);
2518 2519
        return -1;
    }
2520 2521 2522 2523

    /* If the command failed qemu prints:
     * device not found, device is locked ...
     * No message is printed on success it seems */
2524
    DEBUG ("ejectable media change reply: %s", reply);
2525 2526 2527 2528 2529 2530 2531
    if (strstr(reply, "\ndevice ")) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("changing cdrom media failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
2532 2533
    VIR_FREE(reply);
    VIR_FREE(cmd);
2534

2535 2536
    VIR_FREE(origdisk->src);
    origdisk->src = newdisk->src;
2537
    newdisk->src = NULL;
2538
    origdisk->type = newdisk->type;
2539 2540 2541
    return 0;
}

2542
static int qemudDomainAttachPciDiskDevice(virDomainPtr dom, virDomainDeviceDefPtr dev)
2543 2544 2545 2546
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    int ret, i;
2547
    char *cmd, *reply, *s;
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
    char *safe_path;
    const char* type = virDomainDiskBusTypeToString(dev->data.disk->bus);

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }

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

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return -1;
    }

    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%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) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return ret;
    }

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         _("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... */
2595 2596 2597 2598 2599 2600 2601 2602
#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)
            qemudLog(QEMUD_WARN, _("Unable to parse slot number\n"));
    } else {
2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          _("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;
}
2618

2619 2620 2621
static int qemudDomainAttachUsbMassstorageDevice(virDomainPtr dom, virDomainDeviceDefPtr dev)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2622
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2623 2624
    int ret, i;
    char *safe_path;
2625 2626 2627 2628 2629 2630 2631 2632
    char *cmd, *reply;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }

2633 2634 2635 2636 2637 2638 2639 2640
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

2641 2642 2643
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return -1;
2644 2645
    }

2646 2647 2648 2649 2650 2651 2652 2653 2654
    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("out of memory"));
        return -1;
    }

    ret = asprintf(&cmd, "usb_add disk:%s", safe_path);
    VIR_FREE(safe_path);
2655 2656 2657 2658 2659 2660 2661
    if (ret == -1) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return ret;
    }

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2662
                         "%s", _("cannot attach usb disk"));
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
        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 ")) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s",
2673
                          _("adding usb disk failed"));
2674 2675 2676 2677
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
2678

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

2683 2684 2685 2686 2687
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}

2688 2689 2690
static int qemudDomainAttachHostDevice(virDomainPtr dom, virDomainDeviceDefPtr dev)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2691
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2692 2693 2694 2695 2696 2697 2698 2699
    int ret;
    char *cmd, *reply;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }
2700 2701 2702 2703
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return -1;
    }
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736

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

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%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 ")) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s",
                          _("adding usb device failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
2737

2738
    vm->def->hostdevs[vm->def->nhostdevs++] = dev->data.hostdev;
2739

2740 2741
    VIR_FREE(reply);
    VIR_FREE(cmd);
2742 2743 2744
    return 0;
}

2745 2746 2747
static int qemudDomainAttachDevice(virDomainPtr dom,
                                   const char *xml) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2748
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2749
    virDomainDeviceDefPtr dev;
2750
    int ret = 0, supported = 0;
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }

    if (!virDomainIsActive(vm)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot attach device on inactive domain"));
        return -1;
    }

2764 2765 2766
    dev = virDomainDeviceDefParse(dom->conn,
                                  driver->caps,
                                  vm->def, xml);
2767 2768 2769 2770
    if (dev == NULL) {
        return -1;
    }

2771 2772 2773 2774 2775
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        switch (dev->data.disk->device) {
            case VIR_DOMAIN_DISK_DEVICE_CDROM:
            case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
                supported = 1;
2776
                ret = qemudDomainChangeEjectableMedia(dom, dev);
2777 2778 2779 2780 2781 2782 2783 2784
                break;
            case VIR_DOMAIN_DISK_DEVICE_DISK:
                if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
                    supported = 1;
                    ret = qemudDomainAttachUsbMassstorageDevice(dom, dev);
                } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                           dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
                    supported = 1;
2785
                    ret = qemudDomainAttachPciDiskDevice(dom, dev);
2786 2787 2788
                }
                break;
        }
2789 2790 2791
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
        dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
        dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
2792
                supported = 1;
2793
                ret = qemudDomainAttachHostDevice(dom, dev);
2794 2795 2796
    }

    if (!supported) {
2797
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
2798
                         "%s", _("this device type cannot be attached"));
2799 2800 2801 2802 2803 2804 2805
        ret = -1;
    }

    VIR_FREE(dev);
    return ret;
}

2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
static int qemudDomainDetachPciDiskDevice(virDomainPtr dom, virDomainDeviceDefPtr dev)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    int i, ret = -1;
    char *cmd, *reply;
    virDomainDiskDefPtr detach = NULL;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }

    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) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         _("disk %s not found"), dev->data.disk->dst);
        return -1;
    }

    if (detach->slotnum < 1) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2835
                         _("disk %s cannot be detached - invalid slot number %d"),
2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857
                           detach->dst, detach->slotnum);
        return -1;
    }

    ret = asprintf(&cmd, "pci_del 0 %d", detach->slotnum);
    if (ret == -1) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return ret;
    }

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          _("failed to execute detach disk %s command"), detach->dst);
        VIR_FREE(cmd);
        return -1;
    }

    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")) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2858
                          _("failed to detach disk %s: invalid slot %d"),
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922
                            detach->dst, detach->slotnum);
        ret = -1;
        goto out;
    }

    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) {
            qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
            ret = -1;
            goto out;
        }
        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;
out:
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return ret;
}

static int qemudDomainDetachDevice(virDomainPtr dom,
                                   const char *xml) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
    virDomainDeviceDefPtr dev;
    int ret = 0;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }

    if (!virDomainIsActive(vm)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot attach device on inactive domain"));
        return -1;
    }

    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml);
    if (dev == NULL) {
        return -1;
    }

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

    VIR_FREE(dev);
    return ret;
}

2923
static int qemudDomainGetAutostart(virDomainPtr dom,
2924 2925
                            int *autostart) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2926
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2927 2928

    if (!vm) {
2929 2930
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2931 2932 2933 2934 2935 2936 2937 2938
        return -1;
    }

    *autostart = vm->autostart;

    return 0;
}

2939
static int qemudDomainSetAutostart(virDomainPtr dom,
2940
                                   int autostart) {
2941
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2942
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2943 2944
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
2945 2946

    if (!vm) {
2947 2948
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2949 2950 2951
        return -1;
    }

2952 2953 2954 2955 2956 2957
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
        return -1;
    }

2958 2959 2960 2961 2962
    autostart = (autostart != 0);

    if (vm->autostart == autostart)
        return 0;

2963 2964 2965 2966 2967
    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;

2968 2969 2970
    if (autostart) {
        int err;

2971
        if ((err = virFileMakePath(driver->autostartDir))) {
2972
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2973
                             _("cannot create autostart directory %s: %s"),
2974
                             driver->autostartDir, strerror(err));
2975
            goto cleanup;
2976 2977
        }

2978
        if (symlink(configFile, autostartLink) < 0) {
2979
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2980 2981 2982
                             _("Failed to create symlink '%s to '%s': %s"),
                             autostartLink, configFile, strerror(errno));
            goto cleanup;
2983 2984
        }
    } else {
2985
        if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2986
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2987
                             _("Failed to delete symlink '%s': %s"),
2988 2989
                             autostartLink, strerror(errno));
            goto cleanup;
2990 2991 2992
        }
    }

2993
    vm->autostart = autostart;
2994
    ret = 0;
2995

2996 2997 2998 2999 3000
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);

    return ret;
3001 3002
}

3003 3004 3005 3006 3007 3008 3009 3010 3011
/* 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)
{
3012
    struct qemud_driver *driver =
3013
        (struct qemud_driver *)dom->conn->privateData;
3014
    char *dummy, *info = NULL;
3015
    const char *p, *eol;
3016
    const char *qemu_dev_name = NULL;
3017
    size_t len;
3018
    int i, ret = -1;
3019
    const virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
3020
    virDomainDiskDefPtr disk = NULL;
3021 3022 3023 3024 3025 3026

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
        return -1;
    }
3027
    if (!virDomainIsActive (vm)) {
3028 3029 3030 3031 3032
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("domain is not running"));
        return -1;
    }

3033 3034 3035 3036 3037 3038 3039 3040
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
3041 3042 3043 3044 3045
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path: %s"), path);
        return -1;
    }

3046 3047 3048
    qemu_dev_name = qemudDiskDeviceName(dom, disk);
    if (!qemu_dev_name)
        return -1;
3049 3050 3051 3052 3053
    len = strlen (qemu_dev_name);

    if (qemudMonitorCommand (driver, vm, "info blockstats", &info) < 0) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("'info blockstats' command failed"));
3054
        goto out;
3055 3056 3057 3058 3059 3060 3061 3062
    }
    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.
     */
3063
    if (STRPREFIX (info, "info ")) {
3064 3065 3066
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'info blockstats' not supported by this qemu"));
3067
        goto out;
3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
    }

    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) {
3094
                if (STRPREFIX (p, "rd_bytes=")) {
3095 3096 3097
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_bytes) == -1)
                        DEBUG ("error reading rd_bytes: %s", p);
3098
                } else if (STRPREFIX (p, "wr_bytes=")) {
3099 3100 3101
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_bytes) == -1)
                        DEBUG ("error reading wr_bytes: %s", p);
3102
                } else if (STRPREFIX (p, "rd_operations=")) {
3103 3104 3105
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_req) == -1)
                        DEBUG ("error reading rd_req: %s", p);
3106
                } else if (STRPREFIX (p, "wr_operations=")) {
3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117
                    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++;
            }
3118 3119
            ret = 0;
            goto out;
3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130
        }

        /* 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);
3131 3132 3133 3134
 out:
    VIR_FREE(qemu_dev_name);
    VIR_FREE(info);
    return ret;
3135 3136
}

3137 3138 3139 3140 3141 3142 3143
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
#ifdef __linux__
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
3144
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
3145
    int i;
3146 3147 3148

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
3149
                          _("no domain with matching id %d"), dom->id);
3150 3151 3152
        return -1;
    }

3153
    if (!virDomainIsActive(vm)) {
3154
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3155
                         "%s", _("domain is not running"));
3156 3157 3158 3159 3160
        return -1;
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
3161
                         "%s", _("NULL or empty path"));
3162 3163 3164 3165
        return -1;
    }

    /* Check the path is one of the domain's network interfaces. */
3166 3167 3168
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
            STREQ (vm->def->nets[i]->ifname, path))
3169
            goto ok;
3170 3171 3172
    }

    qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
3173
                      _("invalid path, '%s' is not a known interface"), path);
3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184
    return -1;
 ok:

    return linuxDomainInterfaceStats (dom->conn, path, stats);
#else
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                      "%s", __FUNCTION__);
    return -1;
#endif
}

3185 3186 3187 3188 3189 3190 3191 3192
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
3193
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3194
    int fd, ret = -1, i;
3195 3196 3197

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
3198
                          "%s", _("no domain with matching uuid"));
3199 3200 3201 3202 3203
        return -1;
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
3204
                         "%s", _("NULL or empty path"));
3205 3206 3207 3208
        return -1;
    }

    /* Check the path belongs to this domain. */
3209 3210 3211 3212
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
            STREQ (vm->def->disks[i]->src, path))
            goto found;
3213 3214
    }
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
3215
                      "%s", _("invalid path"));
3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243
    return -1;

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

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

    ret = 0;
 done:
    if (fd >= 0) close (fd);
    return ret;
}

R
Richard W.M. Jones 已提交
3244 3245 3246 3247 3248 3249 3250
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
3251
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
R
Richard W.M. Jones 已提交
3252 3253 3254 3255 3256 3257
    char cmd[256], *info;
    char tmp[] = TEMPDIR "/qemu.mem.XXXXXX";
    int fd = -1, ret = -1;

    if (flags != VIR_MEMORY_VIRTUAL) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
3258
                          "%s", _("QEMU driver only supports virtual memory addrs"));
R
Richard W.M. Jones 已提交
3259 3260 3261 3262 3263 3264 3265 3266 3267
        return -1;
    }

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
        return -1;
    }

3268
    if (!virDomainIsActive(vm)) {
R
Richard W.M. Jones 已提交
3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
        return -1;
    }

    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
        return -1;
    }

    /* Issue the memsave command. */
    snprintf (cmd, sizeof cmd, "memsave %llu %zi \"%s\"", offset, size, tmp);
    if (qemudMonitorCommand (driver, vm, cmd, &info) < 0) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3285
                          "%s", _("'memsave' command failed"));
R
Richard W.M. Jones 已提交
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305
        goto done;
    }

    DEBUG ("memsave reply: %s", info);
    free (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));
        goto done;
    }

    ret = 0;
done:
    if (fd >= 0) close (fd);
    unlink (tmp);
    return ret;
}

3306

3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
static int
qemudDomainEventRegister (virConnectPtr conn,
                          void *callback,
                          void *opaque)
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;

    return virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                         callback, opaque);
}

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

    return virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                            callback);
}

static void qemudDomainEventDispatch (struct qemud_driver *driver,
                                      virDomainObjPtr vm,
                                      virDomainEventType evt)
{
    int i;
    virDomainEventCallbackListPtr cbList;

    cbList = driver->domainEventCallbacks;

    for(i=0 ; i < cbList->count ; i++) {
        if(cbList->callbacks[i] && cbList->callbacks[i]->cb) {
            virConnectPtr conn = cbList->callbacks[i]->conn;
            virDomainPtr dom = virGetDomain(conn, vm->def->name,
                                            vm->def->uuid);
            if (dom) {
                dom->id = virDomainIsActive(vm) ? vm->def->id : -1;
                DEBUG("Dispatching callback %p %p event %d",
                        cbList->callbacks[i],
                        cbList->callbacks[i]->cb, evt);
                cbList->callbacks[i]->cb(cbList->callbacks[i]->conn,
                                         dom, evt,
                                         cbList->callbacks[i]->opaque);
                virDomainFree(dom);
            }
        }
    }

}

3357 3358 3359 3360
static virDriver qemuDriver = {
    VIR_DRV_QEMU,
    "QEMU",
    LIBVIR_VERSION_NUMBER,
3361
    qemudProbe, /* probe */
3362 3363
    qemudOpen, /* open */
    qemudClose, /* close */
3364
    NULL, /* supports_feature */
3365 3366
    qemudGetType, /* type */
    qemudGetVersion, /* version */
3367
    qemudGetHostname, /* hostname */
3368
    NULL, /* URI  */
3369 3370 3371 3372 3373
    qemudGetMaxVCPUs, /* getMaxVcpus */
    qemudGetNodeInfo, /* nodeGetInfo */
    qemudGetCapabilities, /* getCapabilities */
    qemudListDomains, /* listDomains */
    qemudNumDomains, /* numOfDomains */
3374
    qemudDomainCreate, /* domainCreateXML */
3375 3376 3377 3378 3379
    qemudDomainLookupByID, /* domainLookupByID */
    qemudDomainLookupByUUID, /* domainLookupByUUID */
    qemudDomainLookupByName, /* domainLookupByName */
    qemudDomainSuspend, /* domainSuspend */
    qemudDomainResume, /* domainResume */
3380
    qemudDomainShutdown, /* domainShutdown */
3381 3382 3383
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */
    qemudDomainGetOSType, /* domainGetOSType */
3384 3385 3386
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
    qemudDomainSetMaxMemory, /* domainSetMaxMemory */
    qemudDomainSetMemory, /* domainSetMemory */
3387 3388 3389 3390
    qemudDomainGetInfo, /* domainGetInfo */
    qemudDomainSave, /* domainSave */
    qemudDomainRestore, /* domainRestore */
    NULL, /* domainCoreDump */
3391
    qemudDomainSetVcpus, /* domainSetVcpus */
3392 3393 3394 3395
#if HAVE_SCHED_GETAFFINITY
    qemudDomainPinVcpu, /* domainPinVcpu */
    qemudDomainGetVcpus, /* domainGetVcpus */
#else
3396 3397
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
3398
#endif
3399
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
3400 3401 3402 3403 3404 3405
    qemudDomainDumpXML, /* domainDumpXML */
    qemudListDefinedDomains, /* listDomains */
    qemudNumDefinedDomains, /* numOfDomains */
    qemudDomainStart, /* domainCreate */
    qemudDomainDefine, /* domainDefineXML */
    qemudDomainUndefine, /* domainUndefine */
3406
    qemudDomainAttachDevice, /* domainAttachDevice */
3407
    qemudDomainDetachDevice, /* domainDetachDevice */
3408 3409 3410 3411 3412
    qemudDomainGetAutostart, /* domainGetAutostart */
    qemudDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
3413 3414 3415
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
3416
    qemudDomainBlockStats, /* domainBlockStats */
3417
    qemudDomainInterfaceStats, /* domainInterfaceStats */
3418
    qemudDomainBlockPeek, /* domainBlockPeek */
R
Richard W.M. Jones 已提交
3419
    qemudDomainMemoryPeek, /* domainMemoryPeek */
3420 3421 3422 3423
#if HAVE_NUMACTL
    qemudNodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    qemudNodeGetFreeMemory,  /* getFreeMemory */
#else
3424
    NULL, /* nodeGetCellsFreeMemory */
3425
    NULL, /* getFreeMemory */
3426
#endif
3427 3428
    qemudDomainEventRegister, /* domainEventRegister */
    qemudDomainEventDeregister, /* domainEventDeregister */
3429 3430 3431
};


3432
static virStateDriver qemuStateDriver = {
3433 3434 3435 3436
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
3437
};
3438

3439 3440 3441 3442 3443 3444
int qemudRegister(void) {
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}