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