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