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 BHYVE_RUN_DIR "/var/run/bhyve"
120 #define CHECKPOINT_RUN_DIR BHYVE_RUN_DIR "/checkpoint"
121 #define MAX_VMNAME 100
123 #define MAX_MSG_SIZE 1024
125 #define SNAPSHOT_BUFFER_SIZE (20 * MB)
127 #define JSON_STRUCT_ARR_KEY "structs"
128 #define JSON_DEV_ARR_KEY "devices"
129 #define JSON_BASIC_METADATA_KEY "basic metadata"
130 #define JSON_SNAPSHOT_REQ_KEY "snapshot_req"
131 #define JSON_SIZE_KEY "size"
132 #define JSON_FILE_OFFSET_KEY "file_offset"
134 #define JSON_NCPUS_KEY "ncpus"
135 #define JSON_VMNAME_KEY "vmname"
136 #define JSON_MEMSIZE_KEY "memsize"
137 #define JSON_MEMFLAGS_KEY "memflags"
141 __typeof__ (a) _a = (a); \
142 __typeof__ (b) _b = (b); \
146 const struct vm_snapshot_dev_info snapshot_devs[] = {
147 { "atkbdc", atkbdc_snapshot, NULL, NULL },
148 { "virtio-net", pci_snapshot, pci_pause, pci_resume },
149 { "virtio-blk", pci_snapshot, pci_pause, pci_resume },
150 { "virtio-rnd", pci_snapshot, NULL, NULL },
151 { "lpc", pci_snapshot, NULL, NULL },
152 { "fbuf", pci_snapshot, NULL, NULL },
153 { "xhci", pci_snapshot, NULL, NULL },
154 { "e1000", pci_snapshot, NULL, NULL },
155 { "ahci", pci_snapshot, pci_pause, pci_resume },
156 { "ahci-hd", pci_snapshot, pci_pause, pci_resume },
157 { "ahci-cd", pci_snapshot, pci_pause, pci_resume },
160 const struct vm_snapshot_kern_info snapshot_kern_structs[] = {
161 { "vhpet", STRUCT_VHPET },
163 { "vmx", STRUCT_VMX },
164 { "vioapic", STRUCT_VIOAPIC },
165 { "vlapic", STRUCT_VLAPIC },
166 { "vmcx", STRUCT_VMCX },
167 { "vatpit", STRUCT_VATPIT },
168 { "vatpic", STRUCT_VATPIC },
169 { "vpmtmr", STRUCT_VPMTMR },
170 { "vrtc", STRUCT_VRTC },
173 static cpuset_t vcpus_active, vcpus_suspended;
174 static pthread_mutex_t vcpu_lock;
175 static pthread_cond_t vcpus_idle, vcpus_can_run;
176 static bool checkpoint_active;
179 * TODO: Harden this function and all of its callers since 'base_str' is a user
183 strcat_extension(const char *base_str, const char *ext)
186 size_t base_len, ext_len;
188 base_len = strnlen(base_str, MAX_VMNAME);
189 ext_len = strnlen(ext, MAX_VMNAME);
191 if (base_len + ext_len > MAX_VMNAME) {
192 fprintf(stderr, "Filename exceeds maximum length.\n");
196 res = malloc(base_len + ext_len + 1);
198 perror("Failed to allocate memory.");
202 memcpy(res, base_str, base_len);
203 memcpy(res + base_len, ext, ext_len);
204 res[base_len + ext_len] = 0;
210 destroy_restore_state(struct restore_state *rstate)
212 if (rstate == NULL) {
213 fprintf(stderr, "Attempting to destroy NULL restore struct.\n");
217 if (rstate->kdata_map != MAP_FAILED)
218 munmap(rstate->kdata_map, rstate->kdata_len);
220 if (rstate->kdata_fd > 0)
221 close(rstate->kdata_fd);
222 if (rstate->vmmem_fd > 0)
223 close(rstate->vmmem_fd);
225 if (rstate->meta_root_obj != NULL)
226 ucl_object_unref(rstate->meta_root_obj);
227 if (rstate->meta_parser != NULL)
228 ucl_parser_free(rstate->meta_parser);
232 load_vmmem_file(const char *filename, struct restore_state *rstate)
237 rstate->vmmem_fd = open(filename, O_RDONLY);
238 if (rstate->vmmem_fd < 0) {
239 perror("Failed to open restore file");
243 err = fstat(rstate->vmmem_fd, &sb);
245 perror("Failed to stat restore file");
249 if (sb.st_size == 0) {
250 fprintf(stderr, "Restore file is empty.\n");
254 rstate->vmmem_len = sb.st_size;
259 if (rstate->vmmem_fd > 0)
260 close(rstate->vmmem_fd);
265 load_kdata_file(const char *filename, struct restore_state *rstate)
270 rstate->kdata_fd = open(filename, O_RDONLY);
271 if (rstate->kdata_fd < 0) {
272 perror("Failed to open kernel data file");
276 err = fstat(rstate->kdata_fd, &sb);
278 perror("Failed to stat kernel data file");
282 if (sb.st_size == 0) {
283 fprintf(stderr, "Kernel data file is empty.\n");
287 rstate->kdata_len = sb.st_size;
288 rstate->kdata_map = mmap(NULL, rstate->kdata_len, PROT_READ,
289 MAP_SHARED, rstate->kdata_fd, 0);
290 if (rstate->kdata_map == MAP_FAILED) {
291 perror("Failed to map restore file");
298 if (rstate->kdata_fd > 0)
299 close(rstate->kdata_fd);
304 load_metadata_file(const char *filename, struct restore_state *rstate)
306 const ucl_object_t *obj;
307 struct ucl_parser *parser;
310 parser = ucl_parser_new(UCL_PARSER_DEFAULT);
311 if (parser == NULL) {
312 fprintf(stderr, "Failed to initialize UCL parser.\n");
313 goto err_load_metadata;
316 err = ucl_parser_add_file(parser, filename);
318 fprintf(stderr, "Failed to parse metadata file: '%s'\n",
321 goto err_load_metadata;
324 obj = ucl_parser_get_object(parser);
326 fprintf(stderr, "Failed to parse object.\n");
328 goto err_load_metadata;
331 rstate->meta_parser = parser;
332 rstate->meta_root_obj = (ucl_object_t *)obj;
338 ucl_parser_free(parser);
343 load_restore_file(const char *filename, struct restore_state *rstate)
346 char *kdata_filename = NULL, *meta_filename = NULL;
348 assert(filename != NULL);
349 assert(rstate != NULL);
351 memset(rstate, 0, sizeof(*rstate));
352 rstate->kdata_map = MAP_FAILED;
354 err = load_vmmem_file(filename, rstate);
356 fprintf(stderr, "Failed to load guest RAM file.\n");
360 kdata_filename = strcat_extension(filename, ".kern");
361 if (kdata_filename == NULL) {
362 fprintf(stderr, "Failed to construct kernel data filename.\n");
366 err = load_kdata_file(kdata_filename, rstate);
368 fprintf(stderr, "Failed to load guest kernel data file.\n");
372 meta_filename = strcat_extension(filename, ".meta");
373 if (meta_filename == NULL) {
374 fprintf(stderr, "Failed to construct kernel metadata filename.\n");
378 err = load_metadata_file(meta_filename, rstate);
380 fprintf(stderr, "Failed to load guest metadata file.\n");
387 destroy_restore_state(rstate);
388 if (kdata_filename != NULL)
389 free(kdata_filename);
390 if (meta_filename != NULL)
395 #define JSON_GET_INT_OR_RETURN(key, obj, result_ptr, ret) \
397 const ucl_object_t *obj__; \
398 obj__ = ucl_object_lookup(obj, key); \
399 if (obj__ == NULL) { \
400 fprintf(stderr, "Missing key: '%s'", key); \
403 if (!ucl_object_toint_safe(obj__, result_ptr)) { \
404 fprintf(stderr, "Cannot convert '%s' value to int.", key); \
409 #define JSON_GET_STRING_OR_RETURN(key, obj, result_ptr, ret) \
411 const ucl_object_t *obj__; \
412 obj__ = ucl_object_lookup(obj, key); \
413 if (obj__ == NULL) { \
414 fprintf(stderr, "Missing key: '%s'", key); \
417 if (!ucl_object_tostring_safe(obj__, result_ptr)) { \
418 fprintf(stderr, "Cannot convert '%s' value to string.", key); \
424 lookup_struct(enum snapshot_req struct_id, struct restore_state *rstate,
427 const ucl_object_t *structs = NULL, *obj = NULL;
428 ucl_object_iter_t it = NULL;
429 int64_t snapshot_req, size, file_offset;
431 structs = ucl_object_lookup(rstate->meta_root_obj, JSON_STRUCT_ARR_KEY);
432 if (structs == NULL) {
433 fprintf(stderr, "Failed to find '%s' object.\n",
434 JSON_STRUCT_ARR_KEY);
438 if (ucl_object_type((ucl_object_t *)structs) != UCL_ARRAY) {
439 fprintf(stderr, "Object '%s' is not an array.\n",
440 JSON_STRUCT_ARR_KEY);
444 while ((obj = ucl_object_iterate(structs, &it, true)) != NULL) {
446 JSON_GET_INT_OR_RETURN(JSON_SNAPSHOT_REQ_KEY, obj,
447 &snapshot_req, NULL);
448 assert(snapshot_req >= 0);
449 if ((enum snapshot_req) snapshot_req == struct_id) {
450 JSON_GET_INT_OR_RETURN(JSON_SIZE_KEY, obj,
454 JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
456 assert(file_offset >= 0);
457 assert(file_offset + size <= rstate->kdata_len);
459 *struct_size = (size_t)size;
460 return (rstate->kdata_map + file_offset);
468 lookup_check_dev(const char *dev_name, struct restore_state *rstate,
469 const ucl_object_t *obj, size_t *data_size)
471 const char *snapshot_req;
472 int64_t size, file_offset;
475 JSON_GET_STRING_OR_RETURN(JSON_SNAPSHOT_REQ_KEY, obj,
476 &snapshot_req, NULL);
477 assert(snapshot_req != NULL);
478 if (!strcmp(snapshot_req, dev_name)) {
479 JSON_GET_INT_OR_RETURN(JSON_SIZE_KEY, obj,
483 JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
485 assert(file_offset >= 0);
486 assert(file_offset + size <= rstate->kdata_len);
488 *data_size = (size_t)size;
489 return (rstate->kdata_map + file_offset);
496 lookup_dev(const char *dev_name, struct restore_state *rstate,
499 const ucl_object_t *devs = NULL, *obj = NULL;
500 ucl_object_iter_t it = NULL;
503 devs = ucl_object_lookup(rstate->meta_root_obj, JSON_DEV_ARR_KEY);
505 fprintf(stderr, "Failed to find '%s' object.\n",
510 if (ucl_object_type((ucl_object_t *)devs) != UCL_ARRAY) {
511 fprintf(stderr, "Object '%s' is not an array.\n",
516 while ((obj = ucl_object_iterate(devs, &it, true)) != NULL) {
517 ret = lookup_check_dev(dev_name, rstate, obj, data_size);
525 static const ucl_object_t *
526 lookup_basic_metadata_object(struct restore_state *rstate)
528 const ucl_object_t *basic_meta_obj = NULL;
530 basic_meta_obj = ucl_object_lookup(rstate->meta_root_obj,
531 JSON_BASIC_METADATA_KEY);
532 if (basic_meta_obj == NULL) {
533 fprintf(stderr, "Failed to find '%s' object.\n",
534 JSON_BASIC_METADATA_KEY);
538 if (ucl_object_type((ucl_object_t *)basic_meta_obj) != UCL_OBJECT) {
539 fprintf(stderr, "Object '%s' is not a JSON object.\n",
540 JSON_BASIC_METADATA_KEY);
544 return (basic_meta_obj);
548 lookup_vmname(struct restore_state *rstate)
551 const ucl_object_t *obj;
553 obj = lookup_basic_metadata_object(rstate);
557 JSON_GET_STRING_OR_RETURN(JSON_VMNAME_KEY, obj, &vmname, NULL);
562 lookup_memflags(struct restore_state *rstate)
565 const ucl_object_t *obj;
567 obj = lookup_basic_metadata_object(rstate);
571 JSON_GET_INT_OR_RETURN(JSON_MEMFLAGS_KEY, obj, &memflags, 0);
573 return ((int)memflags);
577 lookup_memsize(struct restore_state *rstate)
580 const ucl_object_t *obj;
582 obj = lookup_basic_metadata_object(rstate);
586 JSON_GET_INT_OR_RETURN(JSON_MEMSIZE_KEY, obj, &memsize, 0);
590 return ((size_t)memsize);
595 lookup_guest_ncpus(struct restore_state *rstate)
598 const ucl_object_t *obj;
600 obj = lookup_basic_metadata_object(rstate);
604 JSON_GET_INT_OR_RETURN(JSON_NCPUS_KEY, obj, &ncpus, 0);
609 winch_handler(int signal)
612 ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
613 #endif /* TIOCGWINSZ */
617 print_progress(size_t crtval, const size_t maxval)
620 double crtval_gb, maxval_gb;
621 size_t i, win_width, prog_start, prog_done, prog_end;
624 static char prog_buf[PROG_BUF_SZ];
625 static const size_t len = sizeof(prog_buf);
628 static char *div_str;
630 static char wip_bar[] = { '/', '-', '\\', '|' };
631 static int wip_idx = 0;
634 printf("[0B / 0B]\r\n");
641 if (maxval > 10 * GB) {
644 } else if (maxval > 10 * MB) {
652 crtval_gb = (double) crtval / div;
653 maxval_gb = (double) maxval / div;
655 rc = snprintf(prog_buf, len, "%.03lf", maxval_gb);
657 fprintf(stderr, "Maxval too big\n");
662 rc = snprintf(prog_buf, len, "\r[%*.03lf%s / %.03lf%s] |",
663 mval_len, crtval_gb, div_str, maxval_gb, div_str);
666 fprintf(stderr, "Buffer too small to print progress\n");
670 win_width = min(winsize.ws_col, len);
673 if (prog_start < (win_width - 2)) {
674 prog_end = win_width - prog_start - 2;
675 prog_done = prog_end * (crtval_gb / maxval_gb);
677 for (i = prog_start; i < prog_start + prog_done; i++)
680 if (crtval != maxval) {
681 prog_buf[i] = wip_bar[wip_idx];
682 wip_idx = (wip_idx + 1) % sizeof(wip_bar);
688 for (; i < win_width - 2; i++)
691 prog_buf[win_width - 2] = '|';
694 prog_buf[win_width - 1] = '\0';
695 write(STDOUT_FILENO, prog_buf, win_width);
701 snapshot_spinner_cb(void *arg)
704 size_t crtval, maxval, total;
705 struct spinner_info *si;
713 ts.tv_nsec = 50 * 1000 * 1000; /* 50 ms sleep time */
716 crtval = *si->crtval;
720 rc = print_progress(crtval, total);
722 fprintf(stderr, "Failed to parse progress\n");
726 nanosleep(&ts, NULL);
727 } while (crtval < maxval);
734 vm_snapshot_mem_part(const int snapfd, const size_t foff, void *src,
735 const size_t len, const size_t totalmem, const bool op_wr)
738 size_t part_done, todo, rem;
741 pthread_t spinner_th;
742 struct spinner_info *si;
744 if (lseek(snapfd, foff, SEEK_SET) < 0) {
745 perror("Failed to change file offset");
749 show_progress = false;
750 if (isatty(STDIN_FILENO) && (winsize.ws_col != 0))
751 show_progress = true;
757 si = &(struct spinner_info) {
758 .crtval = &part_done,
759 .maxval = foff + len,
763 rc = pthread_create(&spinner_th, 0, snapshot_spinner_cb, si);
765 perror("Unable to create spinner thread");
766 show_progress = false;
772 todo = min(SNAPSHOT_CHUNK, rem);
777 done = write(snapfd, src, todo);
779 done = read(snapfd, src, todo);
781 perror("Failed to write in file");
791 rc = pthread_join(spinner_th, NULL);
793 perror("Unable to end spinner thread");
800 vm_snapshot_mem(struct vmctx *ctx, int snapfd, size_t memsz, const bool op_wr)
803 size_t lowmem, highmem, totalmem;
806 ret = vm_get_guestmem_from_ctx(ctx, &baseaddr, &lowmem, &highmem);
808 fprintf(stderr, "%s: unable to retrieve guest memory size\r\n",
812 totalmem = lowmem + highmem;
814 if ((op_wr == false) && (totalmem != memsz)) {
815 fprintf(stderr, "%s: mem size mismatch: %ld vs %ld\r\n",
816 __func__, totalmem, memsz);
822 ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
823 #endif /* TIOCGWINSZ */
824 old_winch_handler = signal(SIGWINCH, winch_handler);
826 ret = vm_snapshot_mem_part(snapfd, 0, baseaddr, lowmem,
829 fprintf(stderr, "%s: Could not %s lowmem\r\n",
830 __func__, op_wr ? "write" : "read");
838 ret = vm_snapshot_mem_part(snapfd, lowmem, baseaddr + 4*GB,
839 highmem, totalmem, op_wr);
841 fprintf(stderr, "%s: Could not %s highmem\r\n",
842 __func__, op_wr ? "write" : "read");
849 signal(SIGWINCH, old_winch_handler);
855 restore_vm_mem(struct vmctx *ctx, struct restore_state *rstate)
859 restored = vm_snapshot_mem(ctx, rstate->vmmem_fd, rstate->vmmem_len,
862 if (restored != rstate->vmmem_len)
869 vm_restore_kern_struct(struct vmctx *ctx, struct restore_state *rstate,
870 const struct vm_snapshot_kern_info *info)
875 struct vm_snapshot_meta *meta;
877 struct_ptr = lookup_struct(info->req, rstate, &struct_size);
878 if (struct_ptr == NULL) {
879 fprintf(stderr, "%s: Failed to lookup struct %s\r\n",
880 __func__, info->struct_name);
885 if (struct_size == 0) {
886 fprintf(stderr, "%s: Kernel struct size was 0 for: %s\r\n",
887 __func__, info->struct_name);
892 meta = &(struct vm_snapshot_meta) {
894 .dev_name = info->struct_name,
895 .dev_req = info->req,
897 .buffer.buf_start = struct_ptr,
898 .buffer.buf_size = struct_size,
900 .buffer.buf = struct_ptr,
901 .buffer.buf_rem = struct_size,
903 .op = VM_SNAPSHOT_RESTORE,
906 ret = vm_snapshot_req(meta);
908 fprintf(stderr, "%s: Failed to restore struct: %s\r\n",
909 __func__, info->struct_name);
918 vm_restore_kern_structs(struct vmctx *ctx, struct restore_state *rstate)
923 for (i = 0; i < nitems(snapshot_kern_structs); i++) {
924 ret = vm_restore_kern_struct(ctx, rstate,
925 &snapshot_kern_structs[i]);
934 vm_restore_user_dev(struct vmctx *ctx, struct restore_state *rstate,
935 const struct vm_snapshot_dev_info *info)
940 struct vm_snapshot_meta *meta;
942 dev_ptr = lookup_dev(info->dev_name, rstate, &dev_size);
943 if (dev_ptr == NULL) {
944 fprintf(stderr, "Failed to lookup dev: %s\r\n", info->dev_name);
945 fprintf(stderr, "Continuing the restore/migration process\r\n");
950 fprintf(stderr, "%s: Device size is 0. "
951 "Assuming %s is not used\r\n",
952 __func__, info->dev_name);
956 meta = &(struct vm_snapshot_meta) {
958 .dev_name = info->dev_name,
960 .buffer.buf_start = dev_ptr,
961 .buffer.buf_size = dev_size,
963 .buffer.buf = dev_ptr,
964 .buffer.buf_rem = dev_size,
966 .op = VM_SNAPSHOT_RESTORE,
969 ret = (*info->snapshot_cb)(meta);
971 fprintf(stderr, "Failed to restore dev: %s\r\n",
981 vm_restore_user_devs(struct vmctx *ctx, struct restore_state *rstate)
986 for (i = 0; i < nitems(snapshot_devs); i++) {
987 ret = vm_restore_user_dev(ctx, rstate, &snapshot_devs[i]);
996 vm_pause_user_devs(struct vmctx *ctx)
998 const struct vm_snapshot_dev_info *info;
1002 for (i = 0; i < nitems(snapshot_devs); i++) {
1003 info = &snapshot_devs[i];
1004 if (info->pause_cb == NULL)
1007 ret = info->pause_cb(ctx, info->dev_name);
1016 vm_resume_user_devs(struct vmctx *ctx)
1018 const struct vm_snapshot_dev_info *info;
1022 for (i = 0; i < nitems(snapshot_devs); i++) {
1023 info = &snapshot_devs[i];
1024 if (info->resume_cb == NULL)
1027 ret = info->resume_cb(ctx, info->dev_name);
1036 vm_snapshot_kern_struct(int data_fd, xo_handle_t *xop, const char *array_key,
1037 struct vm_snapshot_meta *meta, off_t *offset)
1043 ret = vm_snapshot_req(meta);
1045 fprintf(stderr, "%s: Failed to snapshot struct %s\r\n",
1046 __func__, meta->dev_name);
1051 data_size = vm_get_snapshot_size(meta);
1053 write_cnt = write(data_fd, meta->buffer.buf_start, data_size);
1054 if (write_cnt != data_size) {
1055 perror("Failed to write all snapshotted data.");
1060 /* Write metadata. */
1061 xo_open_instance_h(xop, array_key);
1062 xo_emit_h(xop, "{:debug_name/%s}\n", meta->dev_name);
1063 xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%d}\n",
1065 xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1066 xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1067 xo_close_instance_h(xop, JSON_STRUCT_ARR_KEY);
1069 *offset += data_size;
1076 vm_snapshot_kern_structs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1079 size_t offset, buf_size;
1081 struct vm_snapshot_meta *meta;
1085 buf_size = SNAPSHOT_BUFFER_SIZE;
1087 buffer = malloc(SNAPSHOT_BUFFER_SIZE * sizeof(char));
1088 if (buffer == NULL) {
1090 perror("Failed to allocate memory for snapshot buffer");
1091 goto err_vm_snapshot_kern_data;
1094 meta = &(struct vm_snapshot_meta) {
1097 .buffer.buf_start = buffer,
1098 .buffer.buf_size = buf_size,
1100 .op = VM_SNAPSHOT_SAVE,
1103 xo_open_list_h(xop, JSON_STRUCT_ARR_KEY);
1104 for (i = 0; i < nitems(snapshot_kern_structs); i++) {
1105 meta->dev_name = snapshot_kern_structs[i].struct_name;
1106 meta->dev_req = snapshot_kern_structs[i].req;
1108 memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1109 meta->buffer.buf = meta->buffer.buf_start;
1110 meta->buffer.buf_rem = meta->buffer.buf_size;
1112 ret = vm_snapshot_kern_struct(data_fd, xop, JSON_DEV_ARR_KEY,
1116 goto err_vm_snapshot_kern_data;
1119 xo_close_list_h(xop, JSON_STRUCT_ARR_KEY);
1121 err_vm_snapshot_kern_data:
1128 vm_snapshot_basic_metadata(struct vmctx *ctx, xo_handle_t *xop, size_t memsz)
1132 char vmname_buf[MAX_VMNAME];
1134 memset(vmname_buf, 0, MAX_VMNAME);
1135 error = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1137 perror("Failed to get VM name");
1141 memflags = vm_get_memflags(ctx);
1143 xo_open_container_h(xop, JSON_BASIC_METADATA_KEY);
1144 xo_emit_h(xop, "{:" JSON_NCPUS_KEY "/%ld}\n", guest_ncpus);
1145 xo_emit_h(xop, "{:" JSON_VMNAME_KEY "/%s}\n", vmname_buf);
1146 xo_emit_h(xop, "{:" JSON_MEMSIZE_KEY "/%lu}\n", memsz);
1147 xo_emit_h(xop, "{:" JSON_MEMFLAGS_KEY "/%d}\n", memflags);
1148 xo_close_container_h(xop, JSON_BASIC_METADATA_KEY);
1155 vm_snapshot_dev_write_data(int data_fd, xo_handle_t *xop, const char *array_key,
1156 struct vm_snapshot_meta *meta, off_t *offset)
1161 data_size = vm_get_snapshot_size(meta);
1163 ret = write(data_fd, meta->buffer.buf_start, data_size);
1164 if (ret != data_size) {
1165 perror("Failed to write all snapshotted data.");
1169 /* Write metadata. */
1170 xo_open_instance_h(xop, array_key);
1171 xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%s}\n", meta->dev_name);
1172 xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1173 xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1174 xo_close_instance_h(xop, array_key);
1176 *offset += data_size;
1182 vm_snapshot_user_dev(const struct vm_snapshot_dev_info *info,
1183 int data_fd, xo_handle_t *xop,
1184 struct vm_snapshot_meta *meta, off_t *offset)
1188 ret = (*info->snapshot_cb)(meta);
1190 fprintf(stderr, "Failed to snapshot %s; ret=%d\r\n",
1191 meta->dev_name, ret);
1195 ret = vm_snapshot_dev_write_data(data_fd, xop, JSON_DEV_ARR_KEY, meta,
1204 vm_snapshot_user_devs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1210 struct vm_snapshot_meta *meta;
1212 buf_size = SNAPSHOT_BUFFER_SIZE;
1214 offset = lseek(data_fd, 0, SEEK_CUR);
1216 perror("Failed to get data file current offset.");
1220 buffer = malloc(buf_size);
1221 if (buffer == NULL) {
1222 perror("Failed to allocate memory for snapshot buffer");
1227 meta = &(struct vm_snapshot_meta) {
1230 .buffer.buf_start = buffer,
1231 .buffer.buf_size = buf_size,
1233 .op = VM_SNAPSHOT_SAVE,
1236 xo_open_list_h(xop, JSON_DEV_ARR_KEY);
1238 /* Restore other devices that support this feature */
1239 for (i = 0; i < nitems(snapshot_devs); i++) {
1240 meta->dev_name = snapshot_devs[i].dev_name;
1242 memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1243 meta->buffer.buf = meta->buffer.buf_start;
1244 meta->buffer.buf_rem = meta->buffer.buf_size;
1246 ret = vm_snapshot_user_dev(&snapshot_devs[i], data_fd, xop,
1252 xo_close_list_h(xop, JSON_DEV_ARR_KEY);
1261 checkpoint_cpu_add(int vcpu)
1264 pthread_mutex_lock(&vcpu_lock);
1265 CPU_SET(vcpu, &vcpus_active);
1267 if (checkpoint_active) {
1268 CPU_SET(vcpu, &vcpus_suspended);
1269 while (checkpoint_active)
1270 pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1271 CPU_CLR(vcpu, &vcpus_suspended);
1273 pthread_mutex_unlock(&vcpu_lock);
1277 * When a vCPU is suspended for any reason, it calls
1278 * checkpoint_cpu_suspend(). This records that the vCPU is idle.
1279 * Before returning from suspension, checkpoint_cpu_resume() is
1280 * called. In suspend we note that the vCPU is idle. In resume we
1281 * pause the vCPU thread until the checkpoint is complete. The reason
1282 * for the two-step process is that vCPUs might already be stopped in
1283 * the debug server when a checkpoint is requested. This approach
1284 * allows us to account for and handle those vCPUs.
1287 checkpoint_cpu_suspend(int vcpu)
1290 pthread_mutex_lock(&vcpu_lock);
1291 CPU_SET(vcpu, &vcpus_suspended);
1292 if (checkpoint_active && CPU_CMP(&vcpus_active, &vcpus_suspended) == 0)
1293 pthread_cond_signal(&vcpus_idle);
1294 pthread_mutex_unlock(&vcpu_lock);
1298 checkpoint_cpu_resume(int vcpu)
1301 pthread_mutex_lock(&vcpu_lock);
1302 while (checkpoint_active)
1303 pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1304 CPU_CLR(vcpu, &vcpus_suspended);
1305 pthread_mutex_unlock(&vcpu_lock);
1309 vm_vcpu_pause(struct vmctx *ctx)
1312 pthread_mutex_lock(&vcpu_lock);
1313 checkpoint_active = true;
1314 vm_suspend_cpu(ctx, -1);
1315 while (CPU_CMP(&vcpus_active, &vcpus_suspended) != 0)
1316 pthread_cond_wait(&vcpus_idle, &vcpu_lock);
1317 pthread_mutex_unlock(&vcpu_lock);
1321 vm_vcpu_resume(struct vmctx *ctx)
1324 pthread_mutex_lock(&vcpu_lock);
1325 checkpoint_active = false;
1326 pthread_mutex_unlock(&vcpu_lock);
1327 vm_resume_cpu(ctx, -1);
1328 pthread_cond_broadcast(&vcpus_can_run);
1332 vm_checkpoint(struct vmctx *ctx, char *checkpoint_file, bool stop_vm)
1334 int fd_checkpoint = 0, kdata_fd = 0;
1338 xo_handle_t *xop = NULL;
1339 char *meta_filename = NULL;
1340 char *kdata_filename = NULL;
1341 FILE *meta_file = NULL;
1343 kdata_filename = strcat_extension(checkpoint_file, ".kern");
1344 if (kdata_filename == NULL) {
1345 fprintf(stderr, "Failed to construct kernel data filename.\n");
1349 kdata_fd = open(kdata_filename, O_WRONLY | O_CREAT | O_TRUNC, 0700);
1351 perror("Failed to open kernel data snapshot file.");
1356 fd_checkpoint = open(checkpoint_file, O_RDWR | O_CREAT | O_TRUNC, 0700);
1358 if (fd_checkpoint < 0) {
1359 perror("Failed to create checkpoint file");
1364 meta_filename = strcat_extension(checkpoint_file, ".meta");
1365 if (meta_filename == NULL) {
1366 fprintf(stderr, "Failed to construct vm metadata filename.\n");
1370 meta_file = fopen(meta_filename, "w");
1371 if (meta_file == NULL) {
1372 perror("Failed to open vm metadata snapshot file.");
1376 xop = xo_create_to_file(meta_file, XO_STYLE_JSON, XOF_PRETTY);
1378 perror("Failed to get libxo handle on metadata file.");
1384 ret = vm_pause_user_devs(ctx);
1386 fprintf(stderr, "Could not pause devices\r\n");
1391 memsz = vm_snapshot_mem(ctx, fd_checkpoint, 0, true);
1393 perror("Could not write guest memory to file");
1398 ret = vm_snapshot_basic_metadata(ctx, xop, memsz);
1400 fprintf(stderr, "Failed to snapshot vm basic metadata.\n");
1406 ret = vm_snapshot_kern_structs(ctx, kdata_fd, xop);
1408 fprintf(stderr, "Failed to snapshot vm kernel data.\n");
1413 ret = vm_snapshot_user_devs(ctx, kdata_fd, xop);
1415 fprintf(stderr, "Failed to snapshot device state.\n");
1428 ret = vm_resume_user_devs(ctx);
1430 fprintf(stderr, "Could not resume devices\r\n");
1431 vm_vcpu_resume(ctx);
1432 if (fd_checkpoint > 0)
1433 close(fd_checkpoint);
1434 if (meta_filename != NULL)
1435 free(meta_filename);
1436 if (kdata_filename != NULL)
1437 free(kdata_filename);
1440 if (meta_file != NULL)
1448 get_checkpoint_msg(int conn_fd, struct vmctx *ctx)
1450 unsigned char buf[MAX_MSG_SIZE];
1451 struct checkpoint_op *checkpoint_op;
1452 int len, recv_len, total_recv = 0;
1455 len = sizeof(struct checkpoint_op); /* expected length */
1456 while ((recv_len = recv(conn_fd, buf + total_recv, len - total_recv, 0)) > 0) {
1457 total_recv += recv_len;
1460 perror("Error while receiving data from bhyvectl");
1465 checkpoint_op = (struct checkpoint_op *)buf;
1466 switch (checkpoint_op->op) {
1467 case START_CHECKPOINT:
1468 err = vm_checkpoint(ctx, checkpoint_op->snapshot_filename, false);
1471 err = vm_checkpoint(ctx, checkpoint_op->snapshot_filename, true);
1474 fprintf(stderr, "Unrecognized checkpoint operation.\n");
1484 * Listen for commands from bhyvectl
1487 checkpoint_thread(void *param)
1489 struct checkpoint_thread_info *thread_info;
1492 pthread_set_name_np(pthread_self(), "checkpoint thread");
1493 thread_info = (struct checkpoint_thread_info *)param;
1495 while ((conn_fd = accept(thread_info->socket_fd, NULL, NULL)) > -1) {
1496 ret = get_checkpoint_msg(conn_fd, thread_info->ctx);
1498 fprintf(stderr, "Failed to read message on checkpoint "
1499 "socket. Retrying.\n");
1503 perror("Failed to accept connection");
1510 * Create directory tree to store runtime specific information:
1511 * i.e. UNIX sockets for IPC with bhyvectl.
1514 make_checkpoint_dir(void)
1518 err = mkdir(BHYVE_RUN_DIR, 0755);
1519 if (err < 0 && errno != EEXIST)
1522 err = mkdir(CHECKPOINT_RUN_DIR, 0755);
1523 if (err < 0 && errno != EEXIST)
1530 * Create the listening socket for IPC with bhyvectl
1533 init_checkpoint_thread(struct vmctx *ctx)
1535 struct checkpoint_thread_info *checkpoint_info = NULL;
1536 struct sockaddr_un addr;
1538 pthread_t checkpoint_pthread;
1539 char vmname_buf[MAX_VMNAME];
1542 memset(&addr, 0, sizeof(addr));
1544 err = pthread_mutex_init(&vcpu_lock, NULL);
1546 errc(1, err, "checkpoint mutex init");
1547 err = pthread_cond_init(&vcpus_idle, NULL);
1549 err = pthread_cond_init(&vcpus_can_run, NULL);
1551 errc(1, err, "checkpoint cv init");
1553 socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
1554 if (socket_fd < 0) {
1555 perror("Socket creation failed (IPC with bhyvectl");
1560 err = make_checkpoint_dir();
1562 perror("Failed to create checkpoint runtime directory");
1566 addr.sun_family = AF_UNIX;
1568 err = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1570 perror("Failed to get VM name");
1574 snprintf(addr.sun_path, sizeof(addr.sun_path), "%s/%s",
1575 CHECKPOINT_RUN_DIR, vmname_buf);
1576 addr.sun_len = SUN_LEN(&addr);
1577 unlink(addr.sun_path);
1579 if (bind(socket_fd, (struct sockaddr *)&addr, addr.sun_len) != 0) {
1580 perror("Failed to bind socket (IPC with bhyvectl)");
1585 if (listen(socket_fd, 10) < 0) {
1586 perror("Failed to listen on socket (IPC with bhyvectl)");
1591 checkpoint_info = calloc(1, sizeof(*checkpoint_info));
1592 checkpoint_info->ctx = ctx;
1593 checkpoint_info->socket_fd = socket_fd;
1595 ret = pthread_create(&checkpoint_pthread, NULL, checkpoint_thread,
1604 free(checkpoint_info);
1607 unlink(addr.sun_path);
1613 vm_snapshot_buf_err(const char *bufname, const enum vm_snapshot_op op)
1617 if (op == VM_SNAPSHOT_SAVE)
1619 else if (op == VM_SNAPSHOT_RESTORE)
1624 fprintf(stderr, "%s: snapshot-%s failed for %s\r\n",
1625 __func__, __op, bufname);
1629 vm_snapshot_buf(volatile void *data, size_t data_size,
1630 struct vm_snapshot_meta *meta)
1632 struct vm_snapshot_buffer *buffer;
1635 buffer = &meta->buffer;
1638 if (buffer->buf_rem < data_size) {
1639 fprintf(stderr, "%s: buffer too small\r\n", __func__);
1643 if (op == VM_SNAPSHOT_SAVE)
1644 memcpy(buffer->buf, (uint8_t *) data, data_size);
1645 else if (op == VM_SNAPSHOT_RESTORE)
1646 memcpy((uint8_t *) data, buffer->buf, data_size);
1650 buffer->buf += data_size;
1651 buffer->buf_rem -= data_size;
1657 vm_get_snapshot_size(struct vm_snapshot_meta *meta)
1660 struct vm_snapshot_buffer *buffer;
1662 buffer = &meta->buffer;
1664 if (buffer->buf_size < buffer->buf_rem) {
1665 fprintf(stderr, "%s: Invalid buffer: size = %zu, rem = %zu\r\n",
1666 __func__, buffer->buf_size, buffer->buf_rem);
1669 length = buffer->buf_size - buffer->buf_rem;
1676 vm_snapshot_guest2host_addr(void **addrp, size_t len, bool restore_null,
1677 struct vm_snapshot_meta *meta)
1682 if (meta->op == VM_SNAPSHOT_SAVE) {
1683 gaddr = paddr_host2guest(meta->ctx, *addrp);
1684 if (gaddr == (vm_paddr_t) -1) {
1685 if (!restore_null ||
1686 (restore_null && (*addrp != NULL))) {
1692 SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1693 } else if (meta->op == VM_SNAPSHOT_RESTORE) {
1694 SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1695 if (gaddr == (vm_paddr_t) -1) {
1696 if (!restore_null) {
1702 *addrp = paddr_guest2host(meta->ctx, gaddr, len);
1712 vm_snapshot_buf_cmp(volatile void *data, size_t data_size,
1713 struct vm_snapshot_meta *meta)
1715 struct vm_snapshot_buffer *buffer;
1719 buffer = &meta->buffer;
1722 if (buffer->buf_rem < data_size) {
1723 fprintf(stderr, "%s: buffer too small\r\n", __func__);
1728 if (op == VM_SNAPSHOT_SAVE) {
1730 memcpy(buffer->buf, (uint8_t *) data, data_size);
1731 } else if (op == VM_SNAPSHOT_RESTORE) {
1732 ret = memcmp((uint8_t *) data, buffer->buf, data_size);
1738 buffer->buf += data_size;
1739 buffer->buf_rem -= data_size;