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