Statistics
| Branch: | Revision:

root / savevm.c @ cb88aa88

History | View | Annotate | Download (62.6 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2008 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24

    
25
#include "config-host.h"
26
#include "qemu-common.h"
27
#include "hw/hw.h"
28
#include "hw/qdev.h"
29
#include "net/net.h"
30
#include "monitor/monitor.h"
31
#include "sysemu/sysemu.h"
32
#include "qemu/timer.h"
33
#include "audio/audio.h"
34
#include "migration/migration.h"
35
#include "qemu/sockets.h"
36
#include "qemu/queue.h"
37
#include "sysemu/cpus.h"
38
#include "exec/memory.h"
39
#include "qmp-commands.h"
40
#include "trace.h"
41
#include "qemu/bitops.h"
42
#include "qemu/iov.h"
43

    
44
#define SELF_ANNOUNCE_ROUNDS 5
45

    
46
#ifndef ETH_P_RARP
47
#define ETH_P_RARP 0x8035
48
#endif
49
#define ARP_HTYPE_ETH 0x0001
50
#define ARP_PTYPE_IP 0x0800
51
#define ARP_OP_REQUEST_REV 0x3
52

    
53
static int announce_self_create(uint8_t *buf,
54
                                uint8_t *mac_addr)
55
{
56
    /* Ethernet header. */
57
    memset(buf, 0xff, 6);         /* destination MAC addr */
58
    memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
59
    *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
60

    
61
    /* RARP header. */
62
    *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
63
    *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
64
    *(buf + 18) = 6; /* hardware addr length (ethernet) */
65
    *(buf + 19) = 4; /* protocol addr length (IPv4) */
66
    *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
67
    memcpy(buf + 22, mac_addr, 6); /* source hw addr */
68
    memset(buf + 28, 0x00, 4);     /* source protocol addr */
69
    memcpy(buf + 32, mac_addr, 6); /* target hw addr */
70
    memset(buf + 38, 0x00, 4);     /* target protocol addr */
71

    
72
    /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
73
    memset(buf + 42, 0x00, 18);
74

    
75
    return 60; /* len (FCS will be added by hardware) */
76
}
77

    
78
static void qemu_announce_self_iter(NICState *nic, void *opaque)
79
{
80
    uint8_t buf[60];
81
    int len;
82

    
83
    len = announce_self_create(buf, nic->conf->macaddr.a);
84

    
85
    qemu_send_packet_raw(qemu_get_queue(nic), buf, len);
86
}
87

    
88

    
89
static void qemu_announce_self_once(void *opaque)
90
{
91
    static int count = SELF_ANNOUNCE_ROUNDS;
92
    QEMUTimer *timer = *(QEMUTimer **)opaque;
93

    
94
    qemu_foreach_nic(qemu_announce_self_iter, NULL);
95

    
96
    if (--count) {
97
        /* delay 50ms, 150ms, 250ms, ... */
98
        qemu_mod_timer(timer, qemu_get_clock_ms(rt_clock) +
99
                       50 + (SELF_ANNOUNCE_ROUNDS - count - 1) * 100);
100
    } else {
101
            qemu_del_timer(timer);
102
            qemu_free_timer(timer);
103
    }
104
}
105

    
106
void qemu_announce_self(void)
107
{
108
        static QEMUTimer *timer;
109
        timer = qemu_new_timer_ms(rt_clock, qemu_announce_self_once, &timer);
110
        qemu_announce_self_once(&timer);
111
}
112

    
113
/***********************************************************/
114
/* savevm/loadvm support */
115

    
116
#define IO_BUF_SIZE 32768
117
#define MAX_IOV_SIZE MIN(IOV_MAX, 64)
118

    
119
struct QEMUFile {
120
    const QEMUFileOps *ops;
121
    void *opaque;
122
    int is_write;
123

    
124
    int64_t bytes_xfer;
125
    int64_t xfer_limit;
126

    
127
    int64_t pos; /* start of buffer when writing, end of buffer
128
                    when reading */
129
    int buf_index;
130
    int buf_size; /* 0 when writing */
131
    uint8_t buf[IO_BUF_SIZE];
132

    
133
    struct iovec iov[MAX_IOV_SIZE];
134
    unsigned int iovcnt;
135

    
136
    int last_error;
137
};
138

    
139
typedef struct QEMUFileStdio
140
{
141
    FILE *stdio_file;
142
    QEMUFile *file;
143
} QEMUFileStdio;
144

    
145
typedef struct QEMUFileSocket
146
{
147
    int fd;
148
    QEMUFile *file;
149
} QEMUFileSocket;
150

    
151
typedef struct {
152
    Coroutine *co;
153
    int fd;
154
} FDYieldUntilData;
155

    
156
static void fd_coroutine_enter(void *opaque)
157
{
158
    FDYieldUntilData *data = opaque;
159
    qemu_set_fd_handler(data->fd, NULL, NULL, NULL);
160
    qemu_coroutine_enter(data->co, NULL);
161
}
162

    
163
/**
164
 * Yield until a file descriptor becomes readable
165
 *
166
 * Note that this function clobbers the handlers for the file descriptor.
167
 */
168
static void coroutine_fn yield_until_fd_readable(int fd)
169
{
170
    FDYieldUntilData data;
171

    
172
    assert(qemu_in_coroutine());
173
    data.co = qemu_coroutine_self();
174
    data.fd = fd;
175
    qemu_set_fd_handler(fd, fd_coroutine_enter, NULL, &data);
176
    qemu_coroutine_yield();
177
}
178

    
179
static ssize_t socket_writev_buffer(void *opaque, struct iovec *iov, int iovcnt)
180
{
181
    QEMUFileSocket *s = opaque;
182
    ssize_t len;
183
    ssize_t size = iov_size(iov, iovcnt);
184

    
185
    len = iov_send(s->fd, iov, iovcnt, 0, size);
186
    if (len < size) {
187
        len = -socket_error();
188
    }
189
    return len;
190
}
191

    
192
static int socket_get_fd(void *opaque)
193
{
194
    QEMUFileSocket *s = opaque;
195

    
196
    return s->fd;
197
}
198

    
199
static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
200
{
201
    QEMUFileSocket *s = opaque;
202
    ssize_t len;
203

    
204
    for (;;) {
205
        len = qemu_recv(s->fd, buf, size, 0);
206
        if (len != -1) {
207
            break;
208
        }
209
        if (socket_error() == EAGAIN) {
210
            yield_until_fd_readable(s->fd);
211
        } else if (socket_error() != EINTR) {
212
            break;
213
        }
214
    }
215

    
216
    if (len == -1) {
217
        len = -socket_error();
218
    }
219
    return len;
220
}
221

    
222
static int socket_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
223
{
224
    QEMUFileSocket *s = opaque;
225
    ssize_t len;
226

    
227
    len = qemu_send_full(s->fd, buf, size, 0);
228
    if (len < size) {
229
        len = -socket_error();
230
    }
231
    return len;
232
}
233

    
234
static int socket_close(void *opaque)
235
{
236
    QEMUFileSocket *s = opaque;
237
    closesocket(s->fd);
238
    g_free(s);
239
    return 0;
240
}
241

    
242
static int stdio_get_fd(void *opaque)
243
{
244
    QEMUFileStdio *s = opaque;
245

    
246
    return fileno(s->stdio_file);
247
}
248

    
249
static int stdio_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
250
{
251
    QEMUFileStdio *s = opaque;
252
    return fwrite(buf, 1, size, s->stdio_file);
253
}
254

    
255
static int stdio_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
256
{
257
    QEMUFileStdio *s = opaque;
258
    FILE *fp = s->stdio_file;
259
    int bytes;
260

    
261
    for (;;) {
262
        clearerr(fp);
263
        bytes = fread(buf, 1, size, fp);
264
        if (bytes != 0 || !ferror(fp)) {
265
            break;
266
        }
267
        if (errno == EAGAIN) {
268
            yield_until_fd_readable(fileno(fp));
269
        } else if (errno != EINTR) {
270
            break;
271
        }
272
    }
273
    return bytes;
274
}
275

    
276
static int stdio_pclose(void *opaque)
277
{
278
    QEMUFileStdio *s = opaque;
279
    int ret;
280
    ret = pclose(s->stdio_file);
281
    if (ret == -1) {
282
        ret = -errno;
283
    } else if (!WIFEXITED(ret) || WEXITSTATUS(ret) != 0) {
284
        /* close succeeded, but non-zero exit code: */
285
        ret = -EIO; /* fake errno value */
286
    }
287
    g_free(s);
288
    return ret;
289
}
290

    
291
static int stdio_fclose(void *opaque)
292
{
293
    QEMUFileStdio *s = opaque;
294
    int ret = 0;
295

    
296
    if (s->file->ops->put_buffer || s->file->ops->writev_buffer) {
297
        int fd = fileno(s->stdio_file);
298
        struct stat st;
299

    
300
        ret = fstat(fd, &st);
301
        if (ret == 0 && S_ISREG(st.st_mode)) {
302
            /*
303
             * If the file handle is a regular file make sure the
304
             * data is flushed to disk before signaling success.
305
             */
306
            ret = fsync(fd);
307
            if (ret != 0) {
308
                ret = -errno;
309
                return ret;
310
            }
311
        }
312
    }
313
    if (fclose(s->stdio_file) == EOF) {
314
        ret = -errno;
315
    }
316
    g_free(s);
317
    return ret;
318
}
319

    
320
static const QEMUFileOps stdio_pipe_read_ops = {
321
    .get_fd =     stdio_get_fd,
322
    .get_buffer = stdio_get_buffer,
323
    .close =      stdio_pclose
324
};
325

    
326
static const QEMUFileOps stdio_pipe_write_ops = {
327
    .get_fd =     stdio_get_fd,
328
    .put_buffer = stdio_put_buffer,
329
    .close =      stdio_pclose
330
};
331

    
332
QEMUFile *qemu_popen_cmd(const char *command, const char *mode)
333
{
334
    FILE *stdio_file;
335
    QEMUFileStdio *s;
336

    
337
    stdio_file = popen(command, mode);
338
    if (stdio_file == NULL) {
339
        return NULL;
340
    }
341

    
342
    if (mode == NULL || (mode[0] != 'r' && mode[0] != 'w') || mode[1] != 0) {
343
        fprintf(stderr, "qemu_popen: Argument validity check failed\n");
344
        return NULL;
345
    }
346

    
347
    s = g_malloc0(sizeof(QEMUFileStdio));
348

    
349
    s->stdio_file = stdio_file;
350

    
351
    if(mode[0] == 'r') {
352
        s->file = qemu_fopen_ops(s, &stdio_pipe_read_ops);
353
    } else {
354
        s->file = qemu_fopen_ops(s, &stdio_pipe_write_ops);
355
    }
356
    return s->file;
357
}
358

    
359
static const QEMUFileOps stdio_file_read_ops = {
360
    .get_fd =     stdio_get_fd,
361
    .get_buffer = stdio_get_buffer,
362
    .close =      stdio_fclose
363
};
364

    
365
static const QEMUFileOps stdio_file_write_ops = {
366
    .get_fd =     stdio_get_fd,
367
    .put_buffer = stdio_put_buffer,
368
    .close =      stdio_fclose
369
};
370

    
371
QEMUFile *qemu_fdopen(int fd, const char *mode)
372
{
373
    QEMUFileStdio *s;
374

    
375
    if (mode == NULL ||
376
        (mode[0] != 'r' && mode[0] != 'w') ||
377
        mode[1] != 'b' || mode[2] != 0) {
378
        fprintf(stderr, "qemu_fdopen: Argument validity check failed\n");
379
        return NULL;
380
    }
381

    
382
    s = g_malloc0(sizeof(QEMUFileStdio));
383
    s->stdio_file = fdopen(fd, mode);
384
    if (!s->stdio_file)
385
        goto fail;
386

    
387
    if(mode[0] == 'r') {
388
        s->file = qemu_fopen_ops(s, &stdio_file_read_ops);
389
    } else {
390
        s->file = qemu_fopen_ops(s, &stdio_file_write_ops);
391
    }
392
    return s->file;
393

    
394
fail:
395
    g_free(s);
396
    return NULL;
397
}
398

    
399
static const QEMUFileOps socket_read_ops = {
400
    .get_fd =     socket_get_fd,
401
    .get_buffer = socket_get_buffer,
402
    .close =      socket_close
403
};
404

    
405
static const QEMUFileOps socket_write_ops = {
406
    .get_fd =     socket_get_fd,
407
    .put_buffer = socket_put_buffer,
408
    .writev_buffer = socket_writev_buffer,
409
    .close =      socket_close
410
};
411

    
412
QEMUFile *qemu_fopen_socket(int fd, const char *mode)
413
{
414
    QEMUFileSocket *s = g_malloc0(sizeof(QEMUFileSocket));
415

    
416
    if (mode == NULL ||
417
        (mode[0] != 'r' && mode[0] != 'w') ||
418
        mode[1] != 'b' || mode[2] != 0) {
419
        fprintf(stderr, "qemu_fopen: Argument validity check failed\n");
420
        return NULL;
421
    }
422

    
423
    s->fd = fd;
424
    if (mode[0] == 'w') {
425
        socket_set_block(s->fd);
426
        s->file = qemu_fopen_ops(s, &socket_write_ops);
427
    } else {
428
        s->file = qemu_fopen_ops(s, &socket_read_ops);
429
    }
430
    return s->file;
431
}
432

    
433
QEMUFile *qemu_fopen(const char *filename, const char *mode)
434
{
435
    QEMUFileStdio *s;
436

    
437
    if (mode == NULL ||
438
        (mode[0] != 'r' && mode[0] != 'w') ||
439
        mode[1] != 'b' || mode[2] != 0) {
440
        fprintf(stderr, "qemu_fopen: Argument validity check failed\n");
441
        return NULL;
442
    }
443

    
444
    s = g_malloc0(sizeof(QEMUFileStdio));
445

    
446
    s->stdio_file = fopen(filename, mode);
447
    if (!s->stdio_file)
448
        goto fail;
449
    
450
    if(mode[0] == 'w') {
451
        s->file = qemu_fopen_ops(s, &stdio_file_write_ops);
452
    } else {
453
        s->file = qemu_fopen_ops(s, &stdio_file_read_ops);
454
    }
455
    return s->file;
456
fail:
457
    g_free(s);
458
    return NULL;
459
}
460

    
461
static int block_put_buffer(void *opaque, const uint8_t *buf,
462
                           int64_t pos, int size)
463
{
464
    bdrv_save_vmstate(opaque, buf, pos, size);
465
    return size;
466
}
467

    
468
static int block_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
469
{
470
    return bdrv_load_vmstate(opaque, buf, pos, size);
471
}
472

    
473
static int bdrv_fclose(void *opaque)
474
{
475
    return bdrv_flush(opaque);
476
}
477

    
478
static const QEMUFileOps bdrv_read_ops = {
479
    .get_buffer = block_get_buffer,
480
    .close =      bdrv_fclose
481
};
482

    
483
static const QEMUFileOps bdrv_write_ops = {
484
    .put_buffer = block_put_buffer,
485
    .close =      bdrv_fclose
486
};
487

    
488
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
489
{
490
    if (is_writable)
491
        return qemu_fopen_ops(bs, &bdrv_write_ops);
492
    return qemu_fopen_ops(bs, &bdrv_read_ops);
493
}
494

    
495
QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)
496
{
497
    QEMUFile *f;
498

    
499
    f = g_malloc0(sizeof(QEMUFile));
500

    
501
    f->opaque = opaque;
502
    f->ops = ops;
503
    f->is_write = 0;
504
    return f;
505
}
506

    
507
int qemu_file_get_error(QEMUFile *f)
508
{
509
    return f->last_error;
510
}
511

    
512
static void qemu_file_set_error(QEMUFile *f, int ret)
513
{
514
    if (f->last_error == 0) {
515
        f->last_error = ret;
516
    }
517
}
518

    
519
/**
520
 * Flushes QEMUFile buffer
521
 *
522
 * If there is writev_buffer QEMUFileOps it uses it otherwise uses
523
 * put_buffer ops.
524
 */
