replace bdrv_{get, put}_buffer with bdrv_{load, save}_vmstate
[qemu] / 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 <signal.h>
27 #include <time.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <zlib.h>
31
32 /* Needed early for HOST_BSD etc. */
33 #include "config-host.h"
34
35 #ifndef _WIN32
36 #include <sys/times.h>
37 #include <sys/wait.h>
38 #include <termios.h>
39 #include <sys/mman.h>
40 #include <sys/ioctl.h>
41 #include <sys/resource.h>
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <net/if.h>
45 #if defined(__NetBSD__)
46 #include <net/if_tap.h>
47 #endif
48 #ifdef __linux__
49 #include <linux/if_tun.h>
50 #endif
51 #include <arpa/inet.h>
52 #include <dirent.h>
53 #include <netdb.h>
54 #include <sys/select.h>
55 #ifdef HOST_BSD
56 #include <sys/stat.h>
57 #if defined(__FreeBSD__) || defined(__DragonFly__)
58 #include <libutil.h>
59 #else
60 #include <util.h>
61 #endif
62 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
63 #include <freebsd/stdlib.h>
64 #else
65 #ifdef __linux__
66 #include <pty.h>
67 #include <malloc.h>
68 #include <linux/rtc.h>
69 #endif
70 #endif
71 #endif
72
73 #ifdef _WIN32
74 #include <windows.h>
75 #include <malloc.h>
76 #include <sys/timeb.h>
77 #include <mmsystem.h>
78 #define getopt_long_only getopt_long
79 #define memalign(align, size) malloc(size)
80 #endif
81
82 #include "qemu-common.h"
83 #include "hw/hw.h"
84 #include "net.h"
85 #include "monitor.h"
86 #include "sysemu.h"
87 #include "qemu-timer.h"
88 #include "qemu-char.h"
89 #include "block.h"
90 #include "audio/audio.h"
91 #include "migration.h"
92 #include "qemu_socket.h"
93
94 /* point to the block driver where the snapshots are managed */
95 static BlockDriverState *bs_snapshots;
96
97 #define SELF_ANNOUNCE_ROUNDS 5
98 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
99 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
100 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
101
102 static int announce_self_create(uint8_t *buf, 
103                                 uint8_t *mac_addr)
104 {
105     uint32_t magic = EXPERIMENTAL_MAGIC;
106     uint16_t proto = htons(ETH_P_EXPERIMENTAL);
107
108     /* FIXME: should we send a different packet (arp/rarp/ping)? */
109
110     memset(buf, 0, 64);
111     memset(buf, 0xff, 6);         /* h_dst */
112     memcpy(buf + 6, mac_addr, 6); /* h_src */
113     memcpy(buf + 12, &proto, 2);  /* h_proto */
114     memcpy(buf + 14, &magic, 4);  /* magic */
115
116     return 64; /* len */
117 }
118
119 static void qemu_announce_self_once(void *opaque)
120 {
121     int i, len;
122     VLANState *vlan;
123     VLANClientState *vc;
124     uint8_t buf[256];
125     static int count = SELF_ANNOUNCE_ROUNDS;
126     QEMUTimer *timer = *(QEMUTimer **)opaque;
127
128     for (i = 0; i < MAX_NICS; i++) {
129         if (!nd_table[i].used)
130             continue;
131         len = announce_self_create(buf, nd_table[i].macaddr);
132         vlan = nd_table[i].vlan;
133         for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
134             vc->receive(vc, buf, len);
135         }
136     }
137     if (count--) {
138             qemu_mod_timer(timer, qemu_get_clock(rt_clock) + 100);
139     } else {
140             qemu_del_timer(timer);
141             qemu_free_timer(timer);
142     }
143 }
144
145 void qemu_announce_self(void)
146 {
147         static QEMUTimer *timer;
148         timer = qemu_new_timer(rt_clock, qemu_announce_self_once, &timer);
149         qemu_announce_self_once(&timer);
150 }
151
152 /***********************************************************/
153 /* savevm/loadvm support */
154
155 #define IO_BUF_SIZE 32768
156
157 struct QEMUFile {
158     QEMUFilePutBufferFunc *put_buffer;
159     QEMUFileGetBufferFunc *get_buffer;
160     QEMUFileCloseFunc *close;
161     QEMUFileRateLimit *rate_limit;
162     QEMUFileSetRateLimit *set_rate_limit;
163     void *opaque;
164     int is_write;
165
166     int64_t buf_offset; /* start of buffer when writing, end of buffer
167                            when reading */
168     int buf_index;
169     int buf_size; /* 0 when writing */
170     uint8_t buf[IO_BUF_SIZE];
171
172     int has_error;
173 };
174
175 typedef struct QEMUFilePopen
176 {
177     FILE *popen_file;
178     QEMUFile *file;
179 } QEMUFilePopen;
180
181 typedef struct QEMUFileSocket
182 {
183     int fd;
184     QEMUFile *file;
185 } QEMUFileSocket;
186
187 static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
188 {
189     QEMUFileSocket *s = opaque;
190     ssize_t len;
191
192     do {
193         len = recv(s->fd, (void *)buf, size, 0);
194     } while (len == -1 && socket_error() == EINTR);
195
196     if (len == -1)
197         len = -socket_error();
198
199     return len;
200 }
201
202 static int socket_close(void *opaque)
203 {
204     QEMUFileSocket *s = opaque;
205     qemu_free(s);
206     return 0;
207 }
208
209 static int popen_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
210 {
211     QEMUFilePopen *s = opaque;
212     return fwrite(buf, 1, size, s->popen_file);
213 }
214
215 static int popen_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
216 {
217     QEMUFilePopen *s = opaque;
218     FILE *fp = s->popen_file;
219     int bytes;
220
221     do {
222         clearerr(fp);
223         bytes = fread(buf, 1, size, fp);
224     } while ((bytes == 0) && ferror(fp) && (errno == EINTR));
225     return bytes;
226 }
227
228 static int popen_close(void *opaque)
229 {
230     QEMUFilePopen *s = opaque;
231     pclose(s->popen_file);
232     qemu_free(s);
233     return 0;
234 }
235
236 QEMUFile *qemu_popen(FILE *popen_file, const char *mode)
237 {
238     QEMUFilePopen *s;
239
240     if (popen_file == NULL || mode == NULL || (mode[0] != 'r' && mode[0] != 'w') || mode[1] != 0) {
241         fprintf(stderr, "qemu_popen: Argument validity check failed\n");
242         return NULL;
243     }
244
245     s = qemu_mallocz(sizeof(QEMUFilePopen));
246
247     s->popen_file = popen_file;
248
249     if(mode[0] == 'r') {
250         s->file = qemu_fopen_ops(s, NULL, popen_get_buffer, popen_close, NULL, NULL);
251     } else {
252         s->file = qemu_fopen_ops(s, popen_put_buffer, NULL, popen_close, NULL, NULL);
253     }
254     return s->file;
255 }
256
257 QEMUFile *qemu_popen_cmd(const char *command, const char *mode)
258 {
259     FILE *popen_file;
260
261     popen_file = popen(command, mode);
262     if(popen_file == NULL) {
263         return NULL;
264     }
265
266     return qemu_popen(popen_file, mode);
267 }
268
269 int qemu_popen_fd(QEMUFile *f)
270 {
271     QEMUFilePopen *p;
272     int fd;
273
274     p = (QEMUFilePopen *)f->opaque;
275     fd = fileno(p->popen_file);
276
277     return fd;
278 }
279
280 QEMUFile *qemu_fopen_socket(int fd)
281 {
282     QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
283
284     s->fd = fd;
285     s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close, NULL, NULL);
286     return s->file;
287 }
288
289 typedef struct QEMUFileStdio
290 {
291     FILE *outfile;
292 } QEMUFileStdio;
293
294 static int file_put_buffer(void *opaque, const uint8_t *buf,
295                             int64_t pos, int size)
296 {
297     QEMUFileStdio *s = opaque;
298     fseek(s->outfile, pos, SEEK_SET);
299     fwrite(buf, 1, size, s->outfile);
300     return size;
301 }
302
303 static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
304 {
305     QEMUFileStdio *s = opaque;
306     fseek(s->outfile, pos, SEEK_SET);
307     return fread(buf, 1, size, s->outfile);
308 }
309
310 static int file_close(void *opaque)
311 {
312     QEMUFileStdio *s = opaque;
313     fclose(s->outfile);
314     qemu_free(s);
315     return 0;
316 }
317
318 QEMUFile *qemu_fopen(const char *filename, const char *mode)
319 {
320     QEMUFileStdio *s;
321
322     s = qemu_mallocz(sizeof(QEMUFileStdio));
323
324     s->outfile = fopen(filename, mode);
325     if (!s->outfile)
326         goto fail;
327
328     if (!strcmp(mode, "wb"))
329         return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL, NULL);
330     else if (!strcmp(mode, "rb"))
331         return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL, NULL);
332
333 fail:
334     if (s->outfile)
335         fclose(s->outfile);
336     qemu_free(s);
337     return NULL;
338 }
339
340 static int block_put_buffer(void *opaque, const uint8_t *buf,
341                            int64_t pos, int size)
342 {
343     bdrv_save_vmstate(opaque, buf, pos, size);
344     return size;
345 }
346
347 static int block_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
348 {
349     return bdrv_load_vmstate(opaque, buf, pos, size);
350 }
351
352 static int bdrv_fclose(void *opaque)
353 {
354     return 0;
355 }
356
357 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
358 {
359     if (is_writable)
360         return qemu_fopen_ops(bs, block_put_buffer, NULL, bdrv_fclose, NULL, NULL);
361     return qemu_fopen_ops(bs, NULL, block_get_buffer, bdrv_fclose, NULL, NULL);
362 }
363
364 QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
365                          QEMUFileGetBufferFunc *get_buffer,
366                          QEMUFileCloseFunc *close,
367                          QEMUFileRateLimit *rate_limit,
368                          QEMUFileSetRateLimit *set_rate_limit)
369 {
370     QEMUFile *f;
371
372     f = qemu_mallocz(sizeof(QEMUFile));
373
374     f->opaque = opaque;
375     f->put_buffer = put_buffer;
376     f->get_buffer = get_buffer;
377     f->close = close;
378     f->rate_limit = rate_limit;
379     f->set_rate_limit = set_rate_limit;
380     f->is_write = 0;
381
382     return f;
383 }
384
385 int qemu_file_has_error(QEMUFile *f)
386 {
387     return f->has_error;
388 }
389
390 void qemu_file_set_error(QEMUFile *f)
391 {
392     f->has_error = 1;
393 }
394
395 void qemu_fflush(QEMUFile *f)
396 {
397     if (!f->put_buffer)
398         return;
399
400     if (f->is_write && f->buf_index > 0) {
401         int len;
402
403         len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
404         if (len > 0)
405             f->buf_offset += f->buf_index;
406         else
407             f->has_error = 1;
408         f->buf_index = 0;
409     }
410 }
411
412 static void qemu_fill_buffer(QEMUFile *f)
413 {
414     int len;
415
416     if (!f->get_buffer)
417         return;
418
419     if (f->is_write)
420         abort();
421
422     len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
423     if (len > 0) {
424         f->buf_index = 0;
425         f->buf_size = len;
426         f->buf_offset += len;
427     } else if (len != -EAGAIN)
428         f->has_error = 1;
429 }
430
431 int qemu_fclose(QEMUFile *f)
432 {
433     int ret = 0;
434     qemu_fflush(f);
435     if (f->close)
436         ret = f->close(f->opaque);
437     qemu_free(f);
438     return ret;
439 }
440
441 void qemu_file_put_notify(QEMUFile *f)
442 {
443     f->put_buffer(f->opaque, NULL, 0, 0);
444 }
445
446 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
447 {
448     int l;
449
450     if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
451         fprintf(stderr,
452                 "Attempted to write to buffer while read buffer is not empty\n");
453         abort();
454     }
455
456     while (!f->has_error && size > 0) {
457         l = IO_BUF_SIZE - f->buf_index;
458         if (l > size)
459             l = size;
460         memcpy(f->buf + f->buf_index, buf, l);
461         f->is_write = 1;
462         f->buf_index += l;
463         buf += l;
464         size -= l;
465         if (f->buf_index >= IO_BUF_SIZE)
466             qemu_fflush(f);
467     }
468 }
469
470 void qemu_put_byte(QEMUFile *f, int v)
471 {
472     if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
473         fprintf(stderr,
474                 "Attempted to write to buffer while read buffer is not empty\n");
475         abort();
476     }
477
478     f->buf[f->buf_index++] = v;
479     f->is_write = 1;
480     if (f->buf_index >= IO_BUF_SIZE)
481         qemu_fflush(f);
482 }
483
484 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
485 {
486     int size, l;
487
488     if (f->is_write)
489         abort();
490
491     size = size1;
492     while (size > 0) {
493         l = f->buf_size - f->buf_index;
494         if (l == 0) {
495             qemu_fill_buffer(f);
496             l = f->buf_size - f->buf_index;
497             if (l == 0)
498                 break;
499         }
500         if (l > size)
501             l = size;
502         memcpy(buf, f->buf + f->buf_index, l);
503         f->buf_index += l;
504         buf += l;
505         size -= l;
506     }
507     return size1 - size;
508 }
509
510 int qemu_get_byte(QEMUFile *f)
511 {
512     if (f->is_write)
513         abort();
514
515     if (f->buf_index >= f->buf_size) {
516         qemu_fill_buffer(f);
517         if (f->buf_index >= f->buf_size)
518             return 0;
519     }
520     return f->buf[f->buf_index++];
521 }
522
523 int64_t qemu_ftell(QEMUFile *f)
524 {
525     return f->buf_offset - f->buf_size + f->buf_index;
526 }
527
528 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
529 {
530     if (whence == SEEK_SET) {
531         /* nothing to do */
532     } else if (whence == SEEK_CUR) {
533         pos += qemu_ftell(f);
534     } else {
535         /* SEEK_END not supported */
536         return -1;
537     }
538     if (f->put_buffer) {
539         qemu_fflush(f);
540         f->buf_offset = pos;
541     } else {
542         f->buf_offset = pos;
543         f->buf_index = 0;
544         f->buf_size = 0;
545     }
546     return pos;
547 }
548
549 int qemu_file_rate_limit(QEMUFile *f)
550 {
551     if (f->rate_limit)
552         return f->rate_limit(f->opaque);
553
554     return 0;
555 }
556
557 size_t qemu_file_set_rate_limit(QEMUFile *f, size_t new_rate)
558 {
559     if (f->set_rate_limit)
560         return f->set_rate_limit(f->opaque, new_rate);
561
562     return 0;
563 }
564
565 void qemu_put_be16(QEMUFile *f, unsigned int v)
566 {
567     qemu_put_byte(f, v >> 8);
568     qemu_put_byte(f, v);
569 }
570
571 void qemu_put_be32(QEMUFile *f, unsigned int v)
572 {
573     qemu_put_byte(f, v >> 24);
574     qemu_put_byte(f, v >> 16);
575     qemu_put_byte(f, v >> 8);
576     qemu_put_byte(f, v);
577 }
578
579 void qemu_put_be64(QEMUFile *f, uint64_t v)
580 {
581     qemu_put_be32(f, v >> 32);
582     qemu_put_be32(f, v);
583 }
584
585 unsigned int qemu_get_be16(QEMUFile *f)
586 {
587     unsigned int v;
588     v = qemu_get_byte(f) << 8;
589     v |= qemu_get_byte(f);
590     return v;
591 }
592
593 unsigned int qemu_get_be32(QEMUFile *f)
594 {
595     unsigned int v;
596     v = qemu_get_byte(f) << 24;
597     v |= qemu_get_byte(f) << 16;
598     v |= qemu_get_byte(f) << 8;
599     v |= qemu_get_byte(f);
600     return v;
601 }
602
603 uint64_t qemu_get_be64(QEMUFile *f)
604 {
605     uint64_t v;
606     v = (uint64_t)qemu_get_be32(f) << 32;
607     v |= qemu_get_be32(f);
608     return v;
609 }
610
611 typedef struct SaveStateEntry {
612     char idstr[256];
613     int instance_id;
614     int version_id;
615     int section_id;
616     SaveLiveStateHandler *save_live_state;
617     SaveStateHandler *save_state;
618     LoadStateHandler *load_state;
619     void *opaque;
620     struct SaveStateEntry *next;
621 } SaveStateEntry;
622
623 static SaveStateEntry *first_se;
624
625 /* TODO: Individual devices generally have very little idea about the rest
626    of the system, so instance_id should be removed/replaced.
627    Meanwhile pass -1 as instance_id if you do not already have a clearly
628    distinguishing id for all instances of your device class. */
629 int register_savevm_live(const char *idstr,
630                          int instance_id,
631                          int version_id,
632                          SaveLiveStateHandler *save_live_state,
633                          SaveStateHandler *save_state,
634                          LoadStateHandler *load_state,
635                          void *opaque)
636 {
637     SaveStateEntry *se, **pse;
638     static int global_section_id;
639
640     se = qemu_malloc(sizeof(SaveStateEntry));
641     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
642     se->instance_id = (instance_id == -1) ? 0 : instance_id;
643     se->version_id = version_id;
644     se->section_id = global_section_id++;
645     se->save_live_state = save_live_state;
646     se->save_state = save_state;
647     se->load_state = load_state;
648     se->opaque = opaque;
649     se->next = NULL;
650
651     /* add at the end of list */
652     pse = &first_se;
653     while (*pse != NULL) {
654         if (instance_id == -1
655                 && strcmp(se->idstr, (*pse)->idstr) == 0
656                 && se->instance_id <= (*pse)->instance_id)
657             se->instance_id = (*pse)->instance_id + 1;
658         pse = &(*pse)->next;
659     }
660     *pse = se;
661     return 0;
662 }
663
664 int register_savevm(const char *idstr,
665                     int instance_id,
666                     int version_id,
667                     SaveStateHandler *save_state,
668                     LoadStateHandler *load_state,
669                     void *opaque)
670 {
671     return register_savevm_live(idstr, instance_id, version_id,
672                                 NULL, save_state, load_state, opaque);
673 }
674
675 void unregister_savevm(const char *idstr, void *opaque)
676 {
677     SaveStateEntry **pse;
678
679     pse = &first_se;
680     while (*pse != NULL) {
681         if (strcmp((*pse)->idstr, idstr) == 0 && (*pse)->opaque == opaque) {
682             SaveStateEntry *next = (*pse)->next;
683             qemu_free(*pse);
684             *pse = next;
685             continue;
686         }
687         pse = &(*pse)->next;
688     }
689 }
690
691 #define QEMU_VM_FILE_MAGIC           0x5145564d
692 #define QEMU_VM_FILE_VERSION_COMPAT  0x00000002
693 #define QEMU_VM_FILE_VERSION         0x00000003
694
695 #define QEMU_VM_EOF                  0x00
696 #define QEMU_VM_SECTION_START        0x01
697 #define QEMU_VM_SECTION_PART         0x02
698 #define QEMU_VM_SECTION_END          0x03
699 #define QEMU_VM_SECTION_FULL         0x04
700
701 int qemu_savevm_state_begin(QEMUFile *f)
702 {
703     SaveStateEntry *se;
704
705     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
706     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
707
708     for (se = first_se; se != NULL; se = se->next) {
709         int len;
710
711         if (se->save_live_state == NULL)
712             continue;
713
714         /* Section type */
715         qemu_put_byte(f, QEMU_VM_SECTION_START);
716         qemu_put_be32(f, se->section_id);
717
718         /* ID string */
719         len = strlen(se->idstr);
720         qemu_put_byte(f, len);
721         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
722
723         qemu_put_be32(f, se->instance_id);
724         qemu_put_be32(f, se->version_id);
725
726         se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
727     }
728
729     if (qemu_file_has_error(f))
730         return -EIO;
731
732     return 0;
733 }
734
735 int qemu_savevm_state_iterate(QEMUFile *f)
736 {
737     SaveStateEntry *se;
738     int ret = 1;
739
740     for (se = first_se; se != NULL; se = se->next) {
741         if (se->save_live_state == NULL)
742             continue;
743
744         /* Section type */
745         qemu_put_byte(f, QEMU_VM_SECTION_PART);
746         qemu_put_be32(f, se->section_id);
747
748         ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
749     }
750
751     if (ret)
752         return 1;
753
754     if (qemu_file_has_error(f))
755         return -EIO;
756
757     return 0;
758 }
759
760 int qemu_savevm_state_complete(QEMUFile *f)
761 {
762     SaveStateEntry *se;
763
764     for (se = first_se; se != NULL; se = se->next) {
765         if (se->save_live_state == NULL)
766             continue;
767
768         /* Section type */
769         qemu_put_byte(f, QEMU_VM_SECTION_END);
770         qemu_put_be32(f, se->section_id);
771
772         se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
773     }
774
775     for(se = first_se; se != NULL; se = se->next) {
776         int len;
777
778         if (se->save_state == NULL)
779             continue;
780
781         /* Section type */
782         qemu_put_byte(f, QEMU_VM_SECTION_FULL);
783         qemu_put_be32(f, se->section_id);
784
785         /* ID string */
786         len = strlen(se->idstr);
787         qemu_put_byte(f, len);
788         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
789
790         qemu_put_be32(f, se->instance_id);
791         qemu_put_be32(f, se->version_id);
792
793         se->save_state(f, se->opaque);
794     }
795
796     qemu_put_byte(f, QEMU_VM_EOF);
797
798     if (qemu_file_has_error(f))
799         return -EIO;
800
801     return 0;
802 }
803
804 int qemu_savevm_state(QEMUFile *f)
805 {
806     int saved_vm_running;
807     int ret;
808
809     saved_vm_running = vm_running;
810     vm_stop(0);
811
812     bdrv_flush_all();
813
814     ret = qemu_savevm_state_begin(f);
815     if (ret < 0)
816         goto out;
817
818     do {
819         ret = qemu_savevm_state_iterate(f);
820         if (ret < 0)
821             goto out;
822     } while (ret == 0);
823
824     ret = qemu_savevm_state_complete(f);
825
826 out:
827     if (qemu_file_has_error(f))
828         ret = -EIO;
829
830     if (!ret && saved_vm_running)
831         vm_start();
832
833     return ret;
834 }
835
836 static SaveStateEntry *find_se(const char *idstr, int instance_id)
837 {
838     SaveStateEntry *se;
839
840     for(se = first_se; se != NULL; se = se->next) {
841         if (!strcmp(se->idstr, idstr) &&
842             instance_id == se->instance_id)
843             return se;
844     }
845     return NULL;
846 }
847
848 typedef struct LoadStateEntry {
849     SaveStateEntry *se;
850     int section_id;
851     int version_id;
852     struct LoadStateEntry *next;
853 } LoadStateEntry;
854
855 static int qemu_loadvm_state_v2(QEMUFile *f)
856 {
857     SaveStateEntry *se;
858     int len, ret, instance_id, record_len, version_id;
859     int64_t total_len, end_pos, cur_pos;
860     char idstr[256];
861
862     total_len = qemu_get_be64(f);
863     end_pos = total_len + qemu_ftell(f);
864     for(;;) {
865         if (qemu_ftell(f) >= end_pos)
866             break;
867         len = qemu_get_byte(f);
868         qemu_get_buffer(f, (uint8_t *)idstr, len);
869         idstr[len] = '\0';
870         instance_id = qemu_get_be32(f);
871         version_id = qemu_get_be32(f);
872         record_len = qemu_get_be32(f);
873         cur_pos = qemu_ftell(f);
874         se = find_se(idstr, instance_id);
875         if (!se) {
876             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
877                     instance_id, idstr);
878         } else {
879             ret = se->load_state(f, se->opaque, version_id);
880             if (ret < 0) {
881                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
882                         instance_id, idstr);
883                 return ret;
884             }
885         }
886         /* always seek to exact end of record */
887         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
888     }
889
890     if (qemu_file_has_error(f))
891         return -EIO;
892
893     return 0;
894 }
895
896 int qemu_loadvm_state(QEMUFile *f)
897 {
898     LoadStateEntry *first_le = NULL;
899     uint8_t section_type;
900     unsigned int v;
901     int ret;
902
903     v = qemu_get_be32(f);
904     if (v != QEMU_VM_FILE_MAGIC)
905         return -EINVAL;
906
907     v = qemu_get_be32(f);
908     if (v == QEMU_VM_FILE_VERSION_COMPAT)
909         return qemu_loadvm_state_v2(f);
910     if (v != QEMU_VM_FILE_VERSION)
911         return -ENOTSUP;
912
913     while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
914         uint32_t instance_id, version_id, section_id;
915         LoadStateEntry *le;
916         SaveStateEntry *se;
917         char idstr[257];
918         int len;
919
920         switch (section_type) {
921         case QEMU_VM_SECTION_START:
922         case QEMU_VM_SECTION_FULL:
923             /* Read section start */
924             section_id = qemu_get_be32(f);
925             len = qemu_get_byte(f);
926             qemu_get_buffer(f, (uint8_t *)idstr, len);
927             idstr[len] = 0;
928             instance_id = qemu_get_be32(f);
929             version_id = qemu_get_be32(f);
930
931             /* Find savevm section */
932             se = find_se(idstr, instance_id);
933             if (se == NULL) {
934                 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
935                 ret = -EINVAL;
936                 goto out;
937             }
938
939             /* Validate version */
940             if (version_id > se->version_id) {
941                 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
942                         version_id, idstr, se->version_id);
943                 ret = -EINVAL;
944                 goto out;
945             }
946
947             /* Add entry */
948             le = qemu_mallocz(sizeof(*le));
949
950             le->se = se;
951             le->section_id = section_id;
952             le->version_id = version_id;
953             le->next = first_le;
954             first_le = le;
955
956             le->se->load_state(f, le->se->opaque, le->version_id);
957             break;
958         case QEMU_VM_SECTION_PART:
959         case QEMU_VM_SECTION_END:
960             section_id = qemu_get_be32(f);
961
962             for (le = first_le; le && le->section_id != section_id; le = le->next);
963             if (le == NULL) {
964                 fprintf(stderr, "Unknown savevm section %d\n", section_id);
965                 ret = -EINVAL;
966                 goto out;
967             }
968
969             le->se->load_state(f, le->se->opaque, le->version_id);
970             break;
971         default:
972             fprintf(stderr, "Unknown savevm section type %d\n", section_type);
973             ret = -EINVAL;
974             goto out;
975         }
976     }
977
978     ret = 0;
979
980 out:
981     while (first_le) {
982         LoadStateEntry *le = first_le;
983         first_le = first_le->next;
984         qemu_free(le);
985     }
986
987     if (qemu_file_has_error(f))
988         ret = -EIO;
989
990     return ret;
991 }
992
993 /* device can contain snapshots */
994 static int bdrv_can_snapshot(BlockDriverState *bs)
995 {
996     return (bs &&
997             !bdrv_is_removable(bs) &&
998             !bdrv_is_read_only(bs));
999 }
1000
1001 /* device must be snapshots in order to have a reliable snapshot */
1002 static int bdrv_has_snapshot(BlockDriverState *bs)
1003 {
1004     return (bs &&
1005             !bdrv_is_removable(bs) &&
1006             !bdrv_is_read_only(bs));
1007 }
1008
1009 static BlockDriverState *get_bs_snapshots(void)
1010 {
1011     BlockDriverState *bs;
1012     int i;
1013
1014     if (bs_snapshots)
1015         return bs_snapshots;
1016     for(i = 0; i <= nb_drives; i++) {
1017         bs = drives_table[i].bdrv;
1018         if (bdrv_can_snapshot(bs))
1019             goto ok;
1020     }
1021     return NULL;
1022  ok:
1023     bs_snapshots = bs;
1024     return bs;
1025 }
1026
1027 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
1028                               const char *name)
1029 {
1030     QEMUSnapshotInfo *sn_tab, *sn;
1031     int nb_sns, i, ret;
1032
1033     ret = -ENOENT;
1034     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1035     if (nb_sns < 0)
1036         return ret;
1037     for(i = 0; i < nb_sns; i++) {
1038         sn = &sn_tab[i];
1039         if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
1040             *sn_info = *sn;
1041             ret = 0;
1042             break;
1043         }
1044     }
1045     qemu_free(sn_tab);
1046     return ret;
1047 }
1048
1049 void do_savevm(Monitor *mon, const char *name)
1050 {
1051     BlockDriverState *bs, *bs1;
1052     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
1053     int must_delete, ret, i;
1054     QEMUFile *f;
1055     int saved_vm_running;
1056     uint32_t vm_state_size;
1057 #ifdef _WIN32
1058     struct _timeb tb;
1059 #else
1060     struct timeval tv;
1061 #endif
1062
1063     bs = get_bs_snapshots();
1064     if (!bs) {
1065         monitor_printf(mon, "No block device can accept snapshots\n");
1066         return;
1067     }
1068
1069     /* ??? Should this occur after vm_stop?  */
1070     qemu_aio_flush();
1071
1072     saved_vm_running = vm_running;
1073     vm_stop(0);
1074
1075     must_delete = 0;
1076     if (name) {
1077         ret = bdrv_snapshot_find(bs, old_sn, name);
1078         if (ret >= 0) {
1079             must_delete = 1;
1080         }
1081     }
1082     memset(sn, 0, sizeof(*sn));
1083     if (must_delete) {
1084         pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
1085         pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
1086     } else {
1087         if (name)
1088             pstrcpy(sn->name, sizeof(sn->name), name);
1089     }
1090
1091     /* fill auxiliary fields */
1092 #ifdef _WIN32
1093     _ftime(&tb);
1094     sn->date_sec = tb.time;
1095     sn->date_nsec = tb.millitm * 1000000;
1096 #else
1097     gettimeofday(&tv, NULL);
1098     sn->date_sec = tv.tv_sec;
1099     sn->date_nsec = tv.tv_usec * 1000;
1100 #endif
1101     sn->vm_clock_nsec = qemu_get_clock(vm_clock);
1102
1103     /* save the VM state */
1104     f = qemu_fopen_bdrv(bs, 1);
1105     if (!f) {
1106         monitor_printf(mon, "Could not open VM state file\n");
1107         goto the_end;
1108     }
1109     ret = qemu_savevm_state(f);
1110     vm_state_size = qemu_ftell(f);
1111     qemu_fclose(f);
1112     if (ret < 0) {
1113         monitor_printf(mon, "Error %d while writing VM\n", ret);
1114         goto the_end;
1115     }
1116
1117     /* create the snapshots */
1118
1119     for(i = 0; i < nb_drives; i++) {
1120         bs1 = drives_table[i].bdrv;
1121         if (bdrv_has_snapshot(bs1)) {
1122             if (must_delete) {
1123                 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
1124                 if (ret < 0) {
1125                     monitor_printf(mon,
1126                                    "Error while deleting snapshot on '%s'\n",
1127                                    bdrv_get_device_name(bs1));
1128                 }
1129             }
1130             /* Write VM state size only to the image that contains the state */
1131             sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
1132             ret = bdrv_snapshot_create(bs1, sn);
1133             if (ret < 0) {
1134                 monitor_printf(mon, "Error while creating snapshot on '%s'\n",
1135                                bdrv_get_device_name(bs1));
1136             }
1137         }
1138     }
1139
1140  the_end:
1141     if (saved_vm_running)
1142         vm_start();
1143 }
1144
1145 void do_loadvm(Monitor *mon, const char *name)
1146 {
1147     BlockDriverState *bs, *bs1;
1148     QEMUSnapshotInfo sn;
1149     QEMUFile *f;
1150     int i, ret;
1151     int saved_vm_running;
1152
1153     bs = get_bs_snapshots();
1154     if (!bs) {
1155         monitor_printf(mon, "No block device supports snapshots\n");
1156         return;
1157     }
1158
1159     /* Flush all IO requests so they don't interfere with the new state.  */
1160     qemu_aio_flush();
1161
1162     saved_vm_running = vm_running;
1163     vm_stop(0);
1164
1165     for(i = 0; i <= nb_drives; i++) {
1166         bs1 = drives_table[i].bdrv;
1167         if (bdrv_has_snapshot(bs1)) {
1168             ret = bdrv_snapshot_goto(bs1, name);
1169             if (ret < 0) {
1170                 if (bs != bs1)
1171                     monitor_printf(mon, "Warning: ");
1172                 switch(ret) {
1173                 case -ENOTSUP:
1174                     monitor_printf(mon,
1175                                    "Snapshots not supported on device '%s'\n",
1176                                    bdrv_get_device_name(bs1));
1177                     break;
1178                 case -ENOENT:
1179                     monitor_printf(mon, "Could not find snapshot '%s' on "
1180                                    "device '%s'\n",
1181                                    name, bdrv_get_device_name(bs1));
1182                     break;
1183                 default:
1184                     monitor_printf(mon, "Error %d while activating snapshot on"
1185                                    " '%s'\n", ret, bdrv_get_device_name(bs1));
1186                     break;
1187                 }
1188                 /* fatal on snapshot block device */
1189                 if (bs == bs1)
1190                     goto the_end;
1191             }
1192         }
1193     }
1194
1195     /* Don't even try to load empty VM states */
1196     ret = bdrv_snapshot_find(bs, &sn, name);
1197     if ((ret >= 0) && (sn.vm_state_size == 0))
1198         goto the_end;
1199
1200     /* restore the VM state */
1201     f = qemu_fopen_bdrv(bs, 0);
1202     if (!f) {
1203         monitor_printf(mon, "Could not open VM state file\n");
1204         goto the_end;
1205     }
1206     ret = qemu_loadvm_state(f);
1207     qemu_fclose(f);
1208     if (ret < 0) {
1209         monitor_printf(mon, "Error %d while loading VM state\n", ret);
1210     }
1211  the_end:
1212     if (saved_vm_running)
1213         vm_start();
1214 }
1215
1216 void do_delvm(Monitor *mon, const char *name)
1217 {
1218     BlockDriverState *bs, *bs1;
1219     int i, ret;
1220
1221     bs = get_bs_snapshots();
1222     if (!bs) {
1223         monitor_printf(mon, "No block device supports snapshots\n");
1224         return;
1225     }
1226
1227     for(i = 0; i <= nb_drives; i++) {
1228         bs1 = drives_table[i].bdrv;
1229         if (bdrv_has_snapshot(bs1)) {
1230             ret = bdrv_snapshot_delete(bs1, name);
1231             if (ret < 0) {
1232                 if (ret == -ENOTSUP)
1233                     monitor_printf(mon,
1234                                    "Snapshots not supported on device '%s'\n",
1235                                    bdrv_get_device_name(bs1));
1236                 else
1237                     monitor_printf(mon, "Error %d while deleting snapshot on "
1238                                    "'%s'\n", ret, bdrv_get_device_name(bs1));
1239             }
1240         }
1241     }
1242 }
1243
1244 void do_info_snapshots(Monitor *mon)
1245 {
1246     BlockDriverState *bs, *bs1;
1247     QEMUSnapshotInfo *sn_tab, *sn;
1248     int nb_sns, i;
1249     char buf[256];
1250
1251     bs = get_bs_snapshots();
1252     if (!bs) {
1253         monitor_printf(mon, "No available block device supports snapshots\n");
1254         return;
1255     }
1256     monitor_printf(mon, "Snapshot devices:");
1257     for(i = 0; i <= nb_drives; i++) {
1258         bs1 = drives_table[i].bdrv;
1259         if (bdrv_has_snapshot(bs1)) {
1260             if (bs == bs1)
1261                 monitor_printf(mon, " %s", bdrv_get_device_name(bs1));
1262         }
1263     }
1264     monitor_printf(mon, "\n");
1265
1266     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1267     if (nb_sns < 0) {
1268         monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);
1269         return;
1270     }
1271     monitor_printf(mon, "Snapshot list (from %s):\n",
1272                    bdrv_get_device_name(bs));
1273     monitor_printf(mon, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1274     for(i = 0; i < nb_sns; i++) {
1275         sn = &sn_tab[i];
1276         monitor_printf(mon, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
1277     }
1278     qemu_free(sn_tab);
1279 }