xref: /freebsd/usr.sbin/bhyve/snapshot.c (revision 6fe0a6c80a1aff14236924eb33e4013aa8c14f91)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
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.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
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.
22  *
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
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/types.h>
40 #ifndef WITHOUT_CAPSICUM
41 #include <sys/capsicum.h>
42 #endif
43 #include <sys/mman.h>
44 #include <sys/socket.h>
45 #include <sys/stat.h>
46 #include <sys/time.h>
47 #include <sys/un.h>
48 
49 #include <machine/atomic.h>
50 #include <machine/segments.h>
51 
52 #ifndef WITHOUT_CAPSICUM
53 #include <capsicum_helpers.h>
54 #endif
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <err.h>
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <libgen.h>
62 #include <signal.h>
63 #include <unistd.h>
64 #include <assert.h>
65 #include <errno.h>
66 #include <pthread.h>
67 #include <pthread_np.h>
68 #include <sysexits.h>
69 #include <stdbool.h>
70 #include <sys/ioctl.h>
71 
72 #include <machine/vmm.h>
73 #ifndef WITHOUT_CAPSICUM
74 #include <machine/vmm_dev.h>
75 #endif
76 #include <machine/vmm_snapshot.h>
77 #include <vmmapi.h>
78 
79 #include "bhyverun.h"
80 #include "acpi.h"
81 #include "atkbdc.h"
82 #include "debug.h"
83 #include "inout.h"
84 #include "ipc.h"
85 #include "fwctl.h"
86 #include "ioapic.h"
87 #include "mem.h"
88 #include "mevent.h"
89 #include "mptbl.h"
90 #include "pci_emul.h"
91 #include "pci_irq.h"
92 #include "pci_lpc.h"
93 #include "smbiostbl.h"
94 #include "snapshot.h"
95 #include "xmsr.h"
96 #include "spinup_ap.h"
97 #include "rtc.h"
98 
99 #include <libxo/xo.h>
100 #include <ucl.h>
101 
102 struct spinner_info {
103 	const size_t *crtval;
104 	const size_t maxval;
105 	const size_t total;
106 };
107 
108 extern int guest_ncpus;
109 
110 static struct winsize winsize;
111 static sig_t old_winch_handler;
112 
113 #define	KB		(1024UL)
114 #define	MB		(1024UL * KB)
115 #define	GB		(1024UL * MB)
116 
117 #define	SNAPSHOT_CHUNK	(4 * MB)
118 #define	PROG_BUF_SZ	(8192)
119 
120 #define	SNAPSHOT_BUFFER_SIZE (20 * MB)
121 
122 #define	JSON_STRUCT_ARR_KEY		"structs"
123 #define	JSON_DEV_ARR_KEY		"devices"
124 #define	JSON_BASIC_METADATA_KEY 	"basic metadata"
125 #define	JSON_SNAPSHOT_REQ_KEY		"snapshot_req"
126 #define	JSON_SIZE_KEY			"size"
127 #define	JSON_FILE_OFFSET_KEY		"file_offset"
128 
129 #define	JSON_NCPUS_KEY			"ncpus"
130 #define	JSON_VMNAME_KEY 		"vmname"
131 #define	JSON_MEMSIZE_KEY		"memsize"
132 #define	JSON_MEMFLAGS_KEY		"memflags"
133 
134 #define min(a,b)		\
135 ({				\
136  __typeof__ (a) _a = (a);	\
137  __typeof__ (b) _b = (b); 	\
138  _a < _b ? _a : _b;       	\
139  })
140 
141 static const struct vm_snapshot_dev_info snapshot_devs[] = {
142 	{ "atkbdc",	atkbdc_snapshot,	NULL,		NULL		},
143 	{ "virtio-net",	pci_snapshot,		pci_pause,	pci_resume	},
144 	{ "virtio-blk",	pci_snapshot,		pci_pause,	pci_resume	},
145 	{ "virtio-rnd",	pci_snapshot,		NULL,		NULL		},
146 	{ "lpc",	pci_snapshot,		NULL,		NULL		},
147 	{ "fbuf",	pci_snapshot,		NULL,		NULL		},
148 	{ "xhci",	pci_snapshot,		NULL,		NULL		},
149 	{ "e1000",	pci_snapshot,		NULL,		NULL		},
150 	{ "ahci",	pci_snapshot,		pci_pause,	pci_resume	},
151 	{ "ahci-hd",	pci_snapshot,		pci_pause,	pci_resume	},
152 	{ "ahci-cd",	pci_snapshot,		pci_pause,	pci_resume	},
153 };
154 
155 static const struct vm_snapshot_kern_info snapshot_kern_structs[] = {
156 	{ "vhpet",	STRUCT_VHPET	},
157 	{ "vm",		STRUCT_VM	},
158 	{ "vmx",	STRUCT_VMX	},
159 	{ "vioapic",	STRUCT_VIOAPIC	},
160 	{ "vlapic",	STRUCT_VLAPIC	},
161 	{ "vmcx",	STRUCT_VMCX	},
162 	{ "vatpit",	STRUCT_VATPIT	},
163 	{ "vatpic",	STRUCT_VATPIC	},
164 	{ "vpmtmr",	STRUCT_VPMTMR	},
165 	{ "vrtc",	STRUCT_VRTC	},
166 };
167 
168 static cpuset_t vcpus_active, vcpus_suspended;
169 static pthread_mutex_t vcpu_lock;
170 static pthread_cond_t vcpus_idle, vcpus_can_run;
171 static bool checkpoint_active;
172 
173 /*
174  * TODO: Harden this function and all of its callers since 'base_str' is a user
175  * provided string.
176  */
177 static char *
178 strcat_extension(const char *base_str, const char *ext)
179 {
180 	char *res;
181 	size_t base_len, ext_len;
182 
183 	base_len = strnlen(base_str, NAME_MAX);
184 	ext_len = strnlen(ext, NAME_MAX);
185 
186 	if (base_len + ext_len > NAME_MAX) {
187 		fprintf(stderr, "Filename exceeds maximum length.\n");
188 		return (NULL);
189 	}
190 
191 	res = malloc(base_len + ext_len + 1);
192 	if (res == NULL) {
193 		perror("Failed to allocate memory.");
194 		return (NULL);
195 	}
196 
197 	memcpy(res, base_str, base_len);
198 	memcpy(res + base_len, ext, ext_len);
199 	res[base_len + ext_len] = 0;
200 
201 	return (res);
202 }
203 
204 void
205 destroy_restore_state(struct restore_state *rstate)
206 {
207 	if (rstate == NULL) {
208 		fprintf(stderr, "Attempting to destroy NULL restore struct.\n");
209 		return;
210 	}
211 
212 	if (rstate->kdata_map != MAP_FAILED)
213 		munmap(rstate->kdata_map, rstate->kdata_len);
214 
215 	if (rstate->kdata_fd > 0)
216 		close(rstate->kdata_fd);
217 	if (rstate->vmmem_fd > 0)
218 		close(rstate->vmmem_fd);
219 
220 	if (rstate->meta_root_obj != NULL)
221 		ucl_object_unref(rstate->meta_root_obj);
222 	if (rstate->meta_parser != NULL)
223 		ucl_parser_free(rstate->meta_parser);
224 }
225 
226 static int
227 load_vmmem_file(const char *filename, struct restore_state *rstate)
228 {
229 	struct stat sb;
230 	int err;
231 
232 	rstate->vmmem_fd = open(filename, O_RDONLY);
233 	if (rstate->vmmem_fd < 0) {
234 		perror("Failed to open restore file");
235 		return (-1);
236 	}
237 
238 	err = fstat(rstate->vmmem_fd, &sb);
239 	if (err < 0) {
240 		perror("Failed to stat restore file");
241 		goto err_load_vmmem;
242 	}
243 
244 	if (sb.st_size == 0) {
245 		fprintf(stderr, "Restore file is empty.\n");
246 		goto err_load_vmmem;
247 	}
248 
249 	rstate->vmmem_len = sb.st_size;
250 
251 	return (0);
252 
253 err_load_vmmem:
254 	if (rstate->vmmem_fd > 0)
255 		close(rstate->vmmem_fd);
256 	return (-1);
257 }
258 
259 static int
260 load_kdata_file(const char *filename, struct restore_state *rstate)
261 {
262 	struct stat sb;
263 	int err;
264 
265 	rstate->kdata_fd = open(filename, O_RDONLY);
266 	if (rstate->kdata_fd < 0) {
267 		perror("Failed to open kernel data file");
268 		return (-1);
269 	}
270 
271 	err = fstat(rstate->kdata_fd, &sb);
272 	if (err < 0) {
273 		perror("Failed to stat kernel data file");
274 		goto err_load_kdata;
275 	}
276 
277 	if (sb.st_size == 0) {
278 		fprintf(stderr, "Kernel data file is empty.\n");
279 		goto err_load_kdata;
280 	}
281 
282 	rstate->kdata_len = sb.st_size;
283 	rstate->kdata_map = mmap(NULL, rstate->kdata_len, PROT_READ,
284 				 MAP_SHARED, rstate->kdata_fd, 0);
285 	if (rstate->kdata_map == MAP_FAILED) {
286 		perror("Failed to map restore file");
287 		goto err_load_kdata;
288 	}
289 
290 	return (0);
291 
292 err_load_kdata:
293 	if (rstate->kdata_fd > 0)
294 		close(rstate->kdata_fd);
295 	return (-1);
296 }
297 
298 static int
299 load_metadata_file(const char *filename, struct restore_state *rstate)
300 {
301 	ucl_object_t *obj;
302 	struct ucl_parser *parser;
303 	int err;
304 
305 	parser = ucl_parser_new(UCL_PARSER_DEFAULT);
306 	if (parser == NULL) {
307 		fprintf(stderr, "Failed to initialize UCL parser.\n");
308 		err = -1;
309 		goto err_load_metadata;
310 	}
311 
312 	err = ucl_parser_add_file(parser, filename);
313 	if (err == 0) {
314 		fprintf(stderr, "Failed to parse metadata file: '%s'\n",
315 			filename);
316 		err = -1;
317 		goto err_load_metadata;
318 	}
319 
320 	obj = ucl_parser_get_object(parser);
321 	if (obj == NULL) {
322 		fprintf(stderr, "Failed to parse object.\n");
323 		err = -1;
324 		goto err_load_metadata;
325 	}
326 
327 	rstate->meta_parser = parser;
328 	rstate->meta_root_obj = (ucl_object_t *)obj;
329 
330 	return (0);
331 
332 err_load_metadata:
333 	if (parser != NULL)
334 		ucl_parser_free(parser);
335 	return (err);
336 }
337 
338 int
339 load_restore_file(const char *filename, struct restore_state *rstate)
340 {
341 	int err = 0;
342 	char *kdata_filename = NULL, *meta_filename = NULL;
343 
344 	assert(filename != NULL);
345 	assert(rstate != NULL);
346 
347 	memset(rstate, 0, sizeof(*rstate));
348 	rstate->kdata_map = MAP_FAILED;
349 
350 	err = load_vmmem_file(filename, rstate);
351 	if (err != 0) {
352 		fprintf(stderr, "Failed to load guest RAM file.\n");
353 		goto err_restore;
354 	}
355 
356 	kdata_filename = strcat_extension(filename, ".kern");
357 	if (kdata_filename == NULL) {
358 		fprintf(stderr, "Failed to construct kernel data filename.\n");
359 		goto err_restore;
360 	}
361 
362 	err = load_kdata_file(kdata_filename, rstate);
363 	if (err != 0) {
364 		fprintf(stderr, "Failed to load guest kernel data file.\n");
365 		goto err_restore;
366 	}
367 
368 	meta_filename = strcat_extension(filename, ".meta");
369 	if (meta_filename == NULL) {
370 		fprintf(stderr, "Failed to construct kernel metadata filename.\n");
371 		goto err_restore;
372 	}
373 
374 	err = load_metadata_file(meta_filename, rstate);
375 	if (err != 0) {
376 		fprintf(stderr, "Failed to load guest metadata file.\n");
377 		goto err_restore;
378 	}
379 
380 	return (0);
381 
382 err_restore:
383 	destroy_restore_state(rstate);
384 	if (kdata_filename != NULL)
385 		free(kdata_filename);
386 	if (meta_filename != NULL)
387 		free(meta_filename);
388 	return (-1);
389 }
390 
391 #define JSON_GET_INT_OR_RETURN(key, obj, result_ptr, ret)			\
392 do {										\
393 	const ucl_object_t *obj__;						\
394 	obj__ = ucl_object_lookup(obj, key);					\
395 	if (obj__ == NULL) {							\
396 		fprintf(stderr, "Missing key: '%s'", key);			\
397 		return (ret);							\
398 	}									\
399 	if (!ucl_object_toint_safe(obj__, result_ptr)) {			\
400 		fprintf(stderr, "Cannot convert '%s' value to int.", key);	\
401 		return (ret);							\
402 	}									\
403 } while(0)
404 
405 #define JSON_GET_STRING_OR_RETURN(key, obj, result_ptr, ret)			\
406 do {										\
407 	const ucl_object_t *obj__;						\
408 	obj__ = ucl_object_lookup(obj, key);					\
409 	if (obj__ == NULL) {							\
410 		fprintf(stderr, "Missing key: '%s'", key);			\
411 		return (ret);							\
412 	}									\
413 	if (!ucl_object_tostring_safe(obj__, result_ptr)) {			\
414 		fprintf(stderr, "Cannot convert '%s' value to string.", key);	\
415 		return (ret);							\
416 	}									\
417 } while(0)
418 
419 static void *
420 lookup_struct(enum snapshot_req struct_id, struct restore_state *rstate,
421 	      size_t *struct_size)
422 {
423 	const ucl_object_t *structs = NULL, *obj = NULL;
424 	ucl_object_iter_t it = NULL;
425 	int64_t snapshot_req, size, file_offset;
426 
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);
431 		return (NULL);
432 	}
433 
434 	if (ucl_object_type(structs) != UCL_ARRAY) {
435 		fprintf(stderr, "Object '%s' is not an array.\n",
436 		JSON_STRUCT_ARR_KEY);
437 		return (NULL);
438 	}
439 
440 	while ((obj = ucl_object_iterate(structs, &it, true)) != NULL) {
441 		snapshot_req = -1;
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,
447 					       &size, NULL);
448 			assert(size >= 0);
449 
450 			JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
451 					       &file_offset, NULL);
452 			assert(file_offset >= 0);
453 			assert(file_offset + size <= rstate->kdata_len);
454 
455 			*struct_size = (size_t)size;
456 			return ((uint8_t *)rstate->kdata_map + file_offset);
457 		}
458 	}
459 
460 	return (NULL);
461 }
462 
463 static void *
464 lookup_check_dev(const char *dev_name, struct restore_state *rstate,
465 		 const ucl_object_t *obj, size_t *data_size)
466 {
467 	const char *snapshot_req;
468 	int64_t size, file_offset;
469 
470 	snapshot_req = NULL;
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,
476 				       &size, NULL);
477 		assert(size >= 0);
478 
479 		JSON_GET_INT_OR_RETURN(JSON_FILE_OFFSET_KEY, obj,
480 				       &file_offset, NULL);
481 		assert(file_offset >= 0);
482 		assert(file_offset + size <= rstate->kdata_len);
483 
484 		*data_size = (size_t)size;
485 		return ((uint8_t *)rstate->kdata_map + file_offset);
486 	}
487 
488 	return (NULL);
489 }
490 
491 static void*
492 lookup_dev(const char *dev_name, struct restore_state *rstate,
493 	   size_t *data_size)
494 {
495 	const ucl_object_t *devs = NULL, *obj = NULL;
496 	ucl_object_iter_t it = NULL;
497 	void *ret;
498 
499 	devs = ucl_object_lookup(rstate->meta_root_obj, JSON_DEV_ARR_KEY);
500 	if (devs == NULL) {
501 		fprintf(stderr, "Failed to find '%s' object.\n",
502 			JSON_DEV_ARR_KEY);
503 		return (NULL);
504 	}
505 
506 	if (ucl_object_type(devs) != UCL_ARRAY) {
507 		fprintf(stderr, "Object '%s' is not an array.\n",
508 			JSON_DEV_ARR_KEY);
509 		return (NULL);
510 	}
511 
512 	while ((obj = ucl_object_iterate(devs, &it, true)) != NULL) {
513 		ret = lookup_check_dev(dev_name, rstate, obj, data_size);
514 		if (ret != NULL)
515 			return (ret);
516 	}
517 
518 	return (NULL);
519 }
520 
521 static const ucl_object_t *
522 lookup_basic_metadata_object(struct restore_state *rstate)
523 {
524 	const ucl_object_t *basic_meta_obj = NULL;
525 
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);
531 		return (NULL);
532 	}
533 
534 	if (ucl_object_type(basic_meta_obj) != UCL_OBJECT) {
535 		fprintf(stderr, "Object '%s' is not a JSON object.\n",
536 		JSON_BASIC_METADATA_KEY);
537 		return (NULL);
538 	}
539 
540 	return (basic_meta_obj);
541 }
542 
543 const char *
544 lookup_vmname(struct restore_state *rstate)
545 {
546 	const char *vmname;
547 	const ucl_object_t *obj;
548 
549 	obj = lookup_basic_metadata_object(rstate);
550 	if (obj == NULL)
551 		return (NULL);
552 
553 	JSON_GET_STRING_OR_RETURN(JSON_VMNAME_KEY, obj, &vmname, NULL);
554 	return (vmname);
555 }
556 
557 int
558 lookup_memflags(struct restore_state *rstate)
559 {
560 	int64_t memflags;
561 	const ucl_object_t *obj;
562 
563 	obj = lookup_basic_metadata_object(rstate);
564 	if (obj == NULL)
565 		return (0);
566 
567 	JSON_GET_INT_OR_RETURN(JSON_MEMFLAGS_KEY, obj, &memflags, 0);
568 
569 	return ((int)memflags);
570 }
571 
572 size_t
573 lookup_memsize(struct restore_state *rstate)
574 {
575 	int64_t memsize;
576 	const ucl_object_t *obj;
577 
578 	obj = lookup_basic_metadata_object(rstate);
579 	if (obj == NULL)
580 		return (0);
581 
582 	JSON_GET_INT_OR_RETURN(JSON_MEMSIZE_KEY, obj, &memsize, 0);
583 	if (memsize < 0)
584 		memsize = 0;
585 
586 	return ((size_t)memsize);
587 }
588 
589 
590 int
591 lookup_guest_ncpus(struct restore_state *rstate)
592 {
593 	int64_t ncpus;
594 	const ucl_object_t *obj;
595 
596 	obj = lookup_basic_metadata_object(rstate);
597 	if (obj == NULL)
598 		return (0);
599 
600 	JSON_GET_INT_OR_RETURN(JSON_NCPUS_KEY, obj, &ncpus, 0);
601 	return ((int)ncpus);
602 }
603 
604 static void
605 winch_handler(int signal __unused)
606 {
607 #ifdef TIOCGWINSZ
608 	ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
609 #endif /* TIOCGWINSZ */
610 }
611 
612 static int
613 print_progress(size_t crtval, const size_t maxval)
614 {
615 	size_t rc;
616 	double crtval_gb, maxval_gb;
617 	size_t i, win_width, prog_start, prog_done, prog_end;
618 	int mval_len;
619 
620 	static char prog_buf[PROG_BUF_SZ];
621 	static const size_t len = sizeof(prog_buf);
622 
623 	static size_t div;
624 	static const char *div_str;
625 
626 	static char wip_bar[] = { '/', '-', '\\', '|' };
627 	static int wip_idx = 0;
628 
629 	if (maxval == 0) {
630 		printf("[0B / 0B]\r\n");
631 		return (0);
632 	}
633 
634 	if (crtval > maxval)
635 		crtval = maxval;
636 
637 	if (maxval > 10 * GB) {
638 		div = GB;
639 		div_str = "GiB";
640 	} else if (maxval > 10 * MB) {
641 		div = MB;
642 		div_str = "MiB";
643 	} else {
644 		div = KB;
645 		div_str = "KiB";
646 	}
647 
648 	crtval_gb = (double) crtval / div;
649 	maxval_gb = (double) maxval / div;
650 
651 	rc = snprintf(prog_buf, len, "%.03lf", maxval_gb);
652 	if (rc == len) {
653 		fprintf(stderr, "Maxval too big\n");
654 		return (-1);
655 	}
656 	mval_len = rc;
657 
658 	rc = snprintf(prog_buf, len, "\r[%*.03lf%s / %.03lf%s] |",
659 		mval_len, crtval_gb, div_str, maxval_gb, div_str);
660 
661 	if (rc == len) {
662 		fprintf(stderr, "Buffer too small to print progress\n");
663 		return (-1);
664 	}
665 
666 	win_width = min(winsize.ws_col, len);
667 	prog_start = rc;
668 
669 	if (prog_start < (win_width - 2)) {
670 		prog_end = win_width - prog_start - 2;
671 		prog_done = prog_end * (crtval_gb / maxval_gb);
672 
673 		for (i = prog_start; i < prog_start + prog_done; i++)
674 			prog_buf[i] = '#';
675 
676 		if (crtval != maxval) {
677 			prog_buf[i] = wip_bar[wip_idx];
678 			wip_idx = (wip_idx + 1) % sizeof(wip_bar);
679 			i++;
680 		} else {
681 			prog_buf[i++] = '#';
682 		}
683 
684 		for (; i < win_width - 2; i++)
685 			prog_buf[i] = '_';
686 
687 		prog_buf[win_width - 2] = '|';
688 	}
689 
690 	prog_buf[win_width - 1] = '\0';
691 	write(STDOUT_FILENO, prog_buf, win_width);
692 
693 	return (0);
694 }
695 
696 static void *
697 snapshot_spinner_cb(void *arg)
698 {
699 	int rc;
700 	size_t crtval, maxval, total;
701 	struct spinner_info *si;
702 	struct timespec ts;
703 
704 	si = arg;
705 	if (si == NULL)
706 		pthread_exit(NULL);
707 
708 	ts.tv_sec = 0;
709 	ts.tv_nsec = 50 * 1000 * 1000; /* 50 ms sleep time */
710 
711 	do {
712 		crtval = *si->crtval;
713 		maxval = si->maxval;
714 		total = si->total;
715 
716 		rc = print_progress(crtval, total);
717 		if (rc < 0) {
718 			fprintf(stderr, "Failed to parse progress\n");
719 			break;
720 		}
721 
722 		nanosleep(&ts, NULL);
723 	} while (crtval < maxval);
724 
725 	pthread_exit(NULL);
726 	return NULL;
727 }
728 
729 static int
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)
732 {
733 	int rc;
734 	size_t part_done, todo, rem;
735 	ssize_t done;
736 	bool show_progress;
737 	pthread_t spinner_th;
738 	struct spinner_info *si;
739 
740 	if (lseek(snapfd, foff, SEEK_SET) < 0) {
741 		perror("Failed to change file offset");
742 		return (-1);
743 	}
744 
745 	show_progress = false;
746 	if (isatty(STDIN_FILENO) && (winsize.ws_col != 0))
747 		show_progress = true;
748 
749 	part_done = foff;
750 	rem = len;
751 
752 	if (show_progress) {
753 		si = &(struct spinner_info) {
754 			.crtval = &part_done,
755 			.maxval = foff + len,
756 			.total = totalmem
757 		};
758 
759 		rc = pthread_create(&spinner_th, 0, snapshot_spinner_cb, si);
760 		if (rc) {
761 			perror("Unable to create spinner thread");
762 			show_progress = false;
763 		}
764 	}
765 
766 	while (rem > 0) {
767 		if (show_progress)
768 			todo = min(SNAPSHOT_CHUNK, rem);
769 		else
770 			todo = rem;
771 
772 		if (op_wr)
773 			done = write(snapfd, src, todo);
774 		else
775 			done = read(snapfd, src, todo);
776 		if (done < 0) {
777 			perror("Failed to write in file");
778 			return (-1);
779 		}
780 
781 		src = (uint8_t *)src + done;
782 		part_done += done;
783 		rem -= done;
784 	}
785 
786 	if (show_progress) {
787 		rc = pthread_join(spinner_th, NULL);
788 		if (rc)
789 			perror("Unable to end spinner thread");
790 	}
791 
792 	return (0);
793 }
794 
795 static size_t
796 vm_snapshot_mem(struct vmctx *ctx, int snapfd, size_t memsz, const bool op_wr)
797 {
798 	int ret;
799 	size_t lowmem, highmem, totalmem;
800 	char *baseaddr;
801 
802 	ret = vm_get_guestmem_from_ctx(ctx, &baseaddr, &lowmem, &highmem);
803 	if (ret) {
804 		fprintf(stderr, "%s: unable to retrieve guest memory size\r\n",
805 			__func__);
806 		return (0);
807 	}
808 	totalmem = lowmem + highmem;
809 
810 	if ((op_wr == false) && (totalmem != memsz)) {
811 		fprintf(stderr, "%s: mem size mismatch: %ld vs %ld\r\n",
812 			__func__, totalmem, memsz);
813 		return (0);
814 	}
815 
816 	winsize.ws_col = 80;
817 #ifdef TIOCGWINSZ
818 	ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
819 #endif /* TIOCGWINSZ */
820 	old_winch_handler = signal(SIGWINCH, winch_handler);
821 
822 	ret = vm_snapshot_mem_part(snapfd, 0, baseaddr, lowmem,
823 		totalmem, op_wr);
824 	if (ret) {
825 		fprintf(stderr, "%s: Could not %s lowmem\r\n",
826 			__func__, op_wr ? "write" : "read");
827 		totalmem = 0;
828 		goto done;
829 	}
830 
831 	if (highmem == 0)
832 		goto done;
833 
834 	ret = vm_snapshot_mem_part(snapfd, lowmem, baseaddr + 4*GB,
835 		highmem, totalmem, op_wr);
836 	if (ret) {
837 		fprintf(stderr, "%s: Could not %s highmem\r\n",
838 		        __func__, op_wr ? "write" : "read");
839 		totalmem = 0;
840 		goto done;
841 	}
842 
843 done:
844 	printf("\r\n");
845 	signal(SIGWINCH, old_winch_handler);
846 
847 	return (totalmem);
848 }
849 
850 int
851 restore_vm_mem(struct vmctx *ctx, struct restore_state *rstate)
852 {
853 	size_t restored;
854 
855 	restored = vm_snapshot_mem(ctx, rstate->vmmem_fd, rstate->vmmem_len,
856 				   false);
857 
858 	if (restored != rstate->vmmem_len)
859 		return (-1);
860 
861 	return (0);
862 }
863 
864 static int
865 vm_restore_kern_struct(struct vmctx *ctx, struct restore_state *rstate,
866 		       const struct vm_snapshot_kern_info *info)
867 {
868 	void *struct_ptr;
869 	size_t struct_size;
870 	int ret;
871 	struct vm_snapshot_meta *meta;
872 
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);
877 		ret = -1;
878 		goto done;
879 	}
880 
881 	if (struct_size == 0) {
882 		fprintf(stderr, "%s: Kernel struct size was 0 for: %s\r\n",
883 			__func__, info->struct_name);
884 		ret = -1;
885 		goto done;
886 	}
887 
888 	meta = &(struct vm_snapshot_meta) {
889 		.ctx = ctx,
890 		.dev_name = info->struct_name,
891 		.dev_req  = info->req,
892 
893 		.buffer.buf_start = struct_ptr,
894 		.buffer.buf_size = struct_size,
895 
896 		.buffer.buf = struct_ptr,
897 		.buffer.buf_rem = struct_size,
898 
899 		.op = VM_SNAPSHOT_RESTORE,
900 	};
901 
902 	ret = vm_snapshot_req(meta);
903 	if (ret != 0) {
904 		fprintf(stderr, "%s: Failed to restore struct: %s\r\n",
905 			__func__, info->struct_name);
906 		goto done;
907 	}
908 
909 done:
910 	return (ret);
911 }
912 
913 int
914 vm_restore_kern_structs(struct vmctx *ctx, struct restore_state *rstate)
915 {
916 	size_t i;
917 	int ret;
918 
919 	for (i = 0; i < nitems(snapshot_kern_structs); i++) {
920 		ret = vm_restore_kern_struct(ctx, rstate,
921 					     &snapshot_kern_structs[i]);
922 		if (ret != 0)
923 			return (ret);
924 	}
925 
926 	return (0);
927 }
928 
929 static int
930 vm_restore_user_dev(struct vmctx *ctx, struct restore_state *rstate,
931 		    const struct vm_snapshot_dev_info *info)
932 {
933 	void *dev_ptr;
934 	size_t dev_size;
935 	int ret;
936 	struct vm_snapshot_meta *meta;
937 
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");
942 		return (0);
943 	}
944 
945 	if (dev_size == 0) {
946 		fprintf(stderr, "%s: Device size is 0. "
947 			"Assuming %s is not used\r\n",
948 			__func__, info->dev_name);
949 		return (0);
950 	}
951 
952 	meta = &(struct vm_snapshot_meta) {
953 		.ctx = ctx,
954 		.dev_name = info->dev_name,
955 
956 		.buffer.buf_start = dev_ptr,
957 		.buffer.buf_size = dev_size,
958 
959 		.buffer.buf = dev_ptr,
960 		.buffer.buf_rem = dev_size,
961 
962 		.op = VM_SNAPSHOT_RESTORE,
963 	};
964 
965 	ret = (*info->snapshot_cb)(meta);
966 	if (ret != 0) {
967 		fprintf(stderr, "Failed to restore dev: %s\r\n",
968 			info->dev_name);
969 		return (-1);
970 	}
971 
972 	return (0);
973 }
974 
975 
976 int
977 vm_restore_user_devs(struct vmctx *ctx, struct restore_state *rstate)
978 {
979 	size_t i;
980 	int ret;
981 
982 	for (i = 0; i < nitems(snapshot_devs); i++) {
983 		ret = vm_restore_user_dev(ctx, rstate, &snapshot_devs[i]);
984 		if (ret != 0)
985 			return (ret);
986 	}
987 
988 	return 0;
989 }
990 
991 int
992 vm_pause_user_devs(struct vmctx *ctx)
993 {
994 	const struct vm_snapshot_dev_info *info;
995 	size_t i;
996 	int ret;
997 
998 	for (i = 0; i < nitems(snapshot_devs); i++) {
999 		info = &snapshot_devs[i];
1000 		if (info->pause_cb == NULL)
1001 			continue;
1002 
1003 		ret = info->pause_cb(ctx, info->dev_name);
1004 		if (ret != 0)
1005 			return (ret);
1006 	}
1007 
1008 	return (0);
1009 }
1010 
1011 int
1012 vm_resume_user_devs(struct vmctx *ctx)
1013 {
1014 	const struct vm_snapshot_dev_info *info;
1015 	size_t i;
1016 	int ret;
1017 
1018 	for (i = 0; i < nitems(snapshot_devs); i++) {
1019 		info = &snapshot_devs[i];
1020 		if (info->resume_cb == NULL)
1021 			continue;
1022 
1023 		ret = info->resume_cb(ctx, info->dev_name);
1024 		if (ret != 0)
1025 			return (ret);
1026 	}
1027 
1028 	return (0);
1029 }
1030 
1031 static int
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)
1034 {
1035 	int ret;
1036 	size_t data_size;
1037 	ssize_t write_cnt;
1038 
1039 	ret = vm_snapshot_req(meta);
1040 	if (ret != 0) {
1041 		fprintf(stderr, "%s: Failed to snapshot struct %s\r\n",
1042 			__func__, meta->dev_name);
1043 		ret = -1;
1044 		goto done;
1045 	}
1046 
1047 	data_size = vm_get_snapshot_size(meta);
1048 
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.");
1052 		ret = -1;
1053 		goto done;
1054 	}
1055 
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",
1060 		  meta->dev_req);
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);
1064 
1065 	*offset += data_size;
1066 
1067 done:
1068 	return (ret);
1069 }
1070 
1071 static int
1072 vm_snapshot_kern_structs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1073 {
1074 	int ret, error;
1075 	size_t buf_size, i, offset;
1076 	char *buffer;
1077 	struct vm_snapshot_meta *meta;
1078 
1079 	error = 0;
1080 	offset = 0;
1081 	buf_size = SNAPSHOT_BUFFER_SIZE;
1082 
1083 	buffer = malloc(SNAPSHOT_BUFFER_SIZE * sizeof(char));
1084 	if (buffer == NULL) {
1085 		error = ENOMEM;
1086 		perror("Failed to allocate memory for snapshot buffer");
1087 		goto err_vm_snapshot_kern_data;
1088 	}
1089 
1090 	meta = &(struct vm_snapshot_meta) {
1091 		.ctx = ctx,
1092 
1093 		.buffer.buf_start = buffer,
1094 		.buffer.buf_size = buf_size,
1095 
1096 		.op = VM_SNAPSHOT_SAVE,
1097 	};
1098 
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;
1103 
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;
1107 
1108 		ret = vm_snapshot_kern_struct(data_fd, xop, JSON_DEV_ARR_KEY,
1109 					      meta, &offset);
1110 		if (ret != 0) {
1111 			error = -1;
1112 			goto err_vm_snapshot_kern_data;
1113 		}
1114 	}
1115 	xo_close_list_h(xop, JSON_STRUCT_ARR_KEY);
1116 
1117 err_vm_snapshot_kern_data:
1118 	if (buffer != NULL)
1119 		free(buffer);
1120 	return (error);
1121 }
1122 
1123 static int
1124 vm_snapshot_basic_metadata(struct vmctx *ctx, xo_handle_t *xop, size_t memsz)
1125 {
1126 
1127 	xo_open_container_h(xop, JSON_BASIC_METADATA_KEY);
1128 	xo_emit_h(xop, "{:" JSON_NCPUS_KEY "/%ld}\n", guest_ncpus);
1129 	xo_emit_h(xop, "{:" JSON_VMNAME_KEY "/%s}\n", vm_get_name(ctx));
1130 	xo_emit_h(xop, "{:" JSON_MEMSIZE_KEY "/%lu}\n", memsz);
1131 	xo_emit_h(xop, "{:" JSON_MEMFLAGS_KEY "/%d}\n", vm_get_memflags(ctx));
1132 	xo_close_container_h(xop, JSON_BASIC_METADATA_KEY);
1133 
1134 	return (0);
1135 }
1136 
1137 static int
1138 vm_snapshot_dev_write_data(int data_fd, xo_handle_t *xop, const char *array_key,
1139 			   struct vm_snapshot_meta *meta, off_t *offset)
1140 {
1141 	int ret;
1142 	size_t data_size;
1143 
1144 	data_size = vm_get_snapshot_size(meta);
1145 
1146 	ret = write(data_fd, meta->buffer.buf_start, data_size);
1147 	if (ret != data_size) {
1148 		perror("Failed to write all snapshotted data.");
1149 		return (-1);
1150 	}
1151 
1152 	/* Write metadata. */
1153 	xo_open_instance_h(xop, array_key);
1154 	xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%s}\n", meta->dev_name);
1155 	xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1156 	xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1157 	xo_close_instance_h(xop, array_key);
1158 
1159 	*offset += data_size;
1160 
1161 	return (0);
1162 }
1163 
1164 static int
1165 vm_snapshot_user_dev(const struct vm_snapshot_dev_info *info,
1166 		     int data_fd, xo_handle_t *xop,
1167 		     struct vm_snapshot_meta *meta, off_t *offset)
1168 {
1169 	int ret;
1170 
1171 	ret = (*info->snapshot_cb)(meta);
1172 	if (ret != 0) {
1173 		fprintf(stderr, "Failed to snapshot %s; ret=%d\r\n",
1174 			meta->dev_name, ret);
1175 		return (ret);
1176 	}
1177 
1178 	ret = vm_snapshot_dev_write_data(data_fd, xop, JSON_DEV_ARR_KEY, meta,
1179 					 offset);
1180 	if (ret != 0)
1181 		return (ret);
1182 
1183 	return (0);
1184 }
1185 
1186 static int
1187 vm_snapshot_user_devs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1188 {
1189 	int ret;
1190 	off_t offset;
1191 	void *buffer;
1192 	size_t buf_size, i;
1193 	struct vm_snapshot_meta *meta;
1194 
1195 	buf_size = SNAPSHOT_BUFFER_SIZE;
1196 
1197 	offset = lseek(data_fd, 0, SEEK_CUR);
1198 	if (offset < 0) {
1199 		perror("Failed to get data file current offset.");
1200 		return (-1);
1201 	}
1202 
1203 	buffer = malloc(buf_size);
1204 	if (buffer == NULL) {
1205 		perror("Failed to allocate memory for snapshot buffer");
1206 		ret = ENOSPC;
1207 		goto snapshot_err;
1208 	}
1209 
1210 	meta = &(struct vm_snapshot_meta) {
1211 		.ctx = ctx,
1212 
1213 		.buffer.buf_start = buffer,
1214 		.buffer.buf_size = buf_size,
1215 
1216 		.op = VM_SNAPSHOT_SAVE,
1217 	};
1218 
1219 	xo_open_list_h(xop, JSON_DEV_ARR_KEY);
1220 
1221 	/* Restore other devices that support this feature */
1222 	for (i = 0; i < nitems(snapshot_devs); i++) {
1223 		meta->dev_name = snapshot_devs[i].dev_name;
1224 
1225 		memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1226 		meta->buffer.buf = meta->buffer.buf_start;
1227 		meta->buffer.buf_rem = meta->buffer.buf_size;
1228 
1229 		ret = vm_snapshot_user_dev(&snapshot_devs[i], data_fd, xop,
1230 					   meta, &offset);
1231 		if (ret != 0)
1232 			goto snapshot_err;
1233 	}
1234 
1235 	xo_close_list_h(xop, JSON_DEV_ARR_KEY);
1236 
1237 snapshot_err:
1238 	if (buffer != NULL)
1239 		free(buffer);
1240 	return (ret);
1241 }
1242 
1243 void
1244 checkpoint_cpu_add(int vcpu)
1245 {
1246 
1247 	pthread_mutex_lock(&vcpu_lock);
1248 	CPU_SET(vcpu, &vcpus_active);
1249 
1250 	if (checkpoint_active) {
1251 		CPU_SET(vcpu, &vcpus_suspended);
1252 		while (checkpoint_active)
1253 			pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1254 		CPU_CLR(vcpu, &vcpus_suspended);
1255 	}
1256 	pthread_mutex_unlock(&vcpu_lock);
1257 }
1258 
1259 /*
1260  * When a vCPU is suspended for any reason, it calls
1261  * checkpoint_cpu_suspend().  This records that the vCPU is idle.
1262  * Before returning from suspension, checkpoint_cpu_resume() is
1263  * called.  In suspend we note that the vCPU is idle.  In resume we
1264  * pause the vCPU thread until the checkpoint is complete.  The reason
1265  * for the two-step process is that vCPUs might already be stopped in
1266  * the debug server when a checkpoint is requested.  This approach
1267  * allows us to account for and handle those vCPUs.
1268  */
1269 void
1270 checkpoint_cpu_suspend(int vcpu)
1271 {
1272 
1273 	pthread_mutex_lock(&vcpu_lock);
1274 	CPU_SET(vcpu, &vcpus_suspended);
1275 	if (checkpoint_active && CPU_CMP(&vcpus_active, &vcpus_suspended) == 0)
1276 		pthread_cond_signal(&vcpus_idle);
1277 	pthread_mutex_unlock(&vcpu_lock);
1278 }
1279 
1280 void
1281 checkpoint_cpu_resume(int vcpu)
1282 {
1283 
1284 	pthread_mutex_lock(&vcpu_lock);
1285 	while (checkpoint_active)
1286 		pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1287 	CPU_CLR(vcpu, &vcpus_suspended);
1288 	pthread_mutex_unlock(&vcpu_lock);
1289 }
1290 
1291 static void
1292 vm_vcpu_pause(struct vmctx *ctx)
1293 {
1294 
1295 	pthread_mutex_lock(&vcpu_lock);
1296 	checkpoint_active = true;
1297 	vm_suspend_cpu(ctx, -1);
1298 	while (CPU_CMP(&vcpus_active, &vcpus_suspended) != 0)
1299 		pthread_cond_wait(&vcpus_idle, &vcpu_lock);
1300 	pthread_mutex_unlock(&vcpu_lock);
1301 }
1302 
1303 static void
1304 vm_vcpu_resume(struct vmctx *ctx)
1305 {
1306 
1307 	pthread_mutex_lock(&vcpu_lock);
1308 	checkpoint_active = false;
1309 	pthread_mutex_unlock(&vcpu_lock);
1310 	vm_resume_cpu(ctx, -1);
1311 	pthread_cond_broadcast(&vcpus_can_run);
1312 }
1313 
1314 static int
1315 vm_checkpoint(struct vmctx *ctx, const char *checkpoint_file, bool stop_vm)
1316 {
1317 	int fd_checkpoint = 0, kdata_fd = 0;
1318 	int ret = 0;
1319 	int error = 0;
1320 	size_t memsz;
1321 	xo_handle_t *xop = NULL;
1322 	char *meta_filename = NULL;
1323 	char *kdata_filename = NULL;
1324 	FILE *meta_file = NULL;
1325 
1326 	kdata_filename = strcat_extension(checkpoint_file, ".kern");
1327 	if (kdata_filename == NULL) {
1328 		fprintf(stderr, "Failed to construct kernel data filename.\n");
1329 		return (-1);
1330 	}
1331 
1332 	kdata_fd = open(kdata_filename, O_WRONLY | O_CREAT | O_TRUNC, 0700);
1333 	if (kdata_fd < 0) {
1334 		perror("Failed to open kernel data snapshot file.");
1335 		error = -1;
1336 		goto done;
1337 	}
1338 
1339 	fd_checkpoint = open(checkpoint_file, O_RDWR | O_CREAT | O_TRUNC, 0700);
1340 
1341 	if (fd_checkpoint < 0) {
1342 		perror("Failed to create checkpoint file");
1343 		error = -1;
1344 		goto done;
1345 	}
1346 
1347 	meta_filename = strcat_extension(checkpoint_file, ".meta");
1348 	if (meta_filename == NULL) {
1349 		fprintf(stderr, "Failed to construct vm metadata filename.\n");
1350 		goto done;
1351 	}
1352 
1353 	meta_file = fopen(meta_filename, "w");
1354 	if (meta_file == NULL) {
1355 		perror("Failed to open vm metadata snapshot file.");
1356 		goto done;
1357 	}
1358 
1359 	xop = xo_create_to_file(meta_file, XO_STYLE_JSON, XOF_PRETTY);
1360 	if (xop == NULL) {
1361 		perror("Failed to get libxo handle on metadata file.");
1362 		goto done;
1363 	}
1364 
1365 	vm_vcpu_pause(ctx);
1366 
1367 	ret = vm_pause_user_devs(ctx);
1368 	if (ret != 0) {
1369 		fprintf(stderr, "Could not pause devices\r\n");
1370 		error = ret;
1371 		goto done;
1372 	}
1373 
1374 	memsz = vm_snapshot_mem(ctx, fd_checkpoint, 0, true);
1375 	if (memsz == 0) {
1376 		perror("Could not write guest memory to file");
1377 		error = -1;
1378 		goto done;
1379 	}
1380 
1381 	ret = vm_snapshot_basic_metadata(ctx, xop, memsz);
1382 	if (ret != 0) {
1383 		fprintf(stderr, "Failed to snapshot vm basic metadata.\n");
1384 		error = -1;
1385 		goto done;
1386 	}
1387 
1388 
1389 	ret = vm_snapshot_kern_structs(ctx, kdata_fd, xop);
1390 	if (ret != 0) {
1391 		fprintf(stderr, "Failed to snapshot vm kernel data.\n");
1392 		error = -1;
1393 		goto done;
1394 	}
1395 
1396 	ret = vm_snapshot_user_devs(ctx, kdata_fd, xop);
1397 	if (ret != 0) {
1398 		fprintf(stderr, "Failed to snapshot device state.\n");
1399 		error = -1;
1400 		goto done;
1401 	}
1402 
1403 	xo_finish_h(xop);
1404 
1405 	if (stop_vm) {
1406 		vm_destroy(ctx);
1407 		exit(0);
1408 	}
1409 
1410 done:
1411 	ret = vm_resume_user_devs(ctx);
1412 	if (ret != 0)
1413 		fprintf(stderr, "Could not resume devices\r\n");
1414 	vm_vcpu_resume(ctx);
1415 	if (fd_checkpoint > 0)
1416 		close(fd_checkpoint);
1417 	if (meta_filename != NULL)
1418 		free(meta_filename);
1419 	if (kdata_filename != NULL)
1420 		free(kdata_filename);
1421 	if (xop != NULL)
1422 		xo_destroy(xop);
1423 	if (meta_file != NULL)
1424 		fclose(meta_file);
1425 	if (kdata_fd > 0)
1426 		close(kdata_fd);
1427 	return (error);
1428 }
1429 
1430 static int
1431 handle_message(struct vmctx *ctx, nvlist_t *nvl)
1432 {
1433 	const char *cmd;
1434 	struct ipc_command **ipc_cmd;
1435 
1436 	if (!nvlist_exists_string(nvl, "cmd"))
1437 		return (EINVAL);
1438 
1439 	cmd = nvlist_get_string(nvl, "cmd");
1440 	IPC_COMMAND_FOREACH(ipc_cmd, ipc_cmd_set) {
1441 		if (strcmp(cmd, (*ipc_cmd)->name) == 0)
1442 			return ((*ipc_cmd)->handler(ctx, nvl));
1443 	}
1444 
1445 	return (EOPNOTSUPP);
1446 }
1447 
1448 /*
1449  * Listen for commands from bhyvectl
1450  */
1451 void *
1452 checkpoint_thread(void *param)
1453 {
1454 	int fd;
1455 	struct checkpoint_thread_info *thread_info;
1456 	nvlist_t *nvl;
1457 
1458 	pthread_set_name_np(pthread_self(), "checkpoint thread");
1459 	thread_info = (struct checkpoint_thread_info *)param;
1460 
1461 	while ((fd = accept(thread_info->socket_fd, NULL, NULL)) != -1) {
1462 		nvl = nvlist_recv(fd, 0);
1463 		if (nvl != NULL)
1464 			handle_message(thread_info->ctx, nvl);
1465 		else
1466 			EPRINTLN("nvlist_recv() failed: %s", strerror(errno));
1467 
1468 		close(fd);
1469 		nvlist_destroy(nvl);
1470 	}
1471 
1472 	return (NULL);
1473 }
1474 
1475 static int
1476 vm_do_checkpoint(struct vmctx *ctx, const nvlist_t *nvl)
1477 {
1478 	int error;
1479 
1480 	if (!nvlist_exists_string(nvl, "filename") ||
1481 	    !nvlist_exists_bool(nvl, "suspend"))
1482 		error = EINVAL;
1483 	else
1484 		error = vm_checkpoint(ctx, nvlist_get_string(nvl, "filename"),
1485 		    nvlist_get_bool(nvl, "suspend"));
1486 
1487 	return (error);
1488 }
1489 IPC_COMMAND(ipc_cmd_set, checkpoint, vm_do_checkpoint);
1490 
1491 void
1492 init_snapshot(void)
1493 {
1494 	int err;
1495 
1496 	err = pthread_mutex_init(&vcpu_lock, NULL);
1497 	if (err != 0)
1498 		errc(1, err, "checkpoint mutex init");
1499 	err = pthread_cond_init(&vcpus_idle, NULL);
1500 	if (err != 0)
1501 		errc(1, err, "checkpoint cv init (vcpus_idle)");
1502 	err = pthread_cond_init(&vcpus_can_run, NULL);
1503 	if (err != 0)
1504 		errc(1, err, "checkpoint cv init (vcpus_can_run)");
1505 }
1506 
1507 /*
1508  * Create the listening socket for IPC with bhyvectl
1509  */
1510 int
1511 init_checkpoint_thread(struct vmctx *ctx)
1512 {
1513 	struct checkpoint_thread_info *checkpoint_info = NULL;
1514 	struct sockaddr_un addr;
1515 	int socket_fd;
1516 	pthread_t checkpoint_pthread;
1517 	int err;
1518 
1519 	memset(&addr, 0, sizeof(addr));
1520 
1521 	socket_fd = socket(PF_UNIX, SOCK_STREAM, 0);
1522 	if (socket_fd < 0) {
1523 		EPRINTLN("Socket creation failed: %s", strerror(errno));
1524 		err = -1;
1525 		goto fail;
1526 	}
1527 
1528 	addr.sun_family = AF_UNIX;
1529 
1530 	snprintf(addr.sun_path, sizeof(addr.sun_path), "%s%s",
1531 		 BHYVE_RUN_DIR, vm_get_name(ctx));
1532 	addr.sun_len = SUN_LEN(&addr);
1533 	unlink(addr.sun_path);
1534 
1535 	if (bind(socket_fd, (struct sockaddr *)&addr, addr.sun_len) != 0) {
1536 		EPRINTLN("Failed to bind socket \"%s\": %s\n",
1537 		    addr.sun_path, strerror(errno));
1538 		err = -1;
1539 		goto fail;
1540 	}
1541 
1542 	if (listen(socket_fd, 10) < 0) {
1543 		EPRINTLN("ipc socket listen: %s\n", strerror(errno));
1544 		err = errno;
1545 		goto fail;
1546 	}
1547 
1548 	checkpoint_info = calloc(1, sizeof(*checkpoint_info));
1549 	checkpoint_info->ctx = ctx;
1550 	checkpoint_info->socket_fd = socket_fd;
1551 
1552 	err = pthread_create(&checkpoint_pthread, NULL, checkpoint_thread,
1553 		checkpoint_info);
1554 	if (err != 0)
1555 		goto fail;
1556 
1557 	return (0);
1558 fail:
1559 	free(checkpoint_info);
1560 	if (socket_fd > 0)
1561 		close(socket_fd);
1562 	unlink(addr.sun_path);
1563 
1564 	return (err);
1565 }
1566 
1567 void
1568 vm_snapshot_buf_err(const char *bufname, const enum vm_snapshot_op op)
1569 {
1570 	const char *__op;
1571 
1572 	if (op == VM_SNAPSHOT_SAVE)
1573 		__op = "save";
1574 	else if (op == VM_SNAPSHOT_RESTORE)
1575 		__op = "restore";
1576 	else
1577 		__op = "unknown";
1578 
1579 	fprintf(stderr, "%s: snapshot-%s failed for %s\r\n",
1580 		__func__, __op, bufname);
1581 }
1582 
1583 int
1584 vm_snapshot_buf(volatile void *data, size_t data_size,
1585 		struct vm_snapshot_meta *meta)
1586 {
1587 	struct vm_snapshot_buffer *buffer;
1588 	int op;
1589 
1590 	buffer = &meta->buffer;
1591 	op = meta->op;
1592 
1593 	if (buffer->buf_rem < data_size) {
1594 		fprintf(stderr, "%s: buffer too small\r\n", __func__);
1595 		return (E2BIG);
1596 	}
1597 
1598 	if (op == VM_SNAPSHOT_SAVE)
1599 		memcpy(buffer->buf, (uint8_t *) data, data_size);
1600 	else if (op == VM_SNAPSHOT_RESTORE)
1601 		memcpy((uint8_t *) data, buffer->buf, data_size);
1602 	else
1603 		return (EINVAL);
1604 
1605 	buffer->buf += data_size;
1606 	buffer->buf_rem -= data_size;
1607 
1608 	return (0);
1609 }
1610 
1611 size_t
1612 vm_get_snapshot_size(struct vm_snapshot_meta *meta)
1613 {
1614 	size_t length;
1615 	struct vm_snapshot_buffer *buffer;
1616 
1617 	buffer = &meta->buffer;
1618 
1619 	if (buffer->buf_size < buffer->buf_rem) {
1620 		fprintf(stderr, "%s: Invalid buffer: size = %zu, rem = %zu\r\n",
1621 			__func__, buffer->buf_size, buffer->buf_rem);
1622 		length = 0;
1623 	} else {
1624 		length = buffer->buf_size - buffer->buf_rem;
1625 	}
1626 
1627 	return (length);
1628 }
1629 
1630 int
1631 vm_snapshot_guest2host_addr(void **addrp, size_t len, bool restore_null,
1632 			    struct vm_snapshot_meta *meta)
1633 {
1634 	int ret;
1635 	vm_paddr_t gaddr;
1636 
1637 	if (meta->op == VM_SNAPSHOT_SAVE) {
1638 		gaddr = paddr_host2guest(meta->ctx, *addrp);
1639 		if (gaddr == (vm_paddr_t) -1) {
1640 			if (!restore_null ||
1641 			    (restore_null && (*addrp != NULL))) {
1642 				ret = EFAULT;
1643 				goto done;
1644 			}
1645 		}
1646 
1647 		SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1648 	} else if (meta->op == VM_SNAPSHOT_RESTORE) {
1649 		SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1650 		if (gaddr == (vm_paddr_t) -1) {
1651 			if (!restore_null) {
1652 				ret = EFAULT;
1653 				goto done;
1654 			}
1655 		}
1656 
1657 		*addrp = paddr_guest2host(meta->ctx, gaddr, len);
1658 	} else {
1659 		ret = EINVAL;
1660 	}
1661 
1662 done:
1663 	return (ret);
1664 }
1665 
1666 int
1667 vm_snapshot_buf_cmp(volatile void *data, size_t data_size,
1668 		    struct vm_snapshot_meta *meta)
1669 {
1670 	struct vm_snapshot_buffer *buffer;
1671 	int op;
1672 	int ret;
1673 
1674 	buffer = &meta->buffer;
1675 	op = meta->op;
1676 
1677 	if (buffer->buf_rem < data_size) {
1678 		fprintf(stderr, "%s: buffer too small\r\n", __func__);
1679 		ret = E2BIG;
1680 		goto done;
1681 	}
1682 
1683 	if (op == VM_SNAPSHOT_SAVE) {
1684 		ret = 0;
1685 		memcpy(buffer->buf, (uint8_t *) data, data_size);
1686 	} else if (op == VM_SNAPSHOT_RESTORE) {
1687 		ret = memcmp((uint8_t *) data, buffer->buf, data_size);
1688 	} else {
1689 		ret = EINVAL;
1690 		goto done;
1691 	}
1692 
1693 	buffer->buf += data_size;
1694 	buffer->buf_rem -= data_size;
1695 
1696 done:
1697 	return (ret);
1698 }
1699