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>
92 #include "smbiostbl.h"
95 #include "spinup_ap.h"
101 struct spinner_info {
102 const size_t *crtval;
107 extern int guest_ncpus;
109 static struct winsize winsize;
110 static sig_t old_winch_handler;
113 #define MB (1024UL * KB)
114 #define GB (1024UL * MB)
116 #define SNAPSHOT_CHUNK (4 * MB)
117 #define PROG_BUF_SZ (8192)
119 #define MAX_VMNAME 100
121 #define SNAPSHOT_BUFFER_SIZE (20 * MB)
123 #define JSON_STRUCT_ARR_KEY "structs"
124 #define JSON_DEV_ARR_KEY "devices"
125 #define JSON_BASIC_METADATA_KEY "basic metadata"
126 #define JSON_SNAPSHOT_REQ_KEY "snapshot_req"
127 #define JSON_SIZE_KEY "size"
128 #define JSON_FILE_OFFSET_KEY "file_offset"
130 #define JSON_NCPUS_KEY "ncpus"
131 #define JSON_VMNAME_KEY "vmname"
132 #define JSON_MEMSIZE_KEY "memsize"
133 #define JSON_MEMFLAGS_KEY "memflags"
137 __typeof__ (a) _a = (a); \
138 __typeof__ (b) _b = (b); \
142 const struct vm_snapshot_dev_info snapshot_devs[] = {
143 { "atkbdc", atkbdc_snapshot, NULL, NULL },
144 { "virtio-net", pci_snapshot, pci_pause, pci_resume },
145 { "virtio-blk", pci_snapshot, pci_pause, pci_resume },
146 { "virtio-rnd", pci_snapshot, NULL, NULL },
147 { "lpc", pci_snapshot, NULL, NULL },
148 { "fbuf", pci_snapshot, NULL, NULL },
149 { "xhci", pci_snapshot, NULL, NULL },
150 { "e1000", pci_snapshot, NULL, NULL },
151 { "ahci", pci_snapshot, pci_pause, pci_resume },
152 { "ahci-hd", pci_snapshot, pci_pause, pci_resume },
153 { "ahci-cd", pci_snapshot, pci_pause, pci_resume },
156 const struct vm_snapshot_kern_info snapshot_kern_structs[] = {
157 { "vhpet", STRUCT_VHPET },
159 { "vmx", STRUCT_VMX },
160 { "vioapic", STRUCT_VIOAPIC },
161 { "vlapic", STRUCT_VLAPIC },
162 { "vmcx", STRUCT_VMCX },
163 { "vatpit", STRUCT_VATPIT },
164 { "vatpic", STRUCT_VATPIC },
165 { "vpmtmr", STRUCT_VPMTMR },
166 { "vrtc", STRUCT_VRTC },
169 static cpuset_t vcpus_active, vcpus_suspended;
170 static pthread_mutex_t vcpu_lock;
171 static pthread_cond_t vcpus_idle, vcpus_can_run;
172 static bool checkpoint_active;
175 * TODO: Harden this function and all of its callers since 'base_str' is a user
179 strcat_extension(const char *base_str, const char *ext)
182 size_t base_len, ext_len;
184 base_len = strnlen(base_str, MAX_VMNAME);
185 ext_len = strnlen(ext, MAX_VMNAME);
187 if (base_len + ext_len > MAX_VMNAME) {
188 fprintf(stderr, "Filename exceeds maximum length.\n");
192 res = malloc(base_len + ext_len + 1);
194 perror("Failed to allocate memory.");
198 memcpy(res, base_str, base_len);
199 memcpy(res + base_len, ext, ext_len);
200 res[base_len + ext_len] = 0;
206 destroy_restore_state(struct restore_state *rstate)
208 if (rstate == NULL) {
209 fprintf(stderr, "Attempting to destroy NULL restore struct.\n");
213 if (rstate->kdata_map != MAP_FAILED)
214 munmap(rstate->kdata_map, rstate->kdata_len);
216 if (rstate->kdata_fd > 0)
217 close(rstate->kdata_fd);
218 if (rstate->vmmem_fd > 0)
219 close(rstate->vmmem_fd);
221 if (rstate->meta_root_obj != NULL)
222 ucl_object_unref(rstate->meta_root_obj);
223 if (rstate->meta_parser != NULL)
224 ucl_parser_free(rstate->meta_parser);
228 load_vmmem_file(const char *filename, struct restore_state *rstate)
233 rstate->vmmem_fd = open(filename, O_RDONLY);
234 if (rstate->vmmem_fd < 0) {
235 perror("Failed to open restore file");
239 err = fstat(rstate->vmmem_fd, &sb);
241 perror("Failed to stat restore file");
245 if (sb.st_size == 0) {
246 fprintf(stderr, "Restore file is empty.\n");
250 rstate->vmmem_len = sb.st_size;
255 if (rstate->vmmem_fd > 0)
256 close(rstate->vmmem_fd);
261 load_kdata_file(const char *filename, struct restore_state *rstate)
266 rstate->kdata_fd = open(filename, O_RDONLY);
267 if (rstate->kdata_fd < 0) {
268 perror("Failed to open kernel data file");
272 err = fstat(rstate->kdata_fd, &sb);
274 perror("Failed to stat kernel data file");
278 if (sb.st_size == 0) {
279 fprintf(stderr, "Kernel data file is empty.\n");
283 rstate->kdata_len = sb.st_size;
284 rstate->kdata_map = mmap(NULL, rstate->kdata_len, PROT_READ,
285 MAP_SHARED, rstate->kdata_fd, 0);
286 if (rstate->kdata_map == MAP_FAILED) {
287 perror("Failed to map restore file");
294 if (rstate->kdata_fd > 0)
295 close(rstate->kdata_fd);
300 load_metadata_file(const char *filename, struct restore_state *rstate)
302 const ucl_object_t *obj;
303 struct ucl_parser *parser;
306 parser = ucl_parser_new(UCL_PARSER_DEFAULT);
307 if (parser == NULL) {
308 fprintf(stderr, "Failed to initialize UCL parser.\n");
309 goto err_load_metadata;
312 err = ucl_parser_add_file(parser, filename);
314 fprintf(stderr, "Failed to parse metadata file: '%s'\n",
317 goto err_load_metadata;
320 obj = ucl_parser_get_object(parser);
322 fprintf(stderr, "Failed to parse object.\n");
324 goto err_load_metadata;
327 rstate->meta_parser = parser;
328 rstate->meta_root_obj = (ucl_object_t *)obj;
334 ucl_parser_free(parser);
339 load_restore_file(const char *filename, struct restore_state *rstate)
342 char *kdata_filename = NULL, *meta_filename = NULL;
344 assert(filename != NULL);
345 assert(rstate != NULL);
347 memset(rstate, 0, sizeof(*rstate));
348 rstate->kdata_map = MAP_FAILED;
350 err = load_vmmem_file(filename, rstate);
352 fprintf(stderr, "Failed to load guest RAM file.\n");
356 kdata_filename = strcat_extension(filename, ".kern");
357 if (kdata_filename == NULL) {
358 fprintf(stderr, "Failed to construct kernel data filename.\n");
362 err = load_kdata_file(kdata_filename, rstate);
364 fprintf(stderr, "Failed to load guest kernel data file.\n");
368 meta_filename = strcat_extension(filename, ".meta");
369 if (meta_filename == NULL) {
370 fprintf(stderr, "Failed to construct kernel metadata filename.\n");
374 err = load_metadata_file(meta_filename, rstate);
376 fprintf(stderr, "Failed to load guest metadata file.\n");
383 destroy_restore_state(rstate);
384 if (kdata_filename != NULL)
385 free(kdata_filename);
386 if (meta_filename != NULL)
391 #define JSON_GET_INT_OR_RETURN(key, obj, result_ptr, ret) \
393 const ucl_object_t *obj__; \
394 obj__ = ucl_object_lookup(obj, key); \
395 if (obj__ == NULL) { \
396 fprintf(stderr, "Missing key: '%s'", key); \
399 if (!ucl_object_toint_safe(obj__, result_ptr)) { \
400 fprintf(stderr, "Cannot convert '%s' value to int.", key); \
405 #define JSON_GET_STRING_OR_RETURN(key, obj, result_ptr, ret) \
407 const ucl_object_t *obj__; \
408 obj__ = ucl_object_lookup(obj, key); \
409 if (obj__ == NULL) { \
410 fprintf(stderr, "Missing key: '%s'", key); \
413 if (!ucl_object_tostring_safe(obj__, result_ptr)) { \
414 fprintf(stderr, "Cannot convert '%s' value to string.", key); \
420 lookup_struct(enum snapshot_req struct_id, struct restore_state *rstate,
423 const ucl_object_t *structs = NULL, *obj = NULL;
424 ucl_object_iter_t it = NULL;
425 int64_t snapshot_req, size, file_offset;
427 structs = ucl_object_lookup(rstate->meta_root_obj, JSON_STRUCT_ARR_KEY);
428 if (structs == NULL) {
429 fprintf(stderr, "Failed to find '%s' object.\n",
430 JSON_STRUCT_ARR_KEY);
434 if (ucl_object_type((ucl_object_t *)structs) != UCL_ARRAY) {
435 fprintf(stderr, "Object '%s' is not an array.\n",
436 JSON_STRUCT_ARR_KEY);
440 while ((obj = ucl_object_iterate(structs, &it, true)) != NULL) {
442 JSON_GET_INT_OR_RETURN(JSON_SNAPSHOT_REQ_KEY, obj,
443 &snapshot_req, NULL);
444 assert(snapshot_req >= 0);
445 if ((enum snapshot_req) snapshot_req == struct_id) {
446 JSON_GET_INT_OR_RETURN(JSON_SIZE_KEY, obj,
450 JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
452 assert(file_offset >= 0);
453 assert(file_offset + size <= rstate->kdata_len);
455 *struct_size = (size_t)size;
456 return (rstate->kdata_map + file_offset);
464 lookup_check_dev(const char *dev_name, struct restore_state *rstate,
465 const ucl_object_t *obj, size_t *data_size)
467 const char *snapshot_req;
468 int64_t size, file_offset;
471 JSON_GET_STRING_OR_RETURN(JSON_SNAPSHOT_REQ_KEY, obj,
472 &snapshot_req, NULL);
473 assert(snapshot_req != NULL);
474 if (!strcmp(snapshot_req, dev_name)) {
475 JSON_GET_INT_OR_RETURN(JSON_SIZE_KEY, obj,
479 JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
481 assert(file_offset >= 0);
482 assert(file_offset + size <= rstate->kdata_len);
484 *data_size = (size_t)size;
485 return (rstate->kdata_map + file_offset);
492 lookup_dev(const char *dev_name, struct restore_state *rstate,
495 const ucl_object_t *devs = NULL, *obj = NULL;
496 ucl_object_iter_t it = NULL;
499 devs = ucl_object_lookup(rstate->meta_root_obj, JSON_DEV_ARR_KEY);
501 fprintf(stderr, "Failed to find '%s' object.\n",
506 if (ucl_object_type((ucl_object_t *)devs) != UCL_ARRAY) {
507 fprintf(stderr, "Object '%s' is not an array.\n",
512 while ((obj = ucl_object_iterate(devs, &it, true)) != NULL) {
513 ret = lookup_check_dev(dev_name, rstate, obj, data_size);
521 static const ucl_object_t *
522 lookup_basic_metadata_object(struct restore_state *rstate)
524 const ucl_object_t *basic_meta_obj = NULL;
526 basic_meta_obj = ucl_object_lookup(rstate->meta_root_obj,
527 JSON_BASIC_METADATA_KEY);
528 if (basic_meta_obj == NULL) {
529 fprintf(stderr, "Failed to find '%s' object.\n",
530 JSON_BASIC_METADATA_KEY);
534 if (ucl_object_type((ucl_object_t *)basic_meta_obj) != UCL_OBJECT) {
535 fprintf(stderr, "Object '%s' is not a JSON object.\n",
536 JSON_BASIC_METADATA_KEY);
540 return (basic_meta_obj);
544 lookup_vmname(struct restore_state *rstate)
547 const ucl_object_t *obj;
549 obj = lookup_basic_metadata_object(rstate);
553 JSON_GET_STRING_OR_RETURN(JSON_VMNAME_KEY, obj, &vmname, NULL);
558 lookup_memflags(struct restore_state *rstate)
561 const ucl_object_t *obj;
563 obj = lookup_basic_metadata_object(rstate);
567 JSON_GET_INT_OR_RETURN(JSON_MEMFLAGS_KEY, obj, &memflags, 0);
569 return ((int)memflags);
573 lookup_memsize(struct restore_state *rstate)
576 const ucl_object_t *obj;
578 obj = lookup_basic_metadata_object(rstate);
582 JSON_GET_INT_OR_RETURN(JSON_MEMSIZE_KEY, obj, &memsize, 0);
586 return ((size_t)memsize);
591 lookup_guest_ncpus(struct restore_state *rstate)
594 const ucl_object_t *obj;
596 obj = lookup_basic_metadata_object(rstate);
600 JSON_GET_INT_OR_RETURN(JSON_NCPUS_KEY, obj, &ncpus, 0);
605 winch_handler(int signal)
608 ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
609 #endif /* TIOCGWINSZ */
613 print_progress(size_t crtval, const size_t maxval)
616 double crtval_gb, maxval_gb;
617 size_t i, win_width, prog_start, prog_done, prog_end;
620 static char prog_buf[PROG_BUF_SZ];
621 static const size_t len = sizeof(prog_buf);
624 static char *div_str;
626 static char wip_bar[] = { '/', '-', '\\', '|' };
627 static int wip_idx = 0;
630 printf("[0B / 0B]\r\n");
637 if (maxval > 10 * GB) {
640 } else if (maxval > 10 * MB) {
648 crtval_gb = (double) crtval / div;
649 maxval_gb = (double) maxval / div;
651 rc = snprintf(prog_buf, len, "%.03lf", maxval_gb);
653 fprintf(stderr, "Maxval too big\n");
658 rc = snprintf(prog_buf, len, "\r[%*.03lf%s / %.03lf%s] |",
659 mval_len, crtval_gb, div_str, maxval_gb, div_str);
662 fprintf(stderr, "Buffer too small to print progress\n");
666 win_width = min(winsize.ws_col, len);
669 if (prog_start < (win_width - 2)) {
670 prog_end = win_width - prog_start - 2;
671 prog_done = prog_end * (crtval_gb / maxval_gb);
673 for (i = prog_start; i < prog_start + prog_done; i++)
676 if (crtval != maxval) {
677 prog_buf[i] = wip_bar[wip_idx];
678 wip_idx = (wip_idx + 1) % sizeof(wip_bar);
684 for (; i < win_width - 2; i++)
687 prog_buf[win_width - 2] = '|';
690 prog_buf[win_width - 1] = '\0';
691 write(STDOUT_FILENO, prog_buf, win_width);
697 snapshot_spinner_cb(void *arg)
700 size_t crtval, maxval, total;
701 struct spinner_info *si;
709 ts.tv_nsec = 50 * 1000 * 1000; /* 50 ms sleep time */
712 crtval = *si->crtval;
716 rc = print_progress(crtval, total);
718 fprintf(stderr, "Failed to parse progress\n");
722 nanosleep(&ts, NULL);
723 } while (crtval < maxval);
730 vm_snapshot_mem_part(const int snapfd, const size_t foff, void *src,
731 const size_t len, const size_t totalmem, const bool op_wr)
734 size_t part_done, todo, rem;
737 pthread_t spinner_th;
738 struct spinner_info *si;
740 if (lseek(snapfd, foff, SEEK_SET) < 0) {
741 perror("Failed to change file offset");
745 show_progress = false;
746 if (isatty(STDIN_FILENO) && (winsize.ws_col != 0))
747 show_progress = true;
753 si = &(struct spinner_info) {
754 .crtval = &part_done,
755 .maxval = foff + len,
759 rc = pthread_create(&spinner_th, 0, snapshot_spinner_cb, si);
761 perror("Unable to create spinner thread");
762 show_progress = false;
768 todo = min(SNAPSHOT_CHUNK, rem);
773 done = write(snapfd, src, todo);
775 done = read(snapfd, src, todo);
777 perror("Failed to write in file");
787 rc = pthread_join(spinner_th, NULL);
789 perror("Unable to end spinner thread");
796 vm_snapshot_mem(struct vmctx *ctx, int snapfd, size_t memsz, const bool op_wr)
799 size_t lowmem, highmem, totalmem;
802 ret = vm_get_guestmem_from_ctx(ctx, &baseaddr, &lowmem, &highmem);
804 fprintf(stderr, "%s: unable to retrieve guest memory size\r\n",
808 totalmem = lowmem + highmem;
810 if ((op_wr == false) && (totalmem != memsz)) {
811 fprintf(stderr, "%s: mem size mismatch: %ld vs %ld\r\n",
812 __func__, totalmem, memsz);
818 ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
819 #endif /* TIOCGWINSZ */
820 old_winch_handler = signal(SIGWINCH, winch_handler);
822 ret = vm_snapshot_mem_part(snapfd, 0, baseaddr, lowmem,
825 fprintf(stderr, "%s: Could not %s lowmem\r\n",
826 __func__, op_wr ? "write" : "read");
834 ret = vm_snapshot_mem_part(snapfd, lowmem, baseaddr + 4*GB,
835 highmem, totalmem, op_wr);
837 fprintf(stderr, "%s: Could not %s highmem\r\n",
838 __func__, op_wr ? "write" : "read");
845 signal(SIGWINCH, old_winch_handler);
851 restore_vm_mem(struct vmctx *ctx, struct restore_state *rstate)
855 restored = vm_snapshot_mem(ctx, rstate->vmmem_fd, rstate->vmmem_len,
858 if (restored != rstate->vmmem_len)
865 vm_restore_kern_struct(struct vmctx *ctx, struct restore_state *rstate,
866 const struct vm_snapshot_kern_info *info)
871 struct vm_snapshot_meta *meta;
873 struct_ptr = lookup_struct(info->req, rstate, &struct_size);
874 if (struct_ptr == NULL) {
875 fprintf(stderr, "%s: Failed to lookup struct %s\r\n",
876 __func__, info->struct_name);
881 if (struct_size == 0) {
882 fprintf(stderr, "%s: Kernel struct size was 0 for: %s\r\n",
883 __func__, info->struct_name);
888 meta = &(struct vm_snapshot_meta) {
890 .dev_name = info->struct_name,
891 .dev_req = info->req,
893 .buffer.buf_start = struct_ptr,
894 .buffer.buf_size = struct_size,
896 .buffer.buf = struct_ptr,
897 .buffer.buf_rem = struct_size,
899 .op = VM_SNAPSHOT_RESTORE,
902 ret = vm_snapshot_req(meta);
904 fprintf(stderr, "%s: Failed to restore struct: %s\r\n",
905 __func__, info->struct_name);
914 vm_restore_kern_structs(struct vmctx *ctx, struct restore_state *rstate)
919 for (i = 0; i < nitems(snapshot_kern_structs); i++) {
920 ret = vm_restore_kern_struct(ctx, rstate,
921 &snapshot_kern_structs[i]);
930 vm_restore_user_dev(struct vmctx *ctx, struct restore_state *rstate,
931 const struct vm_snapshot_dev_info *info)
936 struct vm_snapshot_meta *meta;
938 dev_ptr = lookup_dev(info->dev_name, rstate, &dev_size);
939 if (dev_ptr == NULL) {
940 fprintf(stderr, "Failed to lookup dev: %s\r\n", info->dev_name);
941 fprintf(stderr, "Continuing the restore/migration process\r\n");
946 fprintf(stderr, "%s: Device size is 0. "
947 "Assuming %s is not used\r\n",
948 __func__, info->dev_name);
952 meta = &(struct vm_snapshot_meta) {
954 .dev_name = info->dev_name,
956 .buffer.buf_start = dev_ptr,
957 .buffer.buf_size = dev_size,
959 .buffer.buf = dev_ptr,
960 .buffer.buf_rem = dev_size,
962 .op = VM_SNAPSHOT_RESTORE,
965 ret = (*info->snapshot_cb)(meta);
967 fprintf(stderr, "Failed to restore dev: %s\r\n",
977 vm_restore_user_devs(struct vmctx *ctx, struct restore_state *rstate)
982 for (i = 0; i < nitems(snapshot_devs); i++) {
983 ret = vm_restore_user_dev(ctx, rstate, &snapshot_devs[i]);
992 vm_pause_user_devs(struct vmctx *ctx)
994 const struct vm_snapshot_dev_info *info;
998 for (i = 0; i < nitems(snapshot_devs); i++) {
999 info = &snapshot_devs[i];
1000 if (info->pause_cb == NULL)
1003 ret = info->pause_cb(ctx, info->dev_name);
1012 vm_resume_user_devs(struct vmctx *ctx)
1014 const struct vm_snapshot_dev_info *info;
1018 for (i = 0; i < nitems(snapshot_devs); i++) {
1019 info = &snapshot_devs[i];
1020 if (info->resume_cb == NULL)
1023 ret = info->resume_cb(ctx, info->dev_name);
1032 vm_snapshot_kern_struct(int data_fd, xo_handle_t *xop, const char *array_key,
1033 struct vm_snapshot_meta *meta, off_t *offset)
1039 ret = vm_snapshot_req(meta);
1041 fprintf(stderr, "%s: Failed to snapshot struct %s\r\n",
1042 __func__, meta->dev_name);
1047 data_size = vm_get_snapshot_size(meta);
1049 write_cnt = write(data_fd, meta->buffer.buf_start, data_size);
1050 if (write_cnt != data_size) {
1051 perror("Failed to write all snapshotted data.");
1056 /* Write metadata. */
1057 xo_open_instance_h(xop, array_key);
1058 xo_emit_h(xop, "{:debug_name/%s}\n", meta->dev_name);
1059 xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%d}\n",
1061 xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1062 xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1063 xo_close_instance_h(xop, JSON_STRUCT_ARR_KEY);
1065 *offset += data_size;
1072 vm_snapshot_kern_structs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1075 size_t offset, buf_size;
1077 struct vm_snapshot_meta *meta;
1081 buf_size = SNAPSHOT_BUFFER_SIZE;
1083 buffer = malloc(SNAPSHOT_BUFFER_SIZE * sizeof(char));
1084 if (buffer == NULL) {
1086 perror("Failed to allocate memory for snapshot buffer");
1087 goto err_vm_snapshot_kern_data;
1090 meta = &(struct vm_snapshot_meta) {
1093 .buffer.buf_start = buffer,
1094 .buffer.buf_size = buf_size,
1096 .op = VM_SNAPSHOT_SAVE,
1099 xo_open_list_h(xop, JSON_STRUCT_ARR_KEY);
1100 for (i = 0; i < nitems(snapshot_kern_structs); i++) {
1101 meta->dev_name = snapshot_kern_structs[i].struct_name;
1102 meta->dev_req = snapshot_kern_structs[i].req;
1104 memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1105 meta->buffer.buf = meta->buffer.buf_start;
1106 meta->buffer.buf_rem = meta->buffer.buf_size;
1108 ret = vm_snapshot_kern_struct(data_fd, xop, JSON_DEV_ARR_KEY,
1112 goto err_vm_snapshot_kern_data;
1115 xo_close_list_h(xop, JSON_STRUCT_ARR_KEY);
1117 err_vm_snapshot_kern_data:
1124 vm_snapshot_basic_metadata(struct vmctx *ctx, xo_handle_t *xop, size_t memsz)
1128 char vmname_buf[MAX_VMNAME];
1130 memset(vmname_buf, 0, MAX_VMNAME);
1131 error = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1133 perror("Failed to get VM name");
1137 memflags = vm_get_memflags(ctx);
1139 xo_open_container_h(xop, JSON_BASIC_METADATA_KEY);
1140 xo_emit_h(xop, "{:" JSON_NCPUS_KEY "/%ld}\n", guest_ncpus);
1141 xo_emit_h(xop, "{:" JSON_VMNAME_KEY "/%s}\n", vmname_buf);
1142 xo_emit_h(xop, "{:" JSON_MEMSIZE_KEY "/%lu}\n", memsz);
1143 xo_emit_h(xop, "{:" JSON_MEMFLAGS_KEY "/%d}\n", memflags);
1144 xo_close_container_h(xop, JSON_BASIC_METADATA_KEY);
1151 vm_snapshot_dev_write_data(int data_fd, xo_handle_t *xop, const char *array_key,
1152 struct vm_snapshot_meta *meta, off_t *offset)
1157 data_size = vm_get_snapshot_size(meta);
1159 ret = write(data_fd, meta->buffer.buf_start, data_size);
1160 if (ret != data_size) {
1161 perror("Failed to write all snapshotted data.");
1165 /* Write metadata. */
1166 xo_open_instance_h(xop, array_key);
1167 xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%s}\n", meta->dev_name);
1168 xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1169 xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1170 xo_close_instance_h(xop, array_key);
1172 *offset += data_size;
1178 vm_snapshot_user_dev(const struct vm_snapshot_dev_info *info,
1179 int data_fd, xo_handle_t *xop,
1180 struct vm_snapshot_meta *meta, off_t *offset)
1184 ret = (*info->snapshot_cb)(meta);
1186 fprintf(stderr, "Failed to snapshot %s; ret=%d\r\n",
1187 meta->dev_name, ret);
1191 ret = vm_snapshot_dev_write_data(data_fd, xop, JSON_DEV_ARR_KEY, meta,
1200 vm_snapshot_user_devs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1206 struct vm_snapshot_meta *meta;
1208 buf_size = SNAPSHOT_BUFFER_SIZE;
1210 offset = lseek(data_fd, 0, SEEK_CUR);
1212 perror("Failed to get data file current offset.");
1216 buffer = malloc(buf_size);
1217 if (buffer == NULL) {
1218 perror("Failed to allocate memory for snapshot buffer");
1223 meta = &(struct vm_snapshot_meta) {
1226 .buffer.buf_start = buffer,
1227 .buffer.buf_size = buf_size,
1229 .op = VM_SNAPSHOT_SAVE,
1232 xo_open_list_h(xop, JSON_DEV_ARR_KEY);
1234 /* Restore other devices that support this feature */
1235 for (i = 0; i < nitems(snapshot_devs); i++) {
1236 meta->dev_name = snapshot_devs[i].dev_name;
1238 memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1239 meta->buffer.buf = meta->buffer.buf_start;
1240 meta->buffer.buf_rem = meta->buffer.buf_size;
1242 ret = vm_snapshot_user_dev(&snapshot_devs[i], data_fd, xop,
1248 xo_close_list_h(xop, JSON_DEV_ARR_KEY);
1257 checkpoint_cpu_add(int vcpu)
1260 pthread_mutex_lock(&vcpu_lock);
1261 CPU_SET(vcpu, &vcpus_active);
1263 if (checkpoint_active) {
1264 CPU_SET(vcpu, &vcpus_suspended);
1265 while (checkpoint_active)
1266 pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1267 CPU_CLR(vcpu, &vcpus_suspended);
1269 pthread_mutex_unlock(&vcpu_lock);
1273 * When a vCPU is suspended for any reason, it calls
1274 * checkpoint_cpu_suspend(). This records that the vCPU is idle.
1275 * Before returning from suspension, checkpoint_cpu_resume() is
1276 * called. In suspend we note that the vCPU is idle. In resume we
1277 * pause the vCPU thread until the checkpoint is complete. The reason
1278 * for the two-step process is that vCPUs might already be stopped in
1279 * the debug server when a checkpoint is requested. This approach
1280 * allows us to account for and handle those vCPUs.
1283 checkpoint_cpu_suspend(int vcpu)
1286 pthread_mutex_lock(&vcpu_lock);
1287 CPU_SET(vcpu, &vcpus_suspended);
1288 if (checkpoint_active && CPU_CMP(&vcpus_active, &vcpus_suspended) == 0)
1289 pthread_cond_signal(&vcpus_idle);
1290 pthread_mutex_unlock(&vcpu_lock);
1294 checkpoint_cpu_resume(int vcpu)
1297 pthread_mutex_lock(&vcpu_lock);
1298 while (checkpoint_active)
1299 pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1300 CPU_CLR(vcpu, &vcpus_suspended);
1301 pthread_mutex_unlock(&vcpu_lock);
1305 vm_vcpu_pause(struct vmctx *ctx)
1308 pthread_mutex_lock(&vcpu_lock);
1309 checkpoint_active = true;
1310 vm_suspend_cpu(ctx, -1);
1311 while (CPU_CMP(&vcpus_active, &vcpus_suspended) != 0)
1312 pthread_cond_wait(&vcpus_idle, &vcpu_lock);
1313 pthread_mutex_unlock(&vcpu_lock);
1317 vm_vcpu_resume(struct vmctx *ctx)
1320 pthread_mutex_lock(&vcpu_lock);
1321 checkpoint_active = false;
1322 pthread_mutex_unlock(&vcpu_lock);
1323 vm_resume_cpu(ctx, -1);
1324 pthread_cond_broadcast(&vcpus_can_run);
1328 vm_checkpoint(struct vmctx *ctx, char *checkpoint_file, bool stop_vm)
1330 int fd_checkpoint = 0, kdata_fd = 0;
1334 xo_handle_t *xop = NULL;
1335 char *meta_filename = NULL;
1336 char *kdata_filename = NULL;
1337 FILE *meta_file = NULL;
1339 kdata_filename = strcat_extension(checkpoint_file, ".kern");
1340 if (kdata_filename == NULL) {
1341 fprintf(stderr, "Failed to construct kernel data filename.\n");
1345 kdata_fd = open(kdata_filename, O_WRONLY | O_CREAT | O_TRUNC, 0700);
1347 perror("Failed to open kernel data snapshot file.");
1352 fd_checkpoint = open(checkpoint_file, O_RDWR | O_CREAT | O_TRUNC, 0700);
1354 if (fd_checkpoint < 0) {
1355 perror("Failed to create checkpoint file");
1360 meta_filename = strcat_extension(checkpoint_file, ".meta");
1361 if (meta_filename == NULL) {
1362 fprintf(stderr, "Failed to construct vm metadata filename.\n");
1366 meta_file = fopen(meta_filename, "w");
1367 if (meta_file == NULL) {
1368 perror("Failed to open vm metadata snapshot file.");
1372 xop = xo_create_to_file(meta_file, XO_STYLE_JSON, XOF_PRETTY);
1374 perror("Failed to get libxo handle on metadata file.");
1380 ret = vm_pause_user_devs(ctx);
1382 fprintf(stderr, "Could not pause devices\r\n");
1387 memsz = vm_snapshot_mem(ctx, fd_checkpoint, 0, true);
1389 perror("Could not write guest memory to file");
1394 ret = vm_snapshot_basic_metadata(ctx, xop, memsz);
1396 fprintf(stderr, "Failed to snapshot vm basic metadata.\n");
1402 ret = vm_snapshot_kern_structs(ctx, kdata_fd, xop);
1404 fprintf(stderr, "Failed to snapshot vm kernel data.\n");
1409 ret = vm_snapshot_user_devs(ctx, kdata_fd, xop);
1411 fprintf(stderr, "Failed to snapshot device state.\n");
1424 ret = vm_resume_user_devs(ctx);
1426 fprintf(stderr, "Could not resume devices\r\n");
1427 vm_vcpu_resume(ctx);
1428 if (fd_checkpoint > 0)
1429 close(fd_checkpoint);
1430 if (meta_filename != NULL)
1431 free(meta_filename);
1432 if (kdata_filename != NULL)
1433 free(kdata_filename);
1436 if (meta_file != NULL)
1444 handle_message(struct ipc_message *imsg, struct vmctx *ctx)
1448 switch (imsg->code) {
1449 case START_CHECKPOINT:
1450 err = vm_checkpoint(ctx, imsg->data.op.snapshot_filename, false);
1453 err = vm_checkpoint(ctx, imsg->data.op.snapshot_filename, true);
1456 EPRINTLN("Unrecognized checkpoint operation\n");
1461 EPRINTLN("Unable to perform the requested operation\n");
1467 * Listen for commands from bhyvectl
1470 checkpoint_thread(void *param)
1472 struct ipc_message imsg;
1473 struct checkpoint_thread_info *thread_info;
1476 pthread_set_name_np(pthread_self(), "checkpoint thread");
1477 thread_info = (struct checkpoint_thread_info *)param;
1480 n = recvfrom(thread_info->socket_fd, &imsg, sizeof(imsg), 0, NULL, 0);
1483 * slight sanity check: see if there's enough data to at
1484 * least determine the type of message.
1486 if (n >= sizeof(imsg.code))
1487 handle_message(&imsg, thread_info->ctx);
1489 EPRINTLN("Failed to receive message: %s\n",
1490 n == -1 ? strerror(errno) : "unknown error");
1501 err = pthread_mutex_init(&vcpu_lock, NULL);
1503 errc(1, err, "checkpoint mutex init");
1504 err = pthread_cond_init(&vcpus_idle, NULL);
1506 errc(1, err, "checkpoint cv init (vcpus_idle)");
1507 err = pthread_cond_init(&vcpus_can_run, NULL);
1509 errc(1, err, "checkpoint cv init (vcpus_can_run)");
1513 * Create the listening socket for IPC with bhyvectl
1516 init_checkpoint_thread(struct vmctx *ctx)
1518 struct checkpoint_thread_info *checkpoint_info = NULL;
1519 struct sockaddr_un addr;
1521 pthread_t checkpoint_pthread;
1522 char vmname_buf[MAX_VMNAME];
1525 memset(&addr, 0, sizeof(addr));
1527 socket_fd = socket(PF_UNIX, SOCK_DGRAM, 0);
1528 if (socket_fd < 0) {
1529 EPRINTLN("Socket creation failed: %s", strerror(errno));
1534 addr.sun_family = AF_UNIX;
1536 err = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1538 perror("Failed to get VM name");
1542 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s%s",
1543 BHYVE_RUN_DIR, vmname_buf);
1544 addr.sun_len = SUN_LEN(&addr);
1545 unlink(addr.sun_path);
1547 if (bind(socket_fd, (struct sockaddr *)&addr, addr.sun_len) != 0) {
1548 EPRINTLN("Failed to bind socket \"%s\": %s\n",
1549 addr.sun_path, strerror(errno));
1554 checkpoint_info = calloc(1, sizeof(*checkpoint_info));
1555 checkpoint_info->ctx = ctx;
1556 checkpoint_info->socket_fd = socket_fd;
1558 ret = pthread_create(&checkpoint_pthread, NULL, checkpoint_thread,
1567 free(checkpoint_info);
1570 unlink(addr.sun_path);
1576 vm_snapshot_buf_err(const char *bufname, const enum vm_snapshot_op op)
1580 if (op == VM_SNAPSHOT_SAVE)
1582 else if (op == VM_SNAPSHOT_RESTORE)
1587 fprintf(stderr, "%s: snapshot-%s failed for %s\r\n",
1588 __func__, __op, bufname);
1592 vm_snapshot_buf(volatile void *data, size_t data_size,
1593 struct vm_snapshot_meta *meta)
1595 struct vm_snapshot_buffer *buffer;
1598 buffer = &meta->buffer;
1601 if (buffer->buf_rem < data_size) {
1602 fprintf(stderr, "%s: buffer too small\r\n", __func__);
1606 if (op == VM_SNAPSHOT_SAVE)
1607 memcpy(buffer->buf, (uint8_t *) data, data_size);
1608 else if (op == VM_SNAPSHOT_RESTORE)
1609 memcpy((uint8_t *) data, buffer->buf, data_size);
1613 buffer->buf += data_size;
1614 buffer->buf_rem -= data_size;
1620 vm_get_snapshot_size(struct vm_snapshot_meta *meta)
1623 struct vm_snapshot_buffer *buffer;
1625 buffer = &meta->buffer;
1627 if (buffer->buf_size < buffer->buf_rem) {
1628 fprintf(stderr, "%s: Invalid buffer: size = %zu, rem = %zu\r\n",
1629 __func__, buffer->buf_size, buffer->buf_rem);
1632 length = buffer->buf_size - buffer->buf_rem;
1639 vm_snapshot_guest2host_addr(void **addrp, size_t len, bool restore_null,
1640 struct vm_snapshot_meta *meta)
1645 if (meta->op == VM_SNAPSHOT_SAVE) {
1646 gaddr = paddr_host2guest(meta->ctx, *addrp);
1647 if (gaddr == (vm_paddr_t) -1) {
1648 if (!restore_null ||
1649 (restore_null && (*addrp != NULL))) {
1655 SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1656 } else if (meta->op == VM_SNAPSHOT_RESTORE) {
1657 SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1658 if (gaddr == (vm_paddr_t) -1) {
1659 if (!restore_null) {
1665 *addrp = paddr_guest2host(meta->ctx, gaddr, len);
1675 vm_snapshot_buf_cmp(volatile void *data, size_t data_size,
1676 struct vm_snapshot_meta *meta)
1678 struct vm_snapshot_buffer *buffer;
1682 buffer = &meta->buffer;
1685 if (buffer->buf_rem < data_size) {
1686 fprintf(stderr, "%s: buffer too small\r\n", __func__);
1691 if (op == VM_SNAPSHOT_SAVE) {
1693 memcpy(buffer->buf, (uint8_t *) data, data_size);
1694 } else if (op == VM_SNAPSHOT_RESTORE) {
1695 ret = memcmp((uint8_t *) data, buffer->buf, data_size);
1701 buffer->buf += data_size;
1702 buffer->buf_rem -= data_size;