525
static void qemu_fflush(QEMUFile *f)
526
{
527
    ssize_t ret = 0;
528
    int i = 0;
529

    
530
    if (!f->ops->writev_buffer && !f->ops->put_buffer) {
531
        return;
532
    }
533

    
534
    if (f->is_write && f->iovcnt > 0) {
535
        if (f->ops->writev_buffer) {
536
            ret = f->ops->writev_buffer(f->opaque, f->iov, f->iovcnt);
537
            if (ret >= 0) {
538
                f->pos += ret;
539
            }
540
        } else {
541
            for (i = 0; i < f->iovcnt && ret >= 0; i++) {
542
                ret = f->ops->put_buffer(f->opaque, f->iov[i].iov_base, f->pos,
543
                                         f->iov[i].iov_len);
544
                if (ret >= 0) {
545
                    f->pos += ret;
546
                }
547
            }
548
        }
549
        f->buf_index = 0;
550
        f->iovcnt = 0;
551
    }
552
    if (ret < 0) {
553
        qemu_file_set_error(f, ret);
554
    }
555
}
556

    
557
static void qemu_fill_buffer(QEMUFile *f)
558
{
559
    int len;
560
    int pending;
561

    
562
    if (!f->ops->get_buffer)
563
        return;
564

    
565
    if (f->is_write)
566
        abort();
567

    
568
    pending = f->buf_size - f->buf_index;
569
    if (pending > 0) {
570
        memmove(f->buf, f->buf + f->buf_index, pending);
571
    }
572
    f->buf_index = 0;
573
    f->buf_size = pending;
574

    
575
    len = f->ops->get_buffer(f->opaque, f->buf + pending, f->pos,
576
                        IO_BUF_SIZE - pending);
577
    if (len > 0) {
578
        f->buf_size += len;
579
        f->pos += len;
580
    } else if (len == 0) {
581
        qemu_file_set_error(f, -EIO);
582
    } else if (len != -EAGAIN)
583
        qemu_file_set_error(f, len);
584
}
585

    
586
int qemu_get_fd(QEMUFile *f)
587
{
588
    if (f->ops->get_fd) {
589
        return f->ops->get_fd(f->opaque);
590
    }
591
    return -1;
592
}
593

    
594
/** Closes the file
595
 *
596
 * Returns negative error value if any error happened on previous operations or
597
 * while closing the file. Returns 0 or positive number on success.
598
 *
599
 * The meaning of return value on success depends on the specific backend
600
 * being used.
601
 */
