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