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 MAX_VMNAME 100
120 #define MAX_MSG_SIZE 1024
122 #define SNAPSHOT_BUFFER_SIZE (20 * MB)
124 #define JSON_STRUCT_ARR_KEY "structs"
125 #define JSON_DEV_ARR_KEY "devices"
126 #define JSON_BASIC_METADATA_KEY "basic metadata"
127 #define JSON_SNAPSHOT_REQ_KEY "snapshot_req"
128 #define JSON_SIZE_KEY "size"
129 #define JSON_FILE_OFFSET_KEY "file_offset"
131 #define JSON_NCPUS_KEY "ncpus"
132 #define JSON_VMNAME_KEY "vmname"
133 #define JSON_MEMSIZE_KEY "memsize"
134 #define JSON_MEMFLAGS_KEY "memflags"
138 __typeof__ (a) _a = (a); \
139 __typeof__ (b) _b = (b); \
143 const struct vm_snapshot_dev_info snapshot_devs[] = {
144 { "atkbdc", atkbdc_snapshot, NULL, NULL },
145 { "virtio-net", pci_snapshot, pci_pause, pci_resume },
146 { "virtio-blk", pci_snapshot, pci_pause, pci_resume },
147 { "virtio-rnd", pci_snapshot, NULL, NULL },
148 { "lpc", pci_snapshot, NULL, NULL },
149 { "fbuf", pci_snapshot, NULL, NULL },
150 { "xhci", pci_snapshot, NULL, NULL },
151 { "e1000", pci_snapshot, NULL, NULL },
152 { "ahci", pci_snapshot, pci_pause, pci_resume },
153 { "ahci-hd", pci_snapshot, pci_pause, pci_resume },
154 { "ahci-cd", pci_snapshot, pci_pause, pci_resume },
157 const struct vm_snapshot_kern_info snapshot_kern_structs[] = {
158 { "vhpet", STRUCT_VHPET },
160 { "vmx", STRUCT_VMX },
161 { "vioapic", STRUCT_VIOAPIC },
162 { "vlapic", STRUCT_VLAPIC },
163 { "vmcx", STRUCT_VMCX },
164 { "vatpit", STRUCT_VATPIT },
165 { "vatpic", STRUCT_VATPIC },
166 { "vpmtmr", STRUCT_VPMTMR },
167 { "vrtc", STRUCT_VRTC },
170 static cpuset_t vcpus_active, vcpus_suspended;
171 static pthread_mutex_t vcpu_lock;
172 static pthread_cond_t vcpus_idle, vcpus_can_run;
173 static bool checkpoint_active;
176 * TODO: Harden this function and all of its callers since 'base_str' is a user
180 strcat_extension(const char *base_str, const char *ext)
183 size_t base_len, ext_len;
185 base_len = strnlen(base_str, MAX_VMNAME);
186 ext_len = strnlen(ext, MAX_VMNAME);
188 if (base_len + ext_len > MAX_VMNAME) {
189 fprintf(stderr, "Filename exceeds maximum length.\n");
193 res = malloc(base_len + ext_len + 1);
195 perror("Failed to allocate memory.");
199 memcpy(res, base_str, base_len);
200 memcpy(res + base_len, ext, ext_len);
201 res[base_len + ext_len] = 0;
207 destroy_restore_state(struct restore_state *rstate)
209 if (rstate == NULL) {
210 fprintf(stderr, "Attempting to destroy NULL restore struct.\n");
214 if (rstate->kdata_map != MAP_FAILED)
215 munmap(rstate->kdata_map, rstate->kdata_len);
217 if (rstate->kdata_fd > 0)
218 close(rstate->kdata_fd);
219 if (rstate->vmmem_fd > 0)
220 close(rstate->vmmem_fd);
222 if (rstate->meta_root_obj != NULL)
223 ucl_object_unref(rstate->meta_root_obj);
224 if (rstate->meta_parser != NULL)
225 ucl_parser_free(rstate->meta_parser);
229 load_vmmem_file(const char *filename, struct restore_state *rstate)
234 rstate->vmmem_fd = open(filename, O_RDONLY);
235 if (rstate->vmmem_fd < 0) {
236 perror("Failed to open restore file");
240 err = fstat(rstate->vmmem_fd, &sb);
242 perror("Failed to stat restore file");
246 if (sb.st_size == 0) {
247 fprintf(stderr, "Restore file is empty.\n");
251 rstate->vmmem_len = sb.st_size;
256 if (rstate->vmmem_fd > 0)
257 close(rstate->vmmem_fd);
262 load_kdata_file(const char *filename, struct restore_state *rstate)
267 rstate->kdata_fd = open(filename, O_RDONLY);
268 if (rstate->kdata_fd < 0) {
269 perror("Failed to open kernel data file");
273 err = fstat(rstate->kdata_fd, &sb);
275 perror("Failed to stat kernel data file");
279 if (sb.st_size == 0) {
280 fprintf(stderr, "Kernel data file is empty.\n");
284 rstate->kdata_len = sb.st_size;
285 rstate->kdata_map = mmap(NULL, rstate->kdata_len, PROT_READ,
286 MAP_SHARED, rstate->kdata_fd, 0);
287 if (rstate->kdata_map == MAP_FAILED) {
288 perror("Failed to map restore file");
295 if (rstate->kdata_fd > 0)
296 close(rstate->kdata_fd);
301 load_metadata_file(const char *filename, struct restore_state *rstate)
303 const ucl_object_t *obj;
304 struct ucl_parser *parser;
307 parser = ucl_parser_new(UCL_PARSER_DEFAULT);
308 if (parser == NULL) {
309 fprintf(stderr, "Failed to initialize UCL parser.\n");
310 goto err_load_metadata;
313 err = ucl_parser_add_file(parser, filename);
315 fprintf(stderr, "Failed to parse metadata file: '%s'\n",
318 goto err_load_metadata;
321 obj = ucl_parser_get_object(parser);
323 fprintf(stderr, "Failed to parse object.\n");
325 goto err_load_metadata;
328 rstate->meta_parser = parser;
329 rstate->meta_root_obj = (ucl_object_t *)obj;
335 ucl_parser_free(parser);
340 load_restore_file(const char *filename, struct restore_state *rstate)
343 char *kdata_filename = NULL, *meta_filename = NULL;
345 assert(filename != NULL);
346 assert(rstate != NULL);
348 memset(rstate, 0, sizeof(*rstate));
349 rstate->kdata_map = MAP_FAILED;
351 err = load_vmmem_file(filename, rstate);
353 fprintf(stderr, "Failed to load guest RAM file.\n");
357 kdata_filename = strcat_extension(filename, ".kern");
358 if (kdata_filename == NULL) {
359 fprintf(stderr, "Failed to construct kernel data filename.\n");
363 err = load_kdata_file(kdata_filename, rstate);
365 fprintf(stderr, "Failed to load guest kernel data file.\n");
369 meta_filename = strcat_extension(filename, ".meta");
370 if (meta_filename == NULL) {
371 fprintf(stderr, "Failed to construct kernel metadata filename.\n");
375 err = load_metadata_file(meta_filename, rstate);
377 fprintf(stderr, "Failed to load guest metadata file.\n");
384 destroy_restore_state(rstate);
385 if (kdata_filename != NULL)
386 free(kdata_filename);
387 if (meta_filename != NULL)
392 #define JSON_GET_INT_OR_RETURN(key, obj, result_ptr, ret) \
394 const ucl_object_t *obj__; \
395 obj__ = ucl_object_lookup(obj, key); \
396 if (obj__ == NULL) { \
397 fprintf(stderr, "Missing key: '%s'", key); \
400 if (!ucl_object_toint_safe(obj__, result_ptr)) { \
401 fprintf(stderr, "Cannot convert '%s' value to int.", key); \
406 #define JSON_GET_STRING_OR_RETURN(key, obj, result_ptr, ret) \
408 const ucl_object_t *obj__; \
409 obj__ = ucl_object_lookup(obj, key); \
410 if (obj__ == NULL) { \
411 fprintf(stderr, "Missing key: '%s'", key); \
414 if (!ucl_object_tostring_safe(obj__, result_ptr)) { \
415 fprintf(stderr, "Cannot convert '%s' value to string.", key); \
421 lookup_struct(enum snapshot_req struct_id, struct restore_state *rstate,
424 const ucl_object_t *structs = NULL, *obj = NULL;
425 ucl_object_iter_t it = NULL;
426 int64_t snapshot_req, size, file_offset;
428 structs = ucl_object_lookup(rstate->meta_root_obj, JSON_STRUCT_ARR_KEY);
429 if (structs == NULL) {
430 fprintf(stderr, "Failed to find '%s' object.\n",
431 JSON_STRUCT_ARR_KEY);
435 if (ucl_object_type((ucl_object_t *)structs) != UCL_ARRAY) {
436 fprintf(stderr, "Object '%s' is not an array.\n",
437 JSON_STRUCT_ARR_KEY);
441 while ((obj = ucl_object_iterate(structs, &it, true)) != NULL) {
443 JSON_GET_INT_OR_RETURN(JSON_SNAPSHOT_REQ_KEY, obj,
444 &snapshot_req, NULL);
445 assert(snapshot_req >= 0);
446 if ((enum snapshot_req) snapshot_req == struct_id) {
447 JSON_GET_INT_OR_RETURN(JSON_SIZE_KEY, obj,
451 JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
453 assert(file_offset >= 0);
454 assert(file_offset + size <= rstate->kdata_len);
456 *struct_size = (size_t)size;
457 return (rstate->kdata_map + file_offset);
465 lookup_check_dev(const char *dev_name, struct restore_state *rstate,
466 const ucl_object_t *obj, size_t *data_size)
468 const char *snapshot_req;
469 int64_t size, file_offset;
472 JSON_GET_STRING_OR_RETURN(JSON_SNAPSHOT_REQ_KEY, obj,
473 &snapshot_req, NULL);
474 assert(snapshot_req != NULL);
475 if (!strcmp(snapshot_req, dev_name)) {
476 JSON_GET_INT_OR_RETURN(JSON_SIZE_KEY, obj,
480 JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
482 assert(file_offset >= 0);
483 assert(file_offset + size <= rstate->kdata_len);
485 *data_size = (size_t)size;
486 return (rstate->kdata_map + file_offset);
493 lookup_dev(const char *dev_name, struct restore_state *rstate,
496 const ucl_object_t *devs = NULL, *obj = NULL;
497 ucl_object_iter_t it = NULL;
500 devs = ucl_object_lookup(rstate->meta_root_obj, JSON_DEV_ARR_KEY);
502 fprintf(stderr, "Failed to find '%s' object.\n",
507 if (ucl_object_type((ucl_object_t *)devs) != UCL_ARRAY) {
508 fprintf(stderr, "Object '%s' is not an array.\n",
513 while ((obj = ucl_object_iterate(devs, &it, true)) != NULL) {
514 ret = lookup_check_dev(dev_name, rstate, obj, data_size);
522 static const ucl_object_t *
523 lookup_basic_metadata_object(struct restore_state *rstate)
525 const ucl_object_t *basic_meta_obj = NULL;
527 basic_meta_obj = ucl_object_lookup(rstate->meta_root_obj,
528 JSON_BASIC_METADATA_KEY);
529 if (basic_meta_obj == NULL) {
530 fprintf(stderr, "Failed to find '%s' object.\n",
531 JSON_BASIC_METADATA_KEY);
535 if (ucl_object_type((ucl_object_t *)basic_meta_obj) != UCL_OBJECT) {
536 fprintf(stderr, "Object '%s' is not a JSON object.\n",
537 JSON_BASIC_METADATA_KEY);
541 return (basic_meta_obj);
545 lookup_vmname(struct restore_state *rstate)
548 const ucl_object_t *obj;
550 obj = lookup_basic_metadata_object(rstate);
554 JSON_GET_STRING_OR_RETURN(JSON_VMNAME_KEY, obj, &vmname, NULL);
559 lookup_memflags(struct restore_state *rstate)
562 const ucl_object_t *obj;
564 obj = lookup_basic_metadata_object(rstate);
568 JSON_GET_INT_OR_RETURN(JSON_MEMFLAGS_KEY, obj, &memflags, 0);
570 return ((int)memflags);
574 lookup_memsize(struct restore_state *rstate)
577 const ucl_object_t *obj;
579 obj = lookup_basic_metadata_object(rstate);
583 JSON_GET_INT_OR_RETURN(JSON_MEMSIZE_KEY, obj, &memsize, 0);
587 return ((size_t)memsize);
592 lookup_guest_ncpus(struct restore_state *rstate)
595 const ucl_object_t *obj;
597 obj = lookup_basic_metadata_object(rstate);
601 JSON_GET_INT_OR_RETURN(JSON_NCPUS_KEY, obj, &ncpus, 0);
606 winch_handler(int signal)
609 ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
610 #endif /* TIOCGWINSZ */
614 print_progress(size_t crtval, const size_t maxval)
617 double crtval_gb, maxval_gb;
618 size_t i, win_width, prog_start, prog_done, prog_end;
621 static char prog_buf[PROG_BUF_SZ];
622 static const size_t len = sizeof(prog_buf);
625 static char *div_str;
627 static char wip_bar[] = { '/', '-', '\\', '|' };
628 static int wip_idx = 0;
631 printf("[0B / 0B]\r\n");
638 if (maxval > 10 * GB) {
641 } else if (maxval > 10 * MB) {
649 crtval_gb = (double) crtval / div;
650 maxval_gb = (double) maxval / div;
652 rc = snprintf(prog_buf, len, "%.03lf", maxval_gb);
654 fprintf(stderr, "Maxval too big\n");
659 rc = snprintf(prog_buf, len, "\r[%*.03lf%s / %.03lf%s] |",
660 mval_len, crtval_gb, div_str, maxval_gb, div_str);
663 fprintf(stderr, "Buffer too small to print progress\n");
667 win_width = min(winsize.ws_col, len);
670 if (prog_start < (win_width - 2)) {
671 prog_end = win_width - prog_start - 2;
672 prog_done = prog_end * (crtval_gb / maxval_gb);
674 for (i = prog_start; i < prog_start + prog_done; i++)
677 if (crtval != maxval) {
678 prog_buf[i] = wip_bar[wip_idx];
679 wip_idx = (wip_idx + 1) % sizeof(wip_bar);
685 for (; i < win_width - 2; i++)
688 prog_buf[win_width - 2] = '|';
691 prog_buf[win_width - 1] = '\0';
692 write(STDOUT_FILENO, prog_buf, win_width);
698 snapshot_spinner_cb(void *arg)
701 size_t crtval, maxval, total;
702 struct spinner_info *si;
710 ts.tv_nsec = 50 * 1000 * 1000; /* 50 ms sleep time */
713 crtval = *si->crtval;
717 rc = print_progress(crtval, total);
719 fprintf(stderr, "Failed to parse progress\n");
723 nanosleep(&ts, NULL);
724 } while (crtval < maxval);
731 vm_snapshot_mem_part(const int snapfd, const size_t foff, void *src,
732 const size_t len, const size_t totalmem, const bool op_wr)
735 size_t part_done, todo, rem;
738 pthread_t spinner_th;
739 struct spinner_info *si;
741 if (lseek(snapfd, foff, SEEK_SET) < 0) {
742 perror("Failed to change file offset");
746 show_progress = false;
747 if (isatty(STDIN_FILENO) && (winsize.ws_col != 0))
748 show_progress = true;
754 si = &(struct spinner_info) {
755 .crtval = &part_done,
756 .maxval = foff + len,
760 rc = pthread_create(&spinner_th, 0, snapshot_spinner_cb, si);
762 perror("Unable to create spinner thread");
763 show_progress = false;
769 todo = min(SNAPSHOT_CHUNK, rem);
774 done = write(snapfd, src, todo);
776 done = read(snapfd, src, todo);
778 perror("Failed to write in file");
788 rc = pthread_join(spinner_th, NULL);
790 perror("Unable to end spinner thread");
797 vm_snapshot_mem(struct vmctx *ctx, int snapfd, size_t memsz, const bool op_wr)
800 size_t lowmem, highmem, totalmem;
803 ret = vm_get_guestmem_from_ctx(ctx, &baseaddr, &lowmem, &highmem);
805 fprintf(stderr, "%s: unable to retrieve guest memory size\r\n",
809 totalmem = lowmem + highmem;
811 if ((op_wr == false) && (totalmem != memsz)) {
812 fprintf(stderr, "%s: mem size mismatch: %ld vs %ld\r\n",
813 __func__, totalmem, memsz);
819 ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
820 #endif /* TIOCGWINSZ */
821 old_winch_handler = signal(SIGWINCH, winch_handler);
823 ret = vm_snapshot_mem_part(snapfd, 0, baseaddr, lowmem,
826 fprintf(stderr, "%s: Could not %s lowmem\r\n",
827 __func__, op_wr ? "write" : "read");
835 ret = vm_snapshot_mem_part(snapfd, lowmem, baseaddr + 4*GB,
836 highmem, totalmem, op_wr);
838 fprintf(stderr, "%s: Could not %s highmem\r\n",
839 __func__, op_wr ? "write" : "read");
846 signal(SIGWINCH, old_winch_handler);
852 restore_vm_mem(struct vmctx *ctx, struct restore_state *rstate)
856 restored = vm_snapshot_mem(ctx, rstate->vmmem_fd, rstate->vmmem_len,
859 if (restored != rstate->vmmem_len)
866 vm_restore_kern_struct(struct vmctx *ctx, struct restore_state *rstate,
867 const struct vm_snapshot_kern_info *info)
872 struct vm_snapshot_meta *meta;
874 struct_ptr = lookup_struct(info->req, rstate, &struct_size);
875 if (struct_ptr == NULL) {
876 fprintf(stderr, "%s: Failed to lookup struct %s\r\n",
877 __func__, info->struct_name);
882 if (struct_size == 0) {
883 fprintf(stderr, "%s: Kernel struct size was 0 for: %s\r\n",
884 __func__, info->struct_name);
889 meta = &(struct vm_snapshot_meta) {
891 .dev_name = info->struct_name,
892 .dev_req = info->req,
894 .buffer.buf_start = struct_ptr,
895 .buffer.buf_size = struct_size,
897 .buffer.buf = struct_ptr,
898 .buffer.buf_rem = struct_size,
900 .op = VM_SNAPSHOT_RESTORE,
903 ret = vm_snapshot_req(meta);
905 fprintf(stderr, "%s: Failed to restore struct: %s\r\n",
906 __func__, info->struct_name);
915 vm_restore_kern_structs(struct vmctx *ctx, struct restore_state *rstate)
920 for (i = 0; i < nitems(snapshot_kern_structs); i++) {
921 ret = vm_restore_kern_struct(ctx, rstate,
922 &snapshot_kern_structs[i]);
931 vm_restore_user_dev(struct vmctx *ctx, struct restore_state *rstate,
932 const struct vm_snapshot_dev_info *info)
937 struct vm_snapshot_meta *meta;
939 dev_ptr = lookup_dev(info->dev_name, rstate, &dev_size);
940 if (dev_ptr == NULL) {
941 fprintf(stderr, "Failed to lookup dev: %s\r\n", info->dev_name);
942 fprintf(stderr, "Continuing the restore/migration process\r\n");
947 fprintf(stderr, "%s: Device size is 0. "
948 "Assuming %s is not used\r\n",
949 __func__, info->dev_name);
953 meta = &(struct vm_snapshot_meta) {
955 .dev_name = info->dev_name,
957 .buffer.buf_start = dev_ptr,
958 .buffer.buf_size = dev_size,
960 .buffer.buf = dev_ptr,
961 .buffer.buf_rem = dev_size,
963 .op = VM_SNAPSHOT_RESTORE,
966 ret = (*info->snapshot_cb)(meta);
968 fprintf(stderr, "Failed to restore dev: %s\r\n",
978 vm_restore_user_devs(struct vmctx *ctx, struct restore_state *rstate)
983 for (i = 0; i < nitems(snapshot_devs); i++) {
984 ret = vm_restore_user_dev(ctx, rstate, &snapshot_devs[i]);
993 vm_pause_user_devs(struct vmctx *ctx)
995 const struct vm_snapshot_dev_info *info;
999 for (i = 0; i < nitems(snapshot_devs); i++) {
1000 info = &snapshot_devs[i];
1001 if (info->pause_cb == NULL)
1004 ret = info->pause_cb(ctx, info->dev_name);
1013 vm_resume_user_devs(struct vmctx *ctx)
1015 const struct vm_snapshot_dev_info *info;
1019 for (i = 0; i < nitems(snapshot_devs); i++) {
1020 info = &snapshot_devs[i];
1021 if (info->resume_cb == NULL)
1024 ret = info->resume_cb(ctx, info->dev_name);
1033 vm_snapshot_kern_struct(int data_fd, xo_handle_t *xop, const char *array_key,
1034 struct vm_snapshot_meta *meta, off_t *offset)
1040 ret = vm_snapshot_req(meta);
1042 fprintf(stderr, "%s: Failed to snapshot struct %s\r\n",
1043 __func__, meta->dev_name);
1048 data_size = vm_get_snapshot_size(meta);
1050 write_cnt = write(data_fd, meta->buffer.buf_start, data_size);
1051 if (write_cnt != data_size) {
1052 perror("Failed to write all snapshotted data.");
1057 /* Write metadata. */
1058 xo_open_instance_h(xop, array_key);
1059 xo_emit_h(xop, "{:debug_name/%s}\n", meta->dev_name);
1060 xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%d}\n",
1062 xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1063 xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1064 xo_close_instance_h(xop, JSON_STRUCT_ARR_KEY);
1066 *offset += data_size;
1073 vm_snapshot_kern_structs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1076 size_t offset, buf_size;
1078 struct vm_snapshot_meta *meta;
1082 buf_size = SNAPSHOT_BUFFER_SIZE;
1084 buffer = malloc(SNAPSHOT_BUFFER_SIZE * sizeof(char));
1085 if (buffer == NULL) {
1087 perror("Failed to allocate memory for snapshot buffer");
1088 goto err_vm_snapshot_kern_data;
1091 meta = &(struct vm_snapshot_meta) {
1094 .buffer.buf_start = buffer,
1095 .buffer.buf_size = buf_size,
1097 .op = VM_SNAPSHOT_SAVE,
1100 xo_open_list_h(xop, JSON_STRUCT_ARR_KEY);
1101 for (i = 0; i < nitems(snapshot_kern_structs); i++) {
1102 meta->dev_name = snapshot_kern_structs[i].struct_name;
1103 meta->dev_req = snapshot_kern_structs[i].req;
1105 memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1106 meta->buffer.buf = meta->buffer.buf_start;
1107 meta->buffer.buf_rem = meta->buffer.buf_size;
1109 ret = vm_snapshot_kern_struct(data_fd, xop, JSON_DEV_ARR_KEY,
1113 goto err_vm_snapshot_kern_data;
1116 xo_close_list_h(xop, JSON_STRUCT_ARR_KEY);
1118 err_vm_snapshot_kern_data:
1125 vm_snapshot_basic_metadata(struct vmctx *ctx, xo_handle_t *xop, size_t memsz)
1129 char vmname_buf[MAX_VMNAME];
1131 memset(vmname_buf, 0, MAX_VMNAME);
1132 error = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1134 perror("Failed to get VM name");
1138 memflags = vm_get_memflags(ctx);
1140 xo_open_container_h(xop, JSON_BASIC_METADATA_KEY);
1141 xo_emit_h(xop, "{:" JSON_NCPUS_KEY "/%ld}\n", guest_ncpus);
1142 xo_emit_h(xop, "{:" JSON_VMNAME_KEY "/%s}\n", vmname_buf);
1143 xo_emit_h(xop, "{:" JSON_MEMSIZE_KEY "/%lu}\n", memsz);
1144 xo_emit_h(xop, "{:" JSON_MEMFLAGS_KEY "/%d}\n", memflags);
1145 xo_close_container_h(xop, JSON_BASIC_METADATA_KEY);
1152 vm_snapshot_dev_write_data(int data_fd, xo_handle_t *xop, const char *array_key,
1153 struct vm_snapshot_meta *meta, off_t *offset)
1158 data_size = vm_get_snapshot_size(meta);
1160 ret = write(data_fd, meta->buffer.buf_start, data_size);
1161 if (ret != data_size) {
1162 perror("Failed to write all snapshotted data.");
1166 /* Write metadata. */
1167 xo_open_instance_h(xop, array_key);
1168 xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%s}\n", meta->dev_name);
1169 xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1170 xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1171 xo_close_instance_h(xop, array_key);
1173 *offset += data_size;
1179 vm_snapshot_user_dev(const struct vm_snapshot_dev_info *info,
1180 int data_fd, xo_handle_t *xop,
1181 struct vm_snapshot_meta *meta, off_t *offset)
1185 ret = (*info->snapshot_cb)(meta);
1187 fprintf(stderr, "Failed to snapshot %s; ret=%d\r\n",
1188 meta->dev_name, ret);
1192 ret = vm_snapshot_dev_write_data(data_fd, xop, JSON_DEV_ARR_KEY, meta,
1201 vm_snapshot_user_devs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1207 struct vm_snapshot_meta *meta;
1209 buf_size = SNAPSHOT_BUFFER_SIZE;
1211 offset = lseek(data_fd, 0, SEEK_CUR);
1213 perror("Failed to get data file current offset.");
1217 buffer = malloc(buf_size);
1218 if (buffer == NULL) {
1219 perror("Failed to allocate memory for snapshot buffer");
1224 meta = &(struct vm_snapshot_meta) {
1227 .buffer.buf_start = buffer,
1228 .buffer.buf_size = buf_size,
1230 .op = VM_SNAPSHOT_SAVE,
1233 xo_open_list_h(xop, JSON_DEV_ARR_KEY);
1235 /* Restore other devices that support this feature */
1236 for (i = 0; i < nitems(snapshot_devs); i++) {
1237 meta->dev_name = snapshot_devs[i].dev_name;
1239 memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1240 meta->buffer.buf = meta->buffer.buf_start;
1241 meta->buffer.buf_rem = meta->buffer.buf_size;
1243 ret = vm_snapshot_user_dev(&snapshot_devs[i], data_fd, xop,
1249 xo_close_list_h(xop, JSON_DEV_ARR_KEY);
1258 checkpoint_cpu_add(int vcpu)
1261 pthread_mutex_lock(&vcpu_lock);
1262 CPU_SET(vcpu, &vcpus_active);
1264 if (checkpoint_active) {
1265 CPU_SET(vcpu, &vcpus_suspended);
1266 while (checkpoint_active)
1267 pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1268 CPU_CLR(vcpu, &vcpus_suspended);
1270 pthread_mutex_unlock(&vcpu_lock);
1274 * When a vCPU is suspended for any reason, it calls
1275 * checkpoint_cpu_suspend(). This records that the vCPU is idle.
1276 * Before returning from suspension, checkpoint_cpu_resume() is
1277 * called. In suspend we note that the vCPU is idle. In resume we
1278 * pause the vCPU thread until the checkpoint is complete. The reason
1279 * for the two-step process is that vCPUs might already be stopped in
1280 * the debug server when a checkpoint is requested. This approach
1281 * allows us to account for and handle those vCPUs.
1284 checkpoint_cpu_suspend(int vcpu)
1287 pthread_mutex_lock(&vcpu_lock);
1288 CPU_SET(vcpu, &vcpus_suspended);
1289 if (checkpoint_active && CPU_CMP(&vcpus_active, &vcpus_suspended) == 0)
1290 pthread_cond_signal(&vcpus_idle);
1291 pthread_mutex_unlock(&vcpu_lock);
1295 checkpoint_cpu_resume(int vcpu)
1298 pthread_mutex_lock(&vcpu_lock);
1299 while (checkpoint_active)
1300 pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1301 CPU_CLR(vcpu, &vcpus_suspended);
1302 pthread_mutex_unlock(&vcpu_lock);
1306 vm_vcpu_pause(struct vmctx *ctx)
1309 pthread_mutex_lock(&vcpu_lock);
1310 checkpoint_active = true;
1311 vm_suspend_cpu(ctx, -1);
1312 while (CPU_CMP(&vcpus_active, &vcpus_suspended) != 0)
1313 pthread_cond_wait(&vcpus_idle, &vcpu_lock);
1314 pthread_mutex_unlock(&vcpu_lock);
1318 vm_vcpu_resume(struct vmctx *ctx)
1321 pthread_mutex_lock(&vcpu_lock);
1322 checkpoint_active = false;
1323 pthread_mutex_unlock(&vcpu_lock);
1324 vm_resume_cpu(ctx, -1);
1325 pthread_cond_broadcast(&vcpus_can_run);
1329 vm_checkpoint(struct vmctx *ctx, char *checkpoint_file, bool stop_vm)
1331 int fd_checkpoint = 0, kdata_fd = 0;
1335 xo_handle_t *xop = NULL;
1336 char *meta_filename = NULL;
1337 char *kdata_filename = NULL;
1338 FILE *meta_file = NULL;
1340 kdata_filename = strcat_extension(checkpoint_file, ".kern");
1341 if (kdata_filename == NULL) {
1342 fprintf(stderr, "Failed to construct kernel data filename.\n");
1346 kdata_fd = open(kdata_filename, O_WRONLY | O_CREAT | O_TRUNC, 0700);
1348 perror("Failed to open kernel data snapshot file.");
1353 fd_checkpoint = open(checkpoint_file, O_RDWR | O_CREAT | O_TRUNC, 0700);
1355 if (fd_checkpoint < 0) {
1356 perror("Failed to create checkpoint file");
1361 meta_filename = strcat_extension(checkpoint_file, ".meta");
1362 if (meta_filename == NULL) {
1363 fprintf(stderr, "Failed to construct vm metadata filename.\n");
1367 meta_file = fopen(meta_filename, "w");
1368 if (meta_file == NULL) {
1369 perror("Failed to open vm metadata snapshot file.");
1373 xop = xo_create_to_file(meta_file, XO_STYLE_JSON, XOF_PRETTY);
1375 perror("Failed to get libxo handle on metadata file.");
1381 ret = vm_pause_user_devs(ctx);
1383 fprintf(stderr, "Could not pause devices\r\n");
1388 memsz = vm_snapshot_mem(ctx, fd_checkpoint, 0, true);
1390 perror("Could not write guest memory to file");
1395 ret = vm_snapshot_basic_metadata(ctx, xop, memsz);
1397 fprintf(stderr, "Failed to snapshot vm basic metadata.\n");
1403 ret = vm_snapshot_kern_structs(ctx, kdata_fd, xop);
1405 fprintf(stderr, "Failed to snapshot vm kernel data.\n");
1410 ret = vm_snapshot_user_devs(ctx, kdata_fd, xop);
1412 fprintf(stderr, "Failed to snapshot device state.\n");
1425 ret = vm_resume_user_devs(ctx);
1427 fprintf(stderr, "Could not resume devices\r\n");
1428 vm_vcpu_resume(ctx);
1429 if (fd_checkpoint > 0)
1430 close(fd_checkpoint);
1431 if (meta_filename != NULL)
1432 free(meta_filename);
1433 if (kdata_filename != NULL)
1434 free(kdata_filename);
1437 if (meta_file != NULL)
1445 get_checkpoint_msg(int conn_fd, struct vmctx *ctx)
1447 unsigned char buf[MAX_MSG_SIZE];
1448 struct checkpoint_op *checkpoint_op;
1449 int len, recv_len, total_recv = 0;
1452 len = sizeof(struct checkpoint_op); /* expected length */
1453 while ((recv_len = recv(conn_fd, buf + total_recv, len - total_recv, 0)) > 0) {
1454 total_recv += recv_len;
1457 perror("Error while receiving data from bhyvectl");
1462 checkpoint_op = (struct checkpoint_op *)buf;
1463 switch (checkpoint_op->op) {
1464 case START_CHECKPOINT:
1465 err = vm_checkpoint(ctx, checkpoint_op->snapshot_filename, false);
1468 err = vm_checkpoint(ctx, checkpoint_op->snapshot_filename, true);
1471 fprintf(stderr, "Unrecognized checkpoint operation.\n");
1481 * Listen for commands from bhyvectl
1484 checkpoint_thread(void *param)
1486 struct checkpoint_thread_info *thread_info;
1489 pthread_set_name_np(pthread_self(), "checkpoint thread");
1490 thread_info = (struct checkpoint_thread_info *)param;
1492 while ((conn_fd = accept(thread_info->socket_fd, NULL, NULL)) > -1) {
1493 ret = get_checkpoint_msg(conn_fd, thread_info->ctx);
1495 fprintf(stderr, "Failed to read message on checkpoint "
1496 "socket. Retrying.\n");
1500 perror("Failed to accept connection");
1507 * Create the listening socket for IPC with bhyvectl
1510 init_checkpoint_thread(struct vmctx *ctx)
1512 struct checkpoint_thread_info *checkpoint_info = NULL;
1513 struct sockaddr_un addr;
1515 pthread_t checkpoint_pthread;
1516 char vmname_buf[MAX_VMNAME];
1519 memset(&addr, 0, sizeof(addr));
1521 err = pthread_mutex_init(&vcpu_lock, NULL);
1523 errc(1, err, "checkpoint mutex init");
1524 err = pthread_cond_init(&vcpus_idle, NULL);
1526 err = pthread_cond_init(&vcpus_can_run, NULL);
1528 errc(1, err, "checkpoint cv init");
1530 socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
1531 if (socket_fd < 0) {
1532 perror("Socket creation failed (IPC with bhyvectl");
1537 addr.sun_family = AF_UNIX;
1539 err = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1541 perror("Failed to get VM name");
1545 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s%s",
1546 BHYVE_RUN_DIR, vmname_buf);
1547 addr.sun_len = SUN_LEN(&addr);
1548 unlink(addr.sun_path);
1550 if (bind(socket_fd, (struct sockaddr *)&addr, addr.sun_len) != 0) {
1551 perror("Failed to bind socket (IPC with bhyvectl)");
1556 if (listen(socket_fd, 10) < 0) {
1557 perror("Failed to listen on socket (IPC with bhyvectl)");
1562 checkpoint_info = calloc(1, sizeof(*checkpoint_info));
1563 checkpoint_info->ctx = ctx;
1564 checkpoint_info->socket_fd = socket_fd;
1566 ret = pthread_create(&checkpoint_pthread, NULL, checkpoint_thread,
1575 free(checkpoint_info);
1578 unlink(addr.sun_path);
1584 vm_snapshot_buf_err(const char *bufname, const enum vm_snapshot_op op)
1588 if (op == VM_SNAPSHOT_SAVE)
1590 else if (op == VM_SNAPSHOT_RESTORE)
1595 fprintf(stderr, "%s: snapshot-%s failed for %s\r\n",
1596 __func__, __op, bufname);
1600 vm_snapshot_buf(volatile void *data, size_t data_size,
1601 struct vm_snapshot_meta *meta)
1603 struct vm_snapshot_buffer *buffer;
1606 buffer = &meta->buffer;
1609 if (buffer->buf_rem < data_size) {
1610 fprintf(stderr, "%s: buffer too small\r\n", __func__);
1614 if (op == VM_SNAPSHOT_SAVE)
1615 memcpy(buffer->buf, (uint8_t *) data, data_size);
1616 else if (op == VM_SNAPSHOT_RESTORE)
1617 memcpy((uint8_t *) data, buffer->buf, data_size);
1621 buffer->buf += data_size;
1622 buffer->buf_rem -= data_size;
1628 vm_get_snapshot_size(struct vm_snapshot_meta *meta)
1631 struct vm_snapshot_buffer *buffer;
1633 buffer = &meta->buffer;
1635 if (buffer->buf_size < buffer->buf_rem) {
1636 fprintf(stderr, "%s: Invalid buffer: size = %zu, rem = %zu\r\n",
1637 __func__, buffer->buf_size, buffer->buf_rem);
1640 length = buffer->buf_size - buffer->buf_rem;
1647 vm_snapshot_guest2host_addr(void **addrp, size_t len, bool restore_null,
1648 struct vm_snapshot_meta *meta)
1653 if (meta->op == VM_SNAPSHOT_SAVE) {
1654 gaddr = paddr_host2guest(meta->ctx, *addrp);
1655 if (gaddr == (vm_paddr_t) -1) {
1656 if (!restore_null ||
1657 (restore_null && (*addrp != NULL))) {
1663 SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1664 } else if (meta->op == VM_SNAPSHOT_RESTORE) {
1665 SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1666 if (gaddr == (vm_paddr_t) -1) {
1667 if (!restore_null) {
1673 *addrp = paddr_guest2host(meta->ctx, gaddr, len);
1683 vm_snapshot_buf_cmp(volatile void *data, size_t data_size,
1684 struct vm_snapshot_meta *meta)
1686 struct vm_snapshot_buffer *buffer;
1690 buffer = &meta->buffer;
1693 if (buffer->buf_rem < data_size) {
1694 fprintf(stderr, "%s: buffer too small\r\n", __func__);
1699 if (op == VM_SNAPSHOT_SAVE) {
1701 memcpy(buffer->buf, (uint8_t *) data, data_size);
1702 } else if (op == VM_SNAPSHOT_RESTORE) {
1703 ret = memcmp((uint8_t *) data, buffer->buf, data_size);
1709 buffer->buf += data_size;
1710 buffer->buf_rem -= data_size;