602
int qemu_fclose(QEMUFile *f)
603
{
604
    int ret;
605
    qemu_fflush(f);
606
    ret = qemu_file_get_error(f);
607

    
608
    if (f->ops->close) {
609
        int ret2 = f->ops->close(f->opaque);
610
        if (ret >= 0) {
611
            ret = ret2;
612
        }
613
    }
614
    /* If any error was spotted before closing, we should report it
615
     * instead of the close() return value.
616
     */
617
    if (f->last_error) {
618
        ret = f->last_error;
619
    }
620
    g_free(f);
621
    return ret;
622
}
623

    
624
static void add_to_iovec(QEMUFile *f, const uint8_t *buf, int size)
625
{
626
    /* check for adjacent buffer and coalesce them */
627
    if (f->iovcnt > 0 && buf == f->iov[f->iovcnt - 1].iov_base +
628
        f->iov[f->iovcnt - 1].iov_len) {
629
        f->iov[f->iovcnt - 1].iov_len += size;
630
    } else {
631
        f->iov[f->iovcnt].iov_base = (uint8_t *)buf;
632
        f->iov[f->iovcnt++].iov_len = size;
633
    }
634
}
635

    
636
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
637
{
638
    int l;
639

    
640
    if (f->last_error) {
641
        return;
642
    }
643

    
644
    if (f->is_write == 0 && f->buf_index > 0) {
645
        fprintf(stderr,
646
                "Attempted to write to buffer while read buffer is not empty\n");
647
        abort();
648
    }
649

    
650
    while (size > 0) {
651
        l = IO_BUF_SIZE - f->buf_index;
652
        if (l > size)
653
            l = size;
654
        memcpy(f->buf + f->buf_index, buf, l);
655
        add_to_iovec(f, f->buf + f->buf_index, l);
656
        f->is_write = 1;
657
        f->buf_index += l;
658
        f->bytes_xfer += l;
659
        buf += l;
660
        size -= l;
661
        if (f->buf_index >= IO_BUF_SIZE || f->iovcnt >= MAX_IOV_SIZE) {
662
            qemu_fflush(f);
663
            if (qemu_file_get_error(f)) {
664
                break;
665
            }
666
        }
667
    }
668
}
669

    
670
void qemu_put_byte(QEMUFile *f, int v)
671
{
672
    if (f->last_error) {
673
        return;
674
    }
675

    
676
    if (f->is_write == 0 && f->buf_index > 0) {
677
        fprintf(stderr,
678
                "Attempted to write to buffer while read buffer is not empty\n");
679
        abort();
680
    }
681

    
682
    f->buf[f->buf_index++] = v;
683
    f->is_write = 1;
684
    f->bytes_xfer++;
685

    
686
    add_to_iovec(f, f->buf + (f->buf_index - 1), 1);
687

    
688
    if (f->buf_index >= IO_BUF_SIZE || f->iovcnt >= MAX_IOV_SIZE) {
689
        qemu_fflush(f);
690
    }
691
}
692

    
693
static void qemu_file_skip(QEMUFile *f, int size)
694
{
695
    if (f->buf_index + size <= f->buf_size) {
696
        f->buf_index += size;
697
    }
698
}
699

    
700
static int qemu_peek_buffer(QEMUFile *f, uint8_t *buf, int size, size_t offset)
701
{
702
    int pending;
703
    int index;
704

    
705
    if (f->is_write) {
706
        abort();
707
    }
708

    
709
    index = f->buf_index + offset;
710
    pending = f->buf_size - index;
711
    if (pending < size) {
712
        qemu_fill_buffer(f);
713
        index = f->buf_index + offset;
714
        pending = f->buf_size - index;
715
    }
716

    
717
    if (pending <= 0) {
718
        return 0;
719
    }
720
    if (size > pending) {
721
        size = pending;
722
    }
723

    
724
    memcpy(buf, f->buf + index, size);
725
    return size;
726
}
727

    
728
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
729
{
730
    int pending = size;
731
    int done = 0;
732

    
733
    while (pending > 0) {
734
        int res;
735

    
736
        res = qemu_peek_buffer(f, buf, pending, 0);
737
        if (res == 0) {
738
            return done;
739
        }
740
        qemu_file_skip(f, res);
741
        buf += res;
742
        pending -= res;
743
        done += res;
744
    }
745
    return done;
746
}
747

    
748
static int qemu_peek_byte(QEMUFile *f, int offset)
749
{
750
    int index = f->buf_index + offset;
751

    
752
    if (f->is_write) {
753
        abort();
754
    }
755

    
756
    if (index >= f->buf_size) {
757
        qemu_fill_buffer(f);
758
        index = f->buf_index + offset;
759
        if (index >= f->buf_size) {
760
            return 0;
761
        }
762
    }
763
    return f->buf[index];
764
}
765

    
766
int qemu_get_byte(QEMUFile *f)
767
{
768
    int result;
769

    
770
    result = qemu_peek_byte(f, 0);
771
    qemu_file_skip(f, 1);
772
    return result;
773
}
774

    
775
int64_t qemu_ftell(QEMUFile *f)
776
{
777
    qemu_fflush(f);
778
    return f->pos;
779
}
780

    
781
int qemu_file_rate_limit(QEMUFile *f)
782
{
783
    if (qemu_file_get_error(f)) {
784
        return 1;
785
    }
786
    if (f->xfer_limit > 0 && f->bytes_xfer > f->xfer_limit) {
787
        return 1;
788
    }
789
    return 0;
790
}
791

    
792
int64_t qemu_file_get_rate_limit(QEMUFile *f)
793
{
794
    return f->xfer_limit;
795
}
796

    
797
void qemu_file_set_rate_limit(QEMUFile *f, int64_t limit)
798
{
799
    f->xfer_limit = limit;
800
}
801

    
802
void qemu_file_reset_rate_limit(QEMUFile *f)
803
{
804
    f->bytes_xfer = 0;
805
}
806

    
807
void qemu_put_be16(QEMUFile *f, unsigned int v)
808
{
809
    qemu_put_byte(f, v >> 8);
810
    qemu_put_byte(f, v);
811
}
812

    
813
void qemu_put_be32(QEMUFile *f, unsigned int v)
814
{
815
    qemu_put_byte(f, v >> 24);
816
    qemu_put_byte(f, v >> 16);
817
    qemu_put_byte(f, v >> 8);
818
    qemu_put_byte(f, v);
819
}
820

    
821
void qemu_put_be64(QEMUFile *f, uint64_t v)
822
{
823
    qemu_put_be32(f, v >> 32);
824
    qemu_put_be32(f, v);
825
}
826

    
827
unsigned int qemu_get_be16(QEMUFile *f)
828
{
829
    unsigned int v;
830
    v = qemu_get_byte(f) << 8;
831
    v |= qemu_get_byte(f);
832
    return v;
833
}
834

    
835
unsigned int qemu_get_be32(QEMUFile *f)
836
{
837
    unsigned int v;
838
    v = qemu_get_byte(f) << 24;
839
    v |= qemu_get_byte(f) << 16;
840
    v |= qemu_get_byte(f) << 8;
841
    v |= qemu_get_byte(f);
842
    return v;
843
}
844

    
845
uint64_t qemu_get_be64(QEMUFile *f)
846
{
847
    uint64_t v;
848
    v = (uint64_t)qemu_get_be32(f) << 32;
849
    v |= qemu_get_be32(f);
850
    return v;
851
}
852

    
853

    
854
/* timer */
855

    
856
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
857
{
858
    uint64_t expire_time;
859

    
860
    expire_time = qemu_timer_expire_time_ns(ts);
861
    qemu_put_be64(f, expire_time);
862
}
863

    
864
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
865
{
866
    uint64_t expire_time;
867

    
868
    expire_time = qemu_get_be64(f);
869
    if (expire_time != -1) {
870
        qemu_mod_timer_ns(ts, expire_time);
871
    } else {
872
        qemu_del_timer(ts);
873
    }
874
}
875

    
876

    
877
/* bool */
878

    
879
static int get_bool(QEMUFile *f, void *pv, size_t size)
880
{
881
    bool *v = pv;
882
    *v = qemu_get_byte(f);
883
    return 0;
884
}
885

    
886
static void put_bool(QEMUFile *f, void *pv, size_t size)
887
{
888
    bool *v = pv;
889
    qemu_put_byte(f, *v);
890
}
891

    
892
const VMStateInfo vmstate_info_bool = {
893
    .name = "bool",
894
    .get  = get_bool,
895
    .put  = put_bool,
896
};
897

    
898
/* 8 bit int */
899

    
900
static int get_int8(QEMUFile *f, void *pv, size_t size)
901
{
902
    int8_t *v = pv;
903
    qemu_get_s8s(f, v);
904
    return 0;
905
}
906

    
907
static void put_int8(QEMUFile *f, void *pv, size_t size)
908
{
909
    int8_t *v = pv;
910
    qemu_put_s8s(f, v);
911
}
912

    
913
const VMStateInfo vmstate_info_int8 = {
914
    .name = "int8",
915
    .get  = get_int8,
916
    .put  = put_int8,
917
};
918

    
919
/* 16 bit int */
920

    
921
static int get_int16(QEMUFile *f, void *pv, size_t size)
922
{
923
    int16_t *v = pv;
924
    qemu_get_sbe16s(f, v);
925
    return 0;
926
}
927

    
928
static void put_int16(QEMUFile *f, void *pv, size_t size)
929
{
930
    int16_t *v = pv;
931
    qemu_put_sbe16s(f, v);
932
}
933

    
934
const VMStateInfo vmstate_info_int16 = {
935
    .name = "int16",
936
    .get  = get_int16,
937
    .put  = put_int16,
938
};
939

    
940
/* 32 bit int */
941

    
942
static int get_int32(QEMUFile *f, void *pv, size_t size)
943
{
944
    int32_t *v = pv;
945
    qemu_get_sbe32s(f, v);
946
    return 0;
947
}
948

    
949
static void put_int32(QEMUFile *f, void *pv, size_t size)
950
{
951
    int32_t *v = pv;
952
    qemu_put_sbe32s(f, v);
953
}
954

    
955
const VMStateInfo vmstate_info_int32 = {
956
    .name = "int32",
957
    .get  = get_int32,
958
    .put  = put_int32,
959
};
960

    
961
/* 32 bit int. See that the received value is the same than the one
962
   in the field */
963

    
964
static int get_int32_equal(QEMUFile *f, void *pv, size_t size)
965
{
966
    int32_t *v = pv;
967
    int32_t v2;
968
    qemu_get_sbe32s(f, &v2);
969

    
970
    if (*v == v2)
971
        return 0;
972
    return -EINVAL;
973
}
974

    
975
const VMStateInfo vmstate_info_int32_equal = {
976
    .name = "int32 equal",
977
    .get  = get_int32_equal,
978
    .put  = put_int32,
979
};
980

    
981
/* 32 bit int. See that the received value is the less or the same
982
   than the one in the field */
983

    
984
static int get_int32_le(QEMUFile *f, void *pv, size_t size)
985
{
986
    int32_t *old = pv;
987
    int32_t new;
988
    qemu_get_sbe32s(f, &new);
989

    
990
    if (*old <= new)
991
        return 0;
992
    return -EINVAL;
993
}
994

    
995
const VMStateInfo vmstate_info_int32_le = {
996
    .name = "int32 equal",
997
    .get  = get_int32_le,
998
    .put  = put_int32,
999
};
1000

    
1001
/* 64 bit int */
1002

    
1003
static int get_int64(QEMUFile *f, void *pv, size_t size)
1004
{
1005
    int64_t *v = pv;
1006
    qemu_get_sbe64s(f, v);
1007
    return 0;
1008
}
1009

    
1010
static void put_int64(QEMUFile *f, void *pv, size_t size)
1011
{
1012
    int64_t *v = pv;
1013
    qemu_put_sbe64s(f, v);
1014
}
1015

    
1016
const VMStateInfo vmstate_info_int64 = {
1017
    .name = "int64",
1018
    .get  = get_int64,
1019
    .put  = put_int64,
1020
};
1021

    
1022
/* 8 bit unsigned int */
1023

    
1024
static int get_uint8(QEMUFile *f, void *pv, size_t size)
1025
{
1026
    uint8_t *v = pv;
1027
    qemu_get_8s(f, v);
1028
    return 0;
1029
}
1030

    
1031
static void put_uint8(QEMUFile *f, void *pv, size_t size)
1032
{
1033
    uint8_t *v = pv;
1034
    qemu_put_8s(f, v);
1035
}
1036

    
1037
const VMStateInfo vmstate_info_uint8 = {
1038
    .name = "uint8",
1039
    .get  = get_uint8,
1040
    .put  = put_uint8,
1041
};
1042

    
1043
/* 16 bit unsigned int */
1044

    
1045
static int get_uint16(QEMUFile *f, void *pv, size_t size)
1046
{
1047
    uint16_t *v = pv;
1048
    qemu_get_be16s(f, v);
1049
    return 0;
1050
}
1051

    
1052
static void put_uint16(QEMUFile *f, void *pv, size_t size)
1053
{
1054
    uint16_t *v = pv;
1055
    qemu_put_be16s(f, v);
1056
}
1057

    
1058
const VMStateInfo vmstate_info_uint16 = {
1059
    .name = "uint16",
1060
    .get  = get_uint16,
1061
    .put  = put_uint16,
1062
};
1063

    
1064
/* 32 bit unsigned int */
1065

    
1066
static int get_uint32(QEMUFile *f, void *pv, size_t size)
1067
{
1068
    uint32_t *v = pv;
1069
    qemu_get_be32s(f, v);
1070
    return 0;
1071
}
1072

    
1073
static void put_uint32(QEMUFile *f, void *pv, size_t size)
1074
{
1075
    uint32_t *v = pv;
1076
    qemu_put_be32s(f, v);
1077
}
1078

    
1079
const VMStateInfo vmstate_info_uint32 = {
1080
    .name = "uint32",
1081
    .get  = get_uint32,
1082
    .put  = put_uint32,
1083
};
1084

    
1085
/* 32 bit uint. See that the received value is the same than the one
1086
   in the field */
