pseries: Consolidate hack for RTAS display-character usage
[qemu/agraf.git] / savevm.c
blob12fb20954feba27eca1bf9a584259a9c1696edd4
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.
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <time.h>
27 #include <errno.h>
28 #include <sys/time.h>
29 #include <zlib.h>
31 /* Needed early for CONFIG_BSD etc. */
32 #include "config-host.h"
34 #ifndef _WIN32
35 #include <sys/times.h>
36 #include <sys/wait.h>
37 #include <termios.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/resource.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <net/if.h>
44 #include <arpa/inet.h>
45 #include <dirent.h>
46 #include <netdb.h>
47 #include <sys/select.h>
48 #ifdef CONFIG_BSD
49 #include <sys/stat.h>
50 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
51 #include <libutil.h>
52 #else
53 #include <util.h>
54 #endif
55 #ifdef __linux__
56 #include <pty.h>
57 #include <malloc.h>
58 #include <linux/rtc.h>
59 #endif
60 #endif
61 #endif
63 #ifdef _WIN32
64 #include <windows.h>
65 #include <malloc.h>
66 #include <sys/timeb.h>
67 #include <mmsystem.h>
68 #define getopt_long_only getopt_long
69 #define memalign(align, size) malloc(size)
70 #endif
72 #include "qemu-common.h"
73 #include "hw/hw.h"
74 #include "hw/qdev.h"
75 #include "net.h"
76 #include "monitor.h"
77 #include "sysemu.h"
78 #include "qemu-timer.h"
79 #include "qemu-char.h"
80 #include "audio/audio.h"
81 #include "migration.h"
82 #include "qemu_socket.h"
83 #include "qemu-queue.h"
84 #include "qemu-timer.h"
85 #include "cpus.h"
86 #include "memory.h"
87 #include "qmp-commands.h"
89 #define SELF_ANNOUNCE_ROUNDS 5
91 #ifndef ETH_P_RARP
92 #define ETH_P_RARP 0x8035
93 #endif
94 #define ARP_HTYPE_ETH 0x0001
95 #define ARP_PTYPE_IP 0x0800
96 #define ARP_OP_REQUEST_REV 0x3
98 static int announce_self_create(uint8_t *buf,
99 uint8_t *mac_addr)
101 /* Ethernet header. */
102 memset(buf, 0xff, 6); /* destination MAC addr */
103 memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
104 *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
106 /* RARP header. */
107 *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
108 *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
109 *(buf + 18) = 6; /* hardware addr length (ethernet) */
110 *(buf + 19) = 4; /* protocol addr length (IPv4) */
111 *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
112 memcpy(buf + 22, mac_addr, 6); /* source hw addr */
113 memset(buf + 28, 0x00, 4); /* source protocol addr */
114 memcpy(buf + 32, mac_addr, 6); /* target hw addr */
115 memset(buf + 38, 0x00, 4); /* target protocol addr */
117 /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
118 memset(buf + 42, 0x00, 18);
120 return 60; /* len (FCS will be added by hardware) */
123 static void qemu_announce_self_iter(NICState *nic, void *opaque)
125 uint8_t buf[60];
126 int len;
128 len = announce_self_create(buf, nic->conf->macaddr.a);
130 qemu_send_packet_raw(&nic->nc, buf, len);
134 static void qemu_announce_self_once(void *opaque)
136 static int count = SELF_ANNOUNCE_ROUNDS;
137 QEMUTimer *timer = *(QEMUTimer **)opaque;
139 qemu_foreach_nic(qemu_announce_self_iter, NULL);
141 if (--count) {
142 /* delay 50ms, 150ms, 250ms, ... */
143 qemu_mod_timer(timer, qemu_get_clock_ms(rt_clock) +
144 50 + (SELF_ANNOUNCE_ROUNDS - count - 1) * 100);
145 } else {
146 qemu_del_timer(timer);
147 qemu_free_timer(timer);
151 void qemu_announce_self(void)
153 static QEMUTimer *timer;
154 timer = qemu_new_timer_ms(rt_clock, qemu_announce_self_once, &timer);
155 qemu_announce_self_once(&timer);
158 /***********************************************************/
159 /* savevm/loadvm support */
161 #define IO_BUF_SIZE 32768
163 struct QEMUFile {
164 QEMUFilePutBufferFunc *put_buffer;
165 QEMUFileGetBufferFunc *get_buffer;
166 QEMUFileCloseFunc *close;
167 QEMUFileRateLimit *rate_limit;
168 QEMUFileSetRateLimit *set_rate_limit;
169 QEMUFileGetRateLimit *get_rate_limit;
170 void *opaque;
171 int is_write;
173 int64_t buf_offset; /* start of buffer when writing, end of buffer
174 when reading */
175 int buf_index;
176 int buf_size; /* 0 when writing */
177 uint8_t buf[IO_BUF_SIZE];
179 int last_error;
182 typedef struct QEMUFileStdio
184 FILE *stdio_file;
185 QEMUFile *file;
186 } QEMUFileStdio;
188 typedef struct QEMUFileSocket
190 int fd;
191 QEMUFile *file;
192 } QEMUFileSocket;
194 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
196 QEMUFileSocket *s = opaque;
197 ssize_t len;
199 do {
200 len = qemu_recv(s->fd, buf, size, 0);
201 } while (len == -1 && socket_error() == EINTR);
203 if (len == -1)
204 len = -socket_error();
206 return len;
209 static int socket_close(void *opaque)
211 QEMUFileSocket *s = opaque;
212 g_free(s);
213 return 0;
216 static int stdio_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
218 QEMUFileStdio *s = opaque;
219 return fwrite(buf, 1, size, s->stdio_file);
222 static int stdio_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
224 QEMUFileStdio *s = opaque;
225 FILE *fp = s->stdio_file;
226 int bytes;
228 do {
229 clearerr(fp);
230 bytes = fread(buf, 1, size, fp);
231 } while ((bytes == 0) && ferror(fp) && (errno == EINTR));
232 return bytes;
235 static int stdio_pclose(void *opaque)
237 QEMUFileStdio *s = opaque;
238 int ret;
239 ret = pclose(s->stdio_file);
240 if (ret == -1) {
241 ret = -errno;
243 g_free(s);
244 return ret;
247 static int stdio_fclose(void *opaque)
249 QEMUFileStdio *s = opaque;
250 int ret = 0;
251 if (fclose(s->stdio_file) == EOF) {
252 ret = -errno;
254 g_free(s);
255 return ret;
258 QEMUFile *qemu_popen(FILE *stdio_file, const char *mode)
260 QEMUFileStdio *s;
262 if (stdio_file == NULL || mode == NULL || (mode[0] != 'r' && mode[0] != 'w') || mode[1] != 0) {
263 fprintf(stderr, "qemu_popen: Argument validity check failed\n");
264 return NULL;
267 s = g_malloc0(sizeof(QEMUFileStdio));
269 s->stdio_file = stdio_file;
271 if(mode[0] == 'r') {
272 s->file = qemu_fopen_ops(s, NULL, stdio_get_buffer, stdio_pclose,
273 NULL, NULL, NULL);
274 } else {
275 s->file = qemu_fopen_ops(s, stdio_put_buffer, NULL, stdio_pclose,
276 NULL, NULL, NULL);
278 return s->file;
281 QEMUFile *qemu_popen_cmd(const char *command, const char *mode)
283 FILE *popen_file;
285 popen_file = popen(command, mode);
286 if(popen_file == NULL) {
287 return NULL;
290 return qemu_popen(popen_file, mode);
293 int qemu_stdio_fd(QEMUFile *f)
295 QEMUFileStdio *p;
296 int fd;
298 p = (QEMUFileStdio *)f->opaque;
299 fd = fileno(p->stdio_file);
301 return fd;
304 QEMUFile *qemu_fdopen(int fd, const char *mode)
306 QEMUFileStdio *s;
308 if (mode == NULL ||
309 (mode[0] != 'r' && mode[0] != 'w') ||
310 mode[1] != 'b' || mode[2] != 0) {
311 fprintf(stderr, "qemu_fdopen: Argument validity check failed\n");
312 return NULL;
315 s = g_malloc0(sizeof(QEMUFileStdio));
316 s->stdio_file = fdopen(fd, mode);
317 if (!s->stdio_file)
318 goto fail;
320 if(mode[0] == 'r') {
321 s->file = qemu_fopen_ops(s, NULL, stdio_get_buffer, stdio_fclose,
322 NULL, NULL, NULL);
323 } else {
324 s->file = qemu_fopen_ops(s, stdio_put_buffer, NULL, stdio_fclose,
325 NULL, NULL, NULL);
327 return s->file;
329 fail:
330 g_free(s);
331 return NULL;
334 QEMUFile *qemu_fopen_socket(int fd)
336 QEMUFileSocket *s = g_malloc0(sizeof(QEMUFileSocket));
338 s->fd = fd;
339 s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close,
340 NULL, NULL, NULL);
341 return s->file;
344 static int file_put_buffer(void *opaque, const uint8_t *buf,
345 int64_t pos, int size)
347 QEMUFileStdio *s = opaque;
348 fseek(s->stdio_file, pos, SEEK_SET);
349 return fwrite(buf, 1, size, s->stdio_file);
352 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
354 QEMUFileStdio *s = opaque;
355 fseek(s->stdio_file, pos, SEEK_SET);
356 return fread(buf, 1, size, s->stdio_file);
359 QEMUFile *qemu_fopen(const char *filename, const char *mode)
361 QEMUFileStdio *s;
363 if (mode == NULL ||
364 (mode[0] != 'r' && mode[0] != 'w') ||
365 mode[1] != 'b' || mode[2] != 0) {
366 fprintf(stderr, "qemu_fopen: Argument validity check failed\n");
367 return NULL;
370 s = g_malloc0(sizeof(QEMUFileStdio));
372 s->stdio_file = fopen(filename, mode);
373 if (!s->stdio_file)
374 goto fail;
376 if(mode[0] == 'w') {
377 s->file = qemu_fopen_ops(s, file_put_buffer, NULL, stdio_fclose,
378 NULL, NULL, NULL);
379 } else {
380 s->file = qemu_fopen_ops(s, NULL, file_get_buffer, stdio_fclose,
381 NULL, NULL, NULL);
383 return s->file;
384 fail:
385 g_free(s);
386 return NULL;
389 static int block_put_buffer(void *opaque, const uint8_t *buf,
390 int64_t pos, int size)
392 bdrv_save_vmstate(opaque, buf, pos, size);
393 return size;
396 static int block_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
398 return bdrv_load_vmstate(opaque, buf, pos, size);
401 static int bdrv_fclose(void *opaque)
403 return 0;
406 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
408 if (is_writable)
409 return qemu_fopen_ops(bs, block_put_buffer, NULL, bdrv_fclose,
410 NULL, NULL, NULL);
411 return qemu_fopen_ops(bs, NULL, block_get_buffer, bdrv_fclose, NULL, NULL, NULL);
414 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
415 QEMUFileGetBufferFunc *get_buffer,
416 QEMUFileCloseFunc *close,
417 QEMUFileRateLimit *rate_limit,
418 QEMUFileSetRateLimit *set_rate_limit,
419 QEMUFileGetRateLimit *get_rate_limit)
421 QEMUFile *f;
423 f = g_malloc0(sizeof(QEMUFile));
425 f->opaque = opaque;
426 f->put_buffer = put_buffer;
427 f->get_buffer = get_buffer;
428 f->close = close;
429 f->rate_limit = rate_limit;
430 f->set_rate_limit = set_rate_limit;
431 f->get_rate_limit = get_rate_limit;
432 f->is_write = 0;
434 return f;
437 int qemu_file_get_error(QEMUFile *f)
439 return f->last_error;
442 void qemu_file_set_error(QEMUFile *f, int ret)
444 f->last_error = ret;
447 /** Sets last_error conditionally
449 * Sets last_error only if ret is negative _and_ no error
450 * was set before.
452 static void qemu_file_set_if_error(QEMUFile *f, int ret)
454 if (ret < 0 && !f->last_error) {
455 qemu_file_set_error(f, ret);
459 /** Flushes QEMUFile buffer
461 * In case of error, last_error is set.
463 void qemu_fflush(QEMUFile *f)
465 if (!f->put_buffer)
466 return;
468 if (f->is_write && f->buf_index > 0) {
469 int len;
471 len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
472 if (len > 0)
473 f->buf_offset += f->buf_index;
474 else
475 qemu_file_set_error(f, -EINVAL);
476 f->buf_index = 0;
480 static void qemu_fill_buffer(QEMUFile *f)
482 int len;
483 int pending;
485 if (!f->get_buffer)
486 return;
488 if (f->is_write)
489 abort();
491 pending = f->buf_size - f->buf_index;
492 if (pending > 0) {
493 memmove(f->buf, f->buf + f->buf_index, pending);
495 f->buf_index = 0;
496 f->buf_size = pending;
498 len = f->get_buffer(f->opaque, f->buf + pending, f->buf_offset,
499 IO_BUF_SIZE - pending);
500 if (len > 0) {
501 f->buf_size += len;
502 f->buf_offset += len;
503 } else if (len == 0) {
504 f->last_error = -EIO;
505 } else if (len != -EAGAIN)
506 qemu_file_set_error(f, len);
509 /** Calls close function and set last_error if needed
511 * Internal function. qemu_fflush() must be called before this.
513 * Returns f->close() return value, or 0 if close function is not set.
515 static int qemu_close(QEMUFile *f)
517 int ret = 0;
518 if (f->close) {
519 ret = f->close(f->opaque);
520 qemu_file_set_if_error(f, ret);
522 return ret;
525 /** Closes the file
527 * Returns negative error value if any error happened on previous operations or
528 * while closing the file. Returns 0 or positive number on success.
530 * The meaning of return value on success depends on the specific backend
531 * being used.
533 int qemu_fclose(QEMUFile *f)
535 int ret;
536 qemu_fflush(f);
537 ret = qemu_close(f);
538 /* If any error was spotted before closing, we should report it
539 * instead of the close() return value.
541 if (f->last_error) {
542 ret = f->last_error;
544 g_free(f);
545 return ret;
548 void qemu_file_put_notify(QEMUFile *f)
550 f->put_buffer(f->opaque, NULL, 0, 0);
553 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
555 int l;
557 if (!f->last_error && f->is_write == 0 && f->buf_index > 0) {
558 fprintf(stderr,
559 "Attempted to write to buffer while read buffer is not empty\n");
560 abort();
563 while (!f->last_error && size > 0) {
564 l = IO_BUF_SIZE - f->buf_index;
565 if (l > size)
566 l = size;
567 memcpy(f->buf + f->buf_index, buf, l);
568 f->is_write = 1;
569 f->buf_index += l;
570 buf += l;
571 size -= l;
572 if (f->buf_index >= IO_BUF_SIZE)
573 qemu_fflush(f);
577 void qemu_put_byte(QEMUFile *f, int v)
579 if (!f->last_error && f->is_write == 0 && f->buf_index > 0) {
580 fprintf(stderr,
581 "Attempted to write to buffer while read buffer is not empty\n");
582 abort();
585 f->buf[f->buf_index++] = v;
586 f->is_write = 1;
587 if (f->buf_index >= IO_BUF_SIZE)
588 qemu_fflush(f);
591 static void qemu_file_skip(QEMUFile *f, int size)
593 if (f->buf_index + size <= f->buf_size) {
594 f->buf_index += size;
598 static int qemu_peek_buffer(QEMUFile *f, uint8_t *buf, int size, size_t offset)
600 int pending;
601 int index;
603 if (f->is_write) {
604 abort();
607 index = f->buf_index + offset;
608 pending = f->buf_size - index;
609 if (pending < size) {
610 qemu_fill_buffer(f);
611 index = f->buf_index + offset;
612 pending = f->buf_size - index;
615 if (pending <= 0) {
616 return 0;
618 if (size > pending) {
619 size = pending;
622 memcpy(buf, f->buf + index, size);
623 return size;
626 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
628 int pending = size;
629 int done = 0;
631 while (pending > 0) {
632 int res;
634 res = qemu_peek_buffer(f, buf, pending, 0);
635 if (res == 0) {
636 return done;
638 qemu_file_skip(f, res);
639 buf += res;
640 pending -= res;
641 done += res;
643 return done;
646 static int qemu_peek_byte(QEMUFile *f, int offset)
648 int index = f->buf_index + offset;
650 if (f->is_write) {
651 abort();
654 if (index >= f->buf_size) {
655 qemu_fill_buffer(f);
656 index = f->buf_index + offset;
657 if (index >= f->buf_size) {
658 return 0;
661 return f->buf[index];
664 int qemu_get_byte(QEMUFile *f)
666 int result;
668 result = qemu_peek_byte(f, 0);
669 qemu_file_skip(f, 1);
670 return result;
673 int64_t qemu_ftell(QEMUFile *f)
675 return f->buf_offset - f->buf_size + f->buf_index;
678 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
680 if (whence == SEEK_SET) {
681 /* nothing to do */
682 } else if (whence == SEEK_CUR) {
683 pos += qemu_ftell(f);
684 } else {
685 /* SEEK_END not supported */
686 return -1;
688 if (f->put_buffer) {
689 qemu_fflush(f);
690 f->buf_offset = pos;
691 } else {
692 f->buf_offset = pos;
693 f->buf_index = 0;
694 f->buf_size = 0;
696 return pos;
699 int qemu_file_rate_limit(QEMUFile *f)
701 if (f->rate_limit)
702 return f->rate_limit(f->opaque);
704 return 0;
707 int64_t qemu_file_get_rate_limit(QEMUFile *f)
709 if (f->get_rate_limit)
710 return f->get_rate_limit(f->opaque);
712 return 0;
715 int64_t qemu_file_set_rate_limit(QEMUFile *f, int64_t new_rate)
717 /* any failed or completed migration keeps its state to allow probing of
718 * migration data, but has no associated file anymore */
719 if (f && f->set_rate_limit)
720 return f->set_rate_limit(f->opaque, new_rate);
722 return 0;
725 void qemu_put_be16(QEMUFile *f, unsigned int v)
727 qemu_put_byte(f, v >> 8);
728 qemu_put_byte(f, v);
731 void qemu_put_be32(QEMUFile *f, unsigned int v)
733 qemu_put_byte(f, v >> 24);
734 qemu_put_byte(f, v >> 16);
735 qemu_put_byte(f, v >> 8);
736 qemu_put_byte(f, v);
739 void qemu_put_be64(QEMUFile *f, uint64_t v)
741 qemu_put_be32(f, v >> 32);
742 qemu_put_be32(f, v);
745 unsigned int qemu_get_be16(QEMUFile *f)
747 unsigned int v;
748 v = qemu_get_byte(f) << 8;
749 v |= qemu_get_byte(f);
750 return v;
753 unsigned int qemu_get_be32(QEMUFile *f)
755 unsigned int v;
756 v = qemu_get_byte(f) << 24;
757 v |= qemu_get_byte(f) << 16;
758 v |= qemu_get_byte(f) << 8;
759 v |= qemu_get_byte(f);
760 return v;
763 uint64_t qemu_get_be64(QEMUFile *f)
765 uint64_t v;
766 v = (uint64_t)qemu_get_be32(f) << 32;
767 v |= qemu_get_be32(f);
768 return v;
772 /* timer */
774 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
776 uint64_t expire_time;
778 expire_time = qemu_timer_expire_time_ns(ts);
779 qemu_put_be64(f, expire_time);
782 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
784 uint64_t expire_time;
786 expire_time = qemu_get_be64(f);
787 if (expire_time != -1) {
788 qemu_mod_timer_ns(ts, expire_time);
789 } else {
790 qemu_del_timer(ts);
795 /* bool */
797 static int get_bool(QEMUFile *f, void *pv, size_t size)
799 bool *v = pv;
800 *v = qemu_get_byte(f);
801 return 0;
804 static void put_bool(QEMUFile *f, void *pv, size_t size)
806 bool *v = pv;
807 qemu_put_byte(f, *v);
810 const VMStateInfo vmstate_info_bool = {
811 .name = "bool",
812 .get = get_bool,
813 .put = put_bool,
816 /* 8 bit int */
818 static int get_int8(QEMUFile *f, void *pv, size_t size)
820 int8_t *v = pv;
821 qemu_get_s8s(f, v);
822 return 0;
825 static void put_int8(QEMUFile *f, void *pv, size_t size)
827 int8_t *v = pv;
828 qemu_put_s8s(f, v);
831 const VMStateInfo vmstate_info_int8 = {
832 .name = "int8",
833 .get = get_int8,
834 .put = put_int8,
837 /* 16 bit int */
839 static int get_int16(QEMUFile *f, void *pv, size_t size)
841 int16_t *v = pv;
842 qemu_get_sbe16s(f, v);
843 return 0;
846 static void put_int16(QEMUFile *f, void *pv, size_t size)
848 int16_t *v = pv;
849 qemu_put_sbe16s(f, v);
852 const VMStateInfo vmstate_info_int16 = {
853 .name = "int16",
854 .get = get_int16,
855 .put = put_int16,
858 /* 32 bit int */
860 static int get_int32(QEMUFile *f, void *pv, size_t size)
862 int32_t *v = pv;
863 qemu_get_sbe32s(f, v);
864 return 0;
867 static void put_int32(QEMUFile *f, void *pv, size_t size)
869 int32_t *v = pv;
870 qemu_put_sbe32s(f, v);
873 const VMStateInfo vmstate_info_int32 = {
874 .name = "int32",
875 .get = get_int32,
876 .put = put_int32,
879 /* 32 bit int. See that the received value is the same than the one
880 in the field */
882 static int get_int32_equal(QEMUFile *f, void *pv, size_t size)
884 int32_t *v = pv;
885 int32_t v2;
886 qemu_get_sbe32s(f, &v2);
888 if (*v == v2)
889 return 0;
890 return -EINVAL;
893 const VMStateInfo vmstate_info_int32_equal = {
894 .name = "int32 equal",
895 .get = get_int32_equal,
896 .put = put_int32,
899 /* 32 bit int. See that the received value is the less or the same
900 than the one in the field */
902 static int get_int32_le(QEMUFile *f, void *pv, size_t size)
904 int32_t *old = pv;
905 int32_t new;
906 qemu_get_sbe32s(f, &new);
908 if (*old <= new)
909 return 0;
910 return -EINVAL;
913 const VMStateInfo vmstate_info_int32_le = {
914 .name = "int32 equal",
915 .get = get_int32_le,
916 .put = put_int32,
919 /* 64 bit int */
921 static int get_int64(QEMUFile *f, void *pv, size_t size)
923 int64_t *v = pv;
924 qemu_get_sbe64s(f, v);
925 return 0;
928 static void put_int64(QEMUFile *f, void *pv, size_t size)
930 int64_t *v = pv;
931 qemu_put_sbe64s(f, v);
934 const VMStateInfo vmstate_info_int64 = {
935 .name = "int64",
936 .get = get_int64,
937 .put = put_int64,
940 /* 8 bit unsigned int */
942 static int get_uint8(QEMUFile *f, void *pv, size_t size)
944 uint8_t *v = pv;
945 qemu_get_8s(f, v);
946 return 0;
949 static void put_uint8(QEMUFile *f, void *pv, size_t size)
951 uint8_t *v = pv;
952 qemu_put_8s(f, v);
955 const VMStateInfo vmstate_info_uint8 = {
956 .name = "uint8",
957 .get = get_uint8,
958 .put = put_uint8,
961 /* 16 bit unsigned int */
963 static int get_uint16(QEMUFile *f, void *pv, size_t size)
965 uint16_t *v = pv;
966 qemu_get_be16s(f, v);
967 return 0;
970 static void put_uint16(QEMUFile *f, void *pv, size_t size)
972 uint16_t *v = pv;
973 qemu_put_be16s(f, v);
976 const VMStateInfo vmstate_info_uint16 = {
977 .name = "uint16",
978 .get = get_uint16,
979 .put = put_uint16,
982 /* 32 bit unsigned int */
984 static int get_uint32(QEMUFile *f, void *pv, size_t size)
986 uint32_t *v = pv;
987 qemu_get_be32s(f, v);
988 return 0;
991 static void put_uint32(QEMUFile *f, void *pv, size_t size)
993 uint32_t *v = pv;
994 qemu_put_be32s(f, v);
997 const VMStateInfo vmstate_info_uint32 = {
998 .name = "uint32",
999 .get = get_uint32,
1000 .put = put_uint32,
1003 /* 32 bit uint. See that the received value is the same than the one
1004 in the field */
1006 static int get_uint32_equal(QEMUFile *f, void *pv, size_t size)
1008 uint32_t *v = pv;
1009 uint32_t v2;
1010 qemu_get_be32s(f, &v2);
1012 if (*v == v2) {
1013 return 0;
1015 return -EINVAL;
1018 const VMStateInfo vmstate_info_uint32_equal = {
1019 .name = "uint32 equal",
1020 .get = get_uint32_equal,
1021 .put = put_uint32,
1024 /* 64 bit unsigned int */
1026 static int get_uint64(QEMUFile *f, void *pv, size_t size)
1028 uint64_t *v = pv;
1029 qemu_get_be64s(f, v);
1030 return 0;
1033 static void put_uint64(QEMUFile *f, void *pv, size_t size)
1035 uint64_t *v = pv;
1036 qemu_put_be64s(f, v);
1039 const VMStateInfo vmstate_info_uint64 = {
1040 .name = "uint64",
1041 .get = get_uint64,
1042 .put = put_uint64,
1045 /* 8 bit int. See that the received value is the same than the one
1046 in the field */
1048 static int get_uint8_equal(QEMUFile *f, void *pv, size_t size)
1050 uint8_t *v = pv;
1051 uint8_t v2;
1052 qemu_get_8s(f, &v2);
1054 if (*v == v2)
1055 return 0;
1056 return -EINVAL;
1059 const VMStateInfo vmstate_info_uint8_equal = {
1060 .name = "uint8 equal",
1061 .get = get_uint8_equal,
1062 .put = put_uint8,
1065 /* 16 bit unsigned int int. See that the received value is the same than the one
1066 in the field */
1068 static int get_uint16_equal(QEMUFile *f, void *pv, size_t size)
1070 uint16_t *v = pv;
1071 uint16_t v2;
1072 qemu_get_be16s(f, &v2);
1074 if (*v == v2)
1075 return 0;
1076 return -EINVAL;
1079 const VMStateInfo vmstate_info_uint16_equal = {
1080 .name = "uint16 equal",
1081 .get = get_uint16_equal,
1082 .put = put_uint16,
1085 /* timers */
1087 static int get_timer(QEMUFile *f, void *pv, size_t size)
1089 QEMUTimer *v = pv;
1090 qemu_get_timer(f, v);
1091 return 0;
1094 static void put_timer(QEMUFile *f, void *pv, size_t size)
1096 QEMUTimer *v = pv;
1097 qemu_put_timer(f, v);
1100 const VMStateInfo vmstate_info_timer = {
1101 .name = "timer",
1102 .get = get_timer,
1103 .put = put_timer,
1106 /* uint8_t buffers */
1108 static int get_buffer(QEMUFile *f, void *pv, size_t size)
1110 uint8_t *v = pv;
1111 qemu_get_buffer(f, v, size);
1112 return 0;
1115 static void put_buffer(QEMUFile *f, void *pv, size_t size)
1117 uint8_t *v = pv;
1118 qemu_put_buffer(f, v, size);
1121 const VMStateInfo vmstate_info_buffer = {
1122 .name = "buffer",
1123 .get = get_buffer,
1124 .put = put_buffer,
1127 /* unused buffers: space that was used for some fields that are
1128 not useful anymore */
1130 static int get_unused_buffer(QEMUFile *f, void *pv, size_t size)
1132 uint8_t buf[1024];
1133 int block_len;
1135 while (size > 0) {
1136 block_len = MIN(sizeof(buf), size);
1137 size -= block_len;
1138 qemu_get_buffer(f, buf, block_len);
1140 return 0;
1143 static void put_unused_buffer(QEMUFile *f, void *pv, size_t size)
1145 static const uint8_t buf[1024];
1146 int block_len;
1148 while (size > 0) {
1149 block_len = MIN(sizeof(buf), size);
1150 size -= block_len;
1151 qemu_put_buffer(f, buf, block_len);
1155 const VMStateInfo vmstate_info_unused_buffer = {
1156 .name = "unused_buffer",
1157 .get = get_unused_buffer,
1158 .put = put_unused_buffer,
1161 typedef struct CompatEntry {
1162 char idstr[256];
1163 int instance_id;
1164 } CompatEntry;
1166 typedef struct SaveStateEntry {
1167 QTAILQ_ENTRY(SaveStateEntry) entry;
1168 char idstr[256];
1169 int instance_id;
1170 int alias_id;
1171 int version_id;
1172 int section_id;
1173 SaveSetParamsHandler *set_params;
1174 SaveLiveStateHandler *save_live_state;
1175 SaveStateHandler *save_state;
1176 LoadStateHandler *load_state;
1177 const VMStateDescription *vmsd;
1178 void *opaque;
1179 CompatEntry *compat;
1180 int no_migrate;
1181 int is_ram;
1182 } SaveStateEntry;
1185 static QTAILQ_HEAD(savevm_handlers, SaveStateEntry) savevm_handlers =
1186 QTAILQ_HEAD_INITIALIZER(savevm_handlers);
1187 static int global_section_id;
1189 static int calculate_new_instance_id(const char *idstr)
1191 SaveStateEntry *se;
1192 int instance_id = 0;
1194 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1195 if (strcmp(idstr, se->idstr) == 0
1196 && instance_id <= se->instance_id) {
1197 instance_id = se->instance_id + 1;
1200 return instance_id;
1203 static int calculate_compat_instance_id(const char *idstr)
1205 SaveStateEntry *se;
1206 int instance_id = 0;
1208 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1209 if (!se->compat)
1210 continue;
1212 if (strcmp(idstr, se->compat->idstr) == 0
1213 && instance_id <= se->compat->instance_id) {
1214 instance_id = se->compat->instance_id + 1;
1217 return instance_id;
1220 /* TODO: Individual devices generally have very little idea about the rest
1221 of the system, so instance_id should be removed/replaced.
1222 Meanwhile pass -1 as instance_id if you do not already have a clearly
1223 distinguishing id for all instances of your device class. */
1224 int register_savevm_live(DeviceState *dev,
1225 const char *idstr,
1226 int instance_id,
1227 int version_id,
1228 SaveSetParamsHandler *set_params,
1229 SaveLiveStateHandler *save_live_state,
1230 SaveStateHandler *save_state,
1231 LoadStateHandler *load_state,
1232 void *opaque)
1234 SaveStateEntry *se;
1236 se = g_malloc0(sizeof(SaveStateEntry));
1237 se->version_id = version_id;
1238 se->section_id = global_section_id++;
1239 se->set_params = set_params;
1240 se->save_live_state = save_live_state;
1241 se->save_state = save_state;
1242 se->load_state = load_state;
1243 se->opaque = opaque;
1244 se->vmsd = NULL;
1245 se->no_migrate = 0;
1246 /* if this is a live_savem then set is_ram */
1247 if (save_live_state != NULL) {
1248 se->is_ram = 1;
1251 if (dev && dev->parent_bus && dev->parent_bus->info->get_dev_path) {
1252 char *id = dev->parent_bus->info->get_dev_path(dev);
1253 if (id) {
1254 pstrcpy(se->idstr, sizeof(se->idstr), id);
1255 pstrcat(se->idstr, sizeof(se->idstr), "/");
1256 g_free(id);
1258 se->compat = g_malloc0(sizeof(CompatEntry));
1259 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
1260 se->compat->instance_id = instance_id == -1 ?
1261 calculate_compat_instance_id(idstr) : instance_id;
1262 instance_id = -1;
1265 pstrcat(se->idstr, sizeof(se->idstr), idstr);
1267 if (instance_id == -1) {
1268 se->instance_id = calculate_new_instance_id(se->idstr);
1269 } else {
1270 se->instance_id = instance_id;
1272 assert(!se->compat || se->instance_id == 0);
1273 /* add at the end of list */
1274 QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
1275 return 0;
1278 int register_savevm(DeviceState *dev,
1279 const char *idstr,
1280 int instance_id,
1281 int version_id,
1282 SaveStateHandler *save_state,
1283 LoadStateHandler *load_state,
1284 void *opaque)
1286 return register_savevm_live(dev, idstr, instance_id, version_id,
1287 NULL, NULL, save_state, load_state, opaque);
1290 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
1292 SaveStateEntry *se, *new_se;
1293 char id[256] = "";
1295 if (dev && dev->parent_bus && dev->parent_bus->info->get_dev_path) {
1296 char *path = dev->parent_bus->info->get_dev_path(dev);
1297 if (path) {
1298 pstrcpy(id, sizeof(id), path);
1299 pstrcat(id, sizeof(id), "/");
1300 g_free(path);
1303 pstrcat(id, sizeof(id), idstr);
1305 QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
1306 if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
1307 QTAILQ_REMOVE(&savevm_handlers, se, entry);
1308 if (se->compat) {
1309 g_free(se->compat);
1311 g_free(se);
1316 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
1317 const VMStateDescription *vmsd,
1318 void *opaque, int alias_id,
1319 int required_for_version)
1321 SaveStateEntry *se;
1323 /* If this triggers, alias support can be dropped for the vmsd. */
1324 assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
1326 se = g_malloc0(sizeof(SaveStateEntry));
1327 se->version_id = vmsd->version_id;
1328 se->section_id = global_section_id++;
1329 se->save_live_state = NULL;
1330 se->save_state = NULL;
1331 se->load_state = NULL;
1332 se->opaque = opaque;
1333 se->vmsd = vmsd;
1334 se->alias_id = alias_id;
1335 se->no_migrate = vmsd->unmigratable;
1337 if (dev && dev->parent_bus && dev->parent_bus->info->get_dev_path) {
1338 char *id = dev->parent_bus->info->get_dev_path(dev);
1339 if (id) {
1340 pstrcpy(se->idstr, sizeof(se->idstr), id);
1341 pstrcat(se->idstr, sizeof(se->idstr), "/");
1342 g_free(id);
1344 se->compat = g_malloc0(sizeof(CompatEntry));
1345 pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
1346 se->compat->instance_id = instance_id == -1 ?
1347 calculate_compat_instance_id(vmsd->name) : instance_id;
1348 instance_id = -1;
1351 pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
1353 if (instance_id == -1) {
1354 se->instance_id = calculate_new_instance_id(se->idstr);
1355 } else {
1356 se->instance_id = instance_id;
1358 assert(!se->compat || se->instance_id == 0);
1359 /* add at the end of list */
1360 QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
1361 return 0;
1364 int vmstate_register(DeviceState *dev, int instance_id,
1365 const VMStateDescription *vmsd, void *opaque)
1367 return vmstate_register_with_alias_id(dev, instance_id, vmsd,
1368 opaque, -1, 0);
1371 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
1372 void *opaque)
1374 SaveStateEntry *se, *new_se;
1376 QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
1377 if (se->vmsd == vmsd && se->opaque == opaque) {
1378 QTAILQ_REMOVE(&savevm_handlers, se, entry);
1379 if (se->compat) {
1380 g_free(se->compat);
1382 g_free(se);
1387 static void vmstate_subsection_save(QEMUFile *f, const VMStateDescription *vmsd,
1388 void *opaque);
1389 static int vmstate_subsection_load(QEMUFile *f, const VMStateDescription *vmsd,
1390 void *opaque);
1392 int vmstate_load_state(QEMUFile *f, const VMStateDescription *vmsd,
1393 void *opaque, int version_id)
1395 VMStateField *field = vmsd->fields;
1396 int ret;
1398 if (version_id > vmsd->version_id) {
1399 return -EINVAL;
1401 if (version_id < vmsd->minimum_version_id_old) {
1402 return -EINVAL;
1404 if (version_id < vmsd->minimum_version_id) {
1405 return vmsd->load_state_old(f, opaque, version_id);
1407 if (vmsd->pre_load) {
1408 int ret = vmsd->pre_load(opaque);
1409 if (ret)
1410 return ret;
1412 while(field->name) {
1413 if ((field->field_exists &&
1414 field->field_exists(opaque, version_id)) ||
1415 (!field->field_exists &&
1416 field->version_id <= version_id)) {
1417 void *base_addr = opaque + field->offset;
1418 int i, n_elems = 1;
1419 int size = field->size;
1421 if (field->flags & VMS_VBUFFER) {
1422 size = *(int32_t *)(opaque+field->size_offset);
1423 if (field->flags & VMS_MULTIPLY) {
1424 size *= field->size;
1427 if (field->flags & VMS_ARRAY) {
1428 n_elems = field->num;
1429 } else if (field->flags & VMS_VARRAY_INT32) {
1430 n_elems = *(int32_t *)(opaque+field->num_offset);
1431 } else if (field->flags & VMS_VARRAY_UINT32) {
1432 n_elems = *(uint32_t *)(opaque+field->num_offset);
1433 } else if (field->flags & VMS_VARRAY_UINT16) {
1434 n_elems = *(uint16_t *)(opaque+field->num_offset);
1435 } else if (field->flags & VMS_VARRAY_UINT8) {
1436 n_elems = *(uint8_t *)(opaque+field->num_offset);
1438 if (field->flags & VMS_POINTER) {
1439 base_addr = *(void **)base_addr + field->start;
1441 for (i = 0; i < n_elems; i++) {
1442 void *addr = base_addr + size * i;
1444 if (field->flags & VMS_ARRAY_OF_POINTER) {
1445 addr = *(void **)addr;
1447 if (field->flags & VMS_STRUCT) {
1448 ret = vmstate_load_state(f, field->vmsd, addr, field->vmsd->version_id);
1449 } else {
1450 ret = field->info->get(f, addr, size);
1453 if (ret < 0) {
1454 return ret;
1458 field++;
1460 ret = vmstate_subsection_load(f, vmsd, opaque);
1461 if (ret != 0) {
1462 return ret;
1464 if (vmsd->post_load) {
1465 return vmsd->post_load(opaque, version_id);
1467 return 0;
1470 void vmstate_save_state(QEMUFile *f, const VMStateDescription *vmsd,
1471 void *opaque)
1473 VMStateField *field = vmsd->fields;
1475 if (vmsd->pre_save) {
1476 vmsd->pre_save(opaque);
1478 while(field->name) {
1479 if (!field->field_exists ||
1480 field->field_exists(opaque, vmsd->version_id)) {
1481 void *base_addr = opaque + field->offset;
1482 int i, n_elems = 1;
1483 int size = field->size;
1485 if (field->flags & VMS_VBUFFER) {
1486 size = *(int32_t *)(opaque+field->size_offset);
1487 if (field->flags & VMS_MULTIPLY) {
1488 size *= field->size;
1491 if (field->flags & VMS_ARRAY) {
1492 n_elems = field->num;
1493 } else if (field->flags & VMS_VARRAY_INT32) {
1494 n_elems = *(int32_t *)(opaque+field->num_offset);
1495 } else if (field->flags & VMS_VARRAY_UINT32) {
1496 n_elems = *(uint32_t *)(opaque+field->num_offset);
1497 } else if (field->flags & VMS_VARRAY_UINT16) {
1498 n_elems = *(uint16_t *)(opaque+field->num_offset);
1499 } else if (field->flags & VMS_VARRAY_UINT8) {
1500 n_elems = *(uint8_t *)(opaque+field->num_offset);
1502 if (field->flags & VMS_POINTER) {
1503 base_addr = *(void **)base_addr + field->start;
1505 for (i = 0; i < n_elems; i++) {
1506 void *addr = base_addr + size * i;
1508 if (field->flags & VMS_ARRAY_OF_POINTER) {
1509 addr = *(void **)addr;
1511 if (field->flags & VMS_STRUCT) {
1512 vmstate_save_state(f, field->vmsd, addr);
1513 } else {
1514 field->info->put(f, addr, size);
1518 field++;
1520 vmstate_subsection_save(f, vmsd, opaque);
1523 static int vmstate_load(QEMUFile *f, SaveStateEntry *se, int version_id)
1525 if (!se->vmsd) { /* Old style */
1526 return se->load_state(f, se->opaque, version_id);
1528 return vmstate_load_state(f, se->vmsd, se->opaque, version_id);
1531 static void vmstate_save(QEMUFile *f, SaveStateEntry *se)
1533 if (!se->vmsd) { /* Old style */
1534 se->save_state(f, se->opaque);
1535 return;
1537 vmstate_save_state(f,se->vmsd, se->opaque);
1540 #define QEMU_VM_FILE_MAGIC 0x5145564d
1541 #define QEMU_VM_FILE_VERSION_COMPAT 0x00000002
1542 #define QEMU_VM_FILE_VERSION 0x00000003
1544 #define QEMU_VM_EOF 0x00
1545 #define QEMU_VM_SECTION_START 0x01
1546 #define QEMU_VM_SECTION_PART 0x02
1547 #define QEMU_VM_SECTION_END 0x03
1548 #define QEMU_VM_SECTION_FULL 0x04
1549 #define QEMU_VM_SUBSECTION 0x05
1551 bool qemu_savevm_state_blocked(Error **errp)
1553 SaveStateEntry *se;
1555 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1556 if (se->no_migrate) {
1557 error_set(errp, QERR_MIGRATION_NOT_SUPPORTED, se->idstr);
1558 return true;
1561 return false;
1564 int qemu_savevm_state_begin(QEMUFile *f, int blk_enable, int shared)
1566 SaveStateEntry *se;
1567 int ret;
1569 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1570 if(se->set_params == NULL) {
1571 continue;
1573 se->set_params(blk_enable, shared, se->opaque);
1576 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1577 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1579 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1580 int len;
1582 if (se->save_live_state == NULL)
1583 continue;
1585 /* Section type */
1586 qemu_put_byte(f, QEMU_VM_SECTION_START);
1587 qemu_put_be32(f, se->section_id);
1589 /* ID string */
1590 len = strlen(se->idstr);
1591 qemu_put_byte(f, len);
1592 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1594 qemu_put_be32(f, se->instance_id);
1595 qemu_put_be32(f, se->version_id);
1597 ret = se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
1598 if (ret < 0) {
1599 qemu_savevm_state_cancel(f);
1600 return ret;
1603 ret = qemu_file_get_error(f);
1604 if (ret != 0) {
1605 qemu_savevm_state_cancel(f);
1608 return ret;
1613 * this function has three return values:
1614 * negative: there was one error, and we have -errno.
1615 * 0 : We haven't finished, caller have to go again
1616 * 1 : We have finished, we can go to complete phase
1618 int qemu_savevm_state_iterate(QEMUFile *f)
1620 SaveStateEntry *se;
1621 int ret = 1;
1623 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1624 if (se->save_live_state == NULL)
1625 continue;
1627 /* Section type */
1628 qemu_put_byte(f, QEMU_VM_SECTION_PART);
1629 qemu_put_be32(f, se->section_id);
1631 ret = se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
1632 if (ret <= 0) {
1633 /* Do not proceed to the next vmstate before this one reported
1634 completion of the current stage. This serializes the migration
1635 and reduces the probability that a faster changing state is
1636 synchronized over and over again. */
1637 break;
1640 if (ret != 0) {
1641 return ret;
1643 ret = qemu_file_get_error(f);
1644 if (ret != 0) {
1645 qemu_savevm_state_cancel(f);
1647 return ret;
1650 int qemu_savevm_state_complete(QEMUFile *f)
1652 SaveStateEntry *se;
1653 int ret;
1655 cpu_synchronize_all_states();
1657 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1658 if (se->save_live_state == NULL)
1659 continue;
1661 /* Section type */
1662 qemu_put_byte(f, QEMU_VM_SECTION_END);
1663 qemu_put_be32(f, se->section_id);
1665 ret = se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
1666 if (ret < 0) {
1667 return ret;
1671 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1672 int len;
1674 if (se->save_state == NULL && se->vmsd == NULL)
1675 continue;
1677 /* Section type */
1678 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
1679 qemu_put_be32(f, se->section_id);
1681 /* ID string */
1682 len = strlen(se->idstr);
1683 qemu_put_byte(f, len);
1684 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1686 qemu_put_be32(f, se->instance_id);
1687 qemu_put_be32(f, se->version_id);
1689 vmstate_save(f, se);
1692 qemu_put_byte(f, QEMU_VM_EOF);
1694 return qemu_file_get_error(f);
1697 void qemu_savevm_state_cancel(QEMUFile *f)
1699 SaveStateEntry *se;
1701 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1702 if (se->save_live_state) {
1703 se->save_live_state(f, -1, se->opaque);
1708 static int qemu_savevm_state(QEMUFile *f)
1710 int ret;
1712 if (qemu_savevm_state_blocked(NULL)) {
1713 ret = -EINVAL;
1714 goto out;
1717 ret = qemu_savevm_state_begin(f, 0, 0);
1718 if (ret < 0)
1719 goto out;
1721 do {
1722 ret = qemu_savevm_state_iterate(f);
1723 if (ret < 0)
1724 goto out;
1725 } while (ret == 0);
1727 ret = qemu_savevm_state_complete(f);
1729 out:
1730 if (ret == 0) {
1731 ret = qemu_file_get_error(f);
1734 return ret;
1737 static int qemu_save_device_state(QEMUFile *f)
1739 SaveStateEntry *se;
1741 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1742 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1744 cpu_synchronize_all_states();
1746 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1747 int len;
1749 if (se->is_ram) {
1750 continue;
1752 if (se->save_state == NULL && se->vmsd == NULL) {
1753 continue;
1756 /* Section type */
1757 qemu_put_byte(f, QEMU_VM_SECTION_FULL);
1758 qemu_put_be32(f, se->section_id);
1760 /* ID string */
1761 len = strlen(se->idstr);
1762 qemu_put_byte(f, len);
1763 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
1765 qemu_put_be32(f, se->instance_id);
1766 qemu_put_be32(f, se->version_id);
1768 vmstate_save(f, se);
1771 qemu_put_byte(f, QEMU_VM_EOF);
1773 return qemu_file_get_error(f);
1776 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1778 SaveStateEntry *se;
1780 QTAILQ_FOREACH(se, &savevm_handlers, entry) {
1781 if (!strcmp(se->idstr, idstr) &&
1782 (instance_id == se->instance_id ||
1783 instance_id == se->alias_id))
1784 return se;
1785 /* Migrating from an older version? */
1786 if (strstr(se->idstr, idstr) && se->compat) {
1787 if (!strcmp(se->compat->idstr, idstr) &&
1788 (instance_id == se->compat->instance_id ||
1789 instance_id == se->alias_id))
1790 return se;
1793 return NULL;
1796 static const VMStateDescription *vmstate_get_subsection(const VMStateSubsection *sub, char *idstr)
1798 while(sub && sub->needed) {
1799 if (strcmp(idstr, sub->vmsd->name) == 0) {
1800 return sub->vmsd;
1802 sub++;
1804 return NULL;
1807 static int vmstate_subsection_load(QEMUFile *f, const VMStateDescription *vmsd,
1808 void *opaque)
1810 while (qemu_peek_byte(f, 0) == QEMU_VM_SUBSECTION) {
1811 char idstr[256];
1812 int ret;
1813 uint8_t version_id, len, size;
1814 const VMStateDescription *sub_vmsd;
1816 len = qemu_peek_byte(f, 1);
1817 if (len < strlen(vmsd->name) + 1) {
1818 /* subsection name has be be "section_name/a" */
1819 return 0;
1821 size = qemu_peek_buffer(f, (uint8_t *)idstr, len, 2);
1822 if (size != len) {
1823 return 0;
1825 idstr[size] = 0;
1827 if (strncmp(vmsd->name, idstr, strlen(vmsd->name)) != 0) {
1828 /* it don't have a valid subsection name */
1829 return 0;
1831 sub_vmsd = vmstate_get_subsection(vmsd->subsections, idstr);
1832 if (sub_vmsd == NULL) {
1833 return -ENOENT;
1835 qemu_file_skip(f, 1); /* subsection */
1836 qemu_file_skip(f, 1); /* len */
1837 qemu_file_skip(f, len); /* idstr */
1838 version_id = qemu_get_be32(f);
1840 ret = vmstate_load_state(f, sub_vmsd, opaque, version_id);
1841 if (ret) {
1842 return ret;
1845 return 0;
1848 static void vmstate_subsection_save(QEMUFile *f, const VMStateDescription *vmsd,
1849 void *opaque)
1851 const VMStateSubsection *sub = vmsd->subsections;
1853 while (sub && sub->needed) {
1854 if (sub->needed(opaque)) {
1855 const VMStateDescription *vmsd = sub->vmsd;
1856 uint8_t len;
1858 qemu_put_byte(f, QEMU_VM_SUBSECTION);
1859 len = strlen(vmsd->name);
1860 qemu_put_byte(f, len);
1861 qemu_put_buffer(f, (uint8_t *)vmsd->name, len);
1862 qemu_put_be32(f, vmsd->version_id);
1863 vmstate_save_state(f, vmsd, opaque);
1865 sub++;
1869 typedef struct LoadStateEntry {
1870 QLIST_ENTRY(LoadStateEntry) entry;
1871 SaveStateEntry *se;
1872 int section_id;
1873 int version_id;
1874 } LoadStateEntry;
1876 int qemu_loadvm_state(QEMUFile *f)
1878 QLIST_HEAD(, LoadStateEntry) loadvm_handlers =
1879 QLIST_HEAD_INITIALIZER(loadvm_handlers);
1880 LoadStateEntry *le, *new_le;
1881 uint8_t section_type;
1882 unsigned int v;
1883 int ret;
1885 if (qemu_savevm_state_blocked(NULL)) {
1886 return -EINVAL;
1889 v = qemu_get_be32(f);
1890 if (v != QEMU_VM_FILE_MAGIC)
1891 return -EINVAL;
1893 v = qemu_get_be32(f);
1894 if (v == QEMU_VM_FILE_VERSION_COMPAT) {
1895 fprintf(stderr, "SaveVM v2 format is obsolete and don't work anymore\n");
1896 return -ENOTSUP;
1898 if (v != QEMU_VM_FILE_VERSION)
1899 return -ENOTSUP;
1901 while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
1902 uint32_t instance_id, version_id, section_id;
1903 SaveStateEntry *se;
1904 char idstr[257];
1905 int len;
1907 switch (section_type) {
1908 case QEMU_VM_SECTION_START:
1909 case QEMU_VM_SECTION_FULL:
1910 /* Read section start */
1911 section_id = qemu_get_be32(f);
1912 len = qemu_get_byte(f);
1913 qemu_get_buffer(f, (uint8_t *)idstr, len);
1914 idstr[len] = 0;
1915 instance_id = qemu_get_be32(f);
1916 version_id = qemu_get_be32(f);
1918 /* Find savevm section */
1919 se = find_se(idstr, instance_id);
1920 if (se == NULL) {
1921 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
1922 ret = -EINVAL;
1923 goto out;
1926 /* Validate version */
1927 if (version_id > se->version_id) {
1928 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
1929 version_id, idstr, se->version_id);
1930 ret = -EINVAL;
1931 goto out;
1934 /* Add entry */
1935 le = g_malloc0(sizeof(*le));
1937 le->se = se;
1938 le->section_id = section_id;
1939 le->version_id = version_id;
1940 QLIST_INSERT_HEAD(&loadvm_handlers, le, entry);
1942 ret = vmstate_load(f, le->se, le->version_id);
1943 if (ret < 0) {
1944 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1945 instance_id, idstr);
1946 goto out;
1948 break;
1949 case QEMU_VM_SECTION_PART:
1950 case QEMU_VM_SECTION_END:
1951 section_id = qemu_get_be32(f);
1953 QLIST_FOREACH(le, &loadvm_handlers, entry) {
1954 if (le->section_id == section_id) {
1955 break;
1958 if (le == NULL) {
1959 fprintf(stderr, "Unknown savevm section %d\n", section_id);
1960 ret = -EINVAL;
1961 goto out;
1964 ret = vmstate_load(f, le->se, le->version_id);
1965 if (ret < 0) {
1966 fprintf(stderr, "qemu: warning: error while loading state section id %d\n",
1967 section_id);
1968 goto out;
1970 break;
1971 default:
1972 fprintf(stderr, "Unknown savevm section type %d\n", section_type);
1973 ret = -EINVAL;
1974 goto out;
1978 cpu_synchronize_all_post_init();
1980 ret = 0;
1982 out:
1983 QLIST_FOREACH_SAFE(le, &loadvm_handlers, entry, new_le) {
1984 QLIST_REMOVE(le, entry);
1985 g_free(le);
1988 if (ret == 0) {
1989 ret = qemu_file_get_error(f);
1992 return ret;
1995 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
1996 const char *name)
1998 QEMUSnapshotInfo *sn_tab, *sn;
1999 int nb_sns, i, ret;
2001 ret = -ENOENT;
2002 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2003 if (nb_sns < 0)
2004 return ret;
2005 for(i = 0; i < nb_sns; i++) {
2006 sn = &sn_tab[i];
2007 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
2008 *sn_info = *sn;
2009 ret = 0;
2010 break;
2013 g_free(sn_tab);
2014 return ret;
2018 * Deletes snapshots of a given name in all opened images.
2020 static int del_existing_snapshots(Monitor *mon, const char *name)
2022 BlockDriverState *bs;
2023 QEMUSnapshotInfo sn1, *snapshot = &sn1;
2024 int ret;
2026 bs = NULL;
2027 while ((bs = bdrv_next(bs))) {
2028 if (bdrv_can_snapshot(bs) &&
2029 bdrv_snapshot_find(bs, snapshot, name) >= 0)
2031 ret = bdrv_snapshot_delete(bs, name);
2032 if (ret < 0) {
2033 monitor_printf(mon,
2034 "Error while deleting snapshot on '%s'\n",
2035 bdrv_get_device_name(bs));
2036 return -1;
2041 return 0;
2044 void do_savevm(Monitor *mon, const QDict *qdict)
2046 BlockDriverState *bs, *bs1;
2047 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
2048 int ret;
2049 QEMUFile *f;
2050 int saved_vm_running;
2051 uint64_t vm_state_size;
2052 #ifdef _WIN32
2053 struct _timeb tb;
2054 struct tm *ptm;
2055 #else
2056 struct timeval tv;
2057 struct tm tm;
2058 #endif
2059 const char *name = qdict_get_try_str(qdict, "name");
2061 /* Verify if there is a device that doesn't support snapshots and is writable */
2062 bs = NULL;
2063 while ((bs = bdrv_next(bs))) {
2065 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2066 continue;
2069 if (!bdrv_can_snapshot(bs)) {
2070 monitor_printf(mon, "Device '%s' is writable but does not support snapshots.\n",
2071 bdrv_get_device_name(bs));
2072 return;
2076 bs = bdrv_snapshots();
2077 if (!bs) {
2078 monitor_printf(mon, "No block device can accept snapshots\n");
2079 return;
2082 saved_vm_running = runstate_is_running();
2083 vm_stop(RUN_STATE_SAVE_VM);
2085 memset(sn, 0, sizeof(*sn));
2087 /* fill auxiliary fields */
2088 #ifdef _WIN32
2089 _ftime(&tb);
2090 sn->date_sec = tb.time;
2091 sn->date_nsec = tb.millitm * 1000000;
2092 #else
2093 gettimeofday(&tv, NULL);
2094 sn->date_sec = tv.tv_sec;
2095 sn->date_nsec = tv.tv_usec * 1000;
2096 #endif
2097 sn->vm_clock_nsec = qemu_get_clock_ns(vm_clock);
2099 if (name) {
2100 ret = bdrv_snapshot_find(bs, old_sn, name);
2101 if (ret >= 0) {
2102 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
2103 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
2104 } else {
2105 pstrcpy(sn->name, sizeof(sn->name), name);
2107 } else {
2108 #ifdef _WIN32
2109 ptm = localtime(&tb.time);
2110 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", ptm);
2111 #else
2112 /* cast below needed for OpenBSD where tv_sec is still 'long' */
2113 localtime_r((const time_t *)&tv.tv_sec, &tm);
2114 strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
2115 #endif
2118 /* Delete old snapshots of the same name */
2119 if (name && del_existing_snapshots(mon, name) < 0) {
2120 goto the_end;
2123 /* save the VM state */
2124 f = qemu_fopen_bdrv(bs, 1);
2125 if (!f) {
2126 monitor_printf(mon, "Could not open VM state file\n");
2127 goto the_end;
2129 ret = qemu_savevm_state(f);
2130 vm_state_size = qemu_ftell(f);
2131 qemu_fclose(f);
2132 if (ret < 0) {
2133 monitor_printf(mon, "Error %d while writing VM\n", ret);
2134 goto the_end;
2137 /* create the snapshots */
2139 bs1 = NULL;
2140 while ((bs1 = bdrv_next(bs1))) {
2141 if (bdrv_can_snapshot(bs1)) {
2142 /* Write VM state size only to the image that contains the state */
2143 sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
2144 ret = bdrv_snapshot_create(bs1, sn);
2145 if (ret < 0) {
2146 monitor_printf(mon, "Error while creating snapshot on '%s'\n",
2147 bdrv_get_device_name(bs1));
2152 the_end:
2153 if (saved_vm_running)
2154 vm_start();
2157 void qmp_xen_save_devices_state(const char *filename, Error **errp)
2159 QEMUFile *f;
2160 int saved_vm_running;
2161 int ret;
2163 saved_vm_running = runstate_is_running();
2164 vm_stop(RUN_STATE_SAVE_VM);
2166 f = qemu_fopen(filename, "wb");
2167 if (!f) {
2168 error_set(errp, QERR_OPEN_FILE_FAILED, filename);
2169 goto the_end;
2171 ret = qemu_save_device_state(f);
2172 qemu_fclose(f);
2173 if (ret < 0) {
2174 error_set(errp, QERR_IO_ERROR);
2177 the_end:
2178 if (saved_vm_running)
2179 vm_start();
2180 return;
2183 int load_vmstate(const char *name)
2185 BlockDriverState *bs, *bs_vm_state;
2186 QEMUSnapshotInfo sn;
2187 QEMUFile *f;
2188 int ret;
2190 bs_vm_state = bdrv_snapshots();
2191 if (!bs_vm_state) {
2192 error_report("No block device supports snapshots");
2193 return -ENOTSUP;
2196 /* Don't even try to load empty VM states */
2197 ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
2198 if (ret < 0) {
2199 return ret;
2200 } else if (sn.vm_state_size == 0) {
2201 error_report("This is a disk-only snapshot. Revert to it offline "
2202 "using qemu-img.");
2203 return -EINVAL;
2206 /* Verify if there is any device that doesn't support snapshots and is
2207 writable and check if the requested snapshot is available too. */
2208 bs = NULL;
2209 while ((bs = bdrv_next(bs))) {
2211 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2212 continue;
2215 if (!bdrv_can_snapshot(bs)) {
2216 error_report("Device '%s' is writable but does not support snapshots.",
2217 bdrv_get_device_name(bs));
2218 return -ENOTSUP;
2221 ret = bdrv_snapshot_find(bs, &sn, name);
2222 if (ret < 0) {
2223 error_report("Device '%s' does not have the requested snapshot '%s'",
2224 bdrv_get_device_name(bs), name);
2225 return ret;
2229 /* Flush all IO requests so they don't interfere with the new state. */
2230 bdrv_drain_all();
2232 bs = NULL;
2233 while ((bs = bdrv_next(bs))) {
2234 if (bdrv_can_snapshot(bs)) {
2235 ret = bdrv_snapshot_goto(bs, name);
2236 if (ret < 0) {
2237 error_report("Error %d while activating snapshot '%s' on '%s'",
2238 ret, name, bdrv_get_device_name(bs));
2239 return ret;
2244 /* restore the VM state */
2245 f = qemu_fopen_bdrv(bs_vm_state, 0);
2246 if (!f) {
2247 error_report("Could not open VM state file");
2248 return -EINVAL;
2251 qemu_system_reset(VMRESET_SILENT);
2252 ret = qemu_loadvm_state(f);
2254 qemu_fclose(f);
2255 if (ret < 0) {
2256 error_report("Error %d while loading VM state", ret);
2257 return ret;
2260 return 0;
2263 void do_delvm(Monitor *mon, const QDict *qdict)
2265 BlockDriverState *bs, *bs1;
2266 int ret;
2267 const char *name = qdict_get_str(qdict, "name");
2269 bs = bdrv_snapshots();
2270 if (!bs) {
2271 monitor_printf(mon, "No block device supports snapshots\n");
2272 return;
2275 bs1 = NULL;
2276 while ((bs1 = bdrv_next(bs1))) {
2277 if (bdrv_can_snapshot(bs1)) {
2278 ret = bdrv_snapshot_delete(bs1, name);
2279 if (ret < 0) {
2280 if (ret == -ENOTSUP)
2281 monitor_printf(mon,
2282 "Snapshots not supported on device '%s'\n",
2283 bdrv_get_device_name(bs1));
2284 else
2285 monitor_printf(mon, "Error %d while deleting snapshot on "
2286 "'%s'\n", ret, bdrv_get_device_name(bs1));
2292 void do_info_snapshots(Monitor *mon)
2294 BlockDriverState *bs, *bs1;
2295 QEMUSnapshotInfo *sn_tab, *sn, s, *sn_info = &s;
2296 int nb_sns, i, ret, available;
2297 int total;
2298 int *available_snapshots;
2299 char buf[256];
2301 bs = bdrv_snapshots();
2302 if (!bs) {
2303 monitor_printf(mon, "No available block device supports snapshots\n");
2304 return;
2307 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
2308 if (nb_sns < 0) {
2309 monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);
2310 return;
2313 if (nb_sns == 0) {
2314 monitor_printf(mon, "There is no snapshot available.\n");
2315 return;
2318 available_snapshots = g_malloc0(sizeof(int) * nb_sns);
2319 total = 0;
2320 for (i = 0; i < nb_sns; i++) {
2321 sn = &sn_tab[i];
2322 available = 1;
2323 bs1 = NULL;
2325 while ((bs1 = bdrv_next(bs1))) {
2326 if (bdrv_can_snapshot(bs1) && bs1 != bs) {
2327 ret = bdrv_snapshot_find(bs1, sn_info, sn->id_str);
2328 if (ret < 0) {
2329 available = 0;
2330 break;
2335 if (available) {
2336 available_snapshots[total] = i;
2337 total++;
2341 if (total > 0) {
2342 monitor_printf(mon, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
2343 for (i = 0; i < total; i++) {
2344 sn = &sn_tab[available_snapshots[i]];
2345 monitor_printf(mon, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
2347 } else {
2348 monitor_printf(mon, "There is no suitable snapshot available\n");
2351 g_free(sn_tab);
2352 g_free(available_snapshots);
2356 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
2358 qemu_ram_set_idstr(memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK,
2359 memory_region_name(mr), dev);
2362 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
2364 /* Nothing do to while the implementation is in RAMBlock */
2367 void vmstate_register_ram_global(MemoryRegion *mr)
2369 vmstate_register_ram(mr, NULL);