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