1087

    
1088
static int get_uint32_equal(QEMUFile *f, void *pv, size_t size)
1089
{
1090
    uint32_t *v = pv;
1091
    uint32_t v2;
1092
    qemu_get_be32s(f, &v2);
1093

    
1094
    if (*v == v2) {
1095
        return 0;
1096
    }
1097
    return -EINVAL;
1098
}
1099

    
1100
const VMStateInfo vmstate_info_uint32_equal = {
1101
    .name = "uint32 equal",
1102
    .get  = get_uint32_equal,
1103
    .put  = put_uint32,
1104
};
1105

    
1106
/* 64 bit unsigned int */
1107

    
1108
static int get_uint64(QEMUFile *f, void *pv, size_t size)
1109
{
1110
    uint64_t *v = pv;
1111
    qemu_get_be64s(f, v);
1112
    return 0;
1113
}
1114

    
1115
static void put_uint64(QEMUFile *f, void *pv, size_t size)
1116
{
1117
    uint64_t *v = pv;
1118
    qemu_put_be64s(f, v);
1119
}
1120

    
1121
const VMStateInfo vmstate_info_uint64 = {
1122
    .name = "uint64",
1123
    .get  = get_uint64,
1124
    .put  = put_uint64,
1125
};
1126

    
1127
/* 64 bit unsigned int. See that the received value is the same than the one
1128
   in the field */
1129

    
1130
static int get_uint64_equal(QEMUFile *f, void *pv, size_t size)
1131
{
1132
    uint64_t *v = pv;
1133
    uint64_t v2;
1134
    qemu_get_be64s(f, &v2);
1135

    
1136
    if (*v == v2) {
1137
        return 0;
1138
    }
1139
    return -EINVAL;
1140
}
1141

    
1142
const VMStateInfo vmstate_info_uint64_equal = {
1143
    .name = "int64 equal",
1144
    .get  = get_uint64_equal,
1145
    .put  = put_uint64,
1146
};
1147

    
1148
/* 8 bit int. See that the received value is the same than the one
1149
   in the field */
1150

    
1151
static int get_uint8_equal(QEMUFile *f, void *pv, size_t size)
1152
{
1153
    uint8_t *v = pv;
1154
    uint8_t v2;
1155
    qemu_get_8s(f, &v2);
1156

    
1157
    if (*v == v2)
1158
        return 0;
1159
    return -EINVAL;
1160
}
1161

    
1162
const VMStateInfo vmstate_info_uint8_equal = {
1163
    .name = "uint8 equal",
1164
    .get  = get_uint8_equal,
1165
    .put  = put_uint8,
1166
};
1167

    
1168
/* 16 bit unsigned int int. See that the received value is the same than the one
1169
   in the field */
1170

    
1171
static int get_uint16_equal(QEMUFile *f, void *pv, size_t size)
1172
{
1173
    uint16_t *v = pv;
1174
    uint16_t v2;
1175
    qemu_get_be16s(f, &v2);
1176

    
1177
    if (*v == v2)
1178
        return 0;
1179
    return -EINVAL;
1180
}
1181

    
1182
const VMStateInfo vmstate_info_uint16_equal = {
1183
    .name = "uint16 equal",
1184
    .get  = get_uint16_equal,
1185
    .put  = put_uint16,
1186
};
1187

    
1188
/* floating point */
1189

    
1190
static int get_float64(QEMUFile *f, void *pv, size_t size)
1191
{
1192
    float64 *v = pv;
1193

    
1194
    *v = make_float64(qemu_get_be64(f));
1195
    return 0;
1196
}
1197

    
1198
static void put_float64(QEMUFile *f, void *pv, size_t size)
1199
{
1200
    uint64_t *v = pv;
1201

    
1202
    qemu_put_be64(f, float64_val(*v));
1203
}
1204

    
1205
const VMStateInfo vmstate_info_float64 = {
1206
    .name = "float64",
1207
    .get  = get_float64,
1208
    .put  = put_float64,
1209
};
1210

    
1211
/* timers  */
1212

    
1213
static int get_timer(QEMUFile *f, void *pv, size_t size)
1214
{
1215
    QEMUTimer *v = pv;
1216
    qemu_get_timer(f, v);
1217
    return 0;
1218
}
1219

    
1220
static void put_timer(QEMUFile *f, void *pv, size_t size)
1221
{
1222
    QEMUTimer *v = pv;
1223
    qemu_put_timer(f, v);
1224
}
1225

    
1226
const VMStateInfo vmstate_info_timer = {
1227
    .name = "timer",
1228
    .get  = get_timer,
1229
    .put  = put_timer,
1230
};
1231

    
1232
/* uint8_t buffers */
1233

    
1234
static int get_buffer(QEMUFile *f, void *pv, size_t size)
1235
{
1236
    uint8_t *v = pv;
1237
    qemu_get_buffer(f, v, size);
1238
    return 0;
1239
}
1240

    
1241
static void put_buffer(QEMUFile *f, void *pv, size_t size)
1242
{
1243
    uint8_t *v = pv;
1244
    qemu_put_buffer(f, v, size);
1245
}
1246

    
1247
const VMStateInfo vmstate_info_buffer = {
1248
    .name = "buffer",
1249
    .get  = get_buffer,
1250
    .put  = put_buffer,
1251
};
1252

    
1253
/* unused buffers: space that was used for some fields that are
1254
   not useful anymore */
1255

    
1256
static int get_unused_buffer(QEMUFile *f, void *pv, size_t size)
1257
{
1258
    uint8_t buf[1024];
1259
    int block_len;
1260

    
1261
    while (size > 0) {
1262
        block_len = MIN(sizeof(buf), size);
1263
        size -= block_len;
1264
        qemu_get_buffer(f, buf, block_len);
1265
    }
1266
   return 0;
1267
}
1268

    
1269
static void put_unused_buffer(QEMUFile *f, void *pv, size_t size)
1270
{
1271
    static const uint8_t buf[1024];
1272
    int block_len;
1273

    
1274
    while (size > 0) {
1275
        block_len = MIN(sizeof(buf), size);
1276
        size -= block_len;
1277
        qemu_put_buffer(f, buf, block_len);
1278
    }
1279
}
1280

    
1281
const VMStateInfo vmstate_info_unused_buffer = {
1282
    .name = "unused_buffer",
1283
    .get  = get_unused_buffer,
1284
    .put  = put_unused_buffer,
1285
};
1286

    
1287
/* bitmaps (as defined by bitmap.h). Note that size here is the size
1288
 * of the bitmap in bits. The on-the-wire format of a bitmap is 64
1289
 * bit words with the bits in big endian order. The in-memory format
1290
 * is an array of 'unsigned long', which may be either 32 or 64 bits.
1291
 */
1292
/* This is the number of 64 bit words sent over the wire */
1293
#define BITS_TO_U64S(nr) DIV_ROUND_UP(nr, 64)
1294
static int get_bitmap(QEMUFile *f, void *pv, size_t size)
1295
{
1296
    unsigned long *bmp = pv;
1297
    int i, idx = 0;
1298
    for (i = 0; i < BITS_TO_U64S(size); i++) {
1299
        uint64_t w = qemu_get_be64(f);
1300
        bmp[idx++] = w;
1301
        if (sizeof(unsigned long) == 4 && idx < BITS_TO_LONGS(size)) {
1302
            bmp[idx++] = w >> 32;
1303
        }
1304
    }
1305
    return 0;
1306
}
1307

    
1308
static void put_bitmap(QEMUFile *f, void *pv, size_t size)
1309
{
1310
    unsigned long *bmp = pv;
1311
    int i, idx = 0;
1312
    for (i = 0; i < BITS_TO_U64S(size); i++) {
1313
        uint64_t w = bmp[idx++];
1314
        if (sizeof(unsigned long) == 4 && idx < BITS_TO_LONGS(size)) {
1315
            w |= ((uint64_t)bmp[idx++]) << 32;
1316
        }
1317
        qemu_put_be64(f, w);
1318
    }
1319
}
1320

    
1321
const VMStateInfo vmstate_info_bitmap = {
1322
    .name = "bitmap",
1323
    .get = get_bitmap,
1324
    .put = put_bitmap,
1325
};
1326

    
1327
typedef struct CompatEntry {
1328
    char idstr[256];
1329
    int instance_id;
1330
} CompatEntry;
1331

    
1332
typedef struct SaveStateEntry {
1333
    QTAILQ_ENTRY(SaveStateEntry) entry;
1334
    char idstr[256];
1335
    int instance_id;
1336
    int alias_id;
1337
    int version_id;
1338
    int section_id;
1339
    SaveVMHandlers *ops;
1340
    const VMStateDescription *vmsd;
1341
    void *opaque;
1342
    CompatEntry *compat;
1343
    int no_migrate;
1344
    int is_ram;
1345
} SaveStateEntry;
1346

    
1347

    
1348
static QTAILQ_HEAD(savevm_handlers, SaveStateEntry) savevm_handlers =
1349
    QTAILQ_HEAD_INITIALIZER(savevm_handlers);
