savevm: Add VMSTATE_UINT64_EQUAL helpers
[qemu/ar7.git] / savevm.c
blobcd98b0db1dacdb2e9e16a4519d522efbe14e038c
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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"
43 #define SELF_ANNOUNCE_ROUNDS 5
45 #ifndef ETH_P_RARP
46 #define ETH_P_RARP 0x8035
47 #endif
48 #define ARP_HTYPE_ETH 0x0001
49 #define ARP_PTYPE_IP 0x0800
50 #define ARP_OP_REQUEST_REV 0x3
52 static int announce_self_create(uint8_t *buf,
53 uint8_t *mac_addr)
55 /* Ethernet header. */
56 memset(buf, 0xff, 6); /* destination MAC addr */
57 memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
58 *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
60 /* RARP header. */
61 *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
62 *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
63 *(buf + 18) = 6; /* hardware addr length (ethernet) */
64 *(buf + 19) = 4; /* protocol addr length (IPv4) */
65 *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
66 memcpy(buf + 22, mac_addr, 6); /* source hw addr */
67 memset(buf + 28, 0x00, 4); /* source protocol addr */
68 memcpy(buf + 32, mac_addr, 6); /* target hw addr */
69 memset(buf + 38, 0x00, 4); /* target protocol addr */
71 /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
72 memset(buf + 42, 0x00, 18);
74 return 60; /* len (FCS will be added by hardware) */
77 static void qemu_announce_self_iter(NICState *nic, void *opaque)
79 uint8_t buf[60];
80 int len;
82 len = announce_self_create(buf, nic->conf->macaddr.a);
84 qemu_send_packet_raw(qemu_get_queue(nic), buf, len);
88 static void qemu_announce_self_once(void *opaque)
90 static int count = SELF_ANNOUNCE_ROUNDS;
91 QEMUTimer *timer = *(QEMUTimer **)opaque;
93 qemu_foreach_nic(qemu_announce_self_iter, NULL);
95 if (--count) {
96 /* delay 50ms, 150ms, 250ms, ... */
97 qemu_mod_timer(timer, qemu_get_clock_ms(rt_clock) +
98 50 + (SELF_ANNOUNCE_ROUNDS - count - 1) * 100);
99 } else {
100 qemu_del_timer(timer);
101 qemu_free_timer(timer);
105 void qemu_announce_self(void)
107 static QEMUTimer *timer;
108 timer = qemu_new_timer_ms(rt_clock, qemu_announce_self_once, &timer);
109 qemu_announce_self_once(&timer);
112 /***********************************************************/
113 /* savevm/loadvm support */
115 #define IO_BUF_SIZE 32768
117 struct QEMUFile {
118 const QEMUFileOps *ops;
119 void *opaque;
120 int is_write;
122 int64_t bytes_xfer;
123 int64_t xfer_limit;
125 int64_t pos; /* start of buffer when writing, end of buffer
126 when reading */
127 int buf_index;
128 int buf_size; /* 0 when writing */
129 uint8_t buf[IO_BUF_SIZE];
131 int last_error;
134 typedef struct QEMUFileStdio
136 FILE *stdio_file;
137 QEMUFile *file;
138 } QEMUFileStdio;
140 typedef struct QEMUFileSocket
142 int fd;
143 QEMUFile *file;
144 } QEMUFileSocket;
146 typedef struct {
147 Coroutine *co;
148 int fd;
149 } FDYieldUntilData;
151 static void fd_coroutine_enter(void *opaque)
153 FDYieldUntilData *data = opaque;
154 qemu_set_fd_handler(data->fd, NULL, NULL, NULL);
155 qemu_coroutine_enter(data->co, NULL);
159 * Yield until a file descriptor becomes readable
161 * Note that this function clobbers the handlers for the file descriptor.
163 static void coroutine_fn yield_until_fd_readable(int fd)
165 FDYieldUntilData data;
167 assert(qemu_in_coroutine());
168 data.co = qemu_coroutine_self();
169 data.fd = fd;
170 qemu_set_fd_handler(fd, fd_coroutine_enter, NULL, &data);
171 qemu_coroutine_yield();
174 static int socket_get_fd(void *opaque)
176 QEMUFileSocket *s = opaque;
178 return s->fd;
181 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
183 QEMUFileSocket *s = opaque;
184 ssize_t len;
186 for (;;) {
187 len = qemu_recv(s->fd, buf, size, 0);
188 if (len != -1) {
189 break;
191 if (socket_error() == EAGAIN) {
192 yield_until_fd_readable(s->fd);
193 } else if (socket_error() != EINTR) {
194 break;
198 if (len == -1) {
199 len = -socket_error();
201 return len;
204 static int socket_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
206 QEMUFileSocket *s = opaque;
207 ssize_t len;
209 len = qemu_send_full(s->fd, buf, size, 0);
210 if (len < size) {
211 len = -socket_error();
213 return len;
216 static int socket_close(void *opaque)
218 QEMUFileSocket *s = opaque;
219 closesocket(s->fd);
220 g_free(s);
221 return 0;
224 static int stdio_get_fd(void *opaque)
226 QEMUFileStdio *s = opaque;
228 return fileno(s->stdio_file);
231 static int stdio_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
233 QEMUFileStdio *s = opaque;
234 return fwrite(buf, 1, size, s->stdio_file);
237 static int stdio_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
239 QEMUFileStdio *s = opaque;
240 FILE *fp = s->stdio_file;
241 int bytes;
243 for (;;) {
244 clearerr(fp);
245 bytes = fread(buf, 1, size, fp);
246 if (bytes != 0 || !ferror(fp)) {
247 break;
249 if (errno == EAGAIN) {
250 yield_until_fd_readable(fileno(fp));
251 } else if (errno != EINTR) {
252 break;
255 return bytes;
258 static int stdio_pclose(void *opaque)
260 QEMUFileStdio *s = opaque;
261 int ret;
262 ret = pclose(s->stdio_file);
263 if (ret == -1) {
264 ret = -errno;
265 } else if (!WIFEXITED(ret) || WEXITSTATUS(ret) != 0) {
266 /* close succeeded, but non-zero exit code: */
267 ret = -EIO; /* fake errno value */
269 g_free(s);
270 return ret;
273 static int stdio_fclose(void *opaque)
275 QEMUFileStdio *s = opaque;
276 int ret = 0;
278 if (s->file->ops->put_buffer) {
279 int fd = fileno(s->stdio_file);
280 struct stat st;
282 ret = fstat(fd, &st);
283 if (ret == 0 && S_ISREG(st.st_mode)) {
285 * If the file handle is a regular file make sure the
286 * data is flushed to disk before signaling success.
288 ret = fsync(fd);
289 if (ret != 0) {
290 ret = -errno;
291 return ret;
295 if (fclose(s->stdio_file) == EOF) {
296 ret = -errno;
298 g_free(s);
299 return ret;
302 static const QEMUFileOps stdio_pipe_read_ops = {
303 .get_fd = stdio_get_fd,
304 .get_buffer = stdio_get_buffer,
305 .close = stdio_pclose
308 static const QEMUFileOps stdio_pipe_write_ops = {
309 .get_fd = stdio_get_fd,
310 .put_buffer = stdio_put_buffer,
311 .close = stdio_pclose
314 QEMUFile *qemu_popen_cmd(const char *command, const char *mode)
316 FILE *stdio_file;
317 QEMUFileStdio *s;
319 stdio_file = popen(command, mode);
320 if (stdio_file == NULL) {
321 return NULL;
324 if (mode == NULL || (mode[0] != 'r' && mode[0] != 'w') || mode[1] != 0) {
325 fprintf(stderr, "qemu_popen: Argument validity check failed\n");
326 return NULL;
329 s = g_malloc0(sizeof(QEMUFileStdio));
331 s->stdio_file = stdio_file;
333 if(mode[0] == 'r') {
334 s->file = qemu_fopen_ops(s, &stdio_pipe_read_ops);
335 } else {
336 s->file = qemu_fopen_ops(s, &stdio_pipe_write_ops);
338 return s->file;
341 static const QEMUFileOps stdio_file_read_ops = {
342 .get_fd = stdio_get_fd,
343 .get_buffer = stdio_get_buffer,
344 .close = stdio_fclose
347 static const QEMUFileOps stdio_file_write_ops = {
348 .get_fd = stdio_get_fd,
349 .put_buffer = stdio_put_buffer,
350 .close = stdio_fclose
353 QEMUFile *qemu_fdopen(int fd, const char *mode)
355 QEMUFileStdio *s;
357 if (mode == NULL ||
358 (mode[0] != 'r' && mode[0] != 'w') ||
359 mode[1] != 'b' || mode[2] != 0) {
360 fprintf(stderr, "qemu_fdopen: Argument validity check failed\n");
361 return NULL;
364 s = g_malloc0(sizeof(QEMUFileStdio));
365 s->stdio_file = fdopen(fd, mode);
366 if (!s->stdio_file)
367 goto fail;
369 if(mode[0] == 'r') {
370 s->file = qemu_fopen_ops(s, &stdio_file_read_ops);
371 } else {
372 s->file = qemu_fopen_ops(s, &stdio_file_write_ops);
374 return s->file;
376 fail:
377 g_free(s);
378 return NULL;
381 static const QEMUFileOps socket_read_ops = {
382 .get_fd = socket_get_fd,
383 .get_buffer = socket_get_buffer,
384 .close = socket_close
387 static const QEMUFileOps socket_write_ops = {
388 .get_fd = socket_get_fd,
389 .put_buffer = socket_put_buffer,
390 .close = socket_close
393 QEMUFile *qemu_fopen_socket(int fd, const char *mode)
395 QEMUFileSocket *s = g_malloc0(sizeof(QEMUFileSocket));
397 if (mode == NULL ||
398 (mode[0] != 'r' && mode[0] != 'w') ||
399 mode[1] != 'b' || mode[2] != 0) {
400 fprintf(stderr, "qemu_fopen: Argument validity check failed\n");
401 return NULL;
404 s->fd = fd;
405 if (mode[0] == 'w') {
406 socket_set_block(s->fd);
407 s->file = qemu_fopen_ops(s, &socket_write_ops);
408 } else {
409 s->file = qemu_fopen_ops(s, &socket_read_ops);
411 return s->file;
414 QEMUFile *qemu_fopen(const char *filename, const char *mode)
416 QEMUFileStdio *s;
418 if (mode == NULL ||
419 (mode[0] != 'r' && mode[0] != 'w') ||
420 mode[1] != 'b' || mode[2] != 0) {
421 fprintf(stderr, "qemu_fopen: Argument validity check failed\n");
422 return NULL;
425 s = g_malloc0(sizeof(QEMUFileStdio));
427 s->stdio_file = fopen(filename, mode);
428 if (!s->stdio_file)
429 goto fail;
431 if(mode[0] == 'w') {
432 s->file = qemu_fopen_ops(s, &stdio_file_write_ops);
433 } else {
434 s->file = qemu_fopen_ops(s, &stdio_file_read_ops);
436 return s->file;
437 fail:
438 g_free(s);
439 return NULL;
442 static int block_put_buffer(void *opaque, const uint8_t *buf,
443 int64_t pos, int size)
445 bdrv_save_vmstate(opaque, buf, pos, size);
446 return size;
449 static int block_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
451 return bdrv_load_vmstate(opaque, buf, pos, size);
454 static int bdrv_fclose(void *opaque)
456 return bdrv_flush(opaque);
459 static const QEMUFileOps bdrv_read_ops = {
460 .get_buffer = block_get_buffer,
461 .close = bdrv_fclose
464 static const QEMUFileOps bdrv_write_ops = {
465 .put_buffer = block_put_buffer,
466 .close = bdrv_fclose
469 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
471 if (is_writable)
472 return qemu_fopen_ops(bs, &bdrv_write_ops);
473 return qemu_fopen_ops(bs, &bdrv_read_ops);
476 QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)
478 QEMUFile *f;
480 f = g_malloc0(sizeof(QEMUFile));
482 f->opaque = opaque;
483 f->ops = ops;
484 f->is_write = 0;
485 return f;
488 int qemu_file_get_error(QEMUFile *f)
490 return f->last_error;
493 static void qemu_file_set_error(QEMUFile *f, int ret)
495 if (f->last_error == 0) {
496 f->last_error = ret;
500 /** Flushes QEMUFile buffer
503 static void qemu_fflush(QEMUFile *f)
505 int ret = 0;
507 if (!f->ops->put_buffer) {
508 return;
510 if (f->is_write && f->buf_index > 0) {
511 ret = f->ops->put_buffer(f->opaque, f->buf, f->pos, f->buf_index);
512 if (ret >= 0) {
513 f->pos += f->buf_index;
515 f->buf_index = 0;
517 if (ret < 0) {
518 qemu_file_set_error(f, ret);
522 static void qemu_fill_buffer(QEMUFile *f)
524 int len;
525 int pending;
527 if (!f->ops->get_buffer)
528 return;
530 if (f->is_write)
531 abort();
533 pending = f->buf_size - f->buf_index;
534 if (pending > 0) {
535 memmove(f->buf, f->buf + f->buf_index, pending);
537 f->buf_index = 0;
538 f->buf_size = pending;
540 len = f->ops->get_buffer(f->opaque, f->buf + pending, f->pos,
541 IO_BUF_SIZE - pending);
542 if (len > 0) {
543 f->buf_size += len;
544 f->pos += len;
545 } else if (len == 0) {
546 qemu_file_set_error(f, -EIO);
547 } else if (len != -EAGAIN)
548 qemu_file_set_error(f, len);
551 int qemu_get_fd(QEMUFile *f)
553 if (f->ops->get_fd) {
554 return f->ops->get_fd(f->opaque);
556 return -1;
559 /** Closes the file
561 * Returns negative error value if any error happened on previous operations or
562 * while closing the file. Returns 0 or positive number on success.
564 * The meaning of return value on success depends on the specific backend
565 * being used.
567 int qemu_fclose(QEMUFile *f)
569 int ret;
570 qemu_fflush(f);
571 ret = qemu_file_get_error(f);
573 if (f->ops->close) {
574 int ret2 = f->ops->close(f->opaque);
575 if (ret >= 0) {
576 ret = ret2;
579 /* If any error was spotted before closing, we should report it
580 * instead of the close() return value.
582 if (f->last_error) {
583 ret = f->last_error;
585 g_free(f);
586 return ret;
589 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
591 int l;
593 if (f->last_error) {
594 return;
597 if (f->is_write == 0 && f->buf_index > 0) {
598 fprintf(stderr,
599 "Attempted to write to buffer while read buffer is not empty\n");
600 abort();
603 while (size > 0) {
604 l = IO_BUF_SIZE - f->buf_index;
605 if (l > size)
606 l = size;
607 memcpy(f->buf + f->buf_index, buf, l);
608 f->is_write = 1;
609 f->buf_index += l;
610 f->bytes_xfer += l;
611 buf += l;
612 size -= l;
613 if (f->buf_index >= IO_BUF_SIZE) {
614 qemu_fflush(f);
615 if (qemu_file_get_error(f)) {
616 break;
622 void qemu_put_byte(QEMUFile *f, int v)
624 if (f->last_error) {
625 return;
628 if (f->is_write == 0 && f->buf_index > 0) {
629 fprintf(stderr,
630 "Attempted to write to buffer while read buffer is not empty\n");
631 abort();
634 f->buf[f->buf_index++] = v;
635 f->is_write = 1;
636 if (f->buf_index >= IO_BUF_SIZE) {
637 qemu_fflush(f);
641 static void qemu_file_skip(QEMUFile *f, int size)
643 if (f->buf_index + size <= f->buf_size) {
644 f->buf_index += size;
648 static int qemu_peek_buffer(QEMUFile *f, uint8_t *buf, int size, size_t offset)
650 int pending;
651 int index;
653 if (f->is_write) {
654 abort();
657 index = f->buf_index + offset;
658 pending = f->buf_size - index;
659 if (pending < size) {
660 qemu_fill_buffer(f);
661 index = f->buf_index + offset;
662 pending = f->buf_size - index;
665 if (pending <= 0) {
666 return 0;
668 if (size > pending) {
669 size = pending;
672 memcpy(buf, f->buf + index, size);
673 return size;
676 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
678 int pending = size;
679 int done = 0;
681 while (pending > 0) {
682 int res;
684 res = qemu_peek_buffer(f, buf, pending, 0);
685 if (res == 0) {
686 return done;
688 qemu_file_skip(f, res);
689 buf += res;
690 pending -= res;
691 done += res;
693 return done;
696 static int qemu_peek_byte(QEMUFile *f, int offset)
698 int index = f->buf_index + offset;
700 if (f->is_write) {
701 abort();
704 if (index >= f->buf_size) {
705 qemu_fill_buffer(f);
706 index = f->buf_index + offset;
707 if (index >= f->buf_size) {
708 return 0;
711 return f->buf[index];
714 int qemu_get_byte(QEMUFile *f)
716 int result;
718 result = qemu_peek_byte(f, 0);
719 qemu_file_skip(f, 1);
720 return result;
723 int64_t qemu_ftell(QEMUFile *f)
725 qemu_fflush(f);
726 return f->pos;
729 int qemu_file_rate_limit(QEMUFile *f)
731 if (qemu_file_get_error(f)) {
732 return 1;
734 if (f->xfer_limit > 0 && f->bytes_xfer > f->xfer_limit) {
735 return 1;
737 return 0;
740 int64_t qemu_file_get_rate_limit(QEMUFile *f)
742 return f->xfer_limit;
745 void qemu_file_set_rate_limit(QEMUFile *f, int64_t limit)
747 f->xfer_limit = limit;
750 void qemu_file_reset_rate_limit(QEMUFile *f)
752 f->bytes_xfer = 0;
755 void qemu_put_be16(QEMUFile *f, unsigned int v)
757 qemu_put_byte(f, v >> 8);
758 qemu_put_byte(f, v);
761 void qemu_put_be32(QEMUFile *f, unsigned int v)
763 qemu_put_byte(f, v >> 24);
764 qemu_put_byte(f, v >> 16);
765 qemu_put_byte(f, v >> 8);
766 qemu_put_byte(f, v);
769 void qemu_put_be64(QEMUFile *f, uint64_t v)
771 qemu_put_be32(f, v >> 32);
772 qemu_put_be32(f, v);
775 unsigned int qemu_get_be16(QEMUFile *f)
777 unsigned int v;
778 v = qemu_get_byte(f) << 8;
779 v |= qemu_get_byte(f);
780 return v;
783 unsigned int qemu_get_be32(QEMUFile *f)
785 unsigned int v;
786 v = qemu_get_byte(f) << 24;
787 v |= qemu_get_byte(f) << 16;
788 v |= qemu_get_byte(f) << 8;
789 v |= qemu_get_byte(f);
790 return v;
793 uint64_t qemu_get_be64(QEMUFile *f)
795 uint64_t v;
796 v = (uint64_t)qemu_get_be32(f) << 32;
797 v |= qemu_get_be32(f);
798 return v;
802 /* timer */
804 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
806 uint64_t expire_time;
808 expire_time = qemu_timer_expire_time_ns(ts);
809 qemu_put_be64(f, expire_time);
812 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
814 uint64_t expire_time;
816 expire_time = qemu_get_be64(f);
817 if (expire_time != -1) {
818 qemu_mod_timer_ns(ts, expire_time);
819 } else {
820 qemu_del_timer(ts);
825 /* bool */
827 static int get_bool(QEMUFile *f, void *pv, size_t size)
829 bool *v = pv;
830 *v = qemu_get_byte(f);
831 return 0;
834 static void put_bool(QEMUFile *f, void *pv, size_t size)
836 bool *v = pv;
837 qemu_put_byte(f, *v);
840 const VMStateInfo vmstate_info_bool = {
841 .name = "bool",
842 .get = get_bool,
843 .put = put_bool,
846 /* 8 bit int */
848 static int get_int8(QEMUFile *f, void *pv, size_t size)
850 int8_t *v = pv;
851 qemu_get_s8s(f, v);
852 return 0;
855 static void put_int8(QEMUFile *f, void *pv, size_t size)
857 int8_t *v = pv;
858 qemu_put_s8s(f, v);
861 const VMStateInfo vmstate_info_int8 = {
862 .name = "int8",
863 .get = get_int8,
864 .put = put_int8,
867 /* 16 bit int */
869 static int get_int16(QEMUFile *f, void *pv, size_t size)
871 int16_t *v = pv;
872 qemu_get_sbe16s(f, v);
873 return 0;
876 static void put_int16(QEMUFile *f, void *pv, size_t size)
878 int16_t *v = pv;
879 qemu_put_sbe16s(f, v);
882 const VMStateInfo vmstate_info_int16 = {
883 .name = "int16",
884 .get = get_int16,
885 .put = put_int16,
888 /* 32 bit int */
890 static int get_int32(QEMUFile *f, void *pv, size_t size)
892 int32_t *v = pv;
893 qemu_get_sbe32s(f, v);
894 return 0;
897 static void put_int32(QEMUFile *f, void *pv, size_t size)
899 int32_t *v = pv;
900 qemu_put_sbe32s(f, v);
903 const VMStateInfo vmstate_info_int32 = {
904 .name = "int32",
905 .get = get_int32,
906 .put = put_int32,
909 /* 32 bit int. See that the received value is the same than the one
910 in the field */
912 static int get_int32_equal(QEMUFile *f, void *pv, size_t size)
914 int32_t *v = pv;
915 int32_t v2;
916 qemu_get_sbe32s(f, &v2);
918 if (*v == v2)
919 return 0;
920 return -EINVAL;
923 const VMStateInfo vmstate_info_int32_equal = {
924 .name = "int32 equal",
925 .get = get_int32_equal,
926 .put = put_int32,
929 /* 32 bit int. See that the received value is the less or the same
930 than the one in the field */
932 static int get_int32_le(QEMUFile *f, void *pv, size_t size)
934 int32_t *old = pv;
935 int32_t new;
936 qemu_get_sbe32s(f, &new);
938 if (*old <= new)
939 return 0;
940 return -EINVAL;
943 const VMStateInfo vmstate_info_int32_le = {
944 .name = "int32 equal",
945 .get = get_int32_le,
946 .put = put_int32,
949 /* 64 bit int */
951 static int get_int64(QEMUFile *f, void *pv, size_t size)
953 int64_t *v = pv;
954 qemu_get_sbe64s(f, v);
955 return 0;
958 static void put_int64(QEMUFile *f, void *pv, size_t size)
960 int64_t *v = pv;
961 qemu_put_sbe64s(f, v);
964 const VMStateInfo vmstate_info_int64 = {
965 .name = "int64",
966 .get = get_int64,
967 .put = put_int64,
970 /* 8 bit unsigned int */
972 static int get_uint8(QEMUFile *f, void *pv, size_t size)
974 uint8_t *v = pv;
975 qemu_get_8s(f, v);
976 return 0;
979 static void put_uint8(QEMUFile *f, void *pv, size_t size)
981 uint8_t *v = pv;
982 qemu_put_8s(f, v);
985 const VMStateInfo vmstate_info_uint8 = {
986 .name = "uint8",
987 .get = get_uint8,
988 .put = put_uint8,
991 /* 16 bit unsigned int */
993 static int get_uint16(QEMUFile *f, void *pv, size_t size)
995 uint16_t *v = pv;
996 qemu_get_be16s(f, v);
997 return 0;
1000 static void put_uint16(QEMUFile *f, void *pv, size_t size)
1002 uint16_t *v = pv;
1003 qemu_put_be16s(f, v);
1006 const VMStateInfo vmstate_info_uint16 = {
1007 .name = "uint16",
1008 .get = get_uint16,
1009 .put = put_uint16,
1012 /* 32 bit unsigned int */
1014 static int get_uint32(QEMUFile *f, void *pv, size_t size)
1016 uint32_t *v = pv;
1017 qemu_get_be32s(f, v);
1018 return 0;
1021 static void put_uint32(QEMUFile *f, void *pv, size_t size)
1023 uint32_t *v = pv;
1024 qemu_put_be32s(f, v);
1027 const VMStateInfo vmstate_info_uint32 = {
1028 .name = "uint32",
1029 .get = get_uint32,
1030 .put = put_uint32,
1033 /* 32 bit uint. See that the received value is the same than the one
1034 in the field */
1036 static int get_uint32_equal(QEMUFile *f, void *pv, size_t size)
1038 uint32_t *v = pv;
1039 uint32_t v2;
1040 qemu_get_be32s(f, &v2);
1042 if (*v == v2) {
1043 return 0;
1045 return -EINVAL;
1048 const VMStateInfo vmstate_info_uint32_equal = {
1049 .name = "uint32 equal",
1050 .get = get_uint32_equal,
1051 .put = put_uint32,
1054 /* 64 bit unsigned int */
1056 static int get_uint64(QEMUFile *f, void *pv, size_t size)
1058 uint64_t *v = pv;
1059 qemu_get_be64s(f, v);
1060 return 0;
1063 static void put_uint64(QEMUFile *f, void *pv, size_t size)
1065 uint64_t *v = pv;
1066 qemu_put_be64s(f, v);
1069 const VMStateInfo vmstate_info_uint64 = {
1070 .name = "uint64",
1071 .get = get_uint64,
1072 .put = put_uint64,
1075 /* 64 bit unsigned int. See that the received value is the same than the one
1076 in the field */
1078 static int get_uint64_equal(QEMUFile *f, void *pv, size_t size)
1080 uint64_t *v = pv;
1081 uint64_t v2;
1082 qemu_get_be64s(f, &v2);
1084 if (*v == v2) {
1085 return 0;
1087 return -EINVAL;
1090 const VMStateInfo vmstate_info_uint64_equal = {
1091 .name = "int64 equal",
1092 .get = get_uint64_equal,
1093 .put = put_uint64,
1096 /* 8 bit int. See that the received value is the same than the one
1097 in the field */
1099 static int get_uint8_equal(QEMUFile *f, void *pv, size_t size)
1101 uint8_t *v = pv;
1102 uint8_t v2;
1103 qemu_get_8s(f, &v2);
1105 if (*v == v2)
1106 return 0;
1107 return -EINVAL;
1110 const VMStateInfo vmstate_info_uint8_equal = {
1111 .name = "uint8 equal",
1112 .get = get_uint8_equal,
1113 .put = put_uint8,
1116 /* 16 bit unsigned int int. See that the received value is the same than the one
1117 in the field */
1119 static int get_uint16_equal(QEMUFile *f, void *pv, size_t size)
1121 uint16_t *v = pv;
1122 uint16_t v2;
1123 qemu_get_be16s(f, &v2);
1125 if (*v == v2)
1126 return 0;
1127 return -EINVAL;
1130 const VMStateInfo vmstate_info_uint16_equal = {
1131 .name = "uint16 equal",
1132 .get = get_uint16_equal,
1133 .put = put_uint16,
1136 /* timers */
1138 static int get_timer(QEMUFile *f, void *pv, size_t size)
1140 QEMUTimer *v = pv;
1141 qemu_get_timer(f, v);
1142 return 0;
1145 static void put_timer(QEMUFile *f, void *pv, size_t size)
1147 QEMUTimer *v = pv;
1148 qemu_put_timer(f, v);
1151 const VMStateInfo vmstate_info_timer = {
1152 .name = "timer",
1153 .get = get_timer,
1154 .put = put_timer,
1157 /* uint8_t buffers */
1159 static int get_buffer(QEMUFile *f, void *pv, size_t size)
1161 uint8_t *v = pv;
1162 qemu_get_buffer(f, v, size);
1163 return 0;
1166 static void put_buffer(QEMUFile *f, void *pv, size_t size)
1168 uint8_t *v = pv;
1169 qemu_put_buffer(f, v, size);
1172 const VMStateInfo vmstate_info_buffer = {
1173 .name = "buffer",
1174 .get = get_buffer,
1175 .put = put_buffer,
1178 /* unused buffers: space that was used for some fields that are
1179 not useful anymore */
1181 static int get_unused_buffer(QEMUFile *f, void *pv, size_t size)
1183 uint8_t buf[1024];
1184 int block_len;
1186 while (size > 0) {
1187 block_len = MIN(sizeof(buf), size);
1188 size -= block_len;
1189 qemu_get_buffer(f, buf, block_len);
1191 return 0;
1194 static void put_unused_buffer(QEMUFile *f, void *pv, size_t size)
1196 static const uint8_t buf[1024];
1197 int block_len;
1199 while (size > 0) {
1200 block_len = MIN(sizeof(buf), size);
1201 size -= block_len;
1202 qemu_put_buffer(f, buf, block_len);
1206 const VMStateInfo vmstate_info_unused_buffer = {
1207 .name = "unused_buffer",
1208 .get = get_unused_buffer,
1209 .put = put_unused_buffer,
1212 /* bitmaps (as defined by bitmap.h). Note that size here is the size
1213 * of the bitmap in bits. The on-the-wire format of a bitmap is 64
1214 * bit words with the bits in big endian order. The in-memory format
1215 * is an array of 'unsigned long', which may be either 32 or 64 bits.
1217 /* This is the number of 64 bit words sent over the wire */
1218 #define BITS_TO_U64S(nr) DIV_ROUND_UP(nr, 64)
1219 static int get_bitmap(QEMUFile *f, void *pv, size_t size)
1221 unsigned long *bmp = pv;
1222 int i, idx = 0;
1223 for (i = 0; i < BITS_TO_U64S(size); i++) {
1224 uint64_t w = qemu_get_be64(f);
1225 bmp[idx++] = w;
1226 if (sizeof(unsigned long) == 4 && idx < BITS_TO_LONGS(size)) {
1227 bmp[idx++] = w >> 32;
1230 return 0;
1233 static void put_bitmap(QEMUFile *f, void *pv, size_t size)
1235 unsigned long *bmp = pv;
1236 int i, idx = 0;
1237 for (i = 0; i < BITS_TO_U64S(size); i++) {
1238 uint64_t w = bmp[idx++];
1239 if (sizeof(unsigned long) == 4 && idx < BITS_TO_LONGS(size)) {
1240 w |= ((uint64_t)bmp[idx++]) << 32;
1242 qemu_put_be64(f, w);
1246 const VMStateInfo vmstate_info_bitmap = {
1247 .name = "bitmap",
1248 .get = get_bitmap,
1249 .put = put_bitmap,
1252 typedef struct CompatEntry {
1253 char idstr[256];
1254 int instance_id;
1255 } CompatEntry;
1257 typedef struct SaveStateEntry {
1258 QTAILQ_ENTRY(SaveStateEntry) entry;
1259 char idstr[256];
1260 int instance_id;
1261 int alias_id;
1262 int version_id;
1263 int section_id;
1264 SaveVMHandlers *ops;
1265 const VMStateDescription *vmsd;
1266 void *opaque;
1267 CompatEntry *compat;
1268 int no_migrate;
1269 int is_ram;
1270 } SaveStateEntry;
1273 static QTAILQ_HEAD(savevm_handlers, SaveStateEntry) savevm_handlers =
1274 QTAILQ_HEAD_INITIALIZER(savevm_handlers);
1275 static int global_section_id;
1277 static int calculate_new_instance_id(const char *idstr)
1279 SaveStateEntry *se;
1280 int instance_id = 0;
1282 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1283 if (strcmp(idstr, se->idstr) == 0
1284 && instance_id <= se->instance_id) {
1285 instance_id = se->instance_id + 1;
1288 return instance_id;
1291 static int calculate_compat_instance_id(const char *idstr)
1293 SaveStateEntry *se;
1294 int instance_id = 0;
1296 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1297 if (!se->compat)
1298 continue;
1300 if (strcmp(idstr, se->compat->idstr) == 0
1301 && instance_id <= se->compat->instance_id) {
1302 instance_id = se->compat->instance_id + 1;
1305 return instance_id;
1308 /* TODO: Individual devices generally have very little idea about the rest
1309 of the system, so instance_id should be removed/replaced.
1310 Meanwhile pass -1 as instance_id if you do not already have a clearly
1311 distinguishing id for all instances of your device class. */
1312 int register_savevm_live(DeviceState *dev,
1313 const char *idstr,
1314 int instance_id,
1315 int version_id,
1316 SaveVMHandlers *ops,
1317 void *opaque)
1319 SaveStateEntry *se;
1321 se = g_malloc0(sizeof(SaveStateEntry));
1322 se->version_id = version_id;
1323 se->section_id = global_section_id++;
1324 se->ops = ops;
1325 se->opaque = opaque;
1326 se->vmsd = NULL;
1327 se->no_migrate = 0;
1328 /* if this is a live_savem then set is_ram */
1329 if (ops->save_live_setup != NULL) {
1330 se->is_ram = 1;
1333 if (dev) {
1334 char *id = qdev_get_dev_path(dev);
1335 if (id) {
1336 pstrcpy(se->idstr, sizeof(se->idstr), id);
1337 pstrcat(se->idstr, sizeof(se->idstr), "/");
1338 g_free(id);
1340 se->compat = g_malloc0(sizeof(CompatEntry));
1341 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
1342 se->compat->instance_id = instance_id == -1 ?
1343 calculate_compat_instance_id(idstr) : instance_id;
1344 instance_id = -1;
1347 pstrcat(se->idstr, sizeof(se->idstr), idstr);
1349 if (instance_id == -1) {
1350 se->instance_id = calculate_new_instance_id(se->idstr);
1351 } else {
1352 se->instance_id = instance_id;
1354 assert(!se->compat || se->instance_id == 0);
1355 /* add at the end of list */
1356 QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
1357 return 0;
1360 int register_savevm(DeviceState *dev,
1361 const char *idstr,
1362 int instance_id,
1363 int version_id,
1364 SaveStateHandler *save_state,
1365 LoadStateHandler *load_state,
1366 void *opaque)
1368 SaveVMHandlers *ops = g_malloc0(sizeof(SaveVMHandlers));
1369 ops->save_state = save_state;
1370 ops->load_state = load_state;
1371 return register_savevm_live(dev, idstr, instance_id, version_id,
1372 ops, opaque);
1375 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
1377 SaveStateEntry *se, *new_se;
1378 char id[256] = "";
1380 if (dev) {
1381 char *path = qdev_get_dev_path(dev);
1382 if (path) {
1383 pstrcpy(id, sizeof(id), path);
1384 pstrcat(id, sizeof(id), "/");
1385 g_free(path);
1388 pstrcat(id, sizeof(id), idstr);
1390 QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
1391 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
1392 QTAILQ_REMOVE(&savevm_handlers, se, entry);
1393 if (se->compat) {
1394 g_free(se->compat);
1396 g_free(se->ops);
1397 g_free(se);
1402 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
1403 const VMStateDescription *vmsd,
1404 void *opaque, int alias_id,
1405 int required_for_version)
1407 SaveStateEntry *se;
1409 /* If this triggers, alias support can be dropped for the vmsd. */
1410 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
1412 se = g_malloc0(sizeof(SaveStateEntry));
1413 se->version_id = vmsd->version_id;
1414 se->section_id = global_section_id++;
1415 se->opaque = opaque;
1416 se->vmsd = vmsd;
1417 se->alias_id = alias_id;
1418 se->no_migrate = vmsd->unmigratable;
1420 if (dev) {
1421 char *id = qdev_get_dev_path(dev);
1422 if (id) {
1423 pstrcpy(se->idstr, sizeof(se->idstr), id);
1424 pstrcat(se->idstr, sizeof(se->idstr), "/");
1425 g_free(id);
1427 se->compat = g_malloc0(sizeof(CompatEntry));
1428 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
1429 se->compat->instance_id = instance_id == -1 ?
1430 calculate_compat_instance_id(vmsd->name) : instance_id;
1431 instance_id = -1;
1434 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
1436 if (instance_id == -1) {
1437 se->instance_id = calculate_new_instance_id(se->idstr);
1438 } else {
1439 se->instance_id = instance_id;
1441 assert(!se->compat || se->instance_id == 0);
1442 /* add at the end of list */
1443 QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
1444 return 0;
1447 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
1448 void *opaque)
1450 SaveStateEntry *se, *new_se;
1452 QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
1453 if (se->vmsd == vmsd && se->opaque == opaque) {
1454 QTAILQ_REMOVE(&savevm_handlers, se, entry);
1455 if (se->compat) {
1456 g_free(se->compat);
1458 g_free(se);
1463 static void vmstate_subsection_save(QEMUFile *f, const VMStateDescription *vmsd,
1464 void *opaque);
1465 static int vmstate_subsection_load(QEMUFile *f, const VMStateDescription *vmsd,
1466 void *opaque);
1468 int vmstate_load_state(QEMUFile *f, const VMStateDescription *vmsd,
1469 void *opaque, int version_id)
1471 VMStateField *field = vmsd->fields;
1472 int ret;
1474 if (version_id > vmsd->version_id) {
1475 return -EINVAL;
1477 if (version_id < vmsd->minimum_version_id_old) {
1478 return -EINVAL;
1480 if (version_id < vmsd->minimum_version_id) {
1481 return vmsd->load_state_old(f, opaque, version_id);
1483 if (vmsd->pre_load) {
1484 int ret = vmsd->pre_load(opaque);
1485 if (ret)
1486 return ret;
1488 while(field->name) {
1489 if ((field->field_exists &&
1490 field->field_exists(opaque, version_id)) ||
1491 (!field->field_exists &&
1492 field->version_id <= version_id)) {
1493 void *base_addr = opaque + field->offset;
1494 int i, n_elems = 1;
1495 int size = field->size;
1497 if (field->flags & VMS_VBUFFER) {
1498 size = *(int32_t *)(opaque+field->size_offset);
1499 if (field->flags & VMS_MULTIPLY) {
1500 size *= field->size;
1503 if (field->flags & VMS_ARRAY) {
1504 n_elems = field->num;
1505 } else if (field->flags & VMS_VARRAY_INT32) {
1506 n_elems = *(int32_t *)(opaque+field->num_offset);
1507 } else if (field->flags & VMS_VARRAY_UINT32) {
1508 n_elems = *(uint32_t *)(opaque+field->num_offset);
1509 } else if (field->flags & VMS_VARRAY_UINT16) {
1510 n_elems = *(uint16_t *)(opaque+field->num_offset);
1511 } else if (field->flags & VMS_VARRAY_UINT8) {
1512 n_elems = *(uint8_t *)(opaque+field->num_offset);
1514 if (field->flags & VMS_POINTER) {
1515 base_addr = *(void **)base_addr + field->start;
1517 for (i = 0; i < n_elems; i++) {
1518 void *addr = base_addr + size * i;
1520 if (field->flags & VMS_ARRAY_OF_POINTER) {
1521 addr = *(void **)addr;
1523 if (field->flags & VMS_STRUCT) {
1524 ret = vmstate_load_state(f, field->vmsd, addr, field->vmsd->version_id);
1525 } else {
1526 ret = field->info->get(f, addr, size);
1529 if (ret < 0) {
1530 return ret;
1534 field++;
1536 ret = vmstate_subsection_load(f, vmsd, opaque);
1537 if (ret != 0) {
1538 return ret;
1540 if (vmsd->post_load) {
1541 return vmsd->post_load(opaque, version_id);
1543 return 0;
1546 void vmstate_save_state(QEMUFile *f, const VMStateDescription *vmsd,
1547 void *opaque)
1549 VMStateField *field = vmsd->fields;
1551 if (vmsd->pre_save) {
1552 vmsd->pre_save(opaque);
1554 while(field->name) {
1555 if (!field->field_exists ||
1556 field->field_exists(opaque, vmsd->version_id)) {
1557 void *base_addr = opaque + field->offset;
1558 int i, n_elems = 1;
1559 int size = field->size;
1561 if (field->flags & VMS_VBUFFER) {
1562 size = *(int32_t *)(opaque+field->size_offset);
1563 if (field->flags & VMS_MULTIPLY) {
1564 size *= field->size;
1567 if (field->flags & VMS_ARRAY) {
1568 n_elems = field->num;
1569 } else if (field->flags & VMS_VARRAY_INT32) {
1570 n_elems = *(int32_t *)(opaque+field->num_offset);
1571 } else if (field->flags & VMS_VARRAY_UINT32) {
1572 n_elems = *(uint32_t *)(opaque+field->num_offset);
1573 } else if (field->flags & VMS_VARRAY_UINT16) {
1574 n_elems = *(uint16_t *)(opaque+field->num_offset);
1575 } else if (field->flags & VMS_VARRAY_UINT8) {
1576 n_elems = *(uint8_t *)(opaque+field->num_offset);
1578 if (field->flags & VMS_POINTER) {
1579 base_addr = *(void **)base_addr + field->start;
1581 for (i = 0; i < n_elems; i++) {
1582 void *addr = base_addr + size * i;
1584 if (field->flags & VMS_ARRAY_OF_POINTER) {
1585 addr = *(void **)addr;
1587 if (field->flags & VMS_STRUCT) {
1588 vmstate_save_state(f, field->vmsd, addr);
1589 } else {
1590 field->info->put(f, addr, size);
1594 field++;
1596 vmstate_subsection_save(f, vmsd, opaque);
1599 static int vmstate_load(QEMUFile *f, SaveStateEntry *se, int version_id)
1601 if (!se->vmsd) { /* Old style */
1602 return se->ops->load_state(f, se->opaque, version_id);
1604 return vmstate_load_state(f, se->vmsd, se->opaque, version_id);
1607 static void vmstate_save(QEMUFile *f, SaveStateEntry *se)
1609 if (!se->vmsd) { /* Old style */
1610 se->ops->save_state(f, se->opaque);
1611 return;
1613 vmstate_save_state(f,se->vmsd, se->opaque);
1616 #define QEMU_VM_FILE_MAGIC 0x5145564d
1617 #define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
1618 #define QEMU_VM_FILE_VERSION 0x00000003
1620 #define QEMU_VM_EOF 0x00
1621 #define QEMU_VM_SECTION_START 0x01
1622 #define QEMU_VM_SECTION_PART 0x02
1623 #define QEMU_VM_SECTION_END 0x03
1624 #define QEMU_VM_SECTION_FULL 0x04
1625 #define QEMU_VM_SUBSECTION 0x05
1627 bool qemu_savevm_state_blocked(Error **errp)
1629 SaveStateEntry *se;
1631 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1632 if (se->no_migrate) {
1633 error_set(errp, QERR_MIGRATION_NOT_SUPPORTED, se->idstr);
1634 return true;
1637 return false;
1640 void qemu_savevm_state_begin(QEMUFile *f,
1641 const MigrationParams *params)
1643 SaveStateEntry *se;
1644 int ret;
1646 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1647 if (!se->ops || !se->ops->set_params) {
1648 continue;
1650 se->ops->set_params(params, se->opaque);
1653 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1654 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1656 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1657 int len;
1659 if (!se->ops || !se->ops->save_live_setup) {
1660 continue;
1662 if (se->ops && se->ops->is_active) {
1663 if (!se->ops->is_active(se->opaque)) {
1664 continue;
1667 /* Section type */
1668 qemu_put_byte(f, QEMU_VM_SECTION_START);
1669 qemu_put_be32(f, se->section_id);
1671 /* ID string */
1672 len = strlen(se->idstr);
1673 qemu_put_byte(f, len);
1674 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1676 qemu_put_be32(f, se->instance_id);
1677 qemu_put_be32(f, se->version_id);
1679 ret = se->ops->save_live_setup(f, se->opaque);
1680 if (ret < 0) {
1681 qemu_file_set_error(f, ret);
1682 break;
1688 * this function has three return values:
1689 * negative: there was one error, and we have -errno.
1690 * 0 : We haven't finished, caller have to go again
1691 * 1 : We have finished, we can go to complete phase
1693 int qemu_savevm_state_iterate(QEMUFile *f)
1695 SaveStateEntry *se;
1696 int ret = 1;
1698 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1699 if (!se->ops || !se->ops->save_live_iterate) {
1700 continue;
1702 if (se->ops && se->ops->is_active) {
1703 if (!se->ops->is_active(se->opaque)) {
1704 continue;
1707 if (qemu_file_rate_limit(f)) {
1708 return 0;
1710 trace_savevm_section_start();
1711 /* Section type */
1712 qemu_put_byte(f, QEMU_VM_SECTION_PART);
1713 qemu_put_be32(f, se->section_id);
1715 ret = se->ops->save_live_iterate(f, se->opaque);
1716 trace_savevm_section_end(se->section_id);
1718 if (ret < 0) {
1719 qemu_file_set_error(f, ret);
1721 if (ret <= 0) {
1722 /* Do not proceed to the next vmstate before this one reported
1723 completion of the current stage. This serializes the migration
1724 and reduces the probability that a faster changing state is
1725 synchronized over and over again. */
1726 break;
1729 return ret;
1732 void qemu_savevm_state_complete(QEMUFile *f)
1734 SaveStateEntry *se;
1735 int ret;
1737 cpu_synchronize_all_states();
1739 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1740 if (!se->ops || !se->ops->save_live_complete) {
1741 continue;
1743 if (se->ops && se->ops->is_active) {
1744 if (!se->ops->is_active(se->opaque)) {
1745 continue;
1748 trace_savevm_section_start();
1749 /* Section type */
1750 qemu_put_byte(f, QEMU_VM_SECTION_END);
1751 qemu_put_be32(f, se->section_id);
1753 ret = se->ops->save_live_complete(f, se->opaque);
1754 trace_savevm_section_end(se->section_id);
1755 if (ret < 0) {
1756 qemu_file_set_error(f, ret);
1757 return;
1761 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1762 int len;
1764 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1765 continue;
1767 trace_savevm_section_start();
1768 /* Section type */
1769 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
1770 qemu_put_be32(f, se->section_id);
1772 /* ID string */
1773 len = strlen(se->idstr);
1774 qemu_put_byte(f, len);
1775 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1777 qemu_put_be32(f, se->instance_id);
1778 qemu_put_be32(f, se->version_id);
1780 vmstate_save(f, se);
1781 trace_savevm_section_end(se->section_id);
1784 qemu_put_byte(f, QEMU_VM_EOF);
1785 qemu_fflush(f);
1788 uint64_t qemu_savevm_state_pending(QEMUFile *f, uint64_t max_size)
1790 SaveStateEntry *se;
1791 uint64_t ret = 0;
1793 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1794 if (!se->ops || !se->ops->save_live_pending) {
1795 continue;
1797 if (se->ops && se->ops->is_active) {
1798 if (!se->ops->is_active(se->opaque)) {
1799 continue;
1802 ret += se->ops->save_live_pending(f, se->opaque, max_size);
1804 return ret;
1807 void qemu_savevm_state_cancel(void)
1809 SaveStateEntry *se;
1811 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1812 if (se->ops && se->ops->cancel) {
1813 se->ops->cancel(se->opaque);
1818 static int qemu_savevm_state(QEMUFile *f)
1820 int ret;
1821 MigrationParams params = {
1822 .blk = 0,
1823 .shared = 0
1826 if (qemu_savevm_state_blocked(NULL)) {
1827 return -EINVAL;
1830 qemu_mutex_unlock_iothread();
1831 qemu_savevm_state_begin(f, &params);
1832 qemu_mutex_lock_iothread();
1834 while (qemu_file_get_error(f) == 0) {
1835 if (qemu_savevm_state_iterate(f) > 0) {
1836 break;
1840 ret = qemu_file_get_error(f);
1841 if (ret == 0) {
1842 qemu_savevm_state_complete(f);
1843 ret = qemu_file_get_error(f);
1845 if (ret != 0) {
1846 qemu_savevm_state_cancel();
1848 return ret;
1851 static int qemu_save_device_state(QEMUFile *f)
1853 SaveStateEntry *se;
1855 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1856 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1858 cpu_synchronize_all_states();
1860 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1861 int len;
1863 if (se->is_ram) {
1864 continue;
1866 if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
1867 continue;
1870 /* Section type */
1871 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
1872 qemu_put_be32(f, se->section_id);
1874 /* ID string */
1875 len = strlen(se->idstr);
1876 qemu_put_byte(f, len);
1877 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1879 qemu_put_be32(f, se->instance_id);
1880 qemu_put_be32(f, se->version_id);
1882 vmstate_save(f, se);
1885 qemu_put_byte(f, QEMU_VM_EOF);
1887 return qemu_file_get_error(f);
1890 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1892 SaveStateEntry *se;
1894 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1895 if (!strcmp(se->idstr, idstr) &&
1896 (instance_id == se->instance_id ||
1897 instance_id == se->alias_id))
1898 return se;
1899 /* Migrating from an older version? */
1900 if (strstr(se->idstr, idstr) && se->compat) {
1901 if (!strcmp(se->compat->idstr, idstr) &&
1902 (instance_id == se->compat->instance_id ||
1903 instance_id == se->alias_id))
1904 return se;
1907 return NULL;
1910 static const VMStateDescription *vmstate_get_subsection(const VMStateSubsection *sub, char *idstr)
1912 while(sub && sub->needed) {
1913 if (strcmp(idstr, sub->vmsd->name) == 0) {
1914 return sub->vmsd;
1916 sub++;
1918 return NULL;
1921 static int vmstate_subsection_load(QEMUFile *f, const VMStateDescription *vmsd,
1922 void *opaque)
1924 while (qemu_peek_byte(f, 0) == QEMU_VM_SUBSECTION) {
1925 char idstr[256];
1926 int ret;
1927 uint8_t version_id, len, size;
1928 const VMStateDescription *sub_vmsd;
1930 len = qemu_peek_byte(f, 1);
1931 if (len < strlen(vmsd->name) + 1) {
1932 /* subsection name has be be "section_name/a" */
1933 return 0;
1935 size = qemu_peek_buffer(f, (uint8_t *)idstr, len, 2);
1936 if (size != len) {
1937 return 0;
1939 idstr[size] = 0;
1941 if (strncmp(vmsd->name, idstr, strlen(vmsd->name)) != 0) {
1942 /* it don't have a valid subsection name */
1943 return 0;
1945 sub_vmsd = vmstate_get_subsection(vmsd->subsections, idstr);
1946 if (sub_vmsd == NULL) {
1947 return -ENOENT;
1949 qemu_file_skip(f, 1); /* subsection */
1950 qemu_file_skip(f, 1); /* len */
1951 qemu_file_skip(f, len); /* idstr */
1952 version_id = qemu_get_be32(f);
1954 ret = vmstate_load_state(f, sub_vmsd, opaque, version_id);
1955 if (ret) {
1956 return ret;
1959 return 0;
1962 static void vmstate_subsection_save(QEMUFile *f, const VMStateDescription *vmsd,
1963 void *opaque)
1965 const VMStateSubsection *sub = vmsd->subsections;
1967 while (sub && sub->needed) {
1968 if (sub->needed(opaque)) {
1969 const VMStateDescription *vmsd = sub->vmsd;
1970 uint8_t len;
1972 qemu_put_byte(f, QEMU_VM_SUBSECTION);
1973 len = strlen(vmsd->name);
1974 qemu_put_byte(f, len);
1975 qemu_put_buffer(f, (uint8_t *)vmsd->name, len);
1976 qemu_put_be32(f, vmsd->version_id);
1977 vmstate_save_state(f, vmsd, opaque);
1979 sub++;
1983 typedef struct LoadStateEntry {
1984 QLIST_ENTRY(LoadStateEntry) entry;
1985 SaveStateEntry *se;
1986 int section_id;
1987 int version_id;
1988 } LoadStateEntry;
1990 int qemu_loadvm_state(QEMUFile *f)
1992 QLIST_HEAD(, LoadStateEntry) loadvm_handlers =
1993 QLIST_HEAD_INITIALIZER(loadvm_handlers);
1994 LoadStateEntry *le, *new_le;
1995 uint8_t section_type;
1996 unsigned int v;
1997 int ret;
1999 if (qemu_savevm_state_blocked(NULL)) {
2000 return -EINVAL;
2003 v = qemu_get_be32(f);
2004 if (v != QEMU_VM_FILE_MAGIC)
2005 return -EINVAL;
2007 v = qemu_get_be32(f);
2008 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
2009 fprintf(stderr, "SaveVM v2 format is obsolete and don't work anymore\n");
2010 return -ENOTSUP;
2012 if (v != QEMU_VM_FILE_VERSION)
2013 return -ENOTSUP;
2015 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
2016 uint32_t instance_id, version_id, section_id;
2017 SaveStateEntry *se;
2018 char idstr[257];
2019 int len;
2021 switch (section_type) {
2022 case QEMU_VM_SECTION_START:
2023 case QEMU_VM_SECTION_FULL:
2024 /* Read section start */
2025 section_id = qemu_get_be32(f);
2026 len = qemu_get_byte(f);
2027 qemu_get_buffer(f, (uint8_t *)idstr, len);
2028 idstr[len] = 0;
2029 instance_id = qemu_get_be32(f);
2030 version_id = qemu_get_be32(f);
2032 /* Find savevm section */
2033 se = find_se(idstr, instance_id);
2034 if (se == NULL) {
2035 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
2036 ret = -EINVAL;
2037 goto out;
2040 /* Validate version */
2041 if (version_id > se->version_id) {
2042 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
2043 version_id, idstr, se->version_id);
2044 ret = -EINVAL;
2045 goto out;
2048 /* Add entry */
2049 le = g_malloc0(sizeof(*le));
2051 le->se = se;
2052 le->section_id = section_id;
2053 le->version_id = version_id;
2054 QLIST_INSERT_HEAD(&loadvm_handlers, le, entry);
2056 ret = vmstate_load(f, le->se, le->version_id);
2057 if (ret < 0) {
2058 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
2059 instance_id, idstr);
2060 goto out;
2062 break;
2063 case QEMU_VM_SECTION_PART:
2064 case QEMU_VM_SECTION_END:
2065 section_id = qemu_get_be32(f);
2067 QLIST_FOREACH(le, &loadvm_handlers, entry) {
2068 if (le->section_id == section_id) {
2069 break;
2072 if (le == NULL) {
2073 fprintf(stderr, "Unknown savevm section %d\n", section_id);
2074 ret = -EINVAL;
2075 goto out;
2078 ret = vmstate_load(f, le->se, le->version_id);
2079 if (ret < 0) {
2080 fprintf(stderr, "qemu: warning: error while loading state section id %d\n",
2081 section_id);
2082 goto out;
2084 break;
2085 default:
2086 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
2087 ret = -EINVAL;
2088 goto out;
2092 cpu_synchronize_all_post_init();
2094 ret = 0;
2096 out:
2097 QLIST_FOREACH_SAFE(le, &loadvm_handlers, entry, new_le) {
2098 QLIST_REMOVE(le, entry);
2099 g_free(le);
2102 if (ret == 0) {
2103 ret = qemu_file_get_error(f);
2106 return ret;
2109 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
2110 const char *name)
2112 QEMUSnapshotInfo *sn_tab, *sn;
2113 int nb_sns, i, ret;
2115 ret = -ENOENT;
2116 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2117 if (nb_sns < 0)
2118 return ret;
2119 for(i = 0; i < nb_sns; i++) {
2120 sn = &sn_tab[i];
2121 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
2122 *sn_info = *sn;
2123 ret = 0;
2124 break;
2127 g_free(sn_tab);
2128 return ret;
2132 * Deletes snapshots of a given name in all opened images.
2134 static int del_existing_snapshots(Monitor *mon, const char *name)
2136 BlockDriverState *bs;
2137 QEMUSnapshotInfo sn1, *snapshot = &sn1;
2138 int ret;
2140 bs = NULL;
2141 while ((bs = bdrv_next(bs))) {
2142 if (bdrv_can_snapshot(bs) &&
2143 bdrv_snapshot_find(bs, snapshot, name) >= 0)
2145 ret = bdrv_snapshot_delete(bs, name);
2146 if (ret < 0) {
2147 monitor_printf(mon,
2148 "Error while deleting snapshot on '%s'\n",
2149 bdrv_get_device_name(bs));
2150 return -1;
2155 return 0;
2158 void do_savevm(Monitor *mon, const QDict *qdict)
2160 BlockDriverState *bs, *bs1;
2161 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2162 int ret;
2163 QEMUFile *f;
2164 int saved_vm_running;
2165 uint64_t vm_state_size;
2166 qemu_timeval tv;
2167 struct tm tm;
2168 const char *name = qdict_get_try_str(qdict, "name");
2170 /* Verify if there is a device that doesn't support snapshots and is writable */
2171 bs = NULL;
2172 while ((bs = bdrv_next(bs))) {
2174 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2175 continue;
2178 if (!bdrv_can_snapshot(bs)) {
2179 monitor_printf(mon, "Device '%s' is writable but does not support snapshots.\n",
2180 bdrv_get_device_name(bs));
2181 return;
2185 bs = bdrv_snapshots();
2186 if (!bs) {
2187 monitor_printf(mon, "No block device can accept snapshots\n");
2188 return;
2191 saved_vm_running = runstate_is_running();
2192 vm_stop(RUN_STATE_SAVE_VM);
2194 memset(sn, 0, sizeof(*sn));
2196 /* fill auxiliary fields */
2197 qemu_gettimeofday(&tv);
2198 sn->date_sec = tv.tv_sec;
2199 sn->date_nsec = tv.tv_usec * 1000;
2200 sn->vm_clock_nsec = qemu_get_clock_ns(vm_clock);
2202 if (name) {
2203 ret = bdrv_snapshot_find(bs, old_sn, name);
2204 if (ret >= 0) {
2205 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2206 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2207 } else {
2208 pstrcpy(sn->name, sizeof(sn->name), name);
2210 } else {
2211 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2212 localtime_r((const time_t *)&tv.tv_sec, &tm);
2213 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2216 /* Delete old snapshots of the same name */
2217 if (name && del_existing_snapshots(mon, name) < 0) {
2218 goto the_end;
2221 /* save the VM state */
2222 f = qemu_fopen_bdrv(bs, 1);
2223 if (!f) {
2224 monitor_printf(mon, "Could not open VM state file\n");
2225 goto the_end;
2227 ret = qemu_savevm_state(f);
2228 vm_state_size = qemu_ftell(f);
2229 qemu_fclose(f);
2230 if (ret < 0) {
2231 monitor_printf(mon, "Error %d while writing VM\n", ret);
2232 goto the_end;
2235 /* create the snapshots */
2237 bs1 = NULL;
2238 while ((bs1 = bdrv_next(bs1))) {
2239 if (bdrv_can_snapshot(bs1)) {
2240 /* Write VM state size only to the image that contains the state */
2241 sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
2242 ret = bdrv_snapshot_create(bs1, sn);
2243 if (ret < 0) {
2244 monitor_printf(mon, "Error while creating snapshot on '%s'\n",
2245 bdrv_get_device_name(bs1));
2250 the_end:
2251 if (saved_vm_running)
2252 vm_start();
2255 void qmp_xen_save_devices_state(const char *filename, Error **errp)
2257 QEMUFile *f;
2258 int saved_vm_running;
2259 int ret;
2261 saved_vm_running = runstate_is_running();
2262 vm_stop(RUN_STATE_SAVE_VM);
2264 f = qemu_fopen(filename, "wb");
2265 if (!f) {
2266 error_set(errp, QERR_OPEN_FILE_FAILED, filename);
2267 goto the_end;
2269 ret = qemu_save_device_state(f);
2270 qemu_fclose(f);
2271 if (ret < 0) {
2272 error_set(errp, QERR_IO_ERROR);
2275 the_end:
2276 if (saved_vm_running)
2277 vm_start();
2280 int load_vmstate(const char *name)
2282 BlockDriverState *bs, *bs_vm_state;
2283 QEMUSnapshotInfo sn;
2284 QEMUFile *f;
2285 int ret;
2287 bs_vm_state = bdrv_snapshots();
2288 if (!bs_vm_state) {
2289 error_report("No block device supports snapshots");
2290 return -ENOTSUP;
2293 /* Don't even try to load empty VM states */
2294 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2295 if (ret < 0) {
2296 return ret;
2297 } else if (sn.vm_state_size == 0) {
2298 error_report("This is a disk-only snapshot. Revert to it offline "
2299 "using qemu-img.");
2300 return -EINVAL;
2303 /* Verify if there is any device that doesn't support snapshots and is
2304 writable and check if the requested snapshot is available too. */
2305 bs = NULL;
2306 while ((bs = bdrv_next(bs))) {
2308 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2309 continue;
2312 if (!bdrv_can_snapshot(bs)) {
2313 error_report("Device '%s' is writable but does not support snapshots.",
2314 bdrv_get_device_name(bs));
2315 return -ENOTSUP;
2318 ret = bdrv_snapshot_find(bs, &sn, name);
2319 if (ret < 0) {
2320 error_report("Device '%s' does not have the requested snapshot '%s'",
2321 bdrv_get_device_name(bs), name);
2322 return ret;
2326 /* Flush all IO requests so they don't interfere with the new state. */
2327 bdrv_drain_all();
2329 bs = NULL;
2330 while ((bs = bdrv_next(bs))) {
2331 if (bdrv_can_snapshot(bs)) {
2332 ret = bdrv_snapshot_goto(bs, name);
2333 if (ret < 0) {
2334 error_report("Error %d while activating snapshot '%s' on '%s'",
2335 ret, name, bdrv_get_device_name(bs));
2336 return ret;
2341 /* restore the VM state */
2342 f = qemu_fopen_bdrv(bs_vm_state, 0);
2343 if (!f) {
2344 error_report("Could not open VM state file");
2345 return -EINVAL;
2348 qemu_system_reset(VMRESET_SILENT);
2349 ret = qemu_loadvm_state(f);
2351 qemu_fclose(f);
2352 if (ret < 0) {
2353 error_report("Error %d while loading VM state", ret);
2354 return ret;
2357 return 0;
2360 void do_delvm(Monitor *mon, const QDict *qdict)
2362 BlockDriverState *bs, *bs1;
2363 int ret;
2364 const char *name = qdict_get_str(qdict, "name");
2366 bs = bdrv_snapshots();
2367 if (!bs) {
2368 monitor_printf(mon, "No block device supports snapshots\n");
2369 return;
2372 bs1 = NULL;
2373 while ((bs1 = bdrv_next(bs1))) {
2374 if (bdrv_can_snapshot(bs1)) {
2375 ret = bdrv_snapshot_delete(bs1, name);
2376 if (ret < 0) {
2377 if (ret == -ENOTSUP)
2378 monitor_printf(mon,
2379 "Snapshots not supported on device '%s'\n",
2380 bdrv_get_device_name(bs1));
2381 else
2382 monitor_printf(mon, "Error %d while deleting snapshot on "
2383 "'%s'\n", ret, bdrv_get_device_name(bs1));
2389 void do_info_snapshots(Monitor *mon, const QDict *qdict)
2391 BlockDriverState *bs, *bs1;
2392 QEMUSnapshotInfo *sn_tab, *sn, s, *sn_info = &s;
2393 int nb_sns, i, ret, available;
2394 int total;
2395 int *available_snapshots;
2396 char buf[256];
2398 bs = bdrv_snapshots();
2399 if (!bs) {
2400 monitor_printf(mon, "No available block device supports snapshots\n");
2401 return;
2404 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2405 if (nb_sns < 0) {
2406 monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);
2407 return;
2410 if (nb_sns == 0) {
2411 monitor_printf(mon, "There is no snapshot available.\n");
2412 return;
2415 available_snapshots = g_malloc0(sizeof(int) * nb_sns);
2416 total = 0;
2417 for (i = 0; i < nb_sns; i++) {
2418 sn = &sn_tab[i];
2419 available = 1;
2420 bs1 = NULL;
2422 while ((bs1 = bdrv_next(bs1))) {
2423 if (bdrv_can_snapshot(bs1) && bs1 != bs) {
2424 ret = bdrv_snapshot_find(bs1, sn_info, sn->id_str);
2425 if (ret < 0) {
2426 available = 0;
2427 break;
2432 if (available) {
2433 available_snapshots[total] = i;
2434 total++;
2438 if (total > 0) {
2439 monitor_printf(mon, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
2440 for (i = 0; i < total; i++) {
2441 sn = &sn_tab[available_snapshots[i]];
2442 monitor_printf(mon, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
2444 } else {
2445 monitor_printf(mon, "There is no suitable snapshot available\n");
2448 g_free(sn_tab);
2449 g_free(available_snapshots);
2453 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2455 qemu_ram_set_idstr(memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK,
2456 memory_region_name(mr), dev);
2459 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2461 /* Nothing do to while the implementation is in RAMBlock */
2464 void vmstate_register_ram_global(MemoryRegion *mr)
2466 vmstate_register_ram(mr, NULL);