2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2016 Flavius Anton
5 * Copyright (c) 2016 Mihai Tiganus
6 * Copyright (c) 2016-2019 Mihai Carabas
7 * Copyright (c) 2017-2019 Darius Mihai
8 * Copyright (c) 2017-2019 Elena Mihailescu
9 * Copyright (c) 2018-2019 Sergiu Weisz
10 * All rights reserved.
11 * The bhyve-snapshot feature was developed under sponsorships
12 * from Matthew Grooms.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include <sys/types.h>
40 #ifndef WITHOUT_CAPSICUM
41 #include <sys/capsicum.h>
44 #include <sys/socket.h>
49 #include <machine/atomic.h>
50 #include <machine/segments.h>
52 #ifndef WITHOUT_CAPSICUM
53 #include <capsicum_helpers.h>
67 #include <pthread_np.h>
70 #include <sys/ioctl.h>
72 #include <machine/vmm.h>
73 #ifndef WITHOUT_CAPSICUM
74 #include <machine/vmm_dev.h>
76 #include <machine/vmm_snapshot.h>
91 #include "smbiostbl.h"
94 #include "spinup_ap.h"
100 struct spinner_info {
101 const size_t *crtval;
106 extern int guest_ncpus;
108 static struct winsize winsize;
109 static sig_t old_winch_handler;
112 #define MB (1024UL * KB)
113 #define GB (1024UL * MB)
115 #define SNAPSHOT_CHUNK (4 * MB)
116 #define PROG_BUF_SZ (8192)
118 #define BHYVE_RUN_DIR "/var/run/bhyve"
119 #define CHECKPOINT_RUN_DIR BHYVE_RUN_DIR "/checkpoint"
120 #define MAX_VMNAME 100
122 #define MAX_MSG_SIZE 1024
124 #define SNAPSHOT_BUFFER_SIZE (20 * MB)
126 #define JSON_STRUCT_ARR_KEY "structs"
127 #define JSON_DEV_ARR_KEY "devices"
128 #define JSON_BASIC_METADATA_KEY "basic metadata"
129 #define JSON_SNAPSHOT_REQ_KEY "snapshot_req"
130 #define JSON_SIZE_KEY "size"
131 #define JSON_FILE_OFFSET_KEY "file_offset"
133 #define JSON_NCPUS_KEY "ncpus"
134 #define JSON_VMNAME_KEY "vmname"
135 #define JSON_MEMSIZE_KEY "memsize"
136 #define JSON_MEMFLAGS_KEY "memflags"
140 __typeof__ (a) _a = (a); \
141 __typeof__ (b) _b = (b); \
145 const struct vm_snapshot_dev_info snapshot_devs[] = {
146 { "atkbdc", atkbdc_snapshot, NULL, NULL },
147 { "virtio-net", pci_snapshot, pci_pause, pci_resume },
148 { "virtio-blk", pci_snapshot, pci_pause, pci_resume },
149 { "virtio-rnd", pci_snapshot, NULL, NULL },
150 { "lpc", pci_snapshot, NULL, NULL },
151 { "fbuf", pci_snapshot, NULL, NULL },
152 { "xhci", pci_snapshot, NULL, NULL },
153 { "e1000", pci_snapshot, NULL, NULL },
154 { "ahci", pci_snapshot, pci_pause, pci_resume },
155 { "ahci-hd", pci_snapshot, pci_pause, pci_resume },
156 { "ahci-cd", pci_snapshot, pci_pause, pci_resume },
159 const struct vm_snapshot_kern_info snapshot_kern_structs[] = {
160 { "vhpet", STRUCT_VHPET },
162 { "vmx", STRUCT_VMX },
163 { "vioapic", STRUCT_VIOAPIC },
164 { "vlapic", STRUCT_VLAPIC },
165 { "vmcx", STRUCT_VMCX },
166 { "vatpit", STRUCT_VATPIT },
167 { "vatpic", STRUCT_VATPIC },
168 { "vpmtmr", STRUCT_VPMTMR },
169 { "vrtc", STRUCT_VRTC },
172 static cpuset_t vcpus_active, vcpus_suspended;
173 static pthread_mutex_t vcpu_lock;
174 static pthread_cond_t vcpus_idle, vcpus_can_run;
175 static bool checkpoint_active;
178 * TODO: Harden this function and all of its callers since 'base_str' is a user
182 strcat_extension(const char *base_str, const char *ext)
185 size_t base_len, ext_len;
187 base_len = strnlen(base_str, MAX_VMNAME);
188 ext_len = strnlen(ext, MAX_VMNAME);
190 if (base_len + ext_len > MAX_VMNAME) {
191 fprintf(stderr, "Filename exceeds maximum length.\n");
195 res = malloc(base_len + ext_len + 1);
197 perror("Failed to allocate memory.");
201 memcpy(res, base_str, base_len);
202 memcpy(res + base_len, ext, ext_len);
203 res[base_len + ext_len] = 0;
209 destroy_restore_state(struct restore_state *rstate)
211 if (rstate == NULL) {
212 fprintf(stderr, "Attempting to destroy NULL restore struct.\n");
216 if (rstate->kdata_map != MAP_FAILED)
217 munmap(rstate->kdata_map, rstate->kdata_len);
219 if (rstate->kdata_fd > 0)
220 close(rstate->kdata_fd);
221 if (rstate->vmmem_fd > 0)
222 close(rstate->vmmem_fd);
224 if (rstate->meta_root_obj != NULL)
225 ucl_object_unref(rstate->meta_root_obj);
226 if (rstate->meta_parser != NULL)
227 ucl_parser_free(rstate->meta_parser);
231 load_vmmem_file(const char *filename, struct restore_state *rstate)
236 rstate->vmmem_fd = open(filename, O_RDONLY);
237 if (rstate->vmmem_fd < 0) {
238 perror("Failed to open restore file");
242 err = fstat(rstate->vmmem_fd, &sb);
244 perror("Failed to stat restore file");
248 if (sb.st_size == 0) {
249 fprintf(stderr, "Restore file is empty.\n");
253 rstate->vmmem_len = sb.st_size;
258 if (rstate->vmmem_fd > 0)
259 close(rstate->vmmem_fd);
264 load_kdata_file(const char *filename, struct restore_state *rstate)
269 rstate->kdata_fd = open(filename, O_RDONLY);
270 if (rstate->kdata_fd < 0) {
271 perror("Failed to open kernel data file");
275 err = fstat(rstate->kdata_fd, &sb);
277 perror("Failed to stat kernel data file");
281 if (sb.st_size == 0) {
282 fprintf(stderr, "Kernel data file is empty.\n");
286 rstate->kdata_len = sb.st_size;
287 rstate->kdata_map = mmap(NULL, rstate->kdata_len, PROT_READ,
288 MAP_SHARED, rstate->kdata_fd, 0);
289 if (rstate->kdata_map == MAP_FAILED) {
290 perror("Failed to map restore file");
297 if (rstate->kdata_fd > 0)
298 close(rstate->kdata_fd);
303 load_metadata_file(const char *filename, struct restore_state *rstate)
305 const ucl_object_t *obj;
306 struct ucl_parser *parser;
309 parser = ucl_parser_new(UCL_PARSER_DEFAULT);
310 if (parser == NULL) {
311 fprintf(stderr, "Failed to initialize UCL parser.\n");
312 goto err_load_metadata;
315 err = ucl_parser_add_file(parser, filename);
317 fprintf(stderr, "Failed to parse metadata file: '%s'\n",
320 goto err_load_metadata;
323 obj = ucl_parser_get_object(parser);
325 fprintf(stderr, "Failed to parse object.\n");
327 goto err_load_metadata;
330 rstate->meta_parser = parser;
331 rstate->meta_root_obj = (ucl_object_t *)obj;
337 ucl_parser_free(parser);
342 load_restore_file(const char *filename, struct restore_state *rstate)
345 char *kdata_filename = NULL, *meta_filename = NULL;
347 assert(filename != NULL);
348 assert(rstate != NULL);
350 memset(rstate, 0, sizeof(*rstate));
351 rstate->kdata_map = MAP_FAILED;
353 err = load_vmmem_file(filename, rstate);
355 fprintf(stderr, "Failed to load guest RAM file.\n");
359 kdata_filename = strcat_extension(filename, ".kern");
360 if (kdata_filename == NULL) {
361 fprintf(stderr, "Failed to construct kernel data filename.\n");
365 err = load_kdata_file(kdata_filename, rstate);
367 fprintf(stderr, "Failed to load guest kernel data file.\n");
371 meta_filename = strcat_extension(filename, ".meta");
372 if (meta_filename == NULL) {
373 fprintf(stderr, "Failed to construct kernel metadata filename.\n");
377 err = load_metadata_file(meta_filename, rstate);
379 fprintf(stderr, "Failed to load guest metadata file.\n");
386 destroy_restore_state(rstate);
387 if (kdata_filename != NULL)
388 free(kdata_filename);
389 if (meta_filename != NULL)
394 #define JSON_GET_INT_OR_RETURN(key, obj, result_ptr, ret) \
396 const ucl_object_t *obj__; \
397 obj__ = ucl_object_lookup(obj, key); \
398 if (obj__ == NULL) { \
399 fprintf(stderr, "Missing key: '%s'", key); \
402 if (!ucl_object_toint_safe(obj__, result_ptr)) { \
403 fprintf(stderr, "Cannot convert '%s' value to int.", key); \
408 #define JSON_GET_STRING_OR_RETURN(key, obj, result_ptr, ret) \
410 const ucl_object_t *obj__; \
411 obj__ = ucl_object_lookup(obj, key); \
412 if (obj__ == NULL) { \
413 fprintf(stderr, "Missing key: '%s'", key); \
416 if (!ucl_object_tostring_safe(obj__, result_ptr)) { \
417 fprintf(stderr, "Cannot convert '%s' value to string.", key); \
423 lookup_struct(enum snapshot_req struct_id, struct restore_state *rstate,
426 const ucl_object_t *structs = NULL, *obj = NULL;
427 ucl_object_iter_t it = NULL;
428 int64_t snapshot_req, size, file_offset;
430 structs = ucl_object_lookup(rstate->meta_root_obj, JSON_STRUCT_ARR_KEY);
431 if (structs == NULL) {
432 fprintf(stderr, "Failed to find '%s' object.\n",
433 JSON_STRUCT_ARR_KEY);
437 if (ucl_object_type((ucl_object_t *)structs) != UCL_ARRAY) {
438 fprintf(stderr, "Object '%s' is not an array.\n",
439 JSON_STRUCT_ARR_KEY);
443 while ((obj = ucl_object_iterate(structs, &it, true)) != NULL) {
445 JSON_GET_INT_OR_RETURN(JSON_SNAPSHOT_REQ_KEY, obj,
446 &snapshot_req, NULL);
447 assert(snapshot_req >= 0);
448 if ((enum snapshot_req) snapshot_req == struct_id) {
449 JSON_GET_INT_OR_RETURN(JSON_SIZE_KEY, obj,
453 JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
455 assert(file_offset >= 0);
456 assert(file_offset + size <= rstate->kdata_len);
458 *struct_size = (size_t)size;
459 return (rstate->kdata_map + file_offset);
467 lookup_check_dev(const char *dev_name, struct restore_state *rstate,
468 const ucl_object_t *obj, size_t *data_size)
470 const char *snapshot_req;
471 int64_t size, file_offset;
474 JSON_GET_STRING_OR_RETURN(JSON_SNAPSHOT_REQ_KEY, obj,
475 &snapshot_req, NULL);
476 assert(snapshot_req != NULL);
477 if (!strcmp(snapshot_req, dev_name)) {
478 JSON_GET_INT_OR_RETURN(JSON_SIZE_KEY, obj,
482 JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
484 assert(file_offset >= 0);
485 assert(file_offset + size <= rstate->kdata_len);
487 *data_size = (size_t)size;
488 return (rstate->kdata_map + file_offset);
495 lookup_dev(const char *dev_name, struct restore_state *rstate,
498 const ucl_object_t *devs = NULL, *obj = NULL;
499 ucl_object_iter_t it = NULL;
502 devs = ucl_object_lookup(rstate->meta_root_obj, JSON_DEV_ARR_KEY);
504 fprintf(stderr, "Failed to find '%s' object.\n",
509 if (ucl_object_type((ucl_object_t *)devs) != UCL_ARRAY) {
510 fprintf(stderr, "Object '%s' is not an array.\n",
515 while ((obj = ucl_object_iterate(devs, &it, true)) != NULL) {
516 ret = lookup_check_dev(dev_name, rstate, obj, data_size);
524 static const ucl_object_t *
525 lookup_basic_metadata_object(struct restore_state *rstate)
527 const ucl_object_t *basic_meta_obj = NULL;
529 basic_meta_obj = ucl_object_lookup(rstate->meta_root_obj,
530 JSON_BASIC_METADATA_KEY);
531 if (basic_meta_obj == NULL) {
532 fprintf(stderr, "Failed to find '%s' object.\n",
533 JSON_BASIC_METADATA_KEY);
537 if (ucl_object_type((ucl_object_t *)basic_meta_obj) != UCL_OBJECT) {
538 fprintf(stderr, "Object '%s' is not a JSON object.\n",
539 JSON_BASIC_METADATA_KEY);
543 return (basic_meta_obj);
547 lookup_vmname(struct restore_state *rstate)
550 const ucl_object_t *obj;
552 obj = lookup_basic_metadata_object(rstate);
556 JSON_GET_STRING_OR_RETURN(JSON_VMNAME_KEY, obj, &vmname, NULL);
561 lookup_memflags(struct restore_state *rstate)
564 const ucl_object_t *obj;
566 obj = lookup_basic_metadata_object(rstate);
570 JSON_GET_INT_OR_RETURN(JSON_MEMFLAGS_KEY, obj, &memflags, 0);
572 return ((int)memflags);
576 lookup_memsize(struct restore_state *rstate)
579 const ucl_object_t *obj;
581 obj = lookup_basic_metadata_object(rstate);
585 JSON_GET_INT_OR_RETURN(JSON_MEMSIZE_KEY, obj, &memsize, 0);
589 return ((size_t)memsize);
594 lookup_guest_ncpus(struct restore_state *rstate)
597 const ucl_object_t *obj;
599 obj = lookup_basic_metadata_object(rstate);
603 JSON_GET_INT_OR_RETURN(JSON_NCPUS_KEY, obj, &ncpus, 0);
608 winch_handler(int signal)
611 ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
612 #endif /* TIOCGWINSZ */
616 print_progress(size_t crtval, const size_t maxval)
619 double crtval_gb, maxval_gb;
620 size_t i, win_width, prog_start, prog_done, prog_end;
623 static char prog_buf[PROG_BUF_SZ];
624 static const size_t len = sizeof(prog_buf);
627 static char *div_str;
629 static char wip_bar[] = { '/', '-', '\\', '|' };
630 static int wip_idx = 0;
633 printf("[0B / 0B]\r\n");
640 if (maxval > 10 * GB) {
643 } else if (maxval > 10 * MB) {
651 crtval_gb = (double) crtval / div;
652 maxval_gb = (double) maxval / div;
654 rc = snprintf(prog_buf, len, "%.03lf", maxval_gb);
656 fprintf(stderr, "Maxval too big\n");
661 rc = snprintf(prog_buf, len, "\r[%*.03lf%s / %.03lf%s] |",
662 mval_len, crtval_gb, div_str, maxval_gb, div_str);
665 fprintf(stderr, "Buffer too small to print progress\n");
669 win_width = min(winsize.ws_col, len);
672 if (prog_start < (win_width - 2)) {
673 prog_end = win_width - prog_start - 2;
674 prog_done = prog_end * (crtval_gb / maxval_gb);
676 for (i = prog_start; i < prog_start + prog_done; i++)
679 if (crtval != maxval) {
680 prog_buf[i] = wip_bar[wip_idx];
681 wip_idx = (wip_idx + 1) % sizeof(wip_bar);
687 for (; i < win_width - 2; i++)
690 prog_buf[win_width - 2] = '|';
693 prog_buf[win_width - 1] = '\0';
694 write(STDOUT_FILENO, prog_buf, win_width);
700 snapshot_spinner_cb(void *arg)
703 size_t crtval, maxval, total;
704 struct spinner_info *si;
712 ts.tv_nsec = 50 * 1000 * 1000; /* 50 ms sleep time */
715 crtval = *si->crtval;
719 rc = print_progress(crtval, total);
721 fprintf(stderr, "Failed to parse progress\n");
725 nanosleep(&ts, NULL);
726 } while (crtval < maxval);
733 vm_snapshot_mem_part(const int snapfd, const size_t foff, void *src,
734 const size_t len, const size_t totalmem, const bool op_wr)
737 size_t part_done, todo, rem;
740 pthread_t spinner_th;
741 struct spinner_info *si;
743 if (lseek(snapfd, foff, SEEK_SET) < 0) {
744 perror("Failed to change file offset");
748 show_progress = false;
749 if (isatty(STDIN_FILENO) && (winsize.ws_col != 0))
750 show_progress = true;
756 si = &(struct spinner_info) {
757 .crtval = &part_done,
758 .maxval = foff + len,
762 rc = pthread_create(&spinner_th, 0, snapshot_spinner_cb, si);
764 perror("Unable to create spinner thread");
765 show_progress = false;
771 todo = min(SNAPSHOT_CHUNK, rem);
776 done = write(snapfd, src, todo);
778 done = read(snapfd, src, todo);
780 perror("Failed to write in file");
790 rc = pthread_join(spinner_th, NULL);
792 perror("Unable to end spinner thread");
799 vm_snapshot_mem(struct vmctx *ctx, int snapfd, size_t memsz, const bool op_wr)
802 size_t lowmem, highmem, totalmem;
805 ret = vm_get_guestmem_from_ctx(ctx, &baseaddr, &lowmem, &highmem);
807 fprintf(stderr, "%s: unable to retrieve guest memory size\r\n",
811 totalmem = lowmem + highmem;
813 if ((op_wr == false) && (totalmem != memsz)) {
814 fprintf(stderr, "%s: mem size mismatch: %ld vs %ld\r\n",
815 __func__, totalmem, memsz);
821 ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
822 #endif /* TIOCGWINSZ */
823 old_winch_handler = signal(SIGWINCH, winch_handler);
825 ret = vm_snapshot_mem_part(snapfd, 0, baseaddr, lowmem,
828 fprintf(stderr, "%s: Could not %s lowmem\r\n",
829 __func__, op_wr ? "write" : "read");
837 ret = vm_snapshot_mem_part(snapfd, lowmem, baseaddr + 4*GB,
838 highmem, totalmem, op_wr);
840 fprintf(stderr, "%s: Could not %s highmem\r\n",
841 __func__, op_wr ? "write" : "read");
848 signal(SIGWINCH, old_winch_handler);
854 restore_vm_mem(struct vmctx *ctx, struct restore_state *rstate)
858 restored = vm_snapshot_mem(ctx, rstate->vmmem_fd, rstate->vmmem_len,
861 if (restored != rstate->vmmem_len)
868 vm_restore_kern_struct(struct vmctx *ctx, struct restore_state *rstate,
869 const struct vm_snapshot_kern_info *info)
874 struct vm_snapshot_meta *meta;
876 struct_ptr = lookup_struct(info->req, rstate, &struct_size);
877 if (struct_ptr == NULL) {
878 fprintf(stderr, "%s: Failed to lookup struct %s\r\n",
879 __func__, info->struct_name);
884 if (struct_size == 0) {
885 fprintf(stderr, "%s: Kernel struct size was 0 for: %s\r\n",
886 __func__, info->struct_name);
891 meta = &(struct vm_snapshot_meta) {
893 .dev_name = info->struct_name,
894 .dev_req = info->req,
896 .buffer.buf_start = struct_ptr,
897 .buffer.buf_size = struct_size,
899 .buffer.buf = struct_ptr,
900 .buffer.buf_rem = struct_size,
902 .op = VM_SNAPSHOT_RESTORE,
905 ret = vm_snapshot_req(meta);
907 fprintf(stderr, "%s: Failed to restore struct: %s\r\n",
908 __func__, info->struct_name);
917 vm_restore_kern_structs(struct vmctx *ctx, struct restore_state *rstate)
922 for (i = 0; i < nitems(snapshot_kern_structs); i++) {
923 ret = vm_restore_kern_struct(ctx, rstate,
924 &snapshot_kern_structs[i]);
933 vm_restore_user_dev(struct vmctx *ctx, struct restore_state *rstate,
934 const struct vm_snapshot_dev_info *info)
939 struct vm_snapshot_meta *meta;
941 dev_ptr = lookup_dev(info->dev_name, rstate, &dev_size);
942 if (dev_ptr == NULL) {
943 fprintf(stderr, "Failed to lookup dev: %s\r\n", info->dev_name);
944 fprintf(stderr, "Continuing the restore/migration process\r\n");
949 fprintf(stderr, "%s: Device size is 0. "
950 "Assuming %s is not used\r\n",
951 __func__, info->dev_name);
955 meta = &(struct vm_snapshot_meta) {
957 .dev_name = info->dev_name,
959 .buffer.buf_start = dev_ptr,
960 .buffer.buf_size = dev_size,
962 .buffer.buf = dev_ptr,
963 .buffer.buf_rem = dev_size,
965 .op = VM_SNAPSHOT_RESTORE,
968 ret = (*info->snapshot_cb)(meta);
970 fprintf(stderr, "Failed to restore dev: %s\r\n",
980 vm_restore_user_devs(struct vmctx *ctx, struct restore_state *rstate)
985 for (i = 0; i < nitems(snapshot_devs); i++) {
986 ret = vm_restore_user_dev(ctx, rstate, &snapshot_devs[i]);
995 vm_pause_user_devs(struct vmctx *ctx)
997 const struct vm_snapshot_dev_info *info;
1001 for (i = 0; i < nitems(snapshot_devs); i++) {
1002 info = &snapshot_devs[i];
1003 if (info->pause_cb == NULL)
1006 ret = info->pause_cb(ctx, info->dev_name);
1015 vm_resume_user_devs(struct vmctx *ctx)
1017 const struct vm_snapshot_dev_info *info;
1021 for (i = 0; i < nitems(snapshot_devs); i++) {
1022 info = &snapshot_devs[i];
1023 if (info->resume_cb == NULL)
1026 ret = info->resume_cb(ctx, info->dev_name);
1035 vm_snapshot_kern_struct(int data_fd, xo_handle_t *xop, const char *array_key,
1036 struct vm_snapshot_meta *meta, off_t *offset)
1042 ret = vm_snapshot_req(meta);
1044 fprintf(stderr, "%s: Failed to snapshot struct %s\r\n",
1045 __func__, meta->dev_name);
1050 data_size = vm_get_snapshot_size(meta);
1052 write_cnt = write(data_fd, meta->buffer.buf_start, data_size);
1053 if (write_cnt != data_size) {
1054 perror("Failed to write all snapshotted data.");
1059 /* Write metadata. */
1060 xo_open_instance_h(xop, array_key);
1061 xo_emit_h(xop, "{:debug_name/%s}\n", meta->dev_name);
1062 xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%d}\n",
1064 xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1065 xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1066 xo_close_instance_h(xop, JSON_STRUCT_ARR_KEY);
1068 *offset += data_size;
1075 vm_snapshot_kern_structs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1078 size_t offset, buf_size;
1080 struct vm_snapshot_meta *meta;
1084 buf_size = SNAPSHOT_BUFFER_SIZE;
1086 buffer = malloc(SNAPSHOT_BUFFER_SIZE * sizeof(char));
1087 if (buffer == NULL) {
1089 perror("Failed to allocate memory for snapshot buffer");
1090 goto err_vm_snapshot_kern_data;
1093 meta = &(struct vm_snapshot_meta) {
1096 .buffer.buf_start = buffer,
1097 .buffer.buf_size = buf_size,
1099 .op = VM_SNAPSHOT_SAVE,
1102 xo_open_list_h(xop, JSON_STRUCT_ARR_KEY);
1103 for (i = 0; i < nitems(snapshot_kern_structs); i++) {
1104 meta->dev_name = snapshot_kern_structs[i].struct_name;
1105 meta->dev_req = snapshot_kern_structs[i].req;
1107 memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1108 meta->buffer.buf = meta->buffer.buf_start;
1109 meta->buffer.buf_rem = meta->buffer.buf_size;
1111 ret = vm_snapshot_kern_struct(data_fd, xop, JSON_DEV_ARR_KEY,
1115 goto err_vm_snapshot_kern_data;
1118 xo_close_list_h(xop, JSON_STRUCT_ARR_KEY);
1120 err_vm_snapshot_kern_data:
1127 vm_snapshot_basic_metadata(struct vmctx *ctx, xo_handle_t *xop, size_t memsz)
1131 char vmname_buf[MAX_VMNAME];
1133 memset(vmname_buf, 0, MAX_VMNAME);
1134 error = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1136 perror("Failed to get VM name");
1140 memflags = vm_get_memflags(ctx);
1142 xo_open_container_h(xop, JSON_BASIC_METADATA_KEY);
1143 xo_emit_h(xop, "{:" JSON_NCPUS_KEY "/%ld}\n", guest_ncpus);
1144 xo_emit_h(xop, "{:" JSON_VMNAME_KEY "/%s}\n", vmname_buf);
1145 xo_emit_h(xop, "{:" JSON_MEMSIZE_KEY "/%lu}\n", memsz);
1146 xo_emit_h(xop, "{:" JSON_MEMFLAGS_KEY "/%d}\n", memflags);
1147 xo_close_container_h(xop, JSON_BASIC_METADATA_KEY);
1154 vm_snapshot_dev_write_data(int data_fd, xo_handle_t *xop, const char *array_key,
1155 struct vm_snapshot_meta *meta, off_t *offset)
1160 data_size = vm_get_snapshot_size(meta);
1162 ret = write(data_fd, meta->buffer.buf_start, data_size);
1163 if (ret != data_size) {
1164 perror("Failed to write all snapshotted data.");
1168 /* Write metadata. */
1169 xo_open_instance_h(xop, array_key);
1170 xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%s}\n", meta->dev_name);
1171 xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1172 xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1173 xo_close_instance_h(xop, array_key);
1175 *offset += data_size;
1181 vm_snapshot_user_dev(const struct vm_snapshot_dev_info *info,
1182 int data_fd, xo_handle_t *xop,
1183 struct vm_snapshot_meta *meta, off_t *offset)
1187 ret = (*info->snapshot_cb)(meta);
1189 fprintf(stderr, "Failed to snapshot %s; ret=%d\r\n",
1190 meta->dev_name, ret);
1194 ret = vm_snapshot_dev_write_data(data_fd, xop, JSON_DEV_ARR_KEY, meta,
1203 vm_snapshot_user_devs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1209 struct vm_snapshot_meta *meta;
1211 buf_size = SNAPSHOT_BUFFER_SIZE;
1213 offset = lseek(data_fd, 0, SEEK_CUR);
1215 perror("Failed to get data file current offset.");
1219 buffer = malloc(buf_size);
1220 if (buffer == NULL) {
1221 perror("Failed to allocate memory for snapshot buffer");
1226 meta = &(struct vm_snapshot_meta) {
1229 .buffer.buf_start = buffer,
1230 .buffer.buf_size = buf_size,
1232 .op = VM_SNAPSHOT_SAVE,
1235 xo_open_list_h(xop, JSON_DEV_ARR_KEY);
1237 /* Restore other devices that support this feature */
1238 for (i = 0; i < nitems(snapshot_devs); i++) {
1239 meta->dev_name = snapshot_devs[i].dev_name;
1241 memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1242 meta->buffer.buf = meta->buffer.buf_start;
1243 meta->buffer.buf_rem = meta->buffer.buf_size;
1245 ret = vm_snapshot_user_dev(&snapshot_devs[i], data_fd, xop,
1251 xo_close_list_h(xop, JSON_DEV_ARR_KEY);
1260 checkpoint_cpu_add(int vcpu)
1263 pthread_mutex_lock(&vcpu_lock);
1264 CPU_SET(vcpu, &vcpus_active);
1266 if (checkpoint_active) {
1267 CPU_SET(vcpu, &vcpus_suspended);
1268 while (checkpoint_active)
1269 pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1270 CPU_CLR(vcpu, &vcpus_suspended);
1272 pthread_mutex_unlock(&vcpu_lock);
1276 * When a vCPU is suspended for any reason, it calls
1277 * checkpoint_cpu_suspend(). This records that the vCPU is idle.
1278 * Before returning from suspension, checkpoint_cpu_resume() is
1279 * called. In suspend we note that the vCPU is idle. In resume we
1280 * pause the vCPU thread until the checkpoint is complete. The reason
1281 * for the two-step process is that vCPUs might already be stopped in
1282 * the debug server when a checkpoint is requested. This approach
1283 * allows us to account for and handle those vCPUs.
1286 checkpoint_cpu_suspend(int vcpu)
1289 pthread_mutex_lock(&vcpu_lock);
1290 CPU_SET(vcpu, &vcpus_suspended);
1291 if (checkpoint_active && CPU_CMP(&vcpus_active, &vcpus_suspended) == 0)
1292 pthread_cond_signal(&vcpus_idle);
1293 pthread_mutex_unlock(&vcpu_lock);
1297 checkpoint_cpu_resume(int vcpu)
1300 pthread_mutex_lock(&vcpu_lock);
1301 while (checkpoint_active)
1302 pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1303 CPU_CLR(vcpu, &vcpus_suspended);
1304 pthread_mutex_unlock(&vcpu_lock);
1308 vm_vcpu_pause(struct vmctx *ctx)
1311 pthread_mutex_lock(&vcpu_lock);
1312 checkpoint_active = true;
1313 vm_suspend_cpu(ctx, -1);
1314 while (CPU_CMP(&vcpus_active, &vcpus_suspended) != 0)
1315 pthread_cond_wait(&vcpus_idle, &vcpu_lock);
1316 pthread_mutex_unlock(&vcpu_lock);
1320 vm_vcpu_resume(struct vmctx *ctx)
1323 pthread_mutex_lock(&vcpu_lock);
1324 checkpoint_active = false;
1325 pthread_mutex_unlock(&vcpu_lock);
1326 vm_resume_cpu(ctx, -1);
1327 pthread_cond_broadcast(&vcpus_can_run);
1331 vm_checkpoint(struct vmctx *ctx, char *checkpoint_file, bool stop_vm)
1333 int fd_checkpoint = 0, kdata_fd = 0;
1337 xo_handle_t *xop = NULL;
1338 char *meta_filename = NULL;
1339 char *kdata_filename = NULL;
1340 FILE *meta_file = NULL;
1342 kdata_filename = strcat_extension(checkpoint_file, ".kern");
1343 if (kdata_filename == NULL) {
1344 fprintf(stderr, "Failed to construct kernel data filename.\n");
1348 kdata_fd = open(kdata_filename, O_WRONLY | O_CREAT | O_TRUNC, 0700);
1350 perror("Failed to open kernel data snapshot file.");
1355 fd_checkpoint = open(checkpoint_file, O_RDWR | O_CREAT | O_TRUNC, 0700);
1357 if (fd_checkpoint < 0) {
1358 perror("Failed to create checkpoint file");
1363 meta_filename = strcat_extension(checkpoint_file, ".meta");
1364 if (meta_filename == NULL) {
1365 fprintf(stderr, "Failed to construct vm metadata filename.\n");
1369 meta_file = fopen(meta_filename, "w");
1370 if (meta_file == NULL) {
1371 perror("Failed to open vm metadata snapshot file.");
1375 xop = xo_create_to_file(meta_file, XO_STYLE_JSON, XOF_PRETTY);
1377 perror("Failed to get libxo handle on metadata file.");
1383 ret = vm_pause_user_devs(ctx);
1385 fprintf(stderr, "Could not pause devices\r\n");
1390 memsz = vm_snapshot_mem(ctx, fd_checkpoint, 0, true);
1392 perror("Could not write guest memory to file");
1397 ret = vm_snapshot_basic_metadata(ctx, xop, memsz);
1399 fprintf(stderr, "Failed to snapshot vm basic metadata.\n");
1405 ret = vm_snapshot_kern_structs(ctx, kdata_fd, xop);
1407 fprintf(stderr, "Failed to snapshot vm kernel data.\n");
1412 ret = vm_snapshot_user_devs(ctx, kdata_fd, xop);
1414 fprintf(stderr, "Failed to snapshot device state.\n");
1427 ret = vm_resume_user_devs(ctx);
1429 fprintf(stderr, "Could not resume devices\r\n");
1430 vm_vcpu_resume(ctx);
1431 if (fd_checkpoint > 0)
1432 close(fd_checkpoint);
1433 if (meta_filename != NULL)
1434 free(meta_filename);
1435 if (kdata_filename != NULL)
1436 free(kdata_filename);
1439 if (meta_file != NULL)
1447 get_checkpoint_msg(int conn_fd, struct vmctx *ctx)
1449 unsigned char buf[MAX_MSG_SIZE];
1450 struct checkpoint_op *checkpoint_op;
1451 int len, recv_len, total_recv = 0;
1454 len = sizeof(struct checkpoint_op); /* expected length */
1455 while ((recv_len = recv(conn_fd, buf + total_recv, len - total_recv, 0)) > 0) {
1456 total_recv += recv_len;
1459 perror("Error while receiving data from bhyvectl");
1464 checkpoint_op = (struct checkpoint_op *)buf;
1465 switch (checkpoint_op->op) {
1466 case START_CHECKPOINT:
1467 err = vm_checkpoint(ctx, checkpoint_op->snapshot_filename, false);
1470 err = vm_checkpoint(ctx, checkpoint_op->snapshot_filename, true);
1473 fprintf(stderr, "Unrecognized checkpoint operation.\n");
1483 * Listen for commands from bhyvectl
1486 checkpoint_thread(void *param)
1488 struct checkpoint_thread_info *thread_info;
1491 pthread_set_name_np(pthread_self(), "checkpoint thread");
1492 thread_info = (struct checkpoint_thread_info *)param;
1494 while ((conn_fd = accept(thread_info->socket_fd, NULL, NULL)) > -1) {
1495 ret = get_checkpoint_msg(conn_fd, thread_info->ctx);
1497 fprintf(stderr, "Failed to read message on checkpoint "
1498 "socket. Retrying.\n");
1502 perror("Failed to accept connection");
1509 * Create directory tree to store runtime specific information:
1510 * i.e. UNIX sockets for IPC with bhyvectl.
1513 make_checkpoint_dir(void)
1517 err = mkdir(BHYVE_RUN_DIR, 0755);
1518 if (err < 0 && errno != EEXIST)
1521 err = mkdir(CHECKPOINT_RUN_DIR, 0755);
1522 if (err < 0 && errno != EEXIST)
1529 * Create the listening socket for IPC with bhyvectl
1532 init_checkpoint_thread(struct vmctx *ctx)
1534 struct checkpoint_thread_info *checkpoint_info = NULL;
1535 struct sockaddr_un addr;
1537 pthread_t checkpoint_pthread;
1538 char vmname_buf[MAX_VMNAME];
1541 memset(&addr, 0, sizeof(addr));
1543 err = pthread_mutex_init(&vcpu_lock, NULL);
1545 errc(1, err, "checkpoint mutex init");
1546 err = pthread_cond_init(&vcpus_idle, NULL);
1548 err = pthread_cond_init(&vcpus_can_run, NULL);
1550 errc(1, err, "checkpoint cv init");
1552 socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
1553 if (socket_fd < 0) {
1554 perror("Socket creation failed (IPC with bhyvectl");
1559 err = make_checkpoint_dir();
1561 perror("Failed to create checkpoint runtime directory");
1565 addr.sun_family = AF_UNIX;
1567 err = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1569 perror("Failed to get VM name");
1573 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s/%s",
1574 CHECKPOINT_RUN_DIR, vmname_buf);
1575 addr.sun_len = SUN_LEN(&addr);
1576 unlink(addr.sun_path);
1578 if (bind(socket_fd, (struct sockaddr *)&addr, addr.sun_len) != 0) {
1579 perror("Failed to bind socket (IPC with bhyvectl)");
1584 if (listen(socket_fd, 10) < 0) {
1585 perror("Failed to listen on socket (IPC with bhyvectl)");
1590 checkpoint_info = calloc(1, sizeof(*checkpoint_info));
1591 checkpoint_info->ctx = ctx;
1592 checkpoint_info->socket_fd = socket_fd;
1594 ret = pthread_create(&checkpoint_pthread, NULL, checkpoint_thread,
1603 free(checkpoint_info);
1606 unlink(addr.sun_path);
1612 vm_snapshot_buf_err(const char *bufname, const enum vm_snapshot_op op)
1616 if (op == VM_SNAPSHOT_SAVE)
1618 else if (op == VM_SNAPSHOT_RESTORE)
1623 fprintf(stderr, "%s: snapshot-%s failed for %s\r\n",
1624 __func__, __op, bufname);
1628 vm_snapshot_buf(volatile void *data, size_t data_size,
1629 struct vm_snapshot_meta *meta)
1631 struct vm_snapshot_buffer *buffer;
1634 buffer = &meta->buffer;
1637 if (buffer->buf_rem < data_size) {
1638 fprintf(stderr, "%s: buffer too small\r\n", __func__);
1642 if (op == VM_SNAPSHOT_SAVE)
1643 memcpy(buffer->buf, (uint8_t *) data, data_size);
1644 else if (op == VM_SNAPSHOT_RESTORE)
1645 memcpy((uint8_t *) data, buffer->buf, data_size);
1649 buffer->buf += data_size;
1650 buffer->buf_rem -= data_size;
1656 vm_get_snapshot_size(struct vm_snapshot_meta *meta)
1659 struct vm_snapshot_buffer *buffer;
1661 buffer = &meta->buffer;
1663 if (buffer->buf_size < buffer->buf_rem) {
1664 fprintf(stderr, "%s: Invalid buffer: size = %zu, rem = %zu\r\n",
1665 __func__, buffer->buf_size, buffer->buf_rem);
1668 length = buffer->buf_size - buffer->buf_rem;
1675 vm_snapshot_guest2host_addr(void **addrp, size_t len, bool restore_null,
1676 struct vm_snapshot_meta *meta)
1681 if (meta->op == VM_SNAPSHOT_SAVE) {
1682 gaddr = paddr_host2guest(meta->ctx, *addrp);
1683 if (gaddr == (vm_paddr_t) -1) {
1684 if (!restore_null ||
1685 (restore_null && (*addrp != NULL))) {
1691 SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1692 } else if (meta->op == VM_SNAPSHOT_RESTORE) {
1693 SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1694 if (gaddr == (vm_paddr_t) -1) {
1695 if (!restore_null) {
1701 *addrp = paddr_guest2host(meta->ctx, gaddr, len);
1711 vm_snapshot_buf_cmp(volatile void *data, size_t data_size,
1712 struct vm_snapshot_meta *meta)
1714 struct vm_snapshot_buffer *buffer;
1718 buffer = &meta->buffer;
1721 if (buffer->buf_rem < data_size) {
1722 fprintf(stderr, "%s: buffer too small\r\n", __func__);
1727 if (op == VM_SNAPSHOT_SAVE) {
1729 memcpy(buffer->buf, (uint8_t *) data, data_size);
1730 } else if (op == VM_SNAPSHOT_RESTORE) {
1731 ret = memcmp((uint8_t *) data, buffer->buf, data_size);
1737 buffer->buf += data_size;
1738 buffer->buf_rem -= data_size;