1350
static int global_section_id;
1351

    
1352
static int calculate_new_instance_id(const char *idstr)
1353
{
1354
    SaveStateEntry *se;
1355
    int instance_id = 0;
1356

    
1357
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1358
        if (strcmp(idstr, se->idstr) == 0
1359
            && instance_id <= se->instance_id) {
1360
            instance_id = se->instance_id + 1;
1361
        }
1362
    }
1363
    return instance_id;
1364
}
1365

    
1366
static int calculate_compat_instance_id(const char *idstr)
1367
{
1368
    SaveStateEntry *se;
1369
    int instance_id = 0;
1370

    
1371
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1372
        if (!se->compat)
1373
            continue;
1374

    
1375
        if (strcmp(idstr, se->compat->idstr) == 0
1376
            && instance_id <= se->compat->instance_id) {
1377
            instance_id = se->compat->instance_id + 1;
1378
        }
1379
    }
1380
    return instance_id;
1381
}
1382

    
1383
/* TODO: Individual devices generally have very little idea about the rest
1384
   of the system, so instance_id should be removed/replaced.
1385
   Meanwhile pass -1 as instance_id if you do not already have a clearly
1386
   distinguishing id for all instances of your device class. */
1387
int register_savevm_live(DeviceState *dev,
1388
                         const char *idstr,
1389
                         int instance_id,
1390
                         int version_id,
1391
                         SaveVMHandlers *ops,
1392
                         void *opaque)
1393
{
1394
    SaveStateEntry *se;
1395

    
1396
    se = g_malloc0(sizeof(SaveStateEntry));
1397
    se->version_id = version_id;
1398
    se->section_id = global_section_id++;
1399
    se->ops = ops;
1400
    se->opaque = opaque;
1401
    se->vmsd = NULL;
1402
    se->no_migrate = 0;
1403
    /* if this is a live_savem then set is_ram */
1404
    if (ops->save_live_setup != NULL) {
1405
        se->is_ram = 1;
1406
    }
1407

    
1408
    if (dev) {
1409
        char *id = qdev_get_dev_path(dev);
1410
        if (id) {
1411
            pstrcpy(se->idstr, sizeof(se->idstr), id);
1412
            pstrcat(se->idstr, sizeof(se->idstr), "/");
1413
            g_free(id);
1414

    
1415
            se->compat = g_malloc0(sizeof(CompatEntry));
1416
            pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
1417
            se->compat->instance_id = instance_id == -1 ?
1418
                         calculate_compat_instance_id(idstr) : instance_id;
1419
            instance_id = -1;
1420
        }
1421
    }
1422
    pstrcat(se->idstr, sizeof(se->idstr), idstr);
1423

    
1424
    if (instance_id == -1) {
1425
        se->instance_id = calculate_new_instance_id(se->idstr);
1426
    } else {
1427
        se->instance_id = instance_id;
1428
    }
1429
    assert(!se->compat || se->instance_id == 0);
1430
    /* add at the end of list */
1431
    QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
1432
    return 0;
1433
}
1434

    
1435
int register_savevm(DeviceState *dev,
1436
                    const char *idstr,
1437
                    int instance_id,
1438
                    int version_id,
1439
                    SaveStateHandler *save_state,
1440
                    LoadStateHandler *load_state,
1441
                    void *opaque)
1442
{
1443
    SaveVMHandlers *ops = g_malloc0(sizeof(SaveVMHandlers));
1444
    ops->save_state = save_state;
1445
    ops->load_state = load_state;
1446
    return register_savevm_live(dev, idstr, instance_id, version_id,
1447
                                ops, opaque);
1448
}
1449

    
1450
void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
1451
{
1452
    SaveStateEntry *se, *new_se;
1453
    char id[256] = "";
1454

    
1455
    if (dev) {
1456
        char *path = qdev_get_dev_path(dev);
1457
        if (path) {
1458
            pstrcpy(id, sizeof(id), path);
1459
            pstrcat(id, sizeof(id), "/");
1460
            g_free(path);
1461
        }
1462
    }
1463
    pstrcat(id, sizeof(id), idstr);
1464

    
1465
    QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
1466
        if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
1467
            QTAILQ_REMOVE(&savevm_handlers, se, entry);
1468
            if (se->compat) {
1469
                g_free(se->compat);
1470
            }
1471
            g_free(se->ops);
1472
            g_free(se);
1473
        }
1474
    }
1475
}
1476

    
1477
int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
1478
                                   const VMStateDescription *vmsd,
1479
                                   void *opaque, int alias_id,
1480
                                   int required_for_version)
1481
{
1482
    SaveStateEntry *se;
1483

    
1484
    /* If this triggers, alias support can be dropped for the vmsd. */
1485
    assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
1486

    
1487
    se = g_malloc0(sizeof(SaveStateEntry));
1488
    se->version_id = vmsd->version_id;
1489
    se->section_id = global_section_id++;
1490
    se->opaque = opaque;
1491
    se->vmsd = vmsd;
1492
    se->alias_id = alias_id;
1493
    se->no_migrate = vmsd->unmigratable;
1494

    
1495
    if (dev) {
1496
        char *id = qdev_get_dev_path(dev);
1497
        if (id) {
1498
            pstrcpy(se->idstr, sizeof(se->idstr), id);
1499
            pstrcat(se->idstr, sizeof(se->idstr), "/");
1500
            g_free(id);
1501

    
1502
            se->compat = g_malloc0(sizeof(CompatEntry));
1503
            pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
1504
            se->compat->instance_id = instance_id == -1 ?
1505
                         calculate_compat_instance_id(vmsd->name) : instance_id;
1506
            instance_id = -1;
1507
        }
1508
    }
1509
    pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
1510

    
1511
    if (instance_id == -1) {
1512
        se->instance_id = calculate_new_instance_id(se->idstr);
1513
    } else {
1514
        se->instance_id = instance_id;
1515
    }
1516
    assert(!se->compat || se->instance_id == 0);
1517
    /* add at the end of list */
1518
    QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
1519
    return 0;
1520
}
1521

    
1522
void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
1523
                        void *opaque)
1524
{
1525
    SaveStateEntry *se, *new_se;
1526

    
1527
    QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
1528
        if (se->vmsd == vmsd && se->opaque == opaque) {
1529
            QTAILQ_REMOVE(&savevm_handlers, se, entry);
1530
            if (se->compat) {
1531
                g_free(se->compat);
1532
            }
1533
            g_free(se);
1534
        }
1535
    }
1536
}
1537

    
1538
static void vmstate_subsection_save(QEMUFile *f, const VMStateDescription *vmsd,
1539
                                    void *opaque);
1540
static int vmstate_subsection_load(QEMUFile *f, const VMStateDescription *vmsd,
1541
                                   void *opaque);
1542

    
1543
int vmstate_load_state(QEMUFile *f, const VMStateDescription *vmsd,
1544
                       void *opaque, int version_id)
1545
{
1546
    VMStateField *field = vmsd->fields;
1547
    int ret;
1548

    
1549
    if (version_id > vmsd->version_id) {
1550
        return -EINVAL;
1551
    }
1552
    if (version_id < vmsd->minimum_version_id_old) {
1553
        return -EINVAL;
1554
    }
1555
    if  (version_id < vmsd->minimum_version_id) {
1556
        return vmsd->load_state_old(f, opaque, version_id);
1557
    }
1558
    if (vmsd->pre_load) {
1559
        int ret = vmsd->pre_load(opaque);
1560
        if (ret)
1561
            return ret;
1562
    }
1563
    while(field->name) {
1564
        if ((field->field_exists &&
1565
             field->field_exists(opaque, version_id)) ||
1566
            (!field->field_exists &&
1567
             field->version_id <= version_id)) {
1568
            void *base_addr = opaque + field->offset;
1569
            int i, n_elems = 1;
1570
            int size = field->size;
1571

    
1572
            if (field->flags & VMS_VBUFFER) {
1573
                size = *(int32_t *)(opaque+field->size_offset);
1574
                if (field->flags & VMS_MULTIPLY) {
1575
                    size *= field->size;
1576
                }
1577
            }
1578
            if (field->flags & VMS_ARRAY) {
1579
                n_elems = field->num;
1580
            } else if (field->flags & VMS_VARRAY_INT32) {
1581
                n_elems = *(int32_t *)(opaque+field->num_offset);
1582
            } else if (field->flags & VMS_VARRAY_UINT32) {
1583
                n_elems = *(uint32_t *)(opaque+field->num_offset);
1584
            } else if (field->flags & VMS_VARRAY_UINT16) {
1585
                n_elems = *(uint16_t *)(opaque+field->num_offset);
1586
            } else if (field->flags & VMS_VARRAY_UINT8) {
1587
                n_elems = *(uint8_t *)(opaque+field->num_offset);
1588
            }
1589
            if (field->flags & VMS_POINTER) {
1590
                base_addr = *(void **)base_addr + field->start;
1591
            }
1592
            for (i = 0; i < n_elems; i++) {
1593
                void *addr = base_addr + size * i;
1594

    
1595
                if (field->flags & VMS_ARRAY_OF_POINTER) {
1596
                    addr = *(void **)addr;
1597
                }
1598
                if (field->flags & VMS_STRUCT) {
1599
                    ret = vmstate_load_state(f, field->vmsd, addr, field->vmsd->version_id);
1600
                } else {
1601
                    ret = field->info->get(f, addr, size);
1602

    
1603
                }
1604
                if (ret < 0) {
1605
                    return ret;
1606
                }
1607
            }
1608
        }
1609
        field++;
1610
    }
1611
    ret = vmstate_subsection_load(f, vmsd, opaque);
1612
    if (ret != 0) {
1613
        return ret;
1614
    }
1615
    if (vmsd->post_load) {
1616
        return vmsd->post_load(opaque, version_id);
1617
    }
1618
    return 0;
1619
}
1620

    
1621
void vmstate_save_state(QEMUFile *f, const VMStateDescription *vmsd,
1622
                        void *opaque)
