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 CONFIG_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#include <arpa/inet.h>
46#include <dirent.h>
47#include <netdb.h>
48#include <sys/select.h>
49#ifdef CONFIG_BSD
50#include <sys/stat.h>
51#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
52#include <libutil.h>
53#else
54#include <util.h>
55#endif
56#ifdef __linux__
57#include <pty.h>
58#include <malloc.h>
59#include <linux/rtc.h>
60#endif
61#endif
62#endif
63
64#ifdef _WIN32
65#include <windows.h>
66#include <malloc.h>
67#include <sys/timeb.h>
68#include <mmsystem.h>
69#define getopt_long_only getopt_long
70#define memalign(align, size) malloc(size)
71#endif
72
73#include "qemu-common.h"
74#include "hw/hw.h"
75#include "net.h"
76#include "monitor.h"
77#include "sysemu.h"
78#include "qemu-timer.h"
79#include "qemu-char.h"
80#include "blockdev.h"
81#include "block.h"
82#include "audio/audio.h"
83#include "migration.h"
84#include "qemu_socket.h"
85#include "qemu-queue.h"
86#include "qemu_file.h"
87#include "android/snapshot.h"
88
89
90#define SELF_ANNOUNCE_ROUNDS 5
91
92#ifndef ETH_P_RARP
93#define ETH_P_RARP 0x8035
94#endif
95#define ARP_HTYPE_ETH 0x0001
96#define ARP_PTYPE_IP 0x0800
97#define ARP_OP_REQUEST_REV 0x3
98
99static int announce_self_create(uint8_t *buf,
100				uint8_t *mac_addr)
101{
102    /* Ethernet header. */
103    memset(buf, 0xff, 6);         /* destination MAC addr */
104    memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
105    *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
106
107    /* RARP header. */
108    *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
109    *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
110    *(buf + 18) = 6; /* hardware addr length (ethernet) */
111    *(buf + 19) = 4; /* protocol addr length (IPv4) */
112    *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
113    memcpy(buf + 22, mac_addr, 6); /* source hw addr */
114    memset(buf + 28, 0x00, 4);     /* source protocol addr */
115    memcpy(buf + 32, mac_addr, 6); /* target hw addr */
116    memset(buf + 38, 0x00, 4);     /* target protocol addr */
117
118    /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
119    memset(buf + 42, 0x00, 18);
120
121    return 60; /* len (FCS will be added by hardware) */
122}
123
124static void qemu_announce_self_once(void *opaque)
125{
126    int i, len;
127    VLANState *vlan;
128    VLANClientState *vc;
129    uint8_t buf[256];
130    static int count = SELF_ANNOUNCE_ROUNDS;
131    QEMUTimer *timer = *(QEMUTimer **)opaque;
132
133    for (i = 0; i < MAX_NICS; i++) {
134        if (!nd_table[i].used)
135            continue;
136        len = announce_self_create(buf, nd_table[i].macaddr);
137        vlan = nd_table[i].vlan;
138	for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
139            vc->receive(vc, buf, len);
140        }
141    }
142    if (--count) {
143        /* delay 50ms, 150ms, 250ms, ... */
144        qemu_mod_timer(timer, qemu_get_clock_ms(rt_clock) +
145                       50 + (SELF_ANNOUNCE_ROUNDS - count - 1) * 100);
146    } else {
147	    qemu_del_timer(timer);
148	    qemu_free_timer(timer);
149    }
150}
151
152void qemu_announce_self(void)
153{
154	static QEMUTimer *timer;
155	timer = qemu_new_timer_ms(rt_clock, qemu_announce_self_once, &timer);
156	qemu_announce_self_once(&timer);
157}
158
159/***********************************************************/
160/* savevm/loadvm support */
161
162#define IO_BUF_SIZE 32768
163
164struct QEMUFile {
165    QEMUFilePutBufferFunc *put_buffer;
166    QEMUFileGetBufferFunc *get_buffer;
167    QEMUFileCloseFunc *close;
168    QEMUFileRateLimit *rate_limit;
169    QEMUFileSetRateLimit *set_rate_limit;
170    QEMUFileGetRateLimit *get_rate_limit;
171    void *opaque;
172    int is_write;
173
174    int64_t buf_offset; /* start of buffer when writing, end of buffer
175                           when reading */
176    int buf_index;
177    int buf_size; /* 0 when writing */
178    uint8_t buf[IO_BUF_SIZE];
179
180    int has_error;
181};
182
183typedef struct QEMUFileStdio
184{
185    FILE *stdio_file;
186    QEMUFile *file;
187} QEMUFileStdio;
188
189typedef struct QEMUFileSocket
190{
191    int fd;
192    QEMUFile *file;
193} QEMUFileSocket;
194
195static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
196{
197    QEMUFileSocket *s = opaque;
198    ssize_t len;
199
200    do {
201        len = recv(s->fd, (void *)buf, size, 0);
202    } while (len == -1 && socket_error() == EINTR);
203
204    if (len == -1)
205        len = -socket_error();
206
207    return len;
208}
209
210static int file_socket_close(void *opaque)
211{
212    QEMUFileSocket *s = opaque;
213    qemu_free(s);
214    return 0;
215}
216
217static int stdio_put_buffer(void *opaque, const uint8_t *buf, int64_t pos, int size)
218{
219    QEMUFileStdio *s = opaque;
220    return fwrite(buf, 1, size, s->stdio_file);
221}
222
223static int stdio_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
224{
225    QEMUFileStdio *s = opaque;
226    FILE *fp = s->stdio_file;
227    int bytes;
228
229    do {
230        clearerr(fp);
231        bytes = fread(buf, 1, size, fp);
232    } while ((bytes == 0) && ferror(fp) && (errno == EINTR));
233    return bytes;
234}
235
236static int stdio_pclose(void *opaque)
237{
238    QEMUFileStdio *s = opaque;
239    int ret;
240    ret = pclose(s->stdio_file);
241    qemu_free(s);
242    return ret;
243}
244
245static int stdio_fclose(void *opaque)
246{
247    QEMUFileStdio *s = opaque;
248    fclose(s->stdio_file);
249    qemu_free(s);
250    return 0;
251}
252
253QEMUFile *qemu_popen(FILE *stdio_file, const char *mode)
254{
255    QEMUFileStdio *s;
256
257    if (stdio_file == NULL || mode == NULL || (mode[0] != 'r' && mode[0] != 'w') || mode[1] != 0) {
258        fprintf(stderr, "qemu_popen: Argument validity check failed\n");
259        return NULL;
260    }
261
262    s = qemu_mallocz(sizeof(QEMUFileStdio));
263
264    s->stdio_file = stdio_file;
265
266    if(mode[0] == 'r') {
267        s->file = qemu_fopen_ops(s, NULL, stdio_get_buffer, stdio_pclose,
268				 NULL, NULL, NULL);
269    } else {
270        s->file = qemu_fopen_ops(s, stdio_put_buffer, NULL, stdio_pclose,
271				 NULL, NULL, NULL);
272    }
273    return s->file;
274}
275
276QEMUFile *qemu_popen_cmd(const char *command, const char *mode)
277{
278    FILE *popen_file;
279
280    popen_file = popen(command, mode);
281    if(popen_file == NULL) {
282        return NULL;
283    }
284
285    return qemu_popen(popen_file, mode);
286}
287
288int qemu_stdio_fd(QEMUFile *f)
289{
290    QEMUFileStdio *p;
291    int fd;
292
293    p = (QEMUFileStdio *)f->opaque;
294    fd = fileno(p->stdio_file);
295
296    return fd;
297}
298
299QEMUFile *qemu_fdopen(int fd, const char *mode)
300{
301    QEMUFileStdio *s;
302
303    if (mode == NULL ||
304	(mode[0] != 'r' && mode[0] != 'w') ||
305	mode[1] != 'b' || mode[2] != 0) {
306        fprintf(stderr, "qemu_fdopen: Argument validity check failed\n");
307        return NULL;
308    }
309
310    s = qemu_mallocz(sizeof(QEMUFileStdio));
311    s->stdio_file = fdopen(fd, mode);
312    if (!s->stdio_file)
313        goto fail;
314
315    if(mode[0] == 'r') {
316        s->file = qemu_fopen_ops(s, NULL, stdio_get_buffer, stdio_fclose,
317				 NULL, NULL, NULL);
318    } else {
319        s->file = qemu_fopen_ops(s, stdio_put_buffer, NULL, stdio_fclose,
320				 NULL, NULL, NULL);
321    }
322    return s->file;
323
324fail:
325    qemu_free(s);
326    return NULL;
327}
328
329QEMUFile *qemu_fopen_socket(int fd)
330{
331    QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
332
333    s->fd = fd;
334    s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, file_socket_close,
335			     NULL, NULL, NULL);
336    return s->file;
337}
338
339static int file_put_buffer(void *opaque, const uint8_t *buf,
340                            int64_t pos, int size)
341{
342    QEMUFileStdio *s = opaque;
343    fseek(s->stdio_file, pos, SEEK_SET);
344    return fwrite(buf, 1, size, s->stdio_file);
345}
346
347static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
348{
349    QEMUFileStdio *s = opaque;
350    fseek(s->stdio_file, pos, SEEK_SET);
351    return fread(buf, 1, size, s->stdio_file);
352}
353
354QEMUFile *qemu_fopen(const char *filename, const char *mode)
355{
356    QEMUFileStdio *s;
357
358    if (mode == NULL ||
359	(mode[0] != 'r' && mode[0] != 'w') ||
360	mode[1] != 'b' || mode[2] != 0) {
361        fprintf(stderr, "qemu_fopen: Argument validity check failed\n");
362        return NULL;
363    }
364
365    s = qemu_mallocz(sizeof(QEMUFileStdio));
366
367    s->stdio_file = fopen(filename, mode);
368    if (!s->stdio_file)
369        goto fail;
370
371    if(mode[0] == 'w') {
372        s->file = qemu_fopen_ops(s, file_put_buffer, NULL, stdio_fclose,
373				 NULL, NULL, NULL);
374    } else {
375        s->file = qemu_fopen_ops(s, NULL, file_get_buffer, stdio_fclose,
376			       NULL, NULL, NULL);
377    }
378    return s->file;
379fail:
380    qemu_free(s);
381    return NULL;
382}
383
384static int block_put_buffer(void *opaque, const uint8_t *buf,
385                           int64_t pos, int size)
386{
387    bdrv_save_vmstate(opaque, buf, pos, size);
388    return size;
389}
390
391static int block_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
392{
393    return bdrv_load_vmstate(opaque, buf, pos, size);
394}
395
396static int bdrv_fclose(void *opaque)
397{
398    return 0;
399}
400
401static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
402{
403    if (is_writable)
404        return qemu_fopen_ops(bs, block_put_buffer, NULL, bdrv_fclose,
405			      NULL, NULL, NULL);
406    return qemu_fopen_ops(bs, NULL, block_get_buffer, bdrv_fclose, NULL, NULL, NULL);
407}
408
409QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
410                         QEMUFileGetBufferFunc *get_buffer,
411                         QEMUFileCloseFunc *close,
412                         QEMUFileRateLimit *rate_limit,
413                         QEMUFileSetRateLimit *set_rate_limit,
414                         QEMUFileGetRateLimit *get_rate_limit)
415{
416    QEMUFile *f;
417
418    f = qemu_mallocz(sizeof(QEMUFile));
419
420    f->opaque = opaque;
421    f->put_buffer = put_buffer;
422    f->get_buffer = get_buffer;
423    f->close = close;
424    f->rate_limit = rate_limit;
425    f->set_rate_limit = set_rate_limit;
426    f->get_rate_limit = get_rate_limit;
427    f->is_write = 0;
428
429    return f;
430}
431
432int qemu_file_has_error(QEMUFile *f)
433{
434    return f->has_error;
435}
436
437void qemu_file_set_error(QEMUFile *f)
438{
439    f->has_error = 1;
440}
441
442void qemu_fflush(QEMUFile *f)
443{
444    if (!f->put_buffer)
445        return;
446
447    if (f->is_write && f->buf_index > 0) {
448        int len;
449
450        len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
451        if (len > 0)
452            f->buf_offset += f->buf_index;
453        else
454            f->has_error = 1;
455        f->buf_index = 0;
456    }
457}
458
459static void qemu_fill_buffer(QEMUFile *f)
460{
461    int len;
462
463    if (!f->get_buffer)
464        return;
465
466    if (f->is_write)
467        abort();
468
469    len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
470    if (len > 0) {
471        f->buf_index = 0;
472        f->buf_size = len;
473        f->buf_offset += len;
474    } else if (len != -EAGAIN)
475        f->has_error = 1;
476}
477
478int qemu_fclose(QEMUFile *f)
479{
480    int ret = 0;
481    qemu_fflush(f);
482    if (f->close)
483        ret = f->close(f->opaque);
484    qemu_free(f);
485    return ret;
486}
487
488void qemu_file_put_notify(QEMUFile *f)
489{
490    f->put_buffer(f->opaque, NULL, 0, 0);
491}
492
493void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
494{
495    int l;
496
497    if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
498        fprintf(stderr,
499                "Attempted to write to buffer while read buffer is not empty\n");
500        abort();
501    }
502
503    while (!f->has_error && size > 0) {
504        l = IO_BUF_SIZE - f->buf_index;
505        if (l > size)
506            l = size;
507        memcpy(f->buf + f->buf_index, buf, l);
508        f->is_write = 1;
509        f->buf_index += l;
510        buf += l;
511        size -= l;
512        if (f->buf_index >= IO_BUF_SIZE)
513            qemu_fflush(f);
514    }
515}
516
517void qemu_put_byte(QEMUFile *f, int v)
518{
519    if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
520        fprintf(stderr,
521                "Attempted to write to buffer while read buffer is not empty\n");
522        abort();
523    }
524
525    f->buf[f->buf_index++] = v;
526    f->is_write = 1;
527    if (f->buf_index >= IO_BUF_SIZE)
528        qemu_fflush(f);
529}
530
531int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
532{
533    int size, l;
534
535    if (f->is_write)
536        abort();
537
538    size = size1;
539    while (size > 0) {
540        l = f->buf_size - f->buf_index;
541        if (l == 0) {
542            qemu_fill_buffer(f);
543            l = f->buf_size - f->buf_index;
544            if (l == 0)
545                break;
546        }
547        if (l > size)
548            l = size;
549        memcpy(buf, f->buf + f->buf_index, l);
550        f->buf_index += l;
551        buf += l;
552        size -= l;
553    }
554    return size1 - size;
555}
556
557int qemu_get_byte(QEMUFile *f)
558{
559    if (f->is_write)
560        abort();
561
562    if (f->buf_index >= f->buf_size) {
563        qemu_fill_buffer(f);
564        if (f->buf_index >= f->buf_size)
565            return 0;
566    }
567    return f->buf[f->buf_index++];
568}
569
570int64_t qemu_ftell(QEMUFile *f)
571{
572    return f->buf_offset - f->buf_size + f->buf_index;
573}
574
575int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
576{
577    if (whence == SEEK_SET) {
578        /* nothing to do */
579    } else if (whence == SEEK_CUR) {
580        pos += qemu_ftell(f);
581    } else {
582        /* SEEK_END not supported */
583        return -1;
584    }
585    if (f->put_buffer) {
586        qemu_fflush(f);
587        f->buf_offset = pos;
588    } else {
589        f->buf_offset = pos;
590        f->buf_index = 0;
591        f->buf_size = 0;
592    }
593    return pos;
594}
595
596int qemu_file_rate_limit(QEMUFile *f)
597{
598    if (f->rate_limit)
599        return f->rate_limit(f->opaque);
600
601    return 0;
602}
603
604int64_t qemu_file_get_rate_limit(QEMUFile *f)
605{
606    if (f->get_rate_limit)
607        return f->get_rate_limit(f->opaque);
608
609    return 0;
610}
611
612int64_t qemu_file_set_rate_limit(QEMUFile *f, int64_t new_rate)
613{
614    /* any failed or completed migration keeps its state to allow probing of
615     * migration data, but has no associated file anymore */
616    if (f && f->set_rate_limit)
617        return f->set_rate_limit(f->opaque, new_rate);
618
619    return 0;
620}
621
622void qemu_put_be16(QEMUFile *f, unsigned int v)
623{
624    qemu_put_byte(f, v >> 8);
625    qemu_put_byte(f, v);
626}
627
628void qemu_put_be32(QEMUFile *f, unsigned int v)
629{
630    qemu_put_byte(f, v >> 24);
631    qemu_put_byte(f, v >> 16);
632    qemu_put_byte(f, v >> 8);
633    qemu_put_byte(f, v);
634}
635
636void qemu_put_be64(QEMUFile *f, uint64_t v)
637{
638    qemu_put_be32(f, v >> 32);
639    qemu_put_be32(f, v);
640}
641
642unsigned int qemu_get_be16(QEMUFile *f)
643{
644    unsigned int v;
645    v = qemu_get_byte(f) << 8;
646    v |= qemu_get_byte(f);
647    return v;
648}
649
650unsigned int qemu_get_be32(QEMUFile *f)
651{
652    unsigned int v;
653    v = qemu_get_byte(f) << 24;
654    v |= qemu_get_byte(f) << 16;
655    v |= qemu_get_byte(f) << 8;
656    v |= qemu_get_byte(f);
657    return v;
658}
659
660uint64_t qemu_get_be64(QEMUFile *f)
661{
662    uint64_t v;
663    v = (uint64_t)qemu_get_be32(f) << 32;
664    v |= qemu_get_be32(f);
665    return v;
666}
667
668void  qemu_put_struct(QEMUFile*  f, const QField*  fields, const void*  s)
669{
670    const QField*  qf = fields;
671
672    /* Iterate over struct fields */
673    while (qf->type != Q_FIELD_END) {
674        uint8_t*  p = (uint8_t*)s + qf->offset;
675
676        switch (qf->type) {
677            case Q_FIELD_BYTE:
678                qemu_put_byte(f, p[0]);
679                break;
680            case Q_FIELD_INT16:
681                qemu_put_be16(f, ((uint16_t*)p)[0]);
682                break;
683            case Q_FIELD_INT32:
684                qemu_put_be32(f, ((uint32_t*)p)[0]);
685                break;
686            case Q_FIELD_INT64:
687                qemu_put_be64(f, ((uint64_t*)p)[0]);
688                break;
689            case Q_FIELD_BUFFER:
690                if (qf[1].type != Q_FIELD_BUFFER_SIZE ||
691                    qf[2].type != Q_FIELD_BUFFER_SIZE)
692                {
693                    fprintf(stderr, "%s: invalid QFIELD_BUFFER item passed as argument. aborting\n",
694                            __FUNCTION__ );
695                    exit(1);
696                }
697                else
698                {
699                    uint32_t  size = ((uint32_t)qf[1].offset << 16) | (uint32_t)qf[2].offset;
700
701                    qemu_put_buffer(f, p, size);
702                    qf += 2;
703                }
704                break;
705            default:
706                fprintf(stderr, "%s: invalid fields list passed as argument. aborting\n", __FUNCTION__);
707                exit(1);
708        }
709        qf++;
710    }
711}
712
713int   qemu_get_struct(QEMUFile*  f, const QField*  fields, void*  s)
714{
715    const QField*  qf = fields;
716
717    /* Iterate over struct fields */
718    while (qf->type != Q_FIELD_END) {
719        uint8_t*  p = (uint8_t*)s + qf->offset;
720
721        switch (qf->type) {
722            case Q_FIELD_BYTE:
723                p[0] = qemu_get_byte(f);
724                break;
725            case Q_FIELD_INT16:
726                ((uint16_t*)p)[0] = qemu_get_be16(f);
727                break;
728            case Q_FIELD_INT32:
729                ((uint32_t*)p)[0] = qemu_get_be32(f);
730                break;
731            case Q_FIELD_INT64:
732                ((uint64_t*)p)[0] = qemu_get_be64(f);
733                break;
734            case Q_FIELD_BUFFER:
735                if (qf[1].type != Q_FIELD_BUFFER_SIZE ||
736                        qf[2].type != Q_FIELD_BUFFER_SIZE)
737                {
738                    fprintf(stderr, "%s: invalid QFIELD_BUFFER item passed as argument.\n",
739                            __FUNCTION__ );
740                    return -1;
741                }
742                else
743                {
744                    uint32_t  size = ((uint32_t)qf[1].offset << 16) | (uint32_t)qf[2].offset;
745                    int       ret  = qemu_get_buffer(f, p, size);
746
747                    if (ret != size) {
748                        fprintf(stderr, "%s: not enough bytes to load structure\n", __FUNCTION__);
749                        return -1;
750                    }
751                    qf += 2;
752                }
753                break;
754            default:
755                fprintf(stderr, "%s: invalid fields list passed as argument. aborting\n", __FUNCTION__);
756                exit(1);
757        }
758        qf++;
759    }
760    return 0;
761}
762
763/* write a float to file */
764void qemu_put_float(QEMUFile *f, float v)
765{
766    uint8_t *bytes = (uint8_t*) &v;
767    qemu_put_buffer(f, bytes, sizeof(float));
768}
769
770/* read a float from file */
771float qemu_get_float(QEMUFile *f)
772{
773    uint8_t bytes[sizeof(float)];
774    qemu_get_buffer(f, bytes, sizeof(float));
775
776    return *((float*) bytes);
777}
778
779typedef struct SaveStateEntry {
780    char idstr[256];
781    int instance_id;
782    int version_id;
783    int section_id;
784    SaveLiveStateHandler *save_live_state;
785    SaveStateHandler *save_state;
786    LoadStateHandler *load_state;
787    void *opaque;
788    struct SaveStateEntry *next;
789} SaveStateEntry;
790
791static SaveStateEntry *first_se;
792
793/* TODO: Individual devices generally have very little idea about the rest
794   of the system, so instance_id should be removed/replaced.
795   Meanwhile pass -1 as instance_id if you do not already have a clearly
796   distinguishing id for all instances of your device class. */
797int register_savevm_live(const char *idstr,
798                         int instance_id,
799                         int version_id,
800                         SaveLiveStateHandler *save_live_state,
801                         SaveStateHandler *save_state,
802                         LoadStateHandler *load_state,
803                         void *opaque)
804{
805    SaveStateEntry *se, **pse;
806    static int global_section_id;
807
808    se = qemu_malloc(sizeof(SaveStateEntry));
809    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
810    se->instance_id = (instance_id == -1) ? 0 : instance_id;
811    se->version_id = version_id;
812    se->section_id = global_section_id++;
813    se->save_live_state = save_live_state;
814    se->save_state = save_state;
815    se->load_state = load_state;
816    se->opaque = opaque;
817    se->next = NULL;
818
819    /* add at the end of list */
820    pse = &first_se;
821    while (*pse != NULL) {
822        if (instance_id == -1
823                && strcmp(se->idstr, (*pse)->idstr) == 0
824                && se->instance_id <= (*pse)->instance_id)
825            se->instance_id = (*pse)->instance_id + 1;
826        pse = &(*pse)->next;
827    }
828    *pse = se;
829    return 0;
830}
831
832int register_savevm(const char *idstr,
833                    int instance_id,
834                    int version_id,
835                    SaveStateHandler *save_state,
836                    LoadStateHandler *load_state,
837                    void *opaque)
838{
839    return register_savevm_live(idstr, instance_id, version_id,
840                                NULL, save_state, load_state, opaque);
841}
842
843void unregister_savevm(const char *idstr, void *opaque)
844{
845    SaveStateEntry **pse;
846
847    pse = &first_se;
848    while (*pse != NULL) {
849        if (strcmp((*pse)->idstr, idstr) == 0 && (*pse)->opaque == opaque) {
850            SaveStateEntry *next = (*pse)->next;
851            qemu_free(*pse);
852            *pse = next;
853            continue;
854        }
855        pse = &(*pse)->next;
856    }
857}
858
859#define QEMU_VM_FILE_MAGIC           0x5145564d
860#define QEMU_VM_FILE_VERSION_COMPAT  0x00000002
861#define QEMU_VM_FILE_VERSION         0x00000003
862
863#define QEMU_VM_EOF                  0x00
864#define QEMU_VM_SECTION_START        0x01
865#define QEMU_VM_SECTION_PART         0x02
866#define QEMU_VM_SECTION_END          0x03
867#define QEMU_VM_SECTION_FULL         0x04
868
869int qemu_savevm_state_begin(QEMUFile *f)
870{
871    SaveStateEntry *se;
872
873    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
874    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
875
876    for (se = first_se; se != NULL; se = se->next) {
877        int len;
878
879        if (se->save_live_state == NULL)
880            continue;
881
882        /* Section type */
883        qemu_put_byte(f, QEMU_VM_SECTION_START);
884        qemu_put_be32(f, se->section_id);
885
886        /* ID string */
887        len = strlen(se->idstr);
888        qemu_put_byte(f, len);
889        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
890
891        qemu_put_be32(f, se->instance_id);
892        qemu_put_be32(f, se->version_id);
893
894        se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
895    }
896
897    if (qemu_file_has_error(f))
898        return -EIO;
899
900    return 0;
901}
902
903int qemu_savevm_state_iterate(QEMUFile *f)
904{
905    SaveStateEntry *se;
906    int ret = 1;
907
908    for (se = first_se; se != NULL; se = se->next) {
909        if (se->save_live_state == NULL)
910            continue;
911
912        /* Section type */
913        qemu_put_byte(f, QEMU_VM_SECTION_PART);
914        qemu_put_be32(f, se->section_id);
915
916        ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
917    }
918
919    if (ret)
920        return 1;
921
922    if (qemu_file_has_error(f))
923        return -EIO;
924
925    return 0;
926}
927
928int qemu_savevm_state_complete(QEMUFile *f)
929{
930    SaveStateEntry *se;
931
932    for (se = first_se; se != NULL; se = se->next) {
933        if (se->save_live_state == NULL)
934            continue;
935
936        /* Section type */
937        qemu_put_byte(f, QEMU_VM_SECTION_END);
938        qemu_put_be32(f, se->section_id);
939
940        se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
941    }
942
943    for(se = first_se; se != NULL; se = se->next) {
944        int len;
945
946        if (se->save_state == NULL)
947            continue;
948
949        /* Section type */
950        qemu_put_byte(f, QEMU_VM_SECTION_FULL);
951        qemu_put_be32(f, se->section_id);
952
953        /* ID string */
954        len = strlen(se->idstr);
955        qemu_put_byte(f, len);
956        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
957
958        qemu_put_be32(f, se->instance_id);
959        qemu_put_be32(f, se->version_id);
960
961        se->save_state(f, se->opaque);
962    }
963
964    qemu_put_byte(f, QEMU_VM_EOF);
965
966    if (qemu_file_has_error(f))
967        return -EIO;
968
969    return 0;
970}
971
972int qemu_savevm_state(QEMUFile *f)
973{
974    int saved_vm_running;
975    int ret;
976
977    saved_vm_running = vm_running;
978    vm_stop(0);
979
980    bdrv_flush_all();
981
982    ret = qemu_savevm_state_begin(f);
983    if (ret < 0)
984        goto out;
985
986    do {
987        ret = qemu_savevm_state_iterate(f);
988        if (ret < 0)
989            goto out;
990    } while (ret == 0);
991
992    ret = qemu_savevm_state_complete(f);
993
994out:
995    if (qemu_file_has_error(f))
996        ret = -EIO;
997
998    if (!ret && saved_vm_running)
999        vm_start();
1000
1001    return ret;
1002}
1003
1004static SaveStateEntry *find_se(const char *idstr, int instance_id)
1005{
1006    SaveStateEntry *se;
1007
1008    for(se = first_se; se != NULL; se = se->next) {
1009        if (!strcmp(se->idstr, idstr) &&
1010            instance_id == se->instance_id)
1011            return se;
1012    }
1013    return NULL;
1014}
1015
1016typedef struct LoadStateEntry {
1017    SaveStateEntry *se;
1018    int section_id;
1019    int version_id;
1020    struct LoadStateEntry *next;
1021} LoadStateEntry;
1022
1023static int qemu_loadvm_state_v2(QEMUFile *f)
1024{
1025    SaveStateEntry *se;
1026    int len, ret, instance_id, record_len, version_id;
1027    int64_t total_len, end_pos, cur_pos;
1028    char idstr[256];
1029
1030    total_len = qemu_get_be64(f);
1031    end_pos = total_len + qemu_ftell(f);
1032    for(;;) {
1033        if (qemu_ftell(f) >= end_pos)
1034            break;
1035        len = qemu_get_byte(f);
1036        qemu_get_buffer(f, (uint8_t *)idstr, len);
1037        idstr[len] = '\0';
1038        instance_id = qemu_get_be32(f);
1039        version_id = qemu_get_be32(f);
1040        record_len = qemu_get_be32(f);
1041        cur_pos = qemu_ftell(f);
1042        se = find_se(idstr, instance_id);
1043        if (!se) {
1044            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
1045                    instance_id, idstr);
1046        } else {
1047            ret = se->load_state(f, se->opaque, version_id);
1048            if (ret < 0) {
1049                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
1050                        instance_id, idstr);
1051                return ret;
1052            }
1053        }
1054        /* always seek to exact end of record */
1055        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1056    }
1057
1058    if (qemu_file_has_error(f))
1059        return -EIO;
1060
1061    return 0;
1062}
1063
1064int qemu_loadvm_state(QEMUFile *f)
1065{
1066    LoadStateEntry *first_le = NULL;
1067    uint8_t section_type;
1068    unsigned int v;
1069    int ret;
1070
1071    v = qemu_get_be32(f);
1072    if (v != QEMU_VM_FILE_MAGIC)
1073        return -EINVAL;
1074
1075    v = qemu_get_be32(f);
1076    if (v == QEMU_VM_FILE_VERSION_COMPAT)
1077        return qemu_loadvm_state_v2(f);
1078    if (v != QEMU_VM_FILE_VERSION)
1079        return -ENOTSUP;
1080
1081    while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
1082        uint32_t instance_id, version_id, section_id;
1083        LoadStateEntry *le;
1084        SaveStateEntry *se;
1085        char idstr[257];
1086        int len;
1087
1088        switch (section_type) {
1089        case QEMU_VM_SECTION_START:
1090        case QEMU_VM_SECTION_FULL:
1091            /* Read section start */
1092            section_id = qemu_get_be32(f);
1093            len = qemu_get_byte(f);
1094            qemu_get_buffer(f, (uint8_t *)idstr, len);
1095            idstr[len] = 0;
1096            instance_id = qemu_get_be32(f);
1097            version_id = qemu_get_be32(f);
1098
1099            /* Find savevm section */
1100            se = find_se(idstr, instance_id);
1101            if (se == NULL) {
1102                fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
1103                ret = -EINVAL;
1104                goto out;
1105            }
1106
1107            /* Validate version */
1108            if (version_id > se->version_id) {
1109                fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
1110                        version_id, idstr, se->version_id);
1111                ret = -EINVAL;
1112                goto out;
1113            }
1114
1115            /* Add entry */
1116            le = qemu_mallocz(sizeof(*le));
1117
1118            le->se = se;
1119            le->section_id = section_id;
1120            le->version_id = version_id;
1121            le->next = first_le;
1122            first_le = le;
1123
1124            if (le->se->load_state(f, le->se->opaque, le->version_id)) {
1125                fprintf(stderr, "savevm: unable to load section %s\n", idstr);
1126                ret = -EINVAL;
1127                goto out;
1128            }
1129            break;
1130        case QEMU_VM_SECTION_PART:
1131        case QEMU_VM_SECTION_END:
1132            section_id = qemu_get_be32(f);
1133
1134            for (le = first_le; le && le->section_id != section_id; le = le->next);
1135            if (le == NULL) {
1136                fprintf(stderr, "Unknown savevm section %d\n", section_id);
1137                ret = -EINVAL;
1138                goto out;
1139            }
1140
1141            le->se->load_state(f, le->se->opaque, le->version_id);
1142            break;
1143        default:
1144            fprintf(stderr, "Unknown savevm section type %d\n", section_type);
1145            ret = -EINVAL;
1146            goto out;
1147        }
1148    }
1149
1150    ret = 0;
1151
1152out:
1153    while (first_le) {
1154        LoadStateEntry *le = first_le;
1155        first_le = first_le->next;
1156        qemu_free(le);
1157    }
1158
1159    if (qemu_file_has_error(f))
1160        ret = -EIO;
1161
1162    return ret;
1163}
1164#if 0
1165static BlockDriverState *get_bs_snapshots(void)
1166{
1167    BlockDriverState *bs;
1168    int i;
1169
1170    if (bs_snapshots)
1171        return bs_snapshots;
1172    for(i = 0; i <= nb_drives; i++) {
1173        bs = drives_table[i].bdrv;
1174        if (bdrv_can_snapshot(bs))
1175            goto ok;
1176    }
1177    return NULL;
1178 ok:
1179    bs_snapshots = bs;
1180    return bs;
1181}
1182#endif
1183static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
1184                              const char *name)
1185{
1186    QEMUSnapshotInfo *sn_tab, *sn;
1187    int nb_sns, i, ret;
1188
1189    ret = -ENOENT;
1190    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1191    if (nb_sns < 0)
1192        return ret;
1193    for(i = 0; i < nb_sns; i++) {
1194        sn = &sn_tab[i];
1195        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
1196            *sn_info = *sn;
1197            ret = 0;
1198            break;
1199        }
1200    }
1201    qemu_free(sn_tab);
1202    return ret;
1203}
1204
1205void do_savevm(Monitor *err, const char *name)
1206{
1207    BlockDriverState *bs, *bs1;
1208    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
1209    int must_delete, ret;
1210    BlockDriverInfo bdi1, *bdi = &bdi1;
1211    QEMUFile *f;
1212    int saved_vm_running;
1213    uint32_t vm_state_size;
1214#ifdef _WIN32
1215    struct _timeb tb;
1216#else
1217    struct timeval tv;
1218#endif
1219
1220    bs = bdrv_snapshots();
1221    if (!bs) {
1222        monitor_printf(err, "No block device can accept snapshots\n");
1223        return;
1224    }
1225
1226    /* ??? Should this occur after vm_stop?  */
1227    qemu_aio_flush();
1228
1229    saved_vm_running = vm_running;
1230    vm_stop(0);
1231
1232    must_delete = 0;
1233    if (name) {
1234        ret = bdrv_snapshot_find(bs, old_sn, name);
1235        if (ret >= 0) {
1236            must_delete = 1;
1237        }
1238    }
1239    memset(sn, 0, sizeof(*sn));
1240    if (must_delete) {
1241        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
1242        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
1243    } else {
1244        if (name)
1245            pstrcpy(sn->name, sizeof(sn->name), name);
1246    }
1247
1248    /* fill auxiliary fields */
1249#ifdef _WIN32
1250    _ftime(&tb);
1251    sn->date_sec = tb.time;
1252    sn->date_nsec = tb.millitm * 1000000;
1253#else
1254    gettimeofday(&tv, NULL);
1255    sn->date_sec = tv.tv_sec;
1256    sn->date_nsec = tv.tv_usec * 1000;
1257#endif
1258    sn->vm_clock_nsec = qemu_get_clock_ns(vm_clock);
1259
1260    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
1261        monitor_printf(err, "Device %s does not support VM state snapshots\n",
1262                              bdrv_get_device_name(bs));
1263        goto the_end;
1264    }
1265
1266    /* save the VM state */
1267    f = qemu_fopen_bdrv(bs, 1);
1268    if (!f) {
1269        monitor_printf(err, "Could not open VM state file\n");
1270        goto the_end;
1271    }
1272    ret = qemu_savevm_state(f);
1273    vm_state_size = qemu_ftell(f);
1274    qemu_fclose(f);
1275    if (ret < 0) {
1276        monitor_printf(err, "Error %d while writing VM\n", ret);
1277        goto the_end;
1278    }
1279
1280    /* create the snapshots */
1281
1282    bs1 = NULL;
1283    while ((bs1 = bdrv_next(bs1))) {
1284        if (bdrv_can_snapshot(bs1)) {
1285            if (must_delete) {
1286                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
1287                if (ret < 0) {
1288                    monitor_printf(err,
1289                                          "Error while deleting snapshot on '%s'\n",
1290                                          bdrv_get_device_name(bs1));
1291                }
1292            }
1293            /* Write VM state size only to the image that contains the state */
1294            sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
1295            ret = bdrv_snapshot_create(bs1, sn);
1296            if (ret < 0) {
1297                monitor_printf(err, "Error while creating snapshot on '%s'\n",
1298                                      bdrv_get_device_name(bs1));
1299            }
1300        }
1301    }
1302
1303 the_end:
1304    if (saved_vm_running)
1305        vm_start();
1306}
1307
1308void do_loadvm(Monitor *err, const char *name)
1309{
1310    BlockDriverState *bs, *bs1;
1311    BlockDriverInfo bdi1, *bdi = &bdi1;
1312    QEMUSnapshotInfo sn;
1313    QEMUFile *f;
1314    int ret;
1315    int saved_vm_running;
1316
1317    bs = bdrv_snapshots();
1318    if (!bs) {
1319        monitor_printf(err, "No block device supports snapshots\n");
1320        return;
1321    }
1322
1323    /* Flush all IO requests so they don't interfere with the new state.  */
1324    qemu_aio_flush();
1325
1326    saved_vm_running = vm_running;
1327    vm_stop(0);
1328
1329    bs1 = NULL;
1330    while ((bs1 = bdrv_next(bs))) {
1331        if (bdrv_can_snapshot(bs1)) {
1332            ret = bdrv_snapshot_goto(bs1, name);
1333            if (ret < 0) {
1334                if (bs != bs1)
1335                    monitor_printf(err, "Warning: ");
1336                switch(ret) {
1337                case -ENOTSUP:
1338                    monitor_printf(err,
1339                                   "Snapshots not supported on device '%s'\n",
1340                                   bdrv_get_device_name(bs1));
1341                    break;
1342                case -ENOENT:
1343                    monitor_printf(err, "Could not find snapshot '%s' on "
1344                                   "device '%s'\n",
1345                                   name, bdrv_get_device_name(bs1));
1346                    break;
1347                default:
1348                    monitor_printf(err, "Error %d while activating snapshot on"
1349                                   " '%s'\n", ret, bdrv_get_device_name(bs1));
1350                    break;
1351                }
1352                /* fatal on snapshot block device */
1353                if (bs == bs1)
1354                    goto the_end;
1355            }
1356        }
1357    }
1358
1359    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
1360        monitor_printf(err, "Device %s does not support VM state snapshots\n",
1361                       bdrv_get_device_name(bs));
1362        return;
1363    }
1364
1365    /* Don't even try to load empty VM states */
1366    ret = bdrv_snapshot_find(bs, &sn, name);
1367    if ((ret >= 0) && (sn.vm_state_size == 0))
1368        goto the_end;
1369
1370    /* restore the VM state */
1371    f = qemu_fopen_bdrv(bs, 0);
1372    if (!f) {
1373        monitor_printf(err, "Could not open VM state file\n");
1374        goto the_end;
1375    }
1376    ret = qemu_loadvm_state(f);
1377    qemu_fclose(f);
1378    if (ret < 0) {
1379        monitor_printf(err, "Error %d while loading VM state\n", ret);
1380    }
1381 the_end:
1382    if (saved_vm_running)
1383        vm_start();
1384}
1385
1386void do_delvm(Monitor *err, const char *name)
1387{
1388    BlockDriverState *bs, *bs1;
1389    int ret;
1390
1391    bs = bdrv_snapshots();
1392    if (!bs) {
1393        monitor_printf(err, "No block device supports snapshots\n");
1394        return;
1395    }
1396
1397    bs1 = NULL;
1398    while ((bs1 = bdrv_next(bs1))) {
1399        if (bdrv_can_snapshot(bs1)) {
1400            ret = bdrv_snapshot_delete(bs1, name);
1401            if (ret < 0) {
1402                if (ret == -ENOTSUP)
1403                    monitor_printf(err,
1404                                          "Snapshots not supported on device '%s'\n",
1405                                          bdrv_get_device_name(bs1));
1406                else
1407                    monitor_printf(err, "Error %d while deleting snapshot on "
1408                                          "'%s'\n", ret, bdrv_get_device_name(bs1));
1409            }
1410        }
1411    }
1412}
1413
1414void do_info_snapshots(Monitor* out, Monitor* err)
1415{
1416    BlockDriverState *bs, *bs1;
1417    QEMUSnapshotInfo *sn_tab, *sn;
1418    int nb_sns, i;
1419    char buf[256];
1420
1421    bs = bdrv_snapshots();
1422    if (!bs) {
1423        monitor_printf(err, "No available block device supports snapshots\n");
1424        return;
1425    }
1426    monitor_printf(out, "Snapshot devices:");
1427    bs1 = NULL;
1428    while ((bs1 = bdrv_next(bs1))) {
1429        if (bdrv_can_snapshot(bs1)) {
1430            if (bs == bs1)
1431                monitor_printf(out, " %s", bdrv_get_device_name(bs1));
1432        }
1433    }
1434    monitor_printf(out, "\n");
1435
1436    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1437    if (nb_sns < 0) {
1438        monitor_printf(err, "bdrv_snapshot_list: error %d\n", nb_sns);
1439        return;
1440    }
1441    monitor_printf(out, "Snapshot list (from %s):\n",
1442                   bdrv_get_device_name(bs));
1443    monitor_printf(out, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
1444    for(i = 0; i < nb_sns; i++) {
1445        sn = &sn_tab[i];
1446        monitor_printf(out, "%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
1447    }
1448    qemu_free(sn_tab);
1449}
1450