]> rtime.felk.cvut.cz Git - lisovros/qemu_apohw.git/blob - savevm.c
scsi-disk: fix bug in scsi_block_new_request() introduced by commit 137745c
[lisovros/qemu_apohw.git] / savevm.c
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 #include "block/snapshot.h"
44 #include "block/qapi.h"
45
46 #define SELF_ANNOUNCE_ROUNDS 5
47
48 #ifndef ETH_P_RARP
49 #define ETH_P_RARP 0x8035
50 #endif
51 #define ARP_HTYPE_ETH 0x0001
52 #define ARP_PTYPE_IP 0x0800
53 #define ARP_OP_REQUEST_REV 0x3
54
55 static int announce_self_create(uint8_t *buf,
56                                 uint8_t *mac_addr)
57 {
58     /* Ethernet header. */
59     memset(buf, 0xff, 6);         /* destination MAC addr */
60     memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
61     *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
62
63     /* RARP header. */
64     *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
65     *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
66     *(buf + 18) = 6; /* hardware addr length (ethernet) */
67     *(buf + 19) = 4; /* protocol addr length (IPv4) */
68     *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
69     memcpy(buf + 22, mac_addr, 6); /* source hw addr */
70     memset(buf + 28, 0x00, 4);     /* source protocol addr */
71     memcpy(buf + 32, mac_addr, 6); /* target hw addr */
72     memset(buf + 38, 0x00, 4);     /* target protocol addr */
73
74     /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
75     memset(buf + 42, 0x00, 18);
76
77     return 60; /* len (FCS will be added by hardware) */
78 }
79
80 static void qemu_announce_self_iter(NICState *nic, void *opaque)
81 {
82     uint8_t buf[60];
83     int len;
84
85     len = announce_self_create(buf, nic->conf->macaddr.a);
86
87     qemu_send_packet_raw(qemu_get_queue(nic), buf, len);
88 }
89
90
91 static void qemu_announce_self_once(void *opaque)
92 {
93     static int count = SELF_ANNOUNCE_ROUNDS;
94     QEMUTimer *timer = *(QEMUTimer **)opaque;
95
96     qemu_foreach_nic(qemu_announce_self_iter, NULL);
97
98     if (--count) {
99         /* delay 50ms, 150ms, 250ms, ... */
100         timer_mod(timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) +
101                        50 + (SELF_ANNOUNCE_ROUNDS - count - 1) * 100);
102     } else {
103             timer_del(timer);
104             timer_free(timer);
105     }
106 }
107
108 void qemu_announce_self(void)
109 {
110         static QEMUTimer *timer;
111         timer = timer_new_ms(QEMU_CLOCK_REALTIME, qemu_announce_self_once, &timer);
112         qemu_announce_self_once(&timer);
113 }
114
115 /***********************************************************/
116 /* savevm/loadvm support */
117
118 #define IO_BUF_SIZE 32768
119 #define MAX_IOV_SIZE MIN(IOV_MAX, 64)
120
121 struct QEMUFile {
122     const QEMUFileOps *ops;
123     void *opaque;
124
125     int64_t bytes_xfer;
126     int64_t xfer_limit;
127
128     int64_t pos; /* start of buffer when writing, end of buffer
129                     when reading */
130     int buf_index;
131     int buf_size; /* 0 when writing */
132     uint8_t buf[IO_BUF_SIZE];
133
134     struct iovec iov[MAX_IOV_SIZE];
135     unsigned int iovcnt;
136
137     int last_error;
138 };
139
140 typedef struct QEMUFileStdio
141 {
142     FILE *stdio_file;
143     QEMUFile *file;
144 } QEMUFileStdio;
145
146 typedef struct QEMUFileSocket
147 {
148     int fd;
149     QEMUFile *file;
150 } QEMUFileSocket;
151
152 static ssize_t socket_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
153                                     int64_t pos)
154 {
155     QEMUFileSocket *s = opaque;
156     ssize_t len;
157     ssize_t size = iov_size(iov, iovcnt);
158
159     len = iov_send(s->fd, iov, iovcnt, 0, size);
160     if (len < size) {
161         len = -socket_error();
162     }
163     return len;
164 }
165
166 static int socket_get_fd(void *opaque)
167 {
168     QEMUFileSocket *s = opaque;
169
170     return s->fd;
171 }
172
173 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
174 {
175     QEMUFileSocket *s = opaque;
176     ssize_t len;
177
178     for (;;) {
179         len = qemu_recv(s->fd, buf, size, 0);
180         if (len != -1) {
181             break;
182         }
183         if (socket_error() == EAGAIN) {
184             yield_until_fd_readable(s->fd);
185         } else if (socket_error() != EINTR) {
186             break;
187         }
188     }
189
190     if (len == -1) {
191         len = -socket_error();
192     }
193     return len;
194 }
195
196 static int socket_close(void *opaque)
197 {
198     QEMUFileSocket *s = opaque;
199     closesocket(s->fd);
200     g_free(s);
201     return 0;
202 }
203
204 static int stdio_get_fd(void *opaque)
205 {
206     QEMUFileStdio *s = opaque;
207
208     return fileno(s->stdio_file);
209 }
210
211 static int stdio_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
212 {
213     QEMUFileStdio *s = opaque;
214     return fwrite(buf, 1, size, s->stdio_file);
215 }
216
217 static int stdio_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
218 {
219     QEMUFileStdio *s = opaque;
220     FILE *fp = s->stdio_file;
221     int bytes;
222
223     for (;;) {
224         clearerr(fp);
225         bytes = fread(buf, 1, size, fp);
226         if (bytes != 0 || !ferror(fp)) {
227             break;
228         }
229         if (errno == EAGAIN) {
230             yield_until_fd_readable(fileno(fp));
231         } else if (errno != EINTR) {
232             break;
233         }
234     }
235     return bytes;
236 }
237
238 static int stdio_pclose(void *opaque)
239 {
240     QEMUFileStdio *s = opaque;
241     int ret;
242     ret = pclose(s->stdio_file);
243     if (ret == -1) {
244         ret = -errno;
245     } else if (!WIFEXITED(ret) || WEXITSTATUS(ret) != 0) {
246         /* close succeeded, but non-zero exit code: */
247         ret = -EIO; /* fake errno value */
248     }
249     g_free(s);
250     return ret;
251 }
252
253 static int stdio_fclose(void *opaque)
254 {
255     QEMUFileStdio *s = opaque;
256     int ret = 0;
257
258     if (s->file->ops->put_buffer || s->file->ops->writev_buffer) {
259         int fd = fileno(s->stdio_file);
260         struct stat st;
261
262         ret = fstat(fd, &st);
263         if (ret == 0 && S_ISREG(st.st_mode)) {
264             /*
265              * If the file handle is a regular file make sure the
266              * data is flushed to disk before signaling success.
267              */
268             ret = fsync(fd);
269             if (ret != 0) {
270                 ret = -errno;
271                 return ret;
272             }
273         }
274     }
275     if (fclose(s->stdio_file) == EOF) {
276         ret = -errno;
277     }
278     g_free(s);
279     return ret;
280 }
281
282 static const QEMUFileOps stdio_pipe_read_ops = {
283     .get_fd =     stdio_get_fd,
284     .get_buffer = stdio_get_buffer,
285     .close =      stdio_pclose
286 };
287
288 static const QEMUFileOps stdio_pipe_write_ops = {
289     .get_fd =     stdio_get_fd,
290     .put_buffer = stdio_put_buffer,
291     .close =      stdio_pclose
292 };
293
294 QEMUFile *qemu_popen_cmd(const char *command, const char *mode)
295 {
296     FILE *stdio_file;
297     QEMUFileStdio *s;
298
299     if (mode == NULL || (mode[0] != 'r' && mode[0] != 'w') || mode[1] != 0) {
300         fprintf(stderr, "qemu_popen: Argument validity check failed\n");
301         return NULL;
302     }
303
304     stdio_file = popen(command, mode);
305     if (stdio_file == NULL) {
306         return NULL;
307     }
308
309     s = g_malloc0(sizeof(QEMUFileStdio));
310
311     s->stdio_file = stdio_file;
312
313     if(mode[0] == 'r') {
314         s->file = qemu_fopen_ops(s, &stdio_pipe_read_ops);
315     } else {
316         s->file = qemu_fopen_ops(s, &stdio_pipe_write_ops);
317     }
318     return s->file;
319 }
320
321 static const QEMUFileOps stdio_file_read_ops = {
322     .get_fd =     stdio_get_fd,
323     .get_buffer = stdio_get_buffer,
324     .close =      stdio_fclose
325 };
326
327 static const QEMUFileOps stdio_file_write_ops = {
328     .get_fd =     stdio_get_fd,
329     .put_buffer = stdio_put_buffer,
330     .close =      stdio_fclose
331 };
332
333 static ssize_t unix_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
334                                   int64_t pos)
335 {
336     QEMUFileSocket *s = opaque;
337     ssize_t len, offset;
338     ssize_t size = iov_size(iov, iovcnt);
339     ssize_t total = 0;
340
341     assert(iovcnt > 0);
342     offset = 0;
343     while (size > 0) {
344         /* Find the next start position; skip all full-sized vector elements  */
345         while (offset >= iov[0].iov_len) {
346             offset -= iov[0].iov_len;
347             iov++, iovcnt--;
348         }
349
350         /* skip `offset' bytes from the (now) first element, undo it on exit */
351         assert(iovcnt > 0);
352         iov[0].iov_base += offset;
353         iov[0].iov_len -= offset;
354
355         do {
356             len = writev(s->fd, iov, iovcnt);
357         } while (len == -1 && errno == EINTR);
358         if (len == -1) {
359             return -errno;
360         }
361
362         /* Undo the changes above */
363         iov[0].iov_base -= offset;
364         iov[0].iov_len += offset;
365
366         /* Prepare for the next iteration */
367         offset += len;
368         total += len;
369         size -= len;
370     }
371
372     return total;
373 }
374
375 static int unix_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
376 {
377     QEMUFileSocket *s = opaque;
378     ssize_t len;
379
380     for (;;) {
381         len = read(s->fd, buf, size);
382         if (len != -1) {
383             break;
384         }
385         if (errno == EAGAIN) {
386             yield_until_fd_readable(s->fd);
387         } else if (errno != EINTR) {
388             break;
389         }
390     }
391
392     if (len == -1) {
393         len = -errno;
394     }
395     return len;
396 }
397
398 static int unix_close(void *opaque)
399 {
400     QEMUFileSocket *s = opaque;
401     close(s->fd);
402     g_free(s);
403     return 0;
404 }
405
406 static const QEMUFileOps unix_read_ops = {
407     .get_fd =     socket_get_fd,
408     .get_buffer = unix_get_buffer,
409     .close =      unix_close
410 };
411
412 static const QEMUFileOps unix_write_ops = {
413     .get_fd =     socket_get_fd,
414     .writev_buffer = unix_writev_buffer,
415     .close =      unix_close
416 };
417
418 QEMUFile *qemu_fdopen(int fd, const char *mode)
419 {
420     QEMUFileSocket *s;
421
422     if (mode == NULL ||
423         (mode[0] != 'r' && mode[0] != 'w') ||
424         mode[1] != 'b' || mode[2] != 0) {
425         fprintf(stderr, "qemu_fdopen: Argument validity check failed\n");
426         return NULL;
427     }
428
429     s = g_malloc0(sizeof(QEMUFileSocket));
430     s->fd = fd;
431
432     if(mode[0] == 'r') {
433         s->file = qemu_fopen_ops(s, &unix_read_ops);
434     } else {
435         s->file = qemu_fopen_ops(s, &unix_write_ops);
436     }
437     return s->file;
438 }
439
440 static const QEMUFileOps socket_read_ops = {
441     .get_fd =     socket_get_fd,
442     .get_buffer = socket_get_buffer,
443     .close =      socket_close
444 };
445
446 static const QEMUFileOps socket_write_ops = {
447     .get_fd =     socket_get_fd,
448     .writev_buffer = socket_writev_buffer,
449     .close =      socket_close
450 };
451
452 bool qemu_file_mode_is_not_valid(const char *mode)
453 {
454     if (mode == NULL ||
455         (mode[0] != 'r' && mode[0] != 'w') ||
456         mode[1] != 'b' || mode[2] != 0) {
457         fprintf(stderr, "qemu_fopen: Argument validity check failed\n");
458         return true;
459     }
460
461     return false;
462 }
463
464 QEMUFile *qemu_fopen_socket(int fd, const char *mode)
465 {
466     QEMUFileSocket *s;
467
468     if (qemu_file_mode_is_not_valid(mode)) {
469         return NULL;
470     }
471
472     s = g_malloc0(sizeof(QEMUFileSocket));
473     s->fd = fd;
474     if (mode[0] == 'w') {
475         qemu_set_block(s->fd);
476         s->file = qemu_fopen_ops(s, &socket_write_ops);
477     } else {
478         s->file = qemu_fopen_ops(s, &socket_read_ops);
479     }
480     return s->file;
481 }
482
483 QEMUFile *qemu_fopen(const char *filename, const char *mode)
484 {
485     QEMUFileStdio *s;
486
487     if (qemu_file_mode_is_not_valid(mode)) {
488         return NULL;
489     }
490
491     s = g_malloc0(sizeof(QEMUFileStdio));
492
493     s->stdio_file = fopen(filename, mode);
494     if (!s->stdio_file)
495         goto fail;
496     
497     if(mode[0] == 'w') {
498         s->file = qemu_fopen_ops(s, &stdio_file_write_ops);
499     } else {
500         s->file = qemu_fopen_ops(s, &stdio_file_read_ops);
501     }
502     return s->file;
503 fail:
504     g_free(s);
505     return NULL;
506 }
507
508 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
509                                    int64_t pos)
510 {
511     int ret;
512     QEMUIOVector qiov;
513
514     qemu_iovec_init_external(&qiov, iov, iovcnt);
515     ret = bdrv_writev_vmstate(opaque, &qiov, pos);
516     if (ret < 0) {
517         return ret;
518     }
519
520     return qiov.size;
521 }
522
523 static int block_put_buffer(void *opaque, const uint8_t *buf,
524                            int64_t pos, int size)
525 {
526     bdrv_save_vmstate(opaque, buf, pos, size);
527     return size;
528 }
529
530 static int block_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
531 {
532     return bdrv_load_vmstate(opaque, buf, pos, size);
533 }
534
535 static int bdrv_fclose(void *opaque)
536 {
537     return bdrv_flush(opaque);
538 }
539
540 static const QEMUFileOps bdrv_read_ops = {
541     .get_buffer = block_get_buffer,
542     .close =      bdrv_fclose
543 };
544
545 static const QEMUFileOps bdrv_write_ops = {
546     .put_buffer     = block_put_buffer,
547     .writev_buffer  = block_writev_buffer,
548     .close          = bdrv_fclose
549 };
550
551 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
552 {
553     if (is_writable)
554         return qemu_fopen_ops(bs, &bdrv_write_ops);
555     return qemu_fopen_ops(bs, &bdrv_read_ops);
556 }
557
558 QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)
559 {
560     QEMUFile *f;
561
562     f = g_malloc0(sizeof(QEMUFile));
563
564     f->opaque = opaque;
565     f->ops = ops;
566     return f;
567 }
568
569 /*
570  * Get last error for stream f
571  *
572  * Return negative error value if there has been an error on previous
573  * operations, return 0 if no error happened.
574  *
575  */
576 int qemu_file_get_error(QEMUFile *f)
577 {
578     return f->last_error;
579 }
580
581 static void qemu_file_set_error(QEMUFile *f, int ret)
582 {
583     if (f->last_error == 0) {
584         f->last_error = ret;
585     }
586 }
587
588 static inline bool qemu_file_is_writable(QEMUFile *f)
589 {
590     return f->ops->writev_buffer || f->ops->put_buffer;
591 }
592
593 /**
594  * Flushes QEMUFile buffer
595  *
596  * If there is writev_buffer QEMUFileOps it uses it otherwise uses
597  * put_buffer ops.
598  */
599 void qemu_fflush(QEMUFile *f)
600 {
601     ssize_t ret = 0;
602
603     if (!qemu_file_is_writable(f)) {
604         return;
605     }
606
607     if (f->ops->writev_buffer) {
608         if (f->iovcnt > 0) {
609             ret = f->ops->writev_buffer(f->opaque, f->iov, f->iovcnt, f->pos);
610         }
611     } else {
612         if (f->buf_index > 0) {
613             ret = f->ops->put_buffer(f->opaque, f->buf, f->pos, f->buf_index);
614         }
615     }
616     if (ret >= 0) {
617         f->pos += ret;
618     }
619     f->buf_index = 0;
620     f->iovcnt = 0;
621     if (ret < 0) {
622         qemu_file_set_error(f, ret);
623     }
624 }
625
626 void ram_control_before_iterate(QEMUFile *f, uint64_t flags)
627 {
628     int ret = 0;
629
630     if (f->ops->before_ram_iterate) {
631         ret = f->ops->before_ram_iterate(f, f->opaque, flags);
632         if (ret < 0) {
633             qemu_file_set_error(f, ret);
634         }
635     }
636 }
637
638 void ram_control_after_iterate(QEMUFile *f, uint64_t flags)
639 {
640     int ret = 0;
641
642     if (f->ops->after_ram_iterate) {
643         ret = f->ops->after_ram_iterate(f, f->opaque, flags);
644         if (ret < 0) {
645             qemu_file_set_error(f, ret);
646         }
647     }
648 }
649
650 void ram_control_load_hook(QEMUFile *f, uint64_t flags)
651 {
652     int ret = -EINVAL;
653
654     if (f->ops->hook_ram_load) {
655         ret = f->ops->hook_ram_load(f, f->opaque, flags);
656         if (ret < 0) {
657             qemu_file_set_error(f, ret);
658         }
659     } else {
660         qemu_file_set_error(f, ret);
661     }
662 }
663
664 size_t ram_control_save_page(QEMUFile *f, ram_addr_t block_offset,
665                          ram_addr_t offset, size_t size, int *bytes_sent)
666 {
667     if (f->ops->save_page) {
668         int ret = f->ops->save_page(f, f->opaque, block_offset,
669                                     offset, size, bytes_sent);
670
671         if (ret != RAM_SAVE_CONTROL_DELAYED) {
672             if (bytes_sent && *bytes_sent > 0) {
673                 qemu_update_position(f, *bytes_sent);
674             } else if (ret < 0) {
675                 qemu_file_set_error(f, ret);
676             }
677         }
678
679         return ret;
680     }
681
682     return RAM_SAVE_CONTROL_NOT_SUPP;
683 }
684
685 static void qemu_fill_buffer(QEMUFile *f)
686 {
687     int len;
688     int pending;
689
690     assert(!qemu_file_is_writable(f));
691
692     pending = f->buf_size - f->buf_index;
693     if (pending > 0) {
694         memmove(f->buf, f->buf + f->buf_index, pending);
695     }
696     f->buf_index = 0;
697     f->buf_size = pending;
698
699     len = f->ops->get_buffer(f->opaque, f->buf + pending, f->pos,
700                         IO_BUF_SIZE - pending);
701     if (len > 0) {
702         f->buf_size += len;
703         f->pos += len;
704     } else if (len == 0) {
705         qemu_file_set_error(f, -EIO);
706     } else if (len != -EAGAIN)
707         qemu_file_set_error(f, len);
708 }
709
710 int qemu_get_fd(QEMUFile *f)
711 {
712     if (f->ops->get_fd) {
713         return f->ops->get_fd(f->opaque);
714     }
715     return -1;
716 }
717
718 void qemu_update_position(QEMUFile *f, size_t size)
719 {
720     f->pos += size;
721 }
722
723 /** Closes the file
724  *
725  * Returns negative error value if any error happened on previous operations or
726  * while closing the file. Returns 0 or positive number on success.
727  *
728  * The meaning of return value on success depends on the specific backend
729  * being used.
730  */
731 int qemu_fclose(QEMUFile *f)
732 {
733     int ret;
734     qemu_fflush(f);
735     ret = qemu_file_get_error(f);
736
737     if (f->ops->close) {
738         int ret2 = f->ops->close(f->opaque);
739         if (ret >= 0) {
740             ret = ret2;
741         }
742     }
743     /* If any error was spotted before closing, we should report it
744      * instead of the close() return value.
745      */
746     if (f->last_error) {
747         ret = f->last_error;
748     }
749     g_free(f);
750     return ret;
751 }
752
753 static void add_to_iovec(QEMUFile *f, const uint8_t *buf, int size)
754 {
755     /* check for adjacent buffer and coalesce them */
756     if (f->iovcnt > 0 && buf == f->iov[f->iovcnt - 1].iov_base +
757         f->iov[f->iovcnt - 1].iov_len) {
758         f->iov[f->iovcnt - 1].iov_len += size;
759     } else {
760         f->iov[f->iovcnt].iov_base = (uint8_t *)buf;
761         f->iov[f->iovcnt++].iov_len = size;
762     }
763
764     if (f->iovcnt >= MAX_IOV_SIZE) {
765         qemu_fflush(f);
766     }
767 }
768
769 void qemu_put_buffer_async(QEMUFile *f, const uint8_t *buf, int size)
770 {
771     if (!f->ops->writev_buffer) {
772         qemu_put_buffer(f, buf, size);
773         return;
774     }
775
776     if (f->last_error) {
777         return;
778     }
779
780     f->bytes_xfer += size;
781     add_to_iovec(f, buf, size);
782 }
783
784 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
785 {
786     int l;
787
788     if (f->last_error) {
789         return;
790     }
791
792     while (size > 0) {
793         l = IO_BUF_SIZE - f->buf_index;
794         if (l > size)
795             l = size;
796         memcpy(f->buf + f->buf_index, buf, l);
797         f->bytes_xfer += l;
798         if (f->ops->writev_buffer) {
799             add_to_iovec(f, f->buf + f->buf_index, l);
800         }
801         f->buf_index += l;
802         if (f->buf_index == IO_BUF_SIZE) {
803             qemu_fflush(f);
804         }
805         if (qemu_file_get_error(f)) {
806             break;
807         }
808         buf += l;
809         size -= l;
810     }
811 }
812
813 void qemu_put_byte(QEMUFile *f, int v)
814 {
815     if (f->last_error) {
816         return;
817     }
818
819     f->buf[f->buf_index] = v;
820     f->bytes_xfer++;
821     if (f->ops->writev_buffer) {
822         add_to_iovec(f, f->buf + f->buf_index, 1);
823     }
824     f->buf_index++;
825     if (f->buf_index == IO_BUF_SIZE) {
826         qemu_fflush(f);
827     }
828 }
829
830 static void qemu_file_skip(QEMUFile *f, int size)
831 {
832     if (f->buf_index + size <= f->buf_size) {
833         f->buf_index += size;
834     }
835 }
836
837 static int qemu_peek_buffer(QEMUFile *f, uint8_t *buf, int size, size_t offset)
838 {
839     int pending;
840     int index;
841
842     assert(!qemu_file_is_writable(f));
843
844     index = f->buf_index + offset;
845     pending = f->buf_size - index;
846     if (pending < size) {
847         qemu_fill_buffer(f);
848         index = f->buf_index + offset;
849         pending = f->buf_size - index;
850     }
851
852     if (pending <= 0) {
853         return 0;
854     }
855     if (size > pending) {
856         size = pending;
857     }
858
859     memcpy(buf, f->buf + index, size);
860     return size;
861 }
862
863 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
864 {
865     int pending = size;
866     int done = 0;
867
868     while (pending > 0) {
869         int res;
870
871         res = qemu_peek_buffer(f, buf, pending, 0);
872         if (res == 0) {
873             return done;
874         }
875         qemu_file_skip(f, res);
876         buf += res;
877         pending -= res;
878         done += res;
879     }
880     return done;
881 }
882
883 static int qemu_peek_byte(QEMUFile *f, int offset)
884 {
885     int index = f->buf_index + offset;
886
887     assert(!qemu_file_is_writable(f));
888
889     if (index >= f->buf_size) {
890         qemu_fill_buffer(f);
891         index = f->buf_index + offset;
892         if (index >= f->buf_size) {
893             return 0;
894         }
895     }
896     return f->buf[index];
897 }
898
899 int qemu_get_byte(QEMUFile *f)
900 {
901     int result;
902
903     result = qemu_peek_byte(f, 0);
904     qemu_file_skip(f, 1);
905     return result;
906 }
907
908 int64_t qemu_ftell(QEMUFile *f)
909 {
910     qemu_fflush(f);
911     return f->pos;
912 }
913
914 int qemu_file_rate_limit(QEMUFile *f)
915 {
916     if (qemu_file_get_error(f)) {
917         return 1;
918     }
919     if (f->xfer_limit > 0 && f->bytes_xfer > f->xfer_limit) {
920         return 1;
921     }
922     return 0;
923 }
924
925 int64_t qemu_file_get_rate_limit(QEMUFile *f)
926 {
927     return f->xfer_limit;
928 }
929
930 void qemu_file_set_rate_limit(QEMUFile *f, int64_t limit)
931 {
932     f->xfer_limit = limit;
933 }
934
935 void qemu_file_reset_rate_limit(QEMUFile *f)
936 {
937     f->bytes_xfer = 0;
938 }
939
940 void qemu_put_be16(QEMUFile *f, unsigned int v)
941 {
942     qemu_put_byte(f, v >> 8);
943     qemu_put_byte(f, v);
944 }
945
946 void qemu_put_be32(QEMUFile *f, unsigned int v)
947 {
948     qemu_put_byte(f, v >> 24);
949     qemu_put_byte(f, v >> 16);
950     qemu_put_byte(f, v >> 8);
951     qemu_put_byte(f, v);
952 }
953
954 void qemu_put_be64(QEMUFile *f, uint64_t v)
955 {
956     qemu_put_be32(f, v >> 32);
957     qemu_put_be32(f, v);
958 }
959
960 unsigned int qemu_get_be16(QEMUFile *f)
961 {
962     unsigned int v;
963     v = qemu_get_byte(f) << 8;
964     v |= qemu_get_byte(f);
965     return v;
966 }
967
968 unsigned int qemu_get_be32(QEMUFile *f)
969 {
970     unsigned int v;
971     v = qemu_get_byte(f) << 24;
972     v |= qemu_get_byte(f) << 16;
973     v |= qemu_get_byte(f) << 8;
974     v |= qemu_get_byte(f);
975     return v;
976 }
977
978 uint64_t qemu_get_be64(QEMUFile *f)
979 {
980     uint64_t v;
981     v = (uint64_t)qemu_get_be32(f) << 32;
982     v |= qemu_get_be32(f);
983     return v;
984 }
985
986
987 /* timer */
988
989 void timer_put(QEMUFile *f, QEMUTimer *ts)
990 {
991     uint64_t expire_time;
992
993     expire_time = timer_expire_time_ns(ts);
994     qemu_put_be64(f, expire_time);
995 }
996
997 void timer_get(QEMUFile *f, QEMUTimer *ts)
998 {
999     uint64_t expire_time;
1000
1001     expire_time = qemu_get_be64(f);
1002     if (expire_time != -1) {
1003         timer_mod_ns(ts, expire_time);
1004     } else {
1005         timer_del(ts);
1006     }
1007 }
1008
1009
1010 /* bool */
1011
1012 static int get_bool(QEMUFile *f, void *pv, size_t size)
1013 {
1014     bool *v = pv;
1015     *v = qemu_get_byte(f);
1016     return 0;
1017 }
1018
1019 static void put_bool(QEMUFile *f, void *pv, size_t size)
1020 {
1021     bool *v = pv;
1022     qemu_put_byte(f, *v);
1023 }
1024
1025 const VMStateInfo vmstate_info_bool = {
1026     .name = "bool",
1027     .get  = get_bool,
1028     .put  = put_bool,
1029 };
1030
1031 /* 8 bit int */
1032
1033 static int get_int8(QEMUFile *f, void *pv, size_t size)
1034 {
1035     int8_t *v = pv;
1036     qemu_get_s8s(f, v);
1037     return 0;
1038 }
1039
1040 static void put_int8(QEMUFile *f, void *pv, size_t size)
1041 {
1042     int8_t *v = pv;
1043     qemu_put_s8s(f, v);
1044 }
1045
1046 const VMStateInfo vmstate_info_int8 = {
1047     .name = "int8",
1048     .get  = get_int8,
1049     .put  = put_int8,
1050 };
1051
1052 /* 16 bit int */
1053
1054 static int get_int16(QEMUFile *f, void *pv, size_t size)
1055 {
1056     int16_t *v = pv;
1057     qemu_get_sbe16s(f, v);
1058     return 0;
1059 }
1060
1061 static void put_int16(QEMUFile *f, void *pv, size_t size)
1062 {
1063     int16_t *v = pv;
1064     qemu_put_sbe16s(f, v);
1065 }
1066
1067 const VMStateInfo vmstate_info_int16 = {
1068     .name = "int16",
1069     .get  = get_int16,
1070     .put  = put_int16,
1071 };
1072
1073 /* 32 bit int */
1074
1075 static int get_int32(QEMUFile *f, void *pv, size_t size)
1076 {
1077     int32_t *v = pv;
1078     qemu_get_sbe32s(f, v);
1079     return 0;
1080 }
1081
1082 static void put_int32(QEMUFile *f, void *pv, size_t size)
1083 {
1084     int32_t *v = pv;
1085     qemu_put_sbe32s(f, v);
1086 }
1087
1088 const VMStateInfo vmstate_info_int32 = {
1089     .name = "int32",
1090     .get  = get_int32,
1091     .put  = put_int32,
1092 };
1093
1094 /* 32 bit int. See that the received value is the same than the one
1095    in the field */
1096
1097 static int get_int32_equal(QEMUFile *f, void *pv, size_t size)
1098 {
1099     int32_t *v = pv;
1100     int32_t v2;
1101     qemu_get_sbe32s(f, &v2);
1102
1103     if (*v == v2)
1104         return 0;
1105     return -EINVAL;
1106 }
1107
1108 const VMStateInfo vmstate_info_int32_equal = {
1109     .name = "int32 equal",
1110     .get  = get_int32_equal,
1111     .put  = put_int32,
1112 };
1113
1114 /* 32 bit int. Check that the received value is non-negative
1115  * and less than or equal to the one in the field.
1116  */
1117
1118 static int get_int32_le(QEMUFile *f, void *pv, size_t size)
1119 {
1120     int32_t *cur = pv;
1121     int32_t loaded;
1122     qemu_get_sbe32s(f, &loaded);
1123
1124     if (loaded >= 0 && loaded <= *cur) {
1125         *cur = loaded;
1126         return 0;
1127     }
1128     return -EINVAL;
1129 }
1130
1131 const VMStateInfo vmstate_info_int32_le = {
1132     .name = "int32 le",
1133     .get  = get_int32_le,
1134     .put  = put_int32,
1135 };
1136
1137 /* 64 bit int */
1138
1139 static int get_int64(QEMUFile *f, void *pv, size_t size)
1140 {
1141     int64_t *v = pv;
1142     qemu_get_sbe64s(f, v);
1143     return 0;
1144 }
1145
1146 static void put_int64(QEMUFile *f, void *pv, size_t size)
1147 {
1148     int64_t *v = pv;
1149     qemu_put_sbe64s(f, v);
1150 }
1151
1152 const VMStateInfo vmstate_info_int64 = {
1153     .name = "int64",
1154     .get  = get_int64,
1155     .put  = put_int64,
1156 };
1157
1158 /* 8 bit unsigned int */
1159
1160 static int get_uint8(QEMUFile *f, void *pv, size_t size)
1161 {
1162     uint8_t *v = pv;
1163     qemu_get_8s(f, v);
1164     return 0;
1165 }
1166
1167 static void put_uint8(QEMUFile *f, void *pv, size_t size)
1168 {
1169     uint8_t *v = pv;
1170     qemu_put_8s(f, v);
1171 }
1172
1173 const VMStateInfo vmstate_info_uint8 = {
1174     .name = "uint8",
1175     .get  = get_uint8,
1176     .put  = put_uint8,
1177 };
1178
1179 /* 16 bit unsigned int */
1180
1181 static int get_uint16(QEMUFile *f, void *pv, size_t size)
1182 {
1183     uint16_t *v = pv;
1184     qemu_get_be16s(f, v);
1185     return 0;
1186 }
1187
1188 static void put_uint16(QEMUFile *f, void *pv, size_t size)
1189 {
1190     uint16_t *v = pv;
1191     qemu_put_be16s(f, v);
1192 }
1193
1194 const VMStateInfo vmstate_info_uint16 = {
1195     .name = "uint16",
1196     .get  = get_uint16,
1197     .put  = put_uint16,
1198 };
1199
1200 /* 32 bit unsigned int */
1201
1202 static int get_uint32(QEMUFile *f, void *pv, size_t size)
1203 {
1204     uint32_t *v = pv;
1205     qemu_get_be32s(f, v);
1206     return 0;
1207 }
1208
1209 static void put_uint32(QEMUFile *f, void *pv, size_t size)
1210 {
1211     uint32_t *v = pv;
1212     qemu_put_be32s(f, v);
1213 }
1214
1215 const VMStateInfo vmstate_info_uint32 = {
1216     .name = "uint32",
1217     .get  = get_uint32,
1218     .put  = put_uint32,
1219 };
1220
1221 /* 32 bit uint. See that the received value is the same than the one
1222    in the field */
1223
1224 static int get_uint32_equal(QEMUFile *f, void *pv, size_t size)
1225 {
1226     uint32_t *v = pv;
1227     uint32_t v2;
1228     qemu_get_be32s(f, &v2);
1229
1230     if (*v == v2) {
1231         return 0;
1232     }
1233     return -EINVAL;
1234 }
1235
1236 const VMStateInfo vmstate_info_uint32_equal = {
1237     .name = "uint32 equal",
1238     .get  = get_uint32_equal,
1239     .put  = put_uint32,
1240 };
1241
1242 /* 64 bit unsigned int */
1243
1244 static int get_uint64(QEMUFile *f, void *pv, size_t size)
1245 {
1246     uint64_t *v = pv;
1247     qemu_get_be64s(f, v);
1248     return 0;
1249 }
1250
1251 static void put_uint64(QEMUFile *f, void *pv, size_t size)
1252 {
1253     uint64_t *v = pv;
1254     qemu_put_be64s(f, v);
1255 }
1256
1257 const VMStateInfo vmstate_info_uint64 = {
1258     .name = "uint64",
1259     .get  = get_uint64,
1260     .put  = put_uint64,
1261 };
1262
1263 /* 64 bit unsigned int. See that the received value is the same than the one
1264    in the field */
1265
1266 static int get_uint64_equal(QEMUFile *f, void *pv, size_t size)
1267 {
1268     uint64_t *v = pv;
1269     uint64_t v2;
1270     qemu_get_be64s(f, &v2);
1271
1272     if (*v == v2) {
1273         return 0;
1274     }
1275     return -EINVAL;
1276 }
1277
1278 const VMStateInfo vmstate_info_uint64_equal = {
1279     .name = "int64 equal",
1280     .get  = get_uint64_equal,
1281     .put  = put_uint64,
1282 };
1283
1284 /* 8 bit int. See that the received value is the same than the one
1285    in the field */
1286
1287 static int get_uint8_equal(QEMUFile *f, void *pv, size_t size)
1288 {
1289     uint8_t *v = pv;
1290     uint8_t v2;
1291     qemu_get_8s(f, &v2);
1292
1293     if (*v == v2)
1294         return 0;
1295     return -EINVAL;
1296 }
1297
1298 const VMStateInfo vmstate_info_uint8_equal = {
1299     .name = "uint8 equal",
1300     .get  = get_uint8_equal,
1301     .put  = put_uint8,
1302 };
1303
1304 /* 16 bit unsigned int int. See that the received value is the same than the one
1305    in the field */
1306
1307 static int get_uint16_equal(QEMUFile *f, void *pv, size_t size)
1308 {
1309     uint16_t *v = pv;
1310     uint16_t v2;
1311     qemu_get_be16s(f, &v2);
1312
1313     if (*v == v2)
1314         return 0;
1315     return -EINVAL;
1316 }
1317
1318 const VMStateInfo vmstate_info_uint16_equal = {
1319     .name = "uint16 equal",
1320     .get  = get_uint16_equal,
1321     .put  = put_uint16,
1322 };
1323
1324 /* floating point */
1325
1326 static int get_float64(QEMUFile *f, void *pv, size_t size)
1327 {
1328     float64 *v = pv;
1329
1330     *v = make_float64(qemu_get_be64(f));
1331     return 0;
1332 }
1333
1334 static void put_float64(QEMUFile *f, void *pv, size_t size)
1335 {
1336     uint64_t *v = pv;
1337
1338     qemu_put_be64(f, float64_val(*v));
1339 }
1340
1341 const VMStateInfo vmstate_info_float64 = {
1342     .name = "float64",
1343     .get  = get_float64,
1344     .put  = put_float64,
1345 };
1346
1347 /* timers  */
1348
1349 static int get_timer(QEMUFile *f, void *pv, size_t size)
1350 {
1351     QEMUTimer *v = pv;
1352     timer_get(f, v);
1353     return 0;
1354 }
1355
1356 static void put_timer(QEMUFile *f, void *pv, size_t size)
1357 {
1358     QEMUTimer *v = pv;
1359     timer_put(f, v);
1360 }
1361
1362 const VMStateInfo vmstate_info_timer = {
1363     .name = "timer",
1364     .get  = get_timer,
1365     .put  = put_timer,
1366 };
1367
1368 /* uint8_t buffers */
1369
1370 static int get_buffer(QEMUFile *f, void *pv, size_t size)
1371 {
1372     uint8_t *v = pv;
1373     qemu_get_buffer(f, v, size);
1374     return 0;
1375 }
1376
1377 static void put_buffer(QEMUFile *f, void *pv, size_t size)
1378 {
1379     uint8_t *v = pv;
1380     qemu_put_buffer(f, v, size);
1381 }
1382
1383 const VMStateInfo vmstate_info_buffer = {
1384     .name = "buffer",
1385     .get  = get_buffer,
1386     .put  = put_buffer,
1387 };
1388
1389 /* unused buffers: space that was used for some fields that are
1390    not useful anymore */
1391
1392 static int get_unused_buffer(QEMUFile *f, void *pv, size_t size)
1393 {
1394     uint8_t buf[1024];
1395     int block_len;
1396
1397     while (size > 0) {
1398         block_len = MIN(sizeof(buf), size);
1399         size -= block_len;
1400         qemu_get_buffer(f, buf, block_len);
1401     }
1402    return 0;
1403 }
1404
1405 static void put_unused_buffer(QEMUFile *f, void *pv, size_t size)
1406 {
1407     static const uint8_t buf[1024];
1408     int block_len;
1409
1410     while (size > 0) {
1411         block_len = MIN(sizeof(buf), size);
1412         size -= block_len;
1413         qemu_put_buffer(f, buf, block_len);
1414     }
1415 }
1416
1417 const VMStateInfo vmstate_info_unused_buffer = {
1418     .name = "unused_buffer",
1419     .get  = get_unused_buffer,
1420     .put  = put_unused_buffer,
1421 };
1422
1423 /* bitmaps (as defined by bitmap.h). Note that size here is the size
1424  * of the bitmap in bits. The on-the-wire format of a bitmap is 64
1425  * bit words with the bits in big endian order. The in-memory format
1426  * is an array of 'unsigned long', which may be either 32 or 64 bits.
1427  */
1428 /* This is the number of 64 bit words sent over the wire */
1429 #define BITS_TO_U64S(nr) DIV_ROUND_UP(nr, 64)
1430 static int get_bitmap(QEMUFile *f, void *pv, size_t size)
1431 {
1432     unsigned long *bmp = pv;
1433     int i, idx = 0;
1434     for (i = 0; i < BITS_TO_U64S(size); i++) {
1435         uint64_t w = qemu_get_be64(f);
1436         bmp[idx++] = w;
1437         if (sizeof(unsigned long) == 4 && idx < BITS_TO_LONGS(size)) {
1438             bmp[idx++] = w >> 32;
1439         }
1440     }
1441     return 0;
1442 }
1443
1444 static void put_bitmap(QEMUFile *f, void *pv, size_t size)
1445 {
1446     unsigned long *bmp = pv;
1447     int i, idx = 0;
1448     for (i = 0; i < BITS_TO_U64S(size); i++) {
1449         uint64_t w = bmp[idx++];
1450         if (sizeof(unsigned long) == 4 && idx < BITS_TO_LONGS(size)) {
1451             w |= ((uint64_t)bmp[idx++]) << 32;
1452         }
1453         qemu_put_be64(f, w);
1454     }
1455 }
1456
1457 const VMStateInfo vmstate_info_bitmap = {
1458     .name = "bitmap",
1459     .get = get_bitmap,
1460     .put = put_bitmap,
1461 };
1462
1463 typedef struct CompatEntry {
1464     char idstr[256];
1465     int instance_id;
1466 } CompatEntry;
1467
1468 typedef struct SaveStateEntry {
1469     QTAILQ_ENTRY(SaveStateEntry) entry;
1470     char idstr[256];
1471     int instance_id;
1472     int alias_id;
1473     int version_id;
1474     int section_id;
1475     SaveVMHandlers *ops;
1476     const VMStateDescription *vmsd;
1477     void *opaque;
1478     CompatEntry *compat;
1479     int no_migrate;
1480     int is_ram;
1481 } SaveStateEntry;
1482
1483
1484 static QTAILQ_HEAD(savevm_handlers, SaveStateEntry) savevm_handlers =
1485     QTAILQ_HEAD_INITIALIZER(savevm_handlers);
1486 static int global_section_id;
1487
1488 static int calculate_new_instance_id(const char *idstr)
1489 {
1490     SaveStateEntry *se;
1491     int instance_id = 0;
1492
1493     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1494         if (strcmp(idstr, se->idstr) == 0
1495             && instance_id <= se->instance_id) {
1496             instance_id = se->instance_id + 1;
1497         }
1498     }
1499     return instance_id;
1500 }
1501
1502 static int calculate_compat_instance_id(const char *idstr)
1503 {
1504     SaveStateEntry *se;
1505     int instance_id = 0;
1506
1507     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1508         if (!se->compat)
1509             continue;
1510
1511         if (strcmp(idstr, se->compat->idstr) == 0
1512             && instance_id <= se->compat->instance_id) {
1513             instance_id = se->compat->instance_id + 1;
1514         }
1515     }
1516     return instance_id;
1517 }
1518
1519 /* TODO: Individual devices generally have very little idea about the rest
1520    of the system, so instance_id should be removed/replaced.
1521    Meanwhile pass -1 as instance_id if you do not already have a clearly
1522    distinguishing id for all instances of your device class. */
1523 int register_savevm_live(DeviceState *dev,
1524                          const char *idstr,
1525                          int instance_id,
1526                          int version_id,
1527                          SaveVMHandlers *ops,
1528                          void *opaque)
1529 {
1530     SaveStateEntry *se;
1531
1532     se = g_malloc0(sizeof(SaveStateEntry));
1533     se->version_id = version_id;
1534     se->section_id = global_section_id++;
1535     se->ops = ops;
1536     se->opaque = opaque;
1537     se->vmsd = NULL;
1538     se->no_migrate = 0;
1539     /* if this is a live_savem then set is_ram */
1540     if (ops->save_live_setup != NULL) {
1541         se->is_ram = 1;
1542     }
1543
1544     if (dev) {
1545         char *id = qdev_get_dev_path(dev);
1546         if (id) {
1547             pstrcpy(se->idstr, sizeof(se->idstr), id);
1548             pstrcat(se->idstr, sizeof(se->idstr), "/");
1549             g_free(id);
1550
1551             se->compat = g_malloc0(sizeof(CompatEntry));
1552             pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
1553             se->compat->instance_id = instance_id == -1 ?
1554                          calculate_compat_instance_id(idstr) : instance_id;
1555             instance_id = -1;
1556         }
1557     }
1558     pstrcat(se->idstr, sizeof(se->idstr), idstr);
1559
1560     if (instance_id == -1) {
1561         se->instance_id = calculate_new_instance_id(se->idstr);
1562     } else {
1563         se->instance_id = instance_id;
1564     }
1565     assert(!se->compat || se->instance_id == 0);
1566     /* add at the end of list */
1567     QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
1568     return 0;
1569 }
1570
1571 int register_savevm(DeviceState *dev,
1572                     const char *idstr,
1573                     int instance_id,
1574                     int version_id,
1575                     SaveStateHandler *save_state,
1576                     LoadStateHandler *load_state,
1577                     void *opaque)
1578 {
1579     SaveVMHandlers *ops = g_malloc0(sizeof(SaveVMHandlers));
1580     ops->save_state = save_state;
1581     ops->load_state = load_state;
1582     return register_savevm_live(dev, idstr, instance_id, version_id,
1583                                 ops, opaque);
1584 }
1585
1586 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
1587 {
1588     SaveStateEntry *se, *new_se;
1589     char id[256] = "";
1590
1591     if (dev) {
1592         char *path = qdev_get_dev_path(dev);
1593         if (path) {
1594             pstrcpy(id, sizeof(id), path);
1595             pstrcat(id, sizeof(id), "/");
1596             g_free(path);
1597         }
1598     }
1599     pstrcat(id, sizeof(id), idstr);
1600
1601     QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
1602         if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
1603             QTAILQ_REMOVE(&savevm_handlers, se, entry);
1604             if (se->compat) {
1605                 g_free(se->compat);
1606             }
1607             g_free(se->ops);
1608             g_free(se);
1609         }
1610     }
1611 }
1612
1613 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
1614                                    const VMStateDescription *vmsd,
1615                                    void *opaque, int alias_id,
1616                                    int required_for_version)
1617 {
1618     SaveStateEntry *se;
1619
1620     /* If this triggers, alias support can be dropped for the vmsd. */
1621     assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
1622
1623     se = g_malloc0(sizeof(SaveStateEntry));
1624     se->version_id = vmsd->version_id;
1625     se->section_id = global_section_id++;
1626     se->opaque = opaque;
1627     se->vmsd = vmsd;
1628     se->alias_id = alias_id;
1629     se->no_migrate = vmsd->unmigratable;
1630
1631     if (dev) {
1632         char *id = qdev_get_dev_path(dev);
1633         if (id) {
1634             pstrcpy(se->idstr, sizeof(se->idstr), id);
1635             pstrcat(se->idstr, sizeof(se->idstr), "/");
1636             g_free(id);
1637
1638             se->compat = g_malloc0(sizeof(CompatEntry));
1639             pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
1640             se->compat->instance_id = instance_id == -1 ?
1641                          calculate_compat_instance_id(vmsd->name) : instance_id;
1642             instance_id = -1;
1643         }
1644     }
1645     pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
1646
1647     if (instance_id == -1) {
1648         se->instance_id = calculate_new_instance_id(se->idstr);
1649     } else {
1650         se->instance_id = instance_id;
1651     }
1652     assert(!se->compat || se->instance_id == 0);
1653     /* add at the end of list */
1654     QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
1655     return 0;
1656 }
1657
1658 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
1659                         void *opaque)
1660 {
1661     SaveStateEntry *se, *new_se;
1662
1663     QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
1664         if (se->vmsd == vmsd && se->opaque == opaque) {
1665             QTAILQ_REMOVE(&savevm_handlers, se, entry);
1666             if (se->compat) {
1667                 g_free(se->compat);
1668             }
1669             g_free(se);
1670         }
1671     }
1672 }
1673
1674 static void vmstate_subsection_save(QEMUFile *f, const VMStateDescription *vmsd,
1675                                     void *opaque);
1676 static int vmstate_subsection_load(QEMUFile *f, const VMStateDescription *vmsd,
1677                                    void *opaque);
1678
1679 static int vmstate_n_elems(void *opaque, VMStateField *field)
1680 {
1681     int n_elems = 1;
1682
1683     if (field->flags & VMS_ARRAY) {
1684         n_elems = field->num;
1685     } else if (field->flags & VMS_VARRAY_INT32) {
1686         n_elems = *(int32_t *)(opaque+field->num_offset);
1687     } else if (field->flags & VMS_VARRAY_UINT32) {
1688         n_elems = *(uint32_t *)(opaque+field->num_offset);
1689     } else if (field->flags & VMS_VARRAY_UINT16) {
1690         n_elems = *(uint16_t *)(opaque+field->num_offset);
1691     } else if (field->flags & VMS_VARRAY_UINT8) {
1692         n_elems = *(uint8_t *)(opaque+field->num_offset);
1693     }
1694
1695     return n_elems;
1696 }
1697
1698 static int vmstate_size(void *opaque, VMStateField *field)
1699 {
1700     int size = field->size;
1701
1702     if (field->flags & VMS_VBUFFER) {
1703         size = *(int32_t *)(opaque+field->size_offset);
1704         if (field->flags & VMS_MULTIPLY) {
1705             size *= field->size;
1706         }
1707     }
1708
1709     return size;
1710 }
1711
1712 static void *vmstate_base_addr(void *opaque, VMStateField *field)
1713 {
1714     void *base_addr = opaque + field->offset;
1715
1716     if (field->flags & VMS_POINTER) {
1717         base_addr = *(void **)base_addr + field->start;
1718     }
1719
1720     return base_addr;
1721 }
1722
1723 int vmstate_load_state(QEMUFile *f, const VMStateDescription *vmsd,
1724                        void *opaque, int version_id)
1725 {
1726     VMStateField *field = vmsd->fields;
1727     int ret;
1728
1729     if (version_id > vmsd->version_id) {
1730         return -EINVAL;
1731     }
1732     if  (version_id < vmsd->minimum_version_id) {
1733         if (vmsd->load_state_old &&
1734             version_id >= vmsd->minimum_version_id_old) {
1735             return vmsd->load_state_old(f, opaque, version_id);
1736         }
1737         return -EINVAL;
1738     }
1739     if (vmsd->pre_load) {
1740         int ret = vmsd->pre_load(opaque);
1741         if (ret)
1742             return ret;
1743     }
1744     while(field->name) {
1745         if ((field->field_exists &&
1746              field->field_exists(opaque, version_id)) ||
1747             (!field->field_exists &&
1748              field->version_id <= version_id)) {
1749             void *base_addr = vmstate_base_addr(opaque, field);
1750             int i, n_elems = vmstate_n_elems(opaque, field);
1751             int size = vmstate_size(opaque, field);
1752
1753             for (i = 0; i < n_elems; i++) {
1754                 void *addr = base_addr + size * i;
1755
1756                 if (field->flags & VMS_ARRAY_OF_POINTER) {
1757                     addr = *(void **)addr;
1758                 }
1759                 if (field->flags & VMS_STRUCT) {
1760                     ret = vmstate_load_state(f, field->vmsd, addr, field->vmsd->version_id);
1761                 } else {
1762                     ret = field->info->get(f, addr, size);
1763
1764                 }
1765                 if (ret < 0) {
1766                     return ret;
1767                 }
1768             }
1769         } else if (field->flags & VMS_MUST_EXIST) {
1770             fprintf(stderr, "Input validation failed: %s/%s\n",
1771                     vmsd->name, field->name);
1772             return -1;
1773         }
1774         field++;
1775     }
1776     ret = vmstate_subsection_load(f, vmsd, opaque);
1777     if (ret != 0) {
1778         return ret;
1779     }
1780     if (vmsd->post_load) {
1781         return vmsd->post_load(opaque, version_id);
1782     }
1783     return 0;
1784 }
1785
1786 void vmstate_save_state(QEMUFile *f, const VMStateDescription *vmsd,
1787                         void *opaque)
1788 {
1789     VMStateField *field = vmsd->fields;
1790
1791     if (vmsd->pre_save) {
1792         vmsd->pre_save(opaque);
1793     }
1794     while(field->name) {
1795         if (!field->field_exists ||
1796             field->field_exists(opaque, vmsd->version_id)) {
1797             void *base_addr = vmstate_base_addr(opaque, field);
1798             int i, n_elems = vmstate_n_elems(opaque, field);
1799             int size = vmstate_size(opaque, field);
1800
1801             for (i = 0; i < n_elems; i++) {
1802                 void *addr = base_addr + size * i;
1803
1804                 if (field->flags & VMS_ARRAY_OF_POINTER) {
1805                     addr = *(void **)addr;
1806                 }
1807                 if (field->flags & VMS_STRUCT) {
1808                     vmstate_save_state(f, field->vmsd, addr);
1809                 } else {
1810                     field->info->put(f, addr, size);
1811                 }
1812             }
1813         } else {
1814             if (field->flags & VMS_MUST_EXIST) {
1815                 fprintf(stderr, "Output state validation failed: %s/%s\n",
1816                         vmsd->name, field->name);
1817                 assert(!(field->flags & VMS_MUST_EXIST));
1818             }
1819         }
1820         field++;
1821     }
1822     vmstate_subsection_save(f, vmsd, opaque);
1823 }
1824
1825 static int vmstate_load(QEMUFile *f, SaveStateEntry *se, int version_id)
1826 {
1827     if (!se->vmsd) {         /* Old style */
1828         return se->ops->load_state(f, se->opaque, version_id);
1829     }
1830     return vmstate_load_state(f, se->vmsd, se->opaque, version_id);
1831 }
1832
1833 static void vmstate_save(QEMUFile *f, SaveStateEntry *se)
1834 {
1835     if (!se->vmsd) {         /* Old style */
1836         se->ops->save_state(f, se->opaque);
1837         return;
1838     }
1839     vmstate_save_state(f,se->vmsd, se->opaque);
1840 }
1841
1842 #define QEMU_VM_FILE_MAGIC           0x5145564d
1843 #define QEMU_VM_FILE_VERSION_COMPAT  0x00000002
1844 #define QEMU_VM_FILE_VERSION         0x00000003
1845
1846 #define QEMU_VM_EOF                  0x00
1847 #define QEMU_VM_SECTION_START        0x01
1848 #define QEMU_VM_SECTION_PART         0x02
1849 #define QEMU_VM_SECTION_END          0x03
1850 #define QEMU_VM_SECTION_FULL         0x04
1851 #define QEMU_VM_SUBSECTION           0x05
1852
1853 bool qemu_savevm_state_blocked(Error **errp)
1854 {
1855     SaveStateEntry *se;
1856
1857     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1858         if (se->no_migrate) {
1859             error_set(errp, QERR_MIGRATION_NOT_SUPPORTED, se->idstr);
1860             return true;
1861         }
1862     }
1863     return false;
1864 }
1865
1866 void qemu_savevm_state_begin(QEMUFile *f,
1867                              const MigrationParams *params)
1868 {
1869     SaveStateEntry *se;
1870     int ret;
1871
1872     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1873         if (!se->ops || !se->ops->set_params) {
1874             continue;
1875         }
1876         se->ops->set_params(params, se->opaque);
1877     }
1878     
1879     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1880     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1881
1882     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1883         int len;
1884
1885         if (!se->ops || !se->ops->save_live_setup) {
1886             continue;
1887         }
1888         if (se->ops && se->ops->is_active) {
1889             if (!se->ops->is_active(se->opaque)) {
1890                 continue;
1891             }
1892         }
1893         /* Section type */
1894         qemu_put_byte(f, QEMU_VM_SECTION_START);
1895         qemu_put_be32(f, se->section_id);
1896
1897         /* ID string */
1898         len = strlen(se->idstr);
1899         qemu_put_byte(f, len);
1900         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1901
1902         qemu_put_be32(f, se->instance_id);
1903         qemu_put_be32(f, se->version_id);
1904
1905         ret = se->ops->save_live_setup(f, se->opaque);
1906         if (ret < 0) {
1907             qemu_file_set_error(f, ret);
1908             break;
1909         }
1910     }
1911 }
1912
1913 /*
1914  * this function has three return values:
1915  *   negative: there was one error, and we have -errno.
1916  *   0 : We haven't finished, caller have to go again
1917  *   1 : We have finished, we can go to complete phase
1918  */
1919 int qemu_savevm_state_iterate(QEMUFile *f)
1920 {
1921     SaveStateEntry *se;
1922     int ret = 1;
1923
1924     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1925         if (!se->ops || !se->ops->save_live_iterate) {
1926             continue;
1927         }
1928         if (se->ops && se->ops->is_active) {
1929             if (!se->ops->is_active(se->opaque)) {
1930                 continue;
1931             }
1932         }
1933         if (qemu_file_rate_limit(f)) {
1934             return 0;
1935         }
1936         trace_savevm_section_start();
1937         /* Section type */
1938         qemu_put_byte(f, QEMU_VM_SECTION_PART);
1939         qemu_put_be32(f, se->section_id);
1940
1941         ret = se->ops->save_live_iterate(f, se->opaque);
1942         trace_savevm_section_end(se->section_id);
1943
1944         if (ret < 0) {
1945             qemu_file_set_error(f, ret);
1946         }
1947         if (ret <= 0) {
1948             /* Do not proceed to the next vmstate before this one reported
1949                completion of the current stage. This serializes the migration
1950                and reduces the probability that a faster changing state is
1951                synchronized over and over again. */
1952             break;
1953         }
1954     }
1955     return ret;
1956 }
1957
1958 void qemu_savevm_state_complete(QEMUFile *f)
1959 {
1960     SaveStateEntry *se;
1961     int ret;
1962
1963     cpu_synchronize_all_states();
1964
1965     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1966         if (!se->ops || !se->ops->save_live_complete) {
1967             continue;
1968         }
1969         if (se->ops && se->ops->is_active) {
1970             if (!se->ops->is_active(se->opaque)) {
1971                 continue;
1972             }
1973         }
1974         trace_savevm_section_start();
1975         /* Section type */
1976         qemu_put_byte(f, QEMU_VM_SECTION_END);
1977         qemu_put_be32(f, se->section_id);
1978
1979         ret = se->ops->save_live_complete(f, se->opaque);
1980         trace_savevm_section_end(se->section_id);
1981         if (ret < 0) {
1982             qemu_file_set_error(f, ret);
1983             return;
1984         }
1985     }
1986
1987     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1988         int len;
1989
1990         if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1991             continue;
1992         }
1993         trace_savevm_section_start();
1994         /* Section type */
1995         qemu_put_byte(f, QEMU_VM_SECTION_FULL);
1996         qemu_put_be32(f, se->section_id);
1997
1998         /* ID string */
1999         len = strlen(se->idstr);
2000         qemu_put_byte(f, len);
2001         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
2002
2003         qemu_put_be32(f, se->instance_id);
2004         qemu_put_be32(f, se->version_id);
2005
2006         vmstate_save(f, se);
2007         trace_savevm_section_end(se->section_id);
2008     }
2009
2010     qemu_put_byte(f, QEMU_VM_EOF);
2011     qemu_fflush(f);
2012 }
2013
2014 uint64_t qemu_savevm_state_pending(QEMUFile *f, uint64_t max_size)
2015 {
2016     SaveStateEntry *se;
2017     uint64_t ret = 0;
2018
2019     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
2020         if (!se->ops || !se->ops->save_live_pending) {
2021             continue;
2022         }
2023         if (se->ops && se->ops->is_active) {
2024             if (!se->ops->is_active(se->opaque)) {
2025                 continue;
2026             }
2027         }
2028         ret += se->ops->save_live_pending(f, se->opaque, max_size);
2029     }
2030     return ret;
2031 }
2032
2033 void qemu_savevm_state_cancel(void)
2034 {
2035     SaveStateEntry *se;
2036
2037     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
2038         if (se->ops && se->ops->cancel) {
2039             se->ops->cancel(se->opaque);
2040         }
2041     }
2042 }
2043
2044 static int qemu_savevm_state(QEMUFile *f)
2045 {
2046     int ret;
2047     MigrationParams params = {
2048         .blk = 0,
2049         .shared = 0
2050     };
2051
2052     if (qemu_savevm_state_blocked(NULL)) {
2053         return -EINVAL;
2054     }
2055
2056     qemu_mutex_unlock_iothread();
2057     qemu_savevm_state_begin(f, &params);
2058     qemu_mutex_lock_iothread();
2059
2060     while (qemu_file_get_error(f) == 0) {
2061         if (qemu_savevm_state_iterate(f) > 0) {
2062             break;
2063         }
2064     }
2065
2066     ret = qemu_file_get_error(f);
2067     if (ret == 0) {
2068         qemu_savevm_state_complete(f);
2069         ret = qemu_file_get_error(f);
2070     }
2071     if (ret != 0) {
2072         qemu_savevm_state_cancel();
2073     }
2074     return ret;
2075 }
2076
2077 static int qemu_save_device_state(QEMUFile *f)
2078 {
2079     SaveStateEntry *se;
2080
2081     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
2082     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
2083
2084     cpu_synchronize_all_states();
2085
2086     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
2087         int len;
2088
2089         if (se->is_ram) {
2090             continue;
2091         }
2092         if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
2093             continue;
2094         }
2095
2096         /* Section type */
2097         qemu_put_byte(f, QEMU_VM_SECTION_FULL);
2098         qemu_put_be32(f, se->section_id);
2099
2100         /* ID string */
2101         len = strlen(se->idstr);
2102         qemu_put_byte(f, len);
2103         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
2104
2105         qemu_put_be32(f, se->instance_id);
2106         qemu_put_be32(f, se->version_id);
2107
2108         vmstate_save(f, se);
2109     }
2110
2111     qemu_put_byte(f, QEMU_VM_EOF);
2112
2113     return qemu_file_get_error(f);
2114 }
2115
2116 static SaveStateEntry *find_se(const char *idstr, int instance_id)
2117 {
2118     SaveStateEntry *se;
2119
2120     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
2121         if (!strcmp(se->idstr, idstr) &&
2122             (instance_id == se->instance_id ||
2123              instance_id == se->alias_id))
2124             return se;
2125         /* Migrating from an older version? */
2126         if (strstr(se->idstr, idstr) && se->compat) {
2127             if (!strcmp(se->compat->idstr, idstr) &&
2128                 (instance_id == se->compat->instance_id ||
2129                  instance_id == se->alias_id))
2130                 return se;
2131         }
2132     }
2133     return NULL;
2134 }
2135
2136 static const VMStateDescription *vmstate_get_subsection(const VMStateSubsection *sub, char *idstr)
2137 {
2138     while(sub && sub->needed) {
2139         if (strcmp(idstr, sub->vmsd->name) == 0) {
2140             return sub->vmsd;
2141         }
2142         sub++;
2143     }
2144     return NULL;
2145 }
2146
2147 static int vmstate_subsection_load(QEMUFile *f, const VMStateDescription *vmsd,
2148                                    void *opaque)
2149 {
2150     while (qemu_peek_byte(f, 0) == QEMU_VM_SUBSECTION) {
2151         char idstr[256];
2152         int ret;
2153         uint8_t version_id, len, size;
2154         const VMStateDescription *sub_vmsd;
2155
2156         len = qemu_peek_byte(f, 1);
2157         if (len < strlen(vmsd->name) + 1) {
2158             /* subsection name has be be "section_name/a" */
2159             return 0;
2160         }
2161         size = qemu_peek_buffer(f, (uint8_t *)idstr, len, 2);
2162         if (size != len) {
2163             return 0;
2164         }
2165         idstr[size] = 0;
2166
2167         if (strncmp(vmsd->name, idstr, strlen(vmsd->name)) != 0) {
2168             /* it don't have a valid subsection name */
2169             return 0;
2170         }
2171         sub_vmsd = vmstate_get_subsection(vmsd->subsections, idstr);
2172         if (sub_vmsd == NULL) {
2173             return -ENOENT;
2174         }
2175         qemu_file_skip(f, 1); /* subsection */
2176         qemu_file_skip(f, 1); /* len */
2177         qemu_file_skip(f, len); /* idstr */
2178         version_id = qemu_get_be32(f);
2179
2180         ret = vmstate_load_state(f, sub_vmsd, opaque, version_id);
2181         if (ret) {
2182             return ret;
2183         }
2184     }
2185     return 0;
2186 }
2187
2188 static void vmstate_subsection_save(QEMUFile *f, const VMStateDescription *vmsd,
2189                                     void *opaque)
2190 {
2191     const VMStateSubsection *sub = vmsd->subsections;
2192
2193     while (sub && sub->needed) {
2194         if (sub->needed(opaque)) {
2195             const VMStateDescription *vmsd = sub->vmsd;
2196             uint8_t len;
2197
2198             qemu_put_byte(f, QEMU_VM_SUBSECTION);
2199             len = strlen(vmsd->name);
2200             qemu_put_byte(f, len);
2201             qemu_put_buffer(f, (uint8_t *)vmsd->name, len);
2202             qemu_put_be32(f, vmsd->version_id);
2203             vmstate_save_state(f, vmsd, opaque);
2204         }
2205         sub++;
2206     }
2207 }
2208
2209 typedef struct LoadStateEntry {
2210     QLIST_ENTRY(LoadStateEntry) entry;
2211     SaveStateEntry *se;
2212     int section_id;
2213     int version_id;
2214 } LoadStateEntry;
2215
2216 int qemu_loadvm_state(QEMUFile *f)
2217 {
2218     QLIST_HEAD(, LoadStateEntry) loadvm_handlers =
2219         QLIST_HEAD_INITIALIZER(loadvm_handlers);
2220     LoadStateEntry *le, *new_le;
2221     uint8_t section_type;
2222     unsigned int v;
2223     int ret;
2224
2225     if (qemu_savevm_state_blocked(NULL)) {
2226         return -EINVAL;
2227     }
2228
2229     v = qemu_get_be32(f);
2230     if (v != QEMU_VM_FILE_MAGIC)
2231         return -EINVAL;
2232
2233     v = qemu_get_be32(f);
2234     if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2235         fprintf(stderr, "SaveVM v2 format is obsolete and don't work anymore\n");
2236         return -ENOTSUP;
2237     }
2238     if (v != QEMU_VM_FILE_VERSION)
2239         return -ENOTSUP;
2240
2241     while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
2242         uint32_t instance_id, version_id, section_id;
2243         SaveStateEntry *se;
2244         char idstr[257];
2245         int len;
2246
2247         switch (section_type) {
2248         case QEMU_VM_SECTION_START:
2249         case QEMU_VM_SECTION_FULL:
2250             /* Read section start */
2251             section_id = qemu_get_be32(f);
2252             len = qemu_get_byte(f);
2253             qemu_get_buffer(f, (uint8_t *)idstr, len);
2254             idstr[len] = 0;
2255             instance_id = qemu_get_be32(f);
2256             version_id = qemu_get_be32(f);
2257
2258             /* Find savevm section */
2259             se = find_se(idstr, instance_id);
2260             if (se == NULL) {
2261                 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
2262                 ret = -EINVAL;
2263                 goto out;
2264             }
2265
2266             /* Validate version */
2267             if (version_id > se->version_id) {
2268                 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
2269                         version_id, idstr, se->version_id);
2270                 ret = -EINVAL;
2271                 goto out;
2272             }
2273
2274             /* Add entry */
2275             le = g_malloc0(sizeof(*le));
2276
2277             le->se = se;
2278             le->section_id = section_id;
2279             le->version_id = version_id;
2280             QLIST_INSERT_HEAD(&loadvm_handlers, le, entry);
2281
2282             ret = vmstate_load(f, le->se, le->version_id);
2283             if (ret < 0) {
2284                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2285                         instance_id, idstr);
2286                 goto out;
2287             }
2288             break;
2289         case QEMU_VM_SECTION_PART:
2290         case QEMU_VM_SECTION_END:
2291             section_id = qemu_get_be32(f);
2292
2293             QLIST_FOREACH(le, &loadvm_handlers, entry) {
2294                 if (le->section_id == section_id) {
2295                     break;
2296                 }
2297             }
2298             if (le == NULL) {
2299                 fprintf(stderr, "Unknown savevm section %d\n", section_id);
2300                 ret = -EINVAL;
2301                 goto out;
2302             }
2303
2304             ret = vmstate_load(f, le->se, le->version_id);
2305             if (ret < 0) {
2306                 fprintf(stderr, "qemu: warning: error while loading state section id %d\n",
2307                         section_id);
2308                 goto out;
2309             }
2310             break;
2311         default:
2312             fprintf(stderr, "Unknown savevm section type %d\n", section_type);
2313             ret = -EINVAL;
2314             goto out;
2315         }
2316     }
2317
2318     cpu_synchronize_all_post_init();
2319
2320     ret = 0;
2321
2322 out:
2323     QLIST_FOREACH_SAFE(le, &loadvm_handlers, entry, new_le) {
2324         QLIST_REMOVE(le, entry);
2325         g_free(le);
2326     }
2327
2328     if (ret == 0) {
2329         ret = qemu_file_get_error(f);
2330     }
2331
2332     return ret;
2333 }
2334
2335 static BlockDriverState *find_vmstate_bs(void)
2336 {
2337     BlockDriverState *bs = NULL;
2338     while ((bs = bdrv_next(bs))) {
2339         if (bdrv_can_snapshot(bs)) {
2340             return bs;
2341         }
2342     }
2343     return NULL;
2344 }
2345
2346 /*
2347  * Deletes snapshots of a given name in all opened images.
2348  */
2349 static int del_existing_snapshots(Monitor *mon, const char *name)
2350 {
2351     BlockDriverState *bs;
2352     QEMUSnapshotInfo sn1, *snapshot = &sn1;
2353     Error *err = NULL;
2354
2355     bs = NULL;
2356     while ((bs = bdrv_next(bs))) {
2357         if (bdrv_can_snapshot(bs) &&
2358             bdrv_snapshot_find(bs, snapshot, name) >= 0)
2359         {
2360             bdrv_snapshot_delete_by_id_or_name(bs, name, &err);
2361             if (error_is_set(&err)) {
2362                 monitor_printf(mon,
2363                                "Error while deleting snapshot on device '%s':"
2364                                " %s\n",
2365                                bdrv_get_device_name(bs),
2366                                error_get_pretty(err));
2367                 error_free(err);
2368                 return -1;
2369             }
2370         }
2371     }
2372
2373     return 0;
2374 }
2375
2376 void do_savevm(Monitor *mon, const QDict *qdict)
2377 {
2378     BlockDriverState *bs, *bs1;
2379     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2380     int ret;
2381     QEMUFile *f;
2382     int saved_vm_running;
2383     uint64_t vm_state_size;
2384     qemu_timeval tv;
2385     struct tm tm;
2386     const char *name = qdict_get_try_str(qdict, "name");
2387
2388     /* Verify if there is a device that doesn't support snapshots and is writable */
2389     bs = NULL;
2390     while ((bs = bdrv_next(bs))) {
2391
2392         if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2393             continue;
2394         }
2395
2396         if (!bdrv_can_snapshot(bs)) {
2397             monitor_printf(mon, "Device '%s' is writable but does not support snapshots.\n",
2398                                bdrv_get_device_name(bs));
2399             return;
2400         }
2401     }
2402
2403     bs = find_vmstate_bs();
2404     if (!bs) {
2405         monitor_printf(mon, "No block device can accept snapshots\n");
2406         return;
2407     }
2408
2409     saved_vm_running = runstate_is_running();
2410     vm_stop(RUN_STATE_SAVE_VM);
2411
2412     memset(sn, 0, sizeof(*sn));
2413
2414     /* fill auxiliary fields */
2415     qemu_gettimeofday(&tv);
2416     sn->date_sec = tv.tv_sec;
2417     sn->date_nsec = tv.tv_usec * 1000;
2418     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2419
2420     if (name) {
2421         ret = bdrv_snapshot_find(bs, old_sn, name);
2422         if (ret >= 0) {
2423             pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2424             pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2425         } else {
2426             pstrcpy(sn->name, sizeof(sn->name), name);
2427         }
2428     } else {
2429         /* cast below needed for OpenBSD where tv_sec is still 'long' */
2430         localtime_r((const time_t *)&tv.tv_sec, &tm);
2431         strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2432     }
2433
2434     /* Delete old snapshots of the same name */
2435     if (name && del_existing_snapshots(mon, name) < 0) {
2436         goto the_end;
2437     }
2438
2439     /* save the VM state */
2440     f = qemu_fopen_bdrv(bs, 1);
2441     if (!f) {
2442         monitor_printf(mon, "Could not open VM state file\n");
2443         goto the_end;
2444     }
2445     ret = qemu_savevm_state(f);
2446     vm_state_size = qemu_ftell(f);
2447     qemu_fclose(f);
2448     if (ret < 0) {
2449         monitor_printf(mon, "Error %d while writing VM\n", ret);
2450         goto the_end;
2451     }
2452
2453     /* create the snapshots */
2454
2455     bs1 = NULL;
2456     while ((bs1 = bdrv_next(bs1))) {
2457         if (bdrv_can_snapshot(bs1)) {
2458             /* Write VM state size only to the image that contains the state */
2459             sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
2460             ret = bdrv_snapshot_create(bs1, sn);
2461             if (ret < 0) {
2462                 monitor_printf(mon, "Error while creating snapshot on '%s'\n",
2463                                bdrv_get_device_name(bs1));
2464             }
2465         }
2466     }
2467
2468  the_end:
2469     if (saved_vm_running)
2470         vm_start();
2471 }
2472
2473 void qmp_xen_save_devices_state(const char *filename, Error **errp)
2474 {
2475     QEMUFile *f;
2476     int saved_vm_running;
2477     int ret;
2478
2479     saved_vm_running = runstate_is_running();
2480     vm_stop(RUN_STATE_SAVE_VM);
2481
2482     f = qemu_fopen(filename, "wb");
2483     if (!f) {
2484         error_setg_file_open(errp, errno, filename);
2485         goto the_end;
2486     }
2487     ret = qemu_save_device_state(f);
2488     qemu_fclose(f);
2489     if (ret < 0) {
2490         error_set(errp, QERR_IO_ERROR);
2491     }
2492
2493  the_end:
2494     if (saved_vm_running)
2495         vm_start();
2496 }
2497
2498 int load_vmstate(const char *name)
2499 {
2500     BlockDriverState *bs, *bs_vm_state;
2501     QEMUSnapshotInfo sn;
2502     QEMUFile *f;
2503     int ret;
2504
2505     bs_vm_state = find_vmstate_bs();
2506     if (!bs_vm_state) {
2507         error_report("No block device supports snapshots");
2508         return -ENOTSUP;
2509     }
2510
2511     /* Don't even try to load empty VM states */
2512     ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2513     if (ret < 0) {
2514         return ret;
2515     } else if (sn.vm_state_size == 0) {
2516         error_report("This is a disk-only snapshot. Revert to it offline "
2517             "using qemu-img.");
2518         return -EINVAL;
2519     }
2520
2521     /* Verify if there is any device that doesn't support snapshots and is
2522     writable and check if the requested snapshot is available too. */
2523     bs = NULL;
2524     while ((bs = bdrv_next(bs))) {
2525
2526         if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2527             continue;
2528         }
2529
2530         if (!bdrv_can_snapshot(bs)) {
2531             error_report("Device '%s' is writable but does not support snapshots.",
2532                                bdrv_get_device_name(bs));
2533             return -ENOTSUP;
2534         }
2535
2536         ret = bdrv_snapshot_find(bs, &sn, name);
2537         if (ret < 0) {
2538             error_report("Device '%s' does not have the requested snapshot '%s'",
2539                            bdrv_get_device_name(bs), name);
2540             return ret;
2541         }
2542     }
2543
2544     /* Flush all IO requests so they don't interfere with the new state.  */
2545     bdrv_drain_all();
2546
2547     bs = NULL;
2548     while ((bs = bdrv_next(bs))) {
2549         if (bdrv_can_snapshot(bs)) {
2550             ret = bdrv_snapshot_goto(bs, name);
2551             if (ret < 0) {
2552                 error_report("Error %d while activating snapshot '%s' on '%s'",
2553                              ret, name, bdrv_get_device_name(bs));
2554                 return ret;
2555             }
2556         }
2557     }
2558
2559     /* restore the VM state */
2560     f = qemu_fopen_bdrv(bs_vm_state, 0);
2561     if (!f) {
2562         error_report("Could not open VM state file");
2563         return -EINVAL;
2564     }
2565
2566     qemu_system_reset(VMRESET_SILENT);
2567     ret = qemu_loadvm_state(f);
2568
2569     qemu_fclose(f);
2570     if (ret < 0) {
2571         error_report("Error %d while loading VM state", ret);
2572         return ret;
2573     }
2574
2575     return 0;
2576 }
2577
2578 void do_delvm(Monitor *mon, const QDict *qdict)
2579 {
2580     BlockDriverState *bs, *bs1;
2581     Error *err = NULL;
2582     const char *name = qdict_get_str(qdict, "name");
2583
2584     bs = find_vmstate_bs();
2585     if (!bs) {
2586         monitor_printf(mon, "No block device supports snapshots\n");
2587         return;
2588     }
2589
2590     bs1 = NULL;
2591     while ((bs1 = bdrv_next(bs1))) {
2592         if (bdrv_can_snapshot(bs1)) {
2593             bdrv_snapshot_delete_by_id_or_name(bs, name, &err);
2594             if (error_is_set(&err)) {
2595                 monitor_printf(mon,
2596                                "Error while deleting snapshot on device '%s':"
2597                                " %s\n",
2598                                bdrv_get_device_name(bs),
2599                                error_get_pretty(err));
2600                 error_free(err);
2601             }
2602         }
2603     }
2604 }
2605
2606 void do_info_snapshots(Monitor *mon, const QDict *qdict)
2607 {
2608     BlockDriverState *bs, *bs1;
2609     QEMUSnapshotInfo *sn_tab, *sn, s, *sn_info = &s;
2610     int nb_sns, i, ret, available;
2611     int total;
2612     int *available_snapshots;
2613
2614     bs = find_vmstate_bs();
2615     if (!bs) {
2616         monitor_printf(mon, "No available block device supports snapshots\n");
2617         return;
2618     }
2619
2620     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2621     if (nb_sns < 0) {
2622         monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);
2623         return;
2624     }
2625
2626     if (nb_sns == 0) {
2627         monitor_printf(mon, "There is no snapshot available.\n");
2628         return;
2629     }
2630
2631     available_snapshots = g_malloc0(sizeof(int) * nb_sns);
2632     total = 0;
2633     for (i = 0; i < nb_sns; i++) {
2634         sn = &sn_tab[i];
2635         available = 1;
2636         bs1 = NULL;
2637
2638         while ((bs1 = bdrv_next(bs1))) {
2639             if (bdrv_can_snapshot(bs1) && bs1 != bs) {
2640                 ret = bdrv_snapshot_find(bs1, sn_info, sn->id_str);
2641                 if (ret < 0) {
2642                     available = 0;
2643                     break;
2644                 }
2645             }
2646         }
2647
2648         if (available) {
2649             available_snapshots[total] = i;
2650             total++;
2651         }
2652     }
2653
2654     if (total > 0) {
2655         bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, NULL);
2656         monitor_printf(mon, "\n");
2657         for (i = 0; i < total; i++) {
2658             sn = &sn_tab[available_snapshots[i]];
2659             bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, sn);
2660             monitor_printf(mon, "\n");
2661         }
2662     } else {
2663         monitor_printf(mon, "There is no suitable snapshot available\n");
2664     }
2665
2666     g_free(sn_tab);
2667     g_free(available_snapshots);
2668
2669 }
2670
2671 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2672 {
2673     qemu_ram_set_idstr(memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK,
2674                        memory_region_name(mr), dev);
2675 }
2676
2677 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2678 {
2679     /* Nothing do to while the implementation is in RAMBlock */
2680 }
2681
2682 void vmstate_register_ram_global(MemoryRegion *mr)
2683 {
2684     vmstate_register_ram(mr, NULL);
2685 }