1623
{
1624
    VMStateField *field = vmsd->fields;
1625

    
1626
    if (vmsd->pre_save) {
1627
        vmsd->pre_save(opaque);
1628
    }
1629
    while(field->name) {
1630
        if (!field->field_exists ||
1631
            field->field_exists(opaque, vmsd->version_id)) {
1632
            void *base_addr = opaque + field->offset;
1633
            int i, n_elems = 1;
1634
            int size = field->size;
1635

    
1636
            if (field->flags & VMS_VBUFFER) {
1637
                size = *(int32_t *)(opaque+field->size_offset);
1638
                if (field->flags & VMS_MULTIPLY) {
1639
                    size *= field->size;
1640
                }
1641
            }
1642
            if (field->flags & VMS_ARRAY) {
1643
                n_elems = field->num;
1644
            } else if (field->flags & VMS_VARRAY_INT32) {
1645
                n_elems = *(int32_t *)(opaque+field->num_offset);
1646
            } else if (field->flags & VMS_VARRAY_UINT32) {
1647
                n_elems = *(uint32_t *)(opaque+field->num_offset);
1648
            } else if (field->flags & VMS_VARRAY_UINT16) {
1649
                n_elems = *(uint16_t *)(opaque+field->num_offset);
1650
            } else if (field->flags & VMS_VARRAY_UINT8) {
1651
                n_elems = *(uint8_t *)(opaque+field->num_offset);
1652
            }
1653
            if (field->flags & VMS_POINTER) {
1654
                base_addr = *(void **)base_addr + field->start;
1655
            }
1656
            for (i = 0; i < n_elems; i++) {
1657
                void *addr = base_addr + size * i;
1658

    
1659
                if (field->flags & VMS_ARRAY_OF_POINTER) {
1660
                    addr = *(void **)addr;
1661
                }
1662
                if (field->flags & VMS_STRUCT) {
1663
                    vmstate_save_state(f, field->vmsd, addr);
1664
                } else {
1665
                    field->info->put(f, addr, size);
1666
                }
1667
            }
1668
        }
1669
        field++;
1670
    }
1671
    vmstate_subsection_save(f, vmsd, opaque);
1672
}
1673

    
1674
static int vmstate_load(QEMUFile *f, SaveStateEntry *se, int version_id)
1675
{
1676
    if (!se->vmsd) {         /* Old style */
1677
        return se->ops->load_state(f, se->opaque, version_id);
1678
    }
1679
    return vmstate_load_state(f, se->vmsd, se->opaque, version_id);
1680
}
1681

    
1682
static void vmstate_save(QEMUFile *f, SaveStateEntry *se)
1683
{
1684
    if (!se->vmsd) {         /* Old style */
1685
        se->ops->save_state(f, se->opaque);
1686
        return;
1687
    }
1688
    vmstate_save_state(f,se->vmsd, se->opaque);
1689
}
1690

    
1691
#define QEMU_VM_FILE_MAGIC           0x5145564d
1692
#define QEMU_VM_FILE_VERSION_COMPAT  0x00000002
1693
#define QEMU_VM_FILE_VERSION         0x00000003
1694

    
1695
#define QEMU_VM_EOF                  0x00
1696
#define QEMU_VM_SECTION_START        0x01
1697
#define QEMU_VM_SECTION_PART         0x02
1698
#define QEMU_VM_SECTION_END          0x03
1699
#define QEMU_VM_SECTION_FULL         0x04
1700
#define QEMU_VM_SUBSECTION           0x05
1701

    
1702
bool qemu_savevm_state_blocked(Error **errp)
1703
{
1704
    SaveStateEntry *se;
1705

    
1706
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1707
        if (se->no_migrate) {
1708
            error_set(errp, QERR_MIGRATION_NOT_SUPPORTED, se->idstr);
1709
            return true;
1710
        }
1711
    }
1712
    return false;
1713
}
1714

    
1715
void qemu_savevm_state_begin(QEMUFile *f,
1716
                             const MigrationParams *params)
1717
{
1718
    SaveStateEntry *se;
1719
    int ret;
1720

    
1721
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1722
        if (!se->ops || !se->ops->set_params) {
1723
            continue;
1724
        }
1725
        se->ops->set_params(params, se->opaque);
1726
    }
1727
    
1728
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1729
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1730

    
1731
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1732
        int len;
1733

    
1734
        if (!se->ops || !se->ops->save_live_setup) {
1735
            continue;
1736
        }
1737
        if (se->ops && se->ops->is_active) {
1738
            if (!se->ops->is_active(se->opaque)) {
1739
                continue;
1740
            }
1741
        }
1742
        /* Section type */
1743
        qemu_put_byte(f, QEMU_VM_SECTION_START);
1744
        qemu_put_be32(f, se->section_id);
1745

    
1746
        /* ID string */
1747
        len = strlen(se->idstr);
1748
        qemu_put_byte(f, len);
1749
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1750

    
1751
        qemu_put_be32(f, se->instance_id);
1752
        qemu_put_be32(f, se->version_id);
1753

    
1754
        ret = se->ops->save_live_setup(f, se->opaque);
1755
        if (ret < 0) {
1756
            qemu_file_set_error(f, ret);
1757
            break;
1758
        }
1759
    }
1760
}
1761

    
1762
/*
1763
 * this function has three return values:
1764
 *   negative: there was one error, and we have -errno.
1765
 *   0 : We haven't finished, caller have to go again
1766
 *   1 : We have finished, we can go to complete phase
1767
 */
1768
int qemu_savevm_state_iterate(QEMUFile *f)
1769
{
1770
    SaveStateEntry *se;
1771
    int ret = 1;
1772

    
1773
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1774
        if (!se->ops || !se->ops->save_live_iterate) {
1775
            continue;
1776
        }
1777
        if (se->ops && se->ops->is_active) {
1778
            if (!se->ops->is_active(se->opaque)) {
1779
                continue;
1780
            }
1781
        }
1782
        if (qemu_file_rate_limit(f)) {
1783
            return 0;
1784
        }
1785
        trace_savevm_section_start();
1786
        /* Section type */
1787
        qemu_put_byte(f, QEMU_VM_SECTION_PART);
1788
        qemu_put_be32(f, se->section_id);
1789

    
1790
        ret = se->ops->save_live_iterate(f, se->opaque);
1791
        trace_savevm_section_end(se->section_id);
1792

    
1793
        if (ret < 0) {
1794
            qemu_file_set_error(f, ret);
1795
        }
1796
        if (ret <= 0) {
1797
            /* Do not proceed to the next vmstate before this one reported
1798
               completion of the current stage. This serializes the migration
1799
               and reduces the probability that a faster changing state is
1800
               synchronized over and over again. */
1801
            break;
1802
        }
1803
    }
1804
    return ret;
1805
}
1806

    
1807
void qemu_savevm_state_complete(QEMUFile *f)
1808
{
1809
    SaveStateEntry *se;
1810
    int ret;
1811

    
1812
    cpu_synchronize_all_states();
1813

    
1814
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1815
        if (!se->ops || !se->ops->save_live_complete) {
1816
            continue;
1817
        }
1818
        if (se->ops && se->ops->is_active) {
1819
            if (!se->ops->is_active(se->opaque)) {
1820
                continue;
1821
            }
1822
        }
1823
        trace_savevm_section_start();
1824
        /* Section type */
1825
        qemu_put_byte(f, QEMU_VM_SECTION_END);
1826
        qemu_put_be32(f, se->section_id);
1827

    
1828
        ret = se->ops->save_live_complete(f, se->opaque);
1829
        trace_savevm_section_end(se->section_id);
1830
        if (ret < 0) {
1831
            qemu_file_set_error(f, ret);
1832
            return;
1833
        }
1834
    }
1835

    
1836
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1837
        int len;
1838

    
1839
        if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1840
            continue;
1841
        }
1842
        trace_savevm_section_start();
1843
        /* Section type */
1844
        qemu_put_byte(f, QEMU_VM_SECTION_FULL);
1845
        qemu_put_be32(f, se->section_id);
1846

    
1847
        /* ID string */
1848
        len = strlen(se->idstr);
1849
        qemu_put_byte(f, len);
1850
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1851

    
1852
        qemu_put_be32(f, se->instance_id);
1853
        qemu_put_be32(f, se->version_id);
1854

    
1855
        vmstate_save(f, se);
1856
        trace_savevm_section_end(se->section_id);
1857
    }
1858

    
1859
    qemu_put_byte(f, QEMU_VM_EOF);
1860
    qemu_fflush(f);
1861
}
1862

    
1863
uint64_t qemu_savevm_state_pending(QEMUFile *f, uint64_t max_size)
1864
{
1865
    SaveStateEntry *se;
1866
    uint64_t ret = 0;
1867

    
1868
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1869
        if (!se->ops || !se->ops->save_live_pending) {
1870
            continue;
1871
        }
1872
        if (se->ops && se->ops->is_active) {
1873
            if (!se->ops->is_active(se->opaque)) {
1874
                continue;
1875
            }
1876
        }
1877
        ret += se->ops->save_live_pending(f, se->opaque, max_size);
1878
    }
1879
    return ret;
1880
}
1881

    
1882
void qemu_savevm_state_cancel(void)
1883
{
1884
    SaveStateEntry *se;
1885

    
1886
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1887
        if (se->ops && se->ops->cancel) {
1888
            se->ops->cancel(se->opaque);
1889
        }
1890
    }
1891
}
1892

    
1893
static int qemu_savevm_state(QEMUFile *f)
1894
{
1895
    int ret;
1896
    MigrationParams params = {
1897
        .blk = 0,
1898
        .shared = 0
1899
    };
1900

    
1901
    if (qemu_savevm_state_blocked(NULL)) {
1902
        return -EINVAL;
1903
    }
1904

    
1905
    qemu_mutex_unlock_iothread();
1906
    qemu_savevm_state_begin(f, &params);
1907
    qemu_mutex_lock_iothread();
1908

    
1909
    while (qemu_file_get_error(f) == 0) {
1910
        if (qemu_savevm_state_iterate(f) > 0) {
1911
            break;
1912
        }
1913
    }
1914

    
1915
    ret = qemu_file_get_error(f);
1916
    if (ret == 0) {
1917
        qemu_savevm_state_complete(f);
1918
        ret = qemu_file_get_error(f);
1919
    }
1920
    if (ret != 0) {
1921
        qemu_savevm_state_cancel();
1922
    }
1923
    return ret;
1924
}
1925

    
1926
static int qemu_save_device_state(QEMUFile *f)
1927
{
1928
    SaveStateEntry *se;
1929

    
1930
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1931
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1932

    
1933
    cpu_synchronize_all_states();
1934

    
1935
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1936
        int len;
1937

    
1938
        if (se->is_ram) {
1939
            continue;
1940
        }
1941
        if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1942
            continue;
1943
        }
