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