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