1944

    
1945
        /* Section type */
1946
        qemu_put_byte(f, QEMU_VM_SECTION_FULL);
1947
        qemu_put_be32(f, se->section_id);
1948

    
1949
        /* ID string */
1950
        len = strlen(se->idstr);
1951
        qemu_put_byte(f, len);
1952
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1953

    
1954
        qemu_put_be32(f, se->instance_id);
1955
        qemu_put_be32(f, se->version_id);
1956

    
1957
        vmstate_save(f, se);
1958
    }
1959

    
1960
    qemu_put_byte(f, QEMU_VM_EOF);
1961

    
1962
    return qemu_file_get_error(f);
1963
}
1964

    
1965
static SaveStateEntry *find_se(const char *idstr, int instance_id)
1966
{
1967
    SaveStateEntry *se;
1968

    
1969
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1970
        if (!strcmp(se->idstr, idstr) &&
1971
            (instance_id == se->instance_id ||
1972
             instance_id == se->alias_id))
1973
            return se;
1974
        /* Migrating from an older version? */
1975
        if (strstr(se->idstr, idstr) && se->compat) {
1976
            if (!strcmp(se->compat->idstr, idstr) &&
1977
                (instance_id == se->compat->instance_id ||
1978
                 instance_id == se->alias_id))
1979
                return se;
1980
        }
1981
    }
1982
    return NULL;
1983
}
1984

    
1985
static const VMStateDescription *vmstate_get_subsection(const VMStateSubsection *sub, char *idstr)
1986
{
1987
    while(sub && sub->needed) {
1988
        if (strcmp(idstr, sub->vmsd->name) == 0) {
1989
            return sub->vmsd;
1990
        }
1991
        sub++;
1992
    }
1993
    return NULL;
1994
}
1995

    
1996
static int vmstate_subsection_load(QEMUFile *f, const VMStateDescription *vmsd,
1997
                                   void *opaque)
1998
{
1999
    while (qemu_peek_byte(f, 0) == QEMU_VM_SUBSECTION) {
2000
        char idstr[256];
2001
        int ret;
2002
        uint8_t version_id, len, size;
2003
        const VMStateDescription *sub_vmsd;
2004

    
2005
        len = qemu_peek_byte(f, 1);
2006
        if (len < strlen(vmsd->name) + 1) {
2007
            /* subsection name has be be "section_name/a" */
2008
            return 0;
2009
        }
2010
        size = qemu_peek_buffer(f, (uint8_t *)idstr, len, 2);
2011
        if (size != len) {
2012
            return 0;
2013
        }
2014
        idstr[size] = 0;
2015

    
2016
        if (strncmp(vmsd->name, idstr, strlen(vmsd->name)) != 0) {
2017
            /* it don't have a valid subsection name */
2018
            return 0;
2019
        }
2020
        sub_vmsd = vmstate_get_subsection(vmsd->subsections, idstr);
2021
        if (sub_vmsd == NULL) {
2022
            return -ENOENT;
2023
        }
2024
        qemu_file_skip(f, 1); /* subsection */
2025
        qemu_file_skip(f, 1); /* len */
2026
        qemu_file_skip(f, len); /* idstr */
2027
        version_id = qemu_get_be32(f);
2028

    
2029
        ret = vmstate_load_state(f, sub_vmsd, opaque, version_id);
2030
        if (ret) {
2031
            return ret;
2032
        }
2033
    }
2034
    return 0;
2035
}
2036

    
2037
static void vmstate_subsection_save(QEMUFile *f, const VMStateDescription *vmsd,
2038
                                    void *opaque)
2039
{
2040
    const VMStateSubsection *sub = vmsd->subsections;
2041

    
2042
    while (sub && sub->needed) {
2043
        if (sub->needed(opaque)) {
2044
            const VMStateDescription *vmsd = sub->vmsd;
2045
            uint8_t len;
2046

    
2047
            qemu_put_byte(f, QEMU_VM_SUBSECTION);
2048
            len = strlen(vmsd->name);
2049
            qemu_put_byte(f, len);
2050
            qemu_put_buffer(f, (uint8_t *)vmsd->name, len);
2051
            qemu_put_be32(f, vmsd->version_id);
2052
            vmstate_save_state(f, vmsd, opaque);
2053
        }
2054
        sub++;
2055
    }
2056
}
2057

    
2058
typedef struct LoadStateEntry {
2059
    QLIST_ENTRY(LoadStateEntry) entry;
2060
    SaveStateEntry *se;
2061
    int section_id;
2062
    int version_id;
2063
} LoadStateEntry;
2064

    
2065
int qemu_loadvm_state(QEMUFile *f)
2066
{
2067
    QLIST_HEAD(, LoadStateEntry) loadvm_handlers =
2068
        QLIST_HEAD_INITIALIZER(loadvm_handlers);
2069
    LoadStateEntry *le, *new_le;
2070
    uint8_t section_type;
2071
    unsigned int v;
2072
    int ret;
2073

    
2074
    if (qemu_savevm_state_blocked(NULL)) {
2075
        return -EINVAL;
2076
    }
2077

    
2078
    v = qemu_get_be32(f);
2079
    if (v != QEMU_VM_FILE_MAGIC)
2080
        return -EINVAL;
2081

    
2082
    v = qemu_get_be32(f);
2083
    if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2084
        fprintf(stderr, "SaveVM v2 format is obsolete and don't work anymore\n");
2085
        return -ENOTSUP;
2086
    }
2087
    if (v != QEMU_VM_FILE_VERSION)
2088
        return -ENOTSUP;
2089

    
2090
    while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
2091
        uint32_t instance_id, version_id, section_id;
2092
        SaveStateEntry *se;
2093
        char idstr[257];
2094
        int len;
2095

    
2096
        switch (section_type) {
2097
        case QEMU_VM_SECTION_START:
2098
        case QEMU_VM_SECTION_FULL:
2099
            /* Read section start */
2100
            section_id = qemu_get_be32(f);
2101
            len = qemu_get_byte(f);
2102
            qemu_get_buffer(f, (uint8_t *)idstr, len);
2103
            idstr[len] = 0;
2104
            instance_id = qemu_get_be32(f);
2105
            version_id = qemu_get_be32(f);
2106

    
2107
            /* Find savevm section */
2108
            se = find_se(idstr, instance_id);
2109
            if (se == NULL) {
2110
                fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
2111
                ret = -EINVAL;
2112
                goto out;
2113
            }
2114

    
2115
            /* Validate version */
2116
            if (version_id > se->version_id) {
2117
                fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
2118
                        version_id, idstr, se->version_id);
2119
                ret = -EINVAL;
2120
                goto out;
2121
            }
2122

    
2123
            /* Add entry */
2124
            le = g_malloc0(sizeof(*le));
2125

    
2126
            le->se = se;
2127
            le->section_id = section_id;
2128
            le->version_id = version_id;
2129
            QLIST_INSERT_HEAD(&loadvm_handlers, le, entry);
2130

    
2131
            ret = vmstate_load(f, le->se, le->version_id);
2132
            if (ret < 0) {
2133
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2134
                        instance_id, idstr);
2135
                goto out;
2136
            }
2137
            break;
2138
        case QEMU_VM_SECTION_PART:
2139
        case QEMU_VM_SECTION_END:
2140
            section_id = qemu_get_be32(f);
2141

    
2142
            QLIST_FOREACH(le, &loadvm_handlers, entry) {
2143
                if (le->section_id == section_id) {
2144
                    break;
2145
                }
2146
            }
2147
            if (le == NULL) {
2148
                fprintf(stderr, "Unknown savevm section %d\n", section_id);
2149
                ret = -EINVAL;
2150
                goto out;
2151
            }
2152

    
2153
            ret = vmstate_load(f, le->se, le->version_id);
2154
            if (ret < 0) {
2155
                fprintf(stderr, "qemu: warning: error while loading state section id %d\n",
2156
                        section_id);
2157
                goto out;
2158
            }
2159
            break;
2160
        default:
2161
            fprintf(stderr, "Unknown savevm section type %d\n", section_type);
2162
            ret = -EINVAL;
2163
            goto out;
2164
        }
2165
    }
2166

    
2167
    cpu_synchronize_all_post_init();
2168

    
2169
    ret = 0;
2170

    
2171
out:
2172
    QLIST_FOREACH_SAFE(le, &loadvm_handlers, entry, new_le) {
2173
        QLIST_REMOVE(le, entry);
2174
        g_free(le);
2175
    }
2176

    
2177
    if (ret == 0) {
2178
        ret = qemu_file_get_error(f);
2179
    }
2180

    
2181
    return ret;
2182
}
2183

    
2184
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
2185
                              const char *name)
2186
{
2187
    QEMUSnapshotInfo *sn_tab, *sn;
2188
    int nb_sns, i, ret;
2189

    
2190
    ret = -ENOENT;
2191
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2192
    if (nb_sns < 0)
2193
        return ret;
2194
    for(i = 0; i < nb_sns; i++) {
2195
        sn = &sn_tab[i];
2196
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
2197
            *sn_info = *sn;
2198
            ret = 0;
2199
            break;
2200
        }
2201
    }
2202
    g_free(sn_tab);
2203
    return ret;
2204
}
2205

    
2206
/*
2207
 * Deletes snapshots of a given name in all opened images.
2208
 */
2209
static int del_existing_snapshots(Monitor *mon, const char *name)
2210
{
2211
    BlockDriverState *bs;
2212
    QEMUSnapshotInfo sn1, *snapshot = &sn1;
2213
    int ret;
2214

    
2215
    bs = NULL;
2216
    while ((bs = bdrv_next(bs))) {
2217
        if (bdrv_can_snapshot(bs) &&
2218
            bdrv_snapshot_find(bs, snapshot, name) >= 0)
2219
        {
2220
            ret = bdrv_snapshot_delete(bs, name);
2221
            if (ret < 0) {
2222
                monitor_printf(mon,
2223
                               "Error while deleting snapshot on '%s'\n",
2224
                               bdrv_get_device_name(bs));
2225
                return -1;
2226
            }
2227
        }
2228
    }
2229

    
2230
    return 0;
2231
}
2232

    
2233
void do_savevm(Monitor *mon, const QDict *qdict)
2234
{
2235
    BlockDriverState *bs, *bs1;
2236
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2237
    int ret;
2238
    QEMUFile *f;
2239
    int saved_vm_running;
2240
    uint64_t vm_state_size;
2241
    qemu_timeval tv;
2242
    struct tm tm;
2243
    const char *name = qdict_get_try_str(qdict, "name");
2244

    
2245
    /* Verify if there is a device that doesn't support snapshots and is writable */
2246
    bs = NULL;
2247
    while ((bs = bdrv_next(bs))) {
2248

    
2249
        if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2250
            continue;
2251
        }
2252

    
2253
        if (!bdrv_can_snapshot(bs)) {
2254
            monitor_printf(mon, "Device '%s' is writable but does not support snapshots.\n",
2255
                               bdrv_get_device_name(bs));
2256
            return;
2257
        }
2258
    }
