]> Git Repo - qemu.git/blob - savevm.c
qemu-file: Move QEMUFile code to qemu-file.c
[qemu.git] / 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
25 #include "config-host.h"
26 #include "qemu-common.h"
27 #include "hw/hw.h"
28 #include "hw/qdev.h"
29 #include "net/net.h"
30 #include "monitor/monitor.h"
31 #include "sysemu/sysemu.h"
32 #include "qemu/timer.h"
33 #include "audio/audio.h"
34 #include "migration/migration.h"
35 #include "qemu/sockets.h"
36 #include "qemu/queue.h"
37 #include "sysemu/cpus.h"
38 #include "exec/memory.h"
39 #include "qmp-commands.h"
40 #include "trace.h"
41 #include "qemu/iov.h"
42 #include "block/snapshot.h"
43 #include "block/qapi.h"
44
45 #define SELF_ANNOUNCE_ROUNDS 5
46
47 #ifndef ETH_P_RARP
48 #define ETH_P_RARP 0x8035
49 #endif
50 #define ARP_HTYPE_ETH 0x0001
51 #define ARP_PTYPE_IP 0x0800
52 #define ARP_OP_REQUEST_REV 0x3
53
54 static int announce_self_create(uint8_t *buf,
55                                 uint8_t *mac_addr)
56 {
57     /* Ethernet header. */
58     memset(buf, 0xff, 6);         /* destination MAC addr */
59     memcpy(buf + 6, mac_addr, 6); /* source MAC addr */
60     *(uint16_t *)(buf + 12) = htons(ETH_P_RARP); /* ethertype */
61
62     /* RARP header. */
63     *(uint16_t *)(buf + 14) = htons(ARP_HTYPE_ETH); /* hardware addr space */
64     *(uint16_t *)(buf + 16) = htons(ARP_PTYPE_IP); /* protocol addr space */
65     *(buf + 18) = 6; /* hardware addr length (ethernet) */
66     *(buf + 19) = 4; /* protocol addr length (IPv4) */
67     *(uint16_t *)(buf + 20) = htons(ARP_OP_REQUEST_REV); /* opcode */
68     memcpy(buf + 22, mac_addr, 6); /* source hw addr */
69     memset(buf + 28, 0x00, 4);     /* source protocol addr */
70     memcpy(buf + 32, mac_addr, 6); /* target hw addr */
71     memset(buf + 38, 0x00, 4);     /* target protocol addr */
72
73     /* Padding to get up to 60 bytes (ethernet min packet size, minus FCS). */
74     memset(buf + 42, 0x00, 18);
75
76     return 60; /* len (FCS will be added by hardware) */
77 }
78
79 static void qemu_announce_self_iter(NICState *nic, void *opaque)
80 {
81     uint8_t buf[60];
82     int len;
83
84     len = announce_self_create(buf, nic->conf->macaddr.a);
85
86     qemu_send_packet_raw(qemu_get_queue(nic), buf, len);
87 }
88
89
90 static void qemu_announce_self_once(void *opaque)
91 {
92     static int count = SELF_ANNOUNCE_ROUNDS;
93     QEMUTimer *timer = *(QEMUTimer **)opaque;
94
95     qemu_foreach_nic(qemu_announce_self_iter, NULL);
96
97     if (--count) {
98         /* delay 50ms, 150ms, 250ms, ... */
99         timer_mod(timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) +
100                        50 + (SELF_ANNOUNCE_ROUNDS - count - 1) * 100);
101     } else {
102             timer_del(timer);
103             timer_free(timer);
104     }
105 }
106
107 void qemu_announce_self(void)
108 {
109     static QEMUTimer *timer;
110     timer = timer_new_ms(QEMU_CLOCK_REALTIME, qemu_announce_self_once, &timer);
111     qemu_announce_self_once(&timer);
112 }
113
114 /***********************************************************/
115 /* savevm/loadvm support */
116
117 static ssize_t block_writev_buffer(void *opaque, struct iovec *iov, int iovcnt,
118                                    int64_t pos)
119 {
120     int ret;
121     QEMUIOVector qiov;
122
123     qemu_iovec_init_external(&qiov, iov, iovcnt);
124     ret = bdrv_writev_vmstate(opaque, &qiov, pos);
125     if (ret < 0) {
126         return ret;
127     }
128
129     return qiov.size;
130 }
131
132 static int block_put_buffer(void *opaque, const uint8_t *buf,
133                            int64_t pos, int size)
134 {
135     bdrv_save_vmstate(opaque, buf, pos, size);
136     return size;
137 }
138
139 static int block_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
140 {
141     return bdrv_load_vmstate(opaque, buf, pos, size);
142 }
143
144 static int bdrv_fclose(void *opaque)
145 {
146     return bdrv_flush(opaque);
147 }
148
149 static const QEMUFileOps bdrv_read_ops = {
150     .get_buffer = block_get_buffer,
151     .close =      bdrv_fclose
152 };
153
154 static const QEMUFileOps bdrv_write_ops = {
155     .put_buffer     = block_put_buffer,
156     .writev_buffer  = block_writev_buffer,
157     .close          = bdrv_fclose
158 };
159
160 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int is_writable)
161 {
162     if (is_writable) {
163         return qemu_fopen_ops(bs, &bdrv_write_ops);
164     }
165     return qemu_fopen_ops(bs, &bdrv_read_ops);
166 }
167
168
169 /* timer */
170
171 void timer_put(QEMUFile *f, QEMUTimer *ts)
172 {
173     uint64_t expire_time;
174
175     expire_time = timer_expire_time_ns(ts);
176     qemu_put_be64(f, expire_time);
177 }
178
179 void timer_get(QEMUFile *f, QEMUTimer *ts)
180 {
181     uint64_t expire_time;
182
183     expire_time = qemu_get_be64(f);
184     if (expire_time != -1) {
185         timer_mod_ns(ts, expire_time);
186     } else {
187         timer_del(ts);
188     }
189 }
190
191
192 /* timers  */
193
194 static int get_timer(QEMUFile *f, void *pv, size_t size)
195 {
196     QEMUTimer *v = pv;
197     timer_get(f, v);
198     return 0;
199 }
200
201 static void put_timer(QEMUFile *f, void *pv, size_t size)
202 {
203     QEMUTimer *v = pv;
204     timer_put(f, v);
205 }
206
207 const VMStateInfo vmstate_info_timer = {
208     .name = "timer",
209     .get  = get_timer,
210     .put  = put_timer,
211 };
212
213
214 typedef struct CompatEntry {
215     char idstr[256];
216     int instance_id;
217 } CompatEntry;
218
219 typedef struct SaveStateEntry {
220     QTAILQ_ENTRY(SaveStateEntry) entry;
221     char idstr[256];
222     int instance_id;
223     int alias_id;
224     int version_id;
225     int section_id;
226     SaveVMHandlers *ops;
227     const VMStateDescription *vmsd;
228     void *opaque;
229     CompatEntry *compat;
230     int no_migrate;
231     int is_ram;
232 } SaveStateEntry;
233
234
235 static QTAILQ_HEAD(savevm_handlers, SaveStateEntry) savevm_handlers =
236     QTAILQ_HEAD_INITIALIZER(savevm_handlers);
237 static int global_section_id;
238
239 static int calculate_new_instance_id(const char *idstr)
240 {
241     SaveStateEntry *se;
242     int instance_id = 0;
243
244     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
245         if (strcmp(idstr, se->idstr) == 0
246             && instance_id <= se->instance_id) {
247             instance_id = se->instance_id + 1;
248         }
249     }
250     return instance_id;
251 }
252
253 static int calculate_compat_instance_id(const char *idstr)
254 {
255     SaveStateEntry *se;
256     int instance_id = 0;
257
258     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
259         if (!se->compat) {
260             continue;
261         }
262
263         if (strcmp(idstr, se->compat->idstr) == 0
264             && instance_id <= se->compat->instance_id) {
265             instance_id = se->compat->instance_id + 1;
266         }
267     }
268     return instance_id;
269 }
270
271 /* TODO: Individual devices generally have very little idea about the rest
272    of the system, so instance_id should be removed/replaced.
273    Meanwhile pass -1 as instance_id if you do not already have a clearly
274    distinguishing id for all instances of your device class. */
275 int register_savevm_live(DeviceState *dev,
276                          const char *idstr,
277                          int instance_id,
278                          int version_id,
279                          SaveVMHandlers *ops,
280                          void *opaque)
281 {
282     SaveStateEntry *se;
283
284     se = g_malloc0(sizeof(SaveStateEntry));
285     se->version_id = version_id;
286     se->section_id = global_section_id++;
287     se->ops = ops;
288     se->opaque = opaque;
289     se->vmsd = NULL;
290     se->no_migrate = 0;
291     /* if this is a live_savem then set is_ram */
292     if (ops->save_live_setup != NULL) {
293         se->is_ram = 1;
294     }
295
296     if (dev) {
297         char *id = qdev_get_dev_path(dev);
298         if (id) {
299             pstrcpy(se->idstr, sizeof(se->idstr), id);
300             pstrcat(se->idstr, sizeof(se->idstr), "/");
301             g_free(id);
302
303             se->compat = g_malloc0(sizeof(CompatEntry));
304             pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), idstr);
305             se->compat->instance_id = instance_id == -1 ?
306                          calculate_compat_instance_id(idstr) : instance_id;
307             instance_id = -1;
308         }
309     }
310     pstrcat(se->idstr, sizeof(se->idstr), idstr);
311
312     if (instance_id == -1) {
313         se->instance_id = calculate_new_instance_id(se->idstr);
314     } else {
315         se->instance_id = instance_id;
316     }
317     assert(!se->compat || se->instance_id == 0);
318     /* add at the end of list */
319     QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
320     return 0;
321 }
322
323 int register_savevm(DeviceState *dev,
324                     const char *idstr,
325                     int instance_id,
326                     int version_id,
327                     SaveStateHandler *save_state,
328                     LoadStateHandler *load_state,
329                     void *opaque)
330 {
331     SaveVMHandlers *ops = g_malloc0(sizeof(SaveVMHandlers));
332     ops->save_state = save_state;
333     ops->load_state = load_state;
334     return register_savevm_live(dev, idstr, instance_id, version_id,
335                                 ops, opaque);
336 }
337
338 void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)
339 {
340     SaveStateEntry *se, *new_se;
341     char id[256] = "";
342
343     if (dev) {
344         char *path = qdev_get_dev_path(dev);
345         if (path) {
346             pstrcpy(id, sizeof(id), path);
347             pstrcat(id, sizeof(id), "/");
348             g_free(path);
349         }
350     }
351     pstrcat(id, sizeof(id), idstr);
352
353     QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
354         if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {
355             QTAILQ_REMOVE(&savevm_handlers, se, entry);
356             if (se->compat) {
357                 g_free(se->compat);
358             }
359             g_free(se->ops);
360             g_free(se);
361         }
362     }
363 }
364
365 int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,
366                                    const VMStateDescription *vmsd,
367                                    void *opaque, int alias_id,
368                                    int required_for_version)
369 {
370     SaveStateEntry *se;
371
372     /* If this triggers, alias support can be dropped for the vmsd. */
373     assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);
374
375     se = g_malloc0(sizeof(SaveStateEntry));
376     se->version_id = vmsd->version_id;
377     se->section_id = global_section_id++;
378     se->opaque = opaque;
379     se->vmsd = vmsd;
380     se->alias_id = alias_id;
381     se->no_migrate = vmsd->unmigratable;
382
383     if (dev) {
384         char *id = qdev_get_dev_path(dev);
385         if (id) {
386             pstrcpy(se->idstr, sizeof(se->idstr), id);
387             pstrcat(se->idstr, sizeof(se->idstr), "/");
388             g_free(id);
389
390             se->compat = g_malloc0(sizeof(CompatEntry));
391             pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);
392             se->compat->instance_id = instance_id == -1 ?
393                          calculate_compat_instance_id(vmsd->name) : instance_id;
394             instance_id = -1;
395         }
396     }
397     pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);
398
399     if (instance_id == -1) {
400         se->instance_id = calculate_new_instance_id(se->idstr);
401     } else {
402         se->instance_id = instance_id;
403     }
404     assert(!se->compat || se->instance_id == 0);
405     /* add at the end of list */
406     QTAILQ_INSERT_TAIL(&savevm_handlers, se, entry);
407     return 0;
408 }
409
410 void vmstate_unregister(DeviceState *dev, const VMStateDescription *vmsd,
411                         void *opaque)
412 {
413     SaveStateEntry *se, *new_se;
414
415     QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {
416         if (se->vmsd == vmsd && se->opaque == opaque) {
417             QTAILQ_REMOVE(&savevm_handlers, se, entry);
418             if (se->compat) {
419                 g_free(se->compat);
420             }
421             g_free(se);
422         }
423     }
424 }
425
426 static int vmstate_load(QEMUFile *f, SaveStateEntry *se, int version_id)
427 {
428     if (!se->vmsd) {         /* Old style */
429         return se->ops->load_state(f, se->opaque, version_id);
430     }
431     return vmstate_load_state(f, se->vmsd, se->opaque, version_id);
432 }
433
434 static void vmstate_save(QEMUFile *f, SaveStateEntry *se)
435 {
436     if (!se->vmsd) {         /* Old style */
437         se->ops->save_state(f, se->opaque);
438         return;
439     }
440     vmstate_save_state(f, se->vmsd, se->opaque);
441 }
442
443 bool qemu_savevm_state_blocked(Error **errp)
444 {
445     SaveStateEntry *se;
446
447     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
448         if (se->no_migrate) {
449             error_set(errp, QERR_MIGRATION_NOT_SUPPORTED, se->idstr);
450             return true;
451         }
452     }
453     return false;
454 }
455
456 void qemu_savevm_state_begin(QEMUFile *f,
457                              const MigrationParams *params)
458 {
459     SaveStateEntry *se;
460     int ret;
461
462     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
463         if (!se->ops || !se->ops->set_params) {
464             continue;
465         }
466         se->ops->set_params(params, se->opaque);
467     }
468
469     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
470     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
471
472     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
473         int len;
474
475         if (!se->ops || !se->ops->save_live_setup) {
476             continue;
477         }
478         if (se->ops && se->ops->is_active) {
479             if (!se->ops->is_active(se->opaque)) {
480                 continue;
481             }
482         }
483         /* Section type */
484         qemu_put_byte(f, QEMU_VM_SECTION_START);
485         qemu_put_be32(f, se->section_id);
486
487         /* ID string */
488         len = strlen(se->idstr);
489         qemu_put_byte(f, len);
490         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
491
492         qemu_put_be32(f, se->instance_id);
493         qemu_put_be32(f, se->version_id);
494
495         ret = se->ops->save_live_setup(f, se->opaque);
496         if (ret < 0) {
497             qemu_file_set_error(f, ret);
498             break;
499         }
500     }
501 }
502
503 /*
504  * this function has three return values:
505  *   negative: there was one error, and we have -errno.
506  *   0 : We haven't finished, caller have to go again
507  *   1 : We have finished, we can go to complete phase
508  */
509 int qemu_savevm_state_iterate(QEMUFile *f)
510 {
511     SaveStateEntry *se;
512     int ret = 1;
513
514     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
515         if (!se->ops || !se->ops->save_live_iterate) {
516             continue;
517         }
518         if (se->ops && se->ops->is_active) {
519             if (!se->ops->is_active(se->opaque)) {
520                 continue;
521             }
522         }
523         if (qemu_file_rate_limit(f)) {
524             return 0;
525         }
526         trace_savevm_section_start();
527         /* Section type */
528         qemu_put_byte(f, QEMU_VM_SECTION_PART);
529         qemu_put_be32(f, se->section_id);
530
531         ret = se->ops->save_live_iterate(f, se->opaque);
532         trace_savevm_section_end(se->section_id);
533
534         if (ret < 0) {
535             qemu_file_set_error(f, ret);
536         }
537         if (ret <= 0) {
538             /* Do not proceed to the next vmstate before this one reported
539                completion of the current stage. This serializes the migration
540                and reduces the probability that a faster changing state is
541                synchronized over and over again. */
542             break;
543         }
544     }
545     return ret;
546 }
547
548 void qemu_savevm_state_complete(QEMUFile *f)
549 {
550     SaveStateEntry *se;
551     int ret;
552
553     cpu_synchronize_all_states();
554
555     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
556         if (!se->ops || !se->ops->save_live_complete) {
557             continue;
558         }
559         if (se->ops && se->ops->is_active) {
560             if (!se->ops->is_active(se->opaque)) {
561                 continue;
562             }
563         }
564         trace_savevm_section_start();
565         /* Section type */
566         qemu_put_byte(f, QEMU_VM_SECTION_END);
567         qemu_put_be32(f, se->section_id);
568
569         ret = se->ops->save_live_complete(f, se->opaque);
570         trace_savevm_section_end(se->section_id);
571         if (ret < 0) {
572             qemu_file_set_error(f, ret);
573             return;
574         }
575     }
576
577     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
578         int len;
579
580         if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
581             continue;
582         }
583         trace_savevm_section_start();
584         /* Section type */
585         qemu_put_byte(f, QEMU_VM_SECTION_FULL);
586         qemu_put_be32(f, se->section_id);
587
588         /* ID string */
589         len = strlen(se->idstr);
590         qemu_put_byte(f, len);
591         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
592
593         qemu_put_be32(f, se->instance_id);
594         qemu_put_be32(f, se->version_id);
595
596         vmstate_save(f, se);
597         trace_savevm_section_end(se->section_id);
598     }
599
600     qemu_put_byte(f, QEMU_VM_EOF);
601     qemu_fflush(f);
602 }
603
604 uint64_t qemu_savevm_state_pending(QEMUFile *f, uint64_t max_size)
605 {
606     SaveStateEntry *se;
607     uint64_t ret = 0;
608
609     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
610         if (!se->ops || !se->ops->save_live_pending) {
611             continue;
612         }
613         if (se->ops && se->ops->is_active) {
614             if (!se->ops->is_active(se->opaque)) {
615                 continue;
616             }
617         }
618         ret += se->ops->save_live_pending(f, se->opaque, max_size);
619     }
620     return ret;
621 }
622
623 void qemu_savevm_state_cancel(void)
624 {
625     SaveStateEntry *se;
626
627     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
628         if (se->ops && se->ops->cancel) {
629             se->ops->cancel(se->opaque);
630         }
631     }
632 }
633
634 static int qemu_savevm_state(QEMUFile *f)
635 {
636     int ret;
637     MigrationParams params = {
638         .blk = 0,
639         .shared = 0
640     };
641
642     if (qemu_savevm_state_blocked(NULL)) {
643         return -EINVAL;
644     }
645
646     qemu_mutex_unlock_iothread();
647     qemu_savevm_state_begin(f, &params);
648     qemu_mutex_lock_iothread();
649
650     while (qemu_file_get_error(f) == 0) {
651         if (qemu_savevm_state_iterate(f) > 0) {
652             break;
653         }
654     }
655
656     ret = qemu_file_get_error(f);
657     if (ret == 0) {
658         qemu_savevm_state_complete(f);
659         ret = qemu_file_get_error(f);
660     }
661     if (ret != 0) {
662         qemu_savevm_state_cancel();
663     }
664     return ret;
665 }
666
667 static int qemu_save_device_state(QEMUFile *f)
668 {
669     SaveStateEntry *se;
670
671     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
672     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
673
674     cpu_synchronize_all_states();
675
676     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
677         int len;
678
679         if (se->is_ram) {
680             continue;
681         }
682         if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
683             continue;
684         }
685
686         /* Section type */
687         qemu_put_byte(f, QEMU_VM_SECTION_FULL);
688         qemu_put_be32(f, se->section_id);
689
690         /* ID string */
691         len = strlen(se->idstr);
692         qemu_put_byte(f, len);
693         qemu_put_buffer(f, (uint8_t *)se->idstr, len);
694
695         qemu_put_be32(f, se->instance_id);
696         qemu_put_be32(f, se->version_id);
697
698         vmstate_save(f, se);
699     }
700
701     qemu_put_byte(f, QEMU_VM_EOF);
702
703     return qemu_file_get_error(f);
704 }
705
706 static SaveStateEntry *find_se(const char *idstr, int instance_id)
707 {
708     SaveStateEntry *se;
709
710     QTAILQ_FOREACH(se, &savevm_handlers, entry) {
711         if (!strcmp(se->idstr, idstr) &&
712             (instance_id == se->instance_id ||
713              instance_id == se->alias_id))
714             return se;
715         /* Migrating from an older version? */
716         if (strstr(se->idstr, idstr) && se->compat) {
717             if (!strcmp(se->compat->idstr, idstr) &&
718                 (instance_id == se->compat->instance_id ||
719                  instance_id == se->alias_id))
720                 return se;
721         }
722     }
723     return NULL;
724 }
725
726 typedef struct LoadStateEntry {
727     QLIST_ENTRY(LoadStateEntry) entry;
728     SaveStateEntry *se;
729     int section_id;
730     int version_id;
731 } LoadStateEntry;
732
733 int qemu_loadvm_state(QEMUFile *f)
734 {
735     QLIST_HEAD(, LoadStateEntry) loadvm_handlers =
736         QLIST_HEAD_INITIALIZER(loadvm_handlers);
737     LoadStateEntry *le, *new_le;
738     uint8_t section_type;
739     unsigned int v;
740     int ret;
741
742     if (qemu_savevm_state_blocked(NULL)) {
743         return -EINVAL;
744     }
745
746     v = qemu_get_be32(f);
747     if (v != QEMU_VM_FILE_MAGIC) {
748         return -EINVAL;
749     }
750
751     v = qemu_get_be32(f);
752     if (v == QEMU_VM_FILE_VERSION_COMPAT) {
753         fprintf(stderr, "SaveVM v2 format is obsolete and don't work anymore\n");
754         return -ENOTSUP;
755     }
756     if (v != QEMU_VM_FILE_VERSION) {
757         return -ENOTSUP;
758     }
759
760     while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
761         uint32_t instance_id, version_id, section_id;
762         SaveStateEntry *se;
763         char idstr[257];
764         int len;
765
766         switch (section_type) {
767         case QEMU_VM_SECTION_START:
768         case QEMU_VM_SECTION_FULL:
769             /* Read section start */
770             section_id = qemu_get_be32(f);
771             len = qemu_get_byte(f);
772             qemu_get_buffer(f, (uint8_t *)idstr, len);
773             idstr[len] = 0;
774             instance_id = qemu_get_be32(f);
775             version_id = qemu_get_be32(f);
776
777             /* Find savevm section */
778             se = find_se(idstr, instance_id);
779             if (se == NULL) {
780                 fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
781                 ret = -EINVAL;
782                 goto out;
783             }
784
785             /* Validate version */
786             if (version_id > se->version_id) {
787                 fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
788                         version_id, idstr, se->version_id);
789                 ret = -EINVAL;
790                 goto out;
791             }
792
793             /* Add entry */
794             le = g_malloc0(sizeof(*le));
795
796             le->se = se;
797             le->section_id = section_id;
798             le->version_id = version_id;
799             QLIST_INSERT_HEAD(&loadvm_handlers, le, entry);
800
801             ret = vmstate_load(f, le->se, le->version_id);
802             if (ret < 0) {
803                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
804                         instance_id, idstr);
805                 goto out;
806             }
807             break;
808         case QEMU_VM_SECTION_PART:
809         case QEMU_VM_SECTION_END:
810             section_id = qemu_get_be32(f);
811
812             QLIST_FOREACH(le, &loadvm_handlers, entry) {
813                 if (le->section_id == section_id) {
814                     break;
815                 }
816             }
817             if (le == NULL) {
818                 fprintf(stderr, "Unknown savevm section %d\n", section_id);
819                 ret = -EINVAL;
820                 goto out;
821             }
822
823             ret = vmstate_load(f, le->se, le->version_id);
824             if (ret < 0) {
825                 fprintf(stderr, "qemu: warning: error while loading state section id %d\n",
826                         section_id);
827                 goto out;
828             }
829             break;
830         default:
831             fprintf(stderr, "Unknown savevm section type %d\n", section_type);
832             ret = -EINVAL;
833             goto out;
834         }
835     }
836
837     cpu_synchronize_all_post_init();
838
839     ret = 0;
840
841 out:
842     QLIST_FOREACH_SAFE(le, &loadvm_handlers, entry, new_le) {
843         QLIST_REMOVE(le, entry);
844         g_free(le);
845     }
846
847     if (ret == 0) {
848         ret = qemu_file_get_error(f);
849     }
850
851     return ret;
852 }
853
854 static BlockDriverState *find_vmstate_bs(void)
855 {
856     BlockDriverState *bs = NULL;
857     while ((bs = bdrv_next(bs))) {
858         if (bdrv_can_snapshot(bs)) {
859             return bs;
860         }
861     }
862     return NULL;
863 }
864
865 /*
866  * Deletes snapshots of a given name in all opened images.
867  */
868 static int del_existing_snapshots(Monitor *mon, const char *name)
869 {
870     BlockDriverState *bs;
871     QEMUSnapshotInfo sn1, *snapshot = &sn1;
872     Error *err = NULL;
873
874     bs = NULL;
875     while ((bs = bdrv_next(bs))) {
876         if (bdrv_can_snapshot(bs) &&
877             bdrv_snapshot_find(bs, snapshot, name) >= 0) {
878             bdrv_snapshot_delete_by_id_or_name(bs, name, &err);
879             if (error_is_set(&err)) {
880                 monitor_printf(mon,
881                                "Error while deleting snapshot on device '%s':"
882                                " %s\n",
883                                bdrv_get_device_name(bs),
884                                error_get_pretty(err));
885                 error_free(err);
886                 return -1;
887             }
888         }
889     }
890
891     return 0;
892 }
893
894 void do_savevm(Monitor *mon, const QDict *qdict)
895 {
896     BlockDriverState *bs, *bs1;
897     QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
898     int ret;
899     QEMUFile *f;
900     int saved_vm_running;
901     uint64_t vm_state_size;
902     qemu_timeval tv;
903     struct tm tm;
904     const char *name = qdict_get_try_str(qdict, "name");
905
906     /* Verify if there is a device that doesn't support snapshots and is writable */
907     bs = NULL;
908     while ((bs = bdrv_next(bs))) {
909
910         if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
911             continue;
912         }
913
914         if (!bdrv_can_snapshot(bs)) {
915             monitor_printf(mon, "Device '%s' is writable but does not support snapshots.\n",
916                                bdrv_get_device_name(bs));
917             return;
918         }
919     }
920
921     bs = find_vmstate_bs();
922     if (!bs) {
923         monitor_printf(mon, "No block device can accept snapshots\n");
924         return;
925     }
926
927     saved_vm_running = runstate_is_running();
928     vm_stop(RUN_STATE_SAVE_VM);
929
930     memset(sn, 0, sizeof(*sn));
931
932     /* fill auxiliary fields */
933     qemu_gettimeofday(&tv);
934     sn->date_sec = tv.tv_sec;
935     sn->date_nsec = tv.tv_usec * 1000;
936     sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
937
938     if (name) {
939         ret = bdrv_snapshot_find(bs, old_sn, name);
940         if (ret >= 0) {
941             pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
942             pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
943         } else {
944             pstrcpy(sn->name, sizeof(sn->name), name);
945         }
946     } else {
947         /* cast below needed for OpenBSD where tv_sec is still 'long' */
948         localtime_r((const time_t *)&tv.tv_sec, &tm);
949         strftime(sn->name, sizeof(sn->name), "vm-%Y%m%d%H%M%S", &tm);
950     }
951
952     /* Delete old snapshots of the same name */
953     if (name && del_existing_snapshots(mon, name) < 0) {
954         goto the_end;
955     }
956
957     /* save the VM state */
958     f = qemu_fopen_bdrv(bs, 1);
959     if (!f) {
960         monitor_printf(mon, "Could not open VM state file\n");
961         goto the_end;
962     }
963     ret = qemu_savevm_state(f);
964     vm_state_size = qemu_ftell(f);
965     qemu_fclose(f);
966     if (ret < 0) {
967         monitor_printf(mon, "Error %d while writing VM\n", ret);
968         goto the_end;
969     }
970
971     /* create the snapshots */
972
973     bs1 = NULL;
974     while ((bs1 = bdrv_next(bs1))) {
975         if (bdrv_can_snapshot(bs1)) {
976             /* Write VM state size only to the image that contains the state */
977             sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);
978             ret = bdrv_snapshot_create(bs1, sn);
979             if (ret < 0) {
980                 monitor_printf(mon, "Error while creating snapshot on '%s'\n",
981                                bdrv_get_device_name(bs1));
982             }
983         }
984     }
985
986  the_end:
987     if (saved_vm_running) {
988         vm_start();
989     }
990 }
991
992 void qmp_xen_save_devices_state(const char *filename, Error **errp)
993 {
994     QEMUFile *f;
995     int saved_vm_running;
996     int ret;
997
998     saved_vm_running = runstate_is_running();
999     vm_stop(RUN_STATE_SAVE_VM);
1000
1001     f = qemu_fopen(filename, "wb");
1002     if (!f) {
1003         error_setg_file_open(errp, errno, filename);
1004         goto the_end;
1005     }
1006     ret = qemu_save_device_state(f);
1007     qemu_fclose(f);
1008     if (ret < 0) {
1009         error_set(errp, QERR_IO_ERROR);
1010     }
1011
1012  the_end:
1013     if (saved_vm_running) {
1014         vm_start();
1015     }
1016 }
1017
1018 int load_vmstate(const char *name)
1019 {
1020     BlockDriverState *bs, *bs_vm_state;
1021     QEMUSnapshotInfo sn;
1022     QEMUFile *f;
1023     int ret;
1024
1025     bs_vm_state = find_vmstate_bs();
1026     if (!bs_vm_state) {
1027         error_report("No block device supports snapshots");
1028         return -ENOTSUP;
1029     }
1030
1031     /* Don't even try to load empty VM states */
1032     ret = bdrv_snapshot_find(bs_vm_state, &sn, name);
1033     if (ret < 0) {
1034         return ret;
1035     } else if (sn.vm_state_size == 0) {
1036         error_report("This is a disk-only snapshot. Revert to it offline "
1037             "using qemu-img.");
1038         return -EINVAL;
1039     }
1040
1041     /* Verify if there is any device that doesn't support snapshots and is
1042     writable and check if the requested snapshot is available too. */
1043     bs = NULL;
1044     while ((bs = bdrv_next(bs))) {
1045
1046         if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
1047             continue;
1048         }
1049
1050         if (!bdrv_can_snapshot(bs)) {
1051             error_report("Device '%s' is writable but does not support snapshots.",
1052                                bdrv_get_device_name(bs));
1053             return -ENOTSUP;
1054         }
1055
1056         ret = bdrv_snapshot_find(bs, &sn, name);
1057         if (ret < 0) {
1058             error_report("Device '%s' does not have the requested snapshot '%s'",
1059                            bdrv_get_device_name(bs), name);
1060             return ret;
1061         }
1062     }
1063
1064     /* Flush all IO requests so they don't interfere with the new state.  */
1065     bdrv_drain_all();
1066
1067     bs = NULL;
1068     while ((bs = bdrv_next(bs))) {
1069         if (bdrv_can_snapshot(bs)) {
1070             ret = bdrv_snapshot_goto(bs, name);
1071             if (ret < 0) {
1072                 error_report("Error %d while activating snapshot '%s' on '%s'",
1073                              ret, name, bdrv_get_device_name(bs));
1074                 return ret;
1075             }
1076         }
1077     }
1078
1079     /* restore the VM state */
1080     f = qemu_fopen_bdrv(bs_vm_state, 0);
1081     if (!f) {
1082         error_report("Could not open VM state file");
1083         return -EINVAL;
1084     }
1085
1086     qemu_system_reset(VMRESET_SILENT);
1087     ret = qemu_loadvm_state(f);
1088
1089     qemu_fclose(f);
1090     if (ret < 0) {
1091         error_report("Error %d while loading VM state", ret);
1092         return ret;
1093     }
1094
1095     return 0;
1096 }
1097
1098 void do_delvm(Monitor *mon, const QDict *qdict)
1099 {
1100     BlockDriverState *bs, *bs1;
1101     Error *err = NULL;
1102     const char *name = qdict_get_str(qdict, "name");
1103
1104     bs = find_vmstate_bs();
1105     if (!bs) {
1106         monitor_printf(mon, "No block device supports snapshots\n");
1107         return;
1108     }
1109
1110     bs1 = NULL;
1111     while ((bs1 = bdrv_next(bs1))) {
1112         if (bdrv_can_snapshot(bs1)) {
1113             bdrv_snapshot_delete_by_id_or_name(bs, name, &err);
1114             if (error_is_set(&err)) {
1115                 monitor_printf(mon,
1116                                "Error while deleting snapshot on device '%s':"
1117                                " %s\n",
1118                                bdrv_get_device_name(bs),
1119                                error_get_pretty(err));
1120                 error_free(err);
1121             }
1122         }
1123     }
1124 }
1125
1126 void do_info_snapshots(Monitor *mon, const QDict *qdict)
1127 {
1128     BlockDriverState *bs, *bs1;
1129     QEMUSnapshotInfo *sn_tab, *sn, s, *sn_info = &s;
1130     int nb_sns, i, ret, available;
1131     int total;
1132     int *available_snapshots;
1133
1134     bs = find_vmstate_bs();
1135     if (!bs) {
1136         monitor_printf(mon, "No available block device supports snapshots\n");
1137         return;
1138     }
1139
1140     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
1141     if (nb_sns < 0) {
1142         monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);
1143         return;
1144     }
1145
1146     if (nb_sns == 0) {
1147         monitor_printf(mon, "There is no snapshot available.\n");
1148         return;
1149     }
1150
1151     available_snapshots = g_malloc0(sizeof(int) * nb_sns);
1152     total = 0;
1153     for (i = 0; i < nb_sns; i++) {
1154         sn = &sn_tab[i];
1155         available = 1;
1156         bs1 = NULL;
1157
1158         while ((bs1 = bdrv_next(bs1))) {
1159             if (bdrv_can_snapshot(bs1) && bs1 != bs) {
1160                 ret = bdrv_snapshot_find(bs1, sn_info, sn->id_str);
1161                 if (ret < 0) {
1162                     available = 0;
1163                     break;
1164                 }
1165             }
1166         }
1167
1168         if (available) {
1169             available_snapshots[total] = i;
1170             total++;
1171         }
1172     }
1173
1174     if (total > 0) {
1175         bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, NULL);
1176         monitor_printf(mon, "\n");
1177         for (i = 0; i < total; i++) {
1178             sn = &sn_tab[available_snapshots[i]];
1179             bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, sn);
1180             monitor_printf(mon, "\n");
1181         }
1182     } else {
1183         monitor_printf(mon, "There is no suitable snapshot available\n");
1184     }
1185
1186     g_free(sn_tab);
1187     g_free(available_snapshots);
1188
1189 }
1190
1191 void vmstate_register_ram(MemoryRegion *mr, DeviceState *dev)
1192 {
1193     qemu_ram_set_idstr(memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK,
1194                        memory_region_name(mr), dev);
1195 }
1196
1197 void vmstate_unregister_ram(MemoryRegion *mr, DeviceState *dev)
1198 {
1199     /* Nothing do to while the implementation is in RAMBlock */
1200 }
1201
1202 void vmstate_register_ram_global(MemoryRegion *mr)
1203 {
1204     vmstate_register_ram(mr, NULL);
1205 }
This page took 0.090356 seconds and 4 git commands to generate.