2259

    
2260
    bs = bdrv_snapshots();
2261
    if (!bs) {
2262
        monitor_printf(mon, "No block device can accept snapshots\n");
2263
        return;
2264
    }
2265

    
2266
    saved_vm_running = runstate_is_running();
2267
    vm_stop(RUN_STATE_SAVE_VM);
2268

    
2269
    memset(sn, 0, sizeof(*sn));
2270

    
2271
    /* fill auxiliary fields */
2272
    qemu_gettimeofday(&tv);
2273
    sn->date_sec = tv.tv_sec;
2274
    sn->date_nsec = tv.tv_usec * 1000;
2275
    sn->vm_clock_nsec = qemu_get_clock_ns(vm_clock);
2276

    
2277
    if (name) {
2278
        ret = bdrv_snapshot_find(bs, old_sn, name);
2279
        if (ret >= 0) {
2280
            pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2281
            pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2282
        } else {
2283
            pstrcpy(sn->name, sizeof(sn->name), name);
2284
        }
2285
    } else {
2286
        /* cast below needed for OpenBSD where tv_sec is still 'long' */
2287
        localtime_r((const time_t *)&tv.tv_sec, &tm);
2288
        strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2289
    }
2290

    
2291
    /* Delete old snapshots of the same name */
2292
    if (name && del_existing_snapshots(mon, name) < 0) {
2293
        goto the_end;
2294
    }
2295

    
2296
    /* save the VM state */
2297
    f = qemu_fopen_bdrv(bs, 1);
2298
    if (!f) {
2299
        monitor_printf(mon, "Could not open VM state file\n");
2300
        goto the_end;
2301
    }
2302
    ret = qemu_savevm_state(f);
2303
    vm_state_size = qemu_ftell(f);
2304
    qemu_fclose(f);
2305
    if (ret < 0) {
2306
        monitor_printf(mon, "Error %d while writing VM\n", ret);
2307
        goto the_end;
2308
    }
2309

    
2310
    /* create the snapshots */
2311

    
2312
    bs1 = NULL;
2313
    while ((bs1 = bdrv_next(bs1))) {
2314
        if (bdrv_can_snapshot(bs1)) {
2315
            /* Write VM state size only to the image that contains the state */
2316
            sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
2317
            ret = bdrv_snapshot_create(bs1, sn);
2318
            if (ret < 0) {
2319
                monitor_printf(mon, "Error while creating snapshot on '%s'\n",
2320
                               bdrv_get_device_name(bs1));
2321
            }
2322
        }
2323
    }
2324

    
2325
 the_end:
2326
    if (saved_vm_running)
2327
        vm_start();
2328
}
2329

    
2330
void qmp_xen_save_devices_state(const char *filename, Error **errp)
2331
{
2332
    QEMUFile *f;
2333
    int saved_vm_running;
2334
    int ret;
2335

    
2336
    saved_vm_running = runstate_is_running();
2337
    vm_stop(RUN_STATE_SAVE_VM);
2338

    
2339
    f = qemu_fopen(filename, "wb");
2340
    if (!f) {
2341
        error_set(errp, QERR_OPEN_FILE_FAILED, filename);
2342
        goto the_end;
2343
    }
2344
    ret = qemu_save_device_state(f);
2345
    qemu_fclose(f);
2346
    if (ret < 0) {
2347
        error_set(errp, QERR_IO_ERROR);
2348
    }
2349

    
2350
 the_end:
2351
    if (saved_vm_running)
2352
        vm_start();
2353
}
2354

    
2355
int load_vmstate(const char *name)
2356
{
2357
    BlockDriverState *bs, *bs_vm_state;
2358
    QEMUSnapshotInfo sn;
2359
    QEMUFile *f;
2360
    int ret;
2361

    
2362
    bs_vm_state = bdrv_snapshots();
2363
    if (!bs_vm_state) {
2364
        error_report("No block device supports snapshots");
2365
        return -ENOTSUP;
2366
    }
2367

    
2368
    /* Don't even try to load empty VM states */
2369
    ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2370
    if (ret < 0) {
2371
        return ret;
2372
    } else if (sn.vm_state_size == 0) {
2373
        error_report("This is a disk-only snapshot. Revert to it offline "
2374
            "using qemu-img.");
2375
        return -EINVAL;
2376
    }
2377

    
2378
    /* Verify if there is any device that doesn't support snapshots and is
2379
    writable and check if the requested snapshot is available too. */
2380
    bs = NULL;
2381
    while ((bs = bdrv_next(bs))) {
2382

    
2383
        if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2384
            continue;
2385
        }
2386

    
2387
        if (!bdrv_can_snapshot(bs)) {
2388
            error_report("Device '%s' is writable but does not support snapshots.",
2389
                               bdrv_get_device_name(bs));
2390
            return -ENOTSUP;
2391
        }
2392

    
2393
        ret = bdrv_snapshot_find(bs, &sn, name);
2394
        if (ret < 0) {
2395
            error_report("Device '%s' does not have the requested snapshot '%s'",
2396
                           bdrv_get_device_name(bs), name);
2397
            return ret;
2398
        }
2399
    }
2400

    
2401
    /* Flush all IO requests so they don't interfere with the new state.  */
2402
    bdrv_drain_all();
2403

    
2404
    bs = NULL;
2405
    while ((bs = bdrv_next(bs))) {
2406
        if (bdrv_can_snapshot(bs)) {
2407
            ret = bdrv_snapshot_goto(bs, name);
2408
            if (ret < 0) {
2409
                error_report("Error %d while activating snapshot '%s' on '%s'",
2410
                             ret, name, bdrv_get_device_name(bs));
2411
                return ret;
2412
            }
2413
        }
2414
    }
2415

    
2416
    /* restore the VM state */
2417
    f = qemu_fopen_bdrv(bs_vm_state, 0);
2418
    if (!f) {
2419
        error_report("Could not open VM state file");
2420
        return -EINVAL;
2421
    }
2422

    
2423
    qemu_system_reset(VMRESET_SILENT);
2424
    ret = qemu_loadvm_state(f);
2425

    
2426
    qemu_fclose(f);
2427
    if (ret < 0) {
2428
        error_report("Error %d while loading VM state", ret);
2429
        return ret;
2430
    }
2431

    
2432
    return 0;
2433
}
2434

    
2435
void do_delvm(Monitor *mon, const QDict *qdict)
2436
{
2437
    BlockDriverState *bs, *bs1;
2438
    int ret;
2439
    const char *name = qdict_get_str(qdict, "name");
2440

    
2441
    bs = bdrv_snapshots();
2442
    if (!bs) {
2443
        monitor_printf(mon, "No block device supports snapshots\n");
2444
        return;
2445
    }
2446

    
2447
    bs1 = NULL;
2448
    while ((bs1 = bdrv_next(bs1))) {
2449
        if (bdrv_can_snapshot(bs1)) {
2450
            ret = bdrv_snapshot_delete(bs1, name);
2451
            if (ret < 0) {
2452
                if (ret == -ENOTSUP)
2453
                    monitor_printf(mon,
2454
                                   "Snapshots not supported on device '%s'\n",
2455
                                   bdrv_get_device_name(bs1));
2456
                else
2457
                    monitor_printf(mon, "Error %d while deleting snapshot on "
2458
                                   "'%s'\n", ret, bdrv_get_device_name(bs1));
2459
            }
2460
        }
2461
    }
2462
}
2463

    
2464
void do_info_snapshots(Monitor *mon, const QDict *qdict)
2465
{
2466
    BlockDriverState *bs, *bs1;
2467
    QEMUSnapshotInfo *sn_tab, *sn, s, *sn_info = &s;
2468
    int nb_sns, i, ret, available;
2469
    int total;
2470
    int *available_snapshots;
2471
    char buf[256];
2472

    
2473
    bs = bdrv_snapshots();
2474
    if (!bs) {
2475
        monitor_printf(mon, "No available block device supports snapshots\n");
2476
        return;
2477
    }
2478

    
2479
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2480
    if (nb_sns < 0) {
2481
        monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);
2482
        return;
2483
    }
2484

    
2485
    if (nb_sns == 0) {
2486
        monitor_printf(mon, "There is no snapshot available.\n");
2487
        return;
2488
    }
2489

    
2490
    available_snapshots = g_malloc0(sizeof(int) * nb_sns);
2491
    total = 0;
2492
    for (i = 0; i < nb_sns; i++) {
2493
        sn = &sn_tab[i];
2494
        available = 1;
2495
        bs1 = NULL;
2496

    
2497
        while ((bs1 = bdrv_next(bs1))) {
2498
            if (bdrv_can_snapshot(bs1) && bs1 != bs) {
2499
                ret = bdrv_snapshot_find(bs1, sn_info, sn->id_str);
2500
                if (ret < 0) {
2501
                    available = 0;
2502
                    break;
2503
                }
2504
            }
2505
        }
2506

    
2507
        if (available) {
2508
            available_snapshots[total] = i;
2509
            total++;
2510
        }
2511
    }
2512

    
2513
    if (total > 0) {
2514
        monitor_printf(mon, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
2515
        for (i = 0; i < total; i++) {
2516
            sn = &sn_tab[available_snapshots[i]];
2517
            monitor_printf(mon, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
2518
        }
2519
    } else {
2520
        monitor_printf(mon, "There is no suitable snapshot available\n");
2521
    }
2522

    
2523
    g_free(sn_tab);
2524
    g_free(available_snapshots);
2525

    
2526
}
2527

    
2528
void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2529
{
2530
    qemu_ram_set_idstr(memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK,
2531
                       memory_region_name(mr), dev);
2532
}
2533

    
2534
void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2535
{
2536
    /* Nothing do to while the implementation is in RAMBlock */
2537
}
2538

    
2539
void vmstate_register_ram_global(MemoryRegion *mr)
2540
{
2541
    vmstate_register_ram(mr, NULL);
2542
}