xref: /freebsd/usr.sbin/bhyve/snapshot.c (revision 19261079b74319502c6ffa1249920079f0f69a72)
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 "fwctl.h"
85 #include "ioapic.h"
86 #include "mem.h"
87 #include "mevent.h"
88 #include "mptbl.h"
89 #include "pci_emul.h"
90 #include "pci_irq.h"
91 #include "pci_lpc.h"
92 #include "smbiostbl.h"
93 #include "snapshot.h"
94 #include "xmsr.h"
95 #include "spinup_ap.h"
96 #include "rtc.h"
97 
98 #include <libxo/xo.h>
99 #include <ucl.h>
100 
101 struct spinner_info {
102 	const size_t *crtval;
103 	const size_t maxval;
104 	const size_t total;
105 };
106 
107 extern int guest_ncpus;
108 
109 static struct winsize winsize;
110 static sig_t old_winch_handler;
111 
112 #define	KB		(1024UL)
113 #define	MB		(1024UL * KB)
114 #define	GB		(1024UL * MB)
115 
116 #define	SNAPSHOT_CHUNK	(4 * MB)
117 #define	PROG_BUF_SZ	(8192)
118 
119 #define	MAX_VMNAME 100
120 
121 #define	SNAPSHOT_BUFFER_SIZE (20 * MB)
122 
123 #define	JSON_STRUCT_ARR_KEY		"structs"
124 #define	JSON_DEV_ARR_KEY		"devices"
125 #define	JSON_BASIC_METADATA_KEY 	"basic metadata"
126 #define	JSON_SNAPSHOT_REQ_KEY		"snapshot_req"
127 #define	JSON_SIZE_KEY			"size"
128 #define	JSON_FILE_OFFSET_KEY		"file_offset"
129 
130 #define	JSON_NCPUS_KEY			"ncpus"
131 #define	JSON_VMNAME_KEY 		"vmname"
132 #define	JSON_MEMSIZE_KEY		"memsize"
133 #define	JSON_MEMFLAGS_KEY		"memflags"
134 
135 #define min(a,b)		\
136 ({				\
137  __typeof__ (a) _a = (a);	\
138  __typeof__ (b) _b = (b); 	\
139  _a < _b ? _a : _b;       	\
140  })
141 
142 const struct vm_snapshot_dev_info snapshot_devs[] = {
143 	{ "atkbdc",	atkbdc_snapshot,	NULL,		NULL		},
144 	{ "virtio-net",	pci_snapshot,		pci_pause,	pci_resume	},
145 	{ "virtio-blk",	pci_snapshot,		pci_pause,	pci_resume	},
146 	{ "virtio-rnd",	pci_snapshot,		NULL,		NULL		},
147 	{ "lpc",	pci_snapshot,		NULL,		NULL		},
148 	{ "fbuf",	pci_snapshot,		NULL,		NULL		},
149 	{ "xhci",	pci_snapshot,		NULL,		NULL		},
150 	{ "e1000",	pci_snapshot,		NULL,		NULL		},
151 	{ "ahci",	pci_snapshot,		pci_pause,	pci_resume	},
152 	{ "ahci-hd",	pci_snapshot,		pci_pause,	pci_resume	},
153 	{ "ahci-cd",	pci_snapshot,		pci_pause,	pci_resume	},
154 };
155 
156 const struct vm_snapshot_kern_info snapshot_kern_structs[] = {
157 	{ "vhpet",	STRUCT_VHPET	},
158 	{ "vm",		STRUCT_VM	},
159 	{ "vmx",	STRUCT_VMX	},
160 	{ "vioapic",	STRUCT_VIOAPIC	},
161 	{ "vlapic",	STRUCT_VLAPIC	},
162 	{ "vmcx",	STRUCT_VMCX	},
163 	{ "vatpit",	STRUCT_VATPIT	},
164 	{ "vatpic",	STRUCT_VATPIC	},
165 	{ "vpmtmr",	STRUCT_VPMTMR	},
166 	{ "vrtc",	STRUCT_VRTC	},
167 };
168 
169 static cpuset_t vcpus_active, vcpus_suspended;
170 static pthread_mutex_t vcpu_lock;
171 static pthread_cond_t vcpus_idle, vcpus_can_run;
172 static bool checkpoint_active;
173 
174 /*
175  * TODO: Harden this function and all of its callers since 'base_str' is a user
176  * provided string.
177  */
178 static char *
179 strcat_extension(const char *base_str, const char *ext)
180 {
181 	char *res;
182 	size_t base_len, ext_len;
183 
184 	base_len = strnlen(base_str, MAX_VMNAME);
185 	ext_len = strnlen(ext, MAX_VMNAME);
186 
187 	if (base_len + ext_len > MAX_VMNAME) {
188 		fprintf(stderr, "Filename exceeds maximum length.\n");
189 		return (NULL);
190 	}
191 
192 	res = malloc(base_len + ext_len + 1);
193 	if (res == NULL) {
194 		perror("Failed to allocate memory.");
195 		return (NULL);
196 	}
197 
198 	memcpy(res, base_str, base_len);
199 	memcpy(res + base_len, ext, ext_len);
200 	res[base_len + ext_len] = 0;
201 
202 	return (res);
203 }
204 
205 void
206 destroy_restore_state(struct restore_state *rstate)
207 {
208 	if (rstate == NULL) {
209 		fprintf(stderr, "Attempting to destroy NULL restore struct.\n");
210 		return;
211 	}
212 
213 	if (rstate->kdata_map != MAP_FAILED)
214 		munmap(rstate->kdata_map, rstate->kdata_len);
215 
216 	if (rstate->kdata_fd > 0)
217 		close(rstate->kdata_fd);
218 	if (rstate->vmmem_fd > 0)
219 		close(rstate->vmmem_fd);
220 
221 	if (rstate->meta_root_obj != NULL)
222 		ucl_object_unref(rstate->meta_root_obj);
223 	if (rstate->meta_parser != NULL)
224 		ucl_parser_free(rstate->meta_parser);
225 }
226 
227 static int
228 load_vmmem_file(const char *filename, struct restore_state *rstate)
229 {
230 	struct stat sb;
231 	int err;
232 
233 	rstate->vmmem_fd = open(filename, O_RDONLY);
234 	if (rstate->vmmem_fd < 0) {
235 		perror("Failed to open restore file");
236 		return (-1);
237 	}
238 
239 	err = fstat(rstate->vmmem_fd, &sb);
240 	if (err < 0) {
241 		perror("Failed to stat restore file");
242 		goto err_load_vmmem;
243 	}
244 
245 	if (sb.st_size == 0) {
246 		fprintf(stderr, "Restore file is empty.\n");
247 		goto err_load_vmmem;
248 	}
249 
250 	rstate->vmmem_len = sb.st_size;
251 
252 	return (0);
253 
254 err_load_vmmem:
255 	if (rstate->vmmem_fd > 0)
256 		close(rstate->vmmem_fd);
257 	return (-1);
258 }
259 
260 static int
261 load_kdata_file(const char *filename, struct restore_state *rstate)
262 {
263 	struct stat sb;
264 	int err;
265 
266 	rstate->kdata_fd = open(filename, O_RDONLY);
267 	if (rstate->kdata_fd < 0) {
268 		perror("Failed to open kernel data file");
269 		return (-1);
270 	}
271 
272 	err = fstat(rstate->kdata_fd, &sb);
273 	if (err < 0) {
274 		perror("Failed to stat kernel data file");
275 		goto err_load_kdata;
276 	}
277 
278 	if (sb.st_size == 0) {
279 		fprintf(stderr, "Kernel data file is empty.\n");
280 		goto err_load_kdata;
281 	}
282 
283 	rstate->kdata_len = sb.st_size;
284 	rstate->kdata_map = mmap(NULL, rstate->kdata_len, PROT_READ,
285 				 MAP_SHARED, rstate->kdata_fd, 0);
286 	if (rstate->kdata_map == MAP_FAILED) {
287 		perror("Failed to map restore file");
288 		goto err_load_kdata;
289 	}
290 
291 	return (0);
292 
293 err_load_kdata:
294 	if (rstate->kdata_fd > 0)
295 		close(rstate->kdata_fd);
296 	return (-1);
297 }
298 
299 static int
300 load_metadata_file(const char *filename, struct restore_state *rstate)
301 {
302 	const ucl_object_t *obj;
303 	struct ucl_parser *parser;
304 	int err;
305 
306 	parser = ucl_parser_new(UCL_PARSER_DEFAULT);
307 	if (parser == NULL) {
308 		fprintf(stderr, "Failed to initialize UCL parser.\n");
309 		goto err_load_metadata;
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((ucl_object_t *)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 (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 (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((ucl_object_t *)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((ucl_object_t *)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)
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 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 += 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 	int ret;
917 	int i;
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 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 	int ret;
980 	int i;
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 	int ret;
996 	int i;
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 	int ret;
1016 	int i;
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, i, error;
1075 	size_t offset, buf_size;
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 	int error;
1127 	int memflags;
1128 	char vmname_buf[MAX_VMNAME];
1129 
1130 	memset(vmname_buf, 0, MAX_VMNAME);
1131 	error = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1132 	if (error != 0) {
1133 		perror("Failed to get VM name");
1134 		goto err;
1135 	}
1136 
1137 	memflags = vm_get_memflags(ctx);
1138 
1139 	xo_open_container_h(xop, JSON_BASIC_METADATA_KEY);
1140 	xo_emit_h(xop, "{:" JSON_NCPUS_KEY "/%ld}\n", guest_ncpus);
1141 	xo_emit_h(xop, "{:" JSON_VMNAME_KEY "/%s}\n", vmname_buf);
1142 	xo_emit_h(xop, "{:" JSON_MEMSIZE_KEY "/%lu}\n", memsz);
1143 	xo_emit_h(xop, "{:" JSON_MEMFLAGS_KEY "/%d}\n", memflags);
1144 	xo_close_container_h(xop, JSON_BASIC_METADATA_KEY);
1145 
1146 err:
1147 	return (error);
1148 }
1149 
1150 static int
1151 vm_snapshot_dev_write_data(int data_fd, xo_handle_t *xop, const char *array_key,
1152 			   struct vm_snapshot_meta *meta, off_t *offset)
1153 {
1154 	int ret;
1155 	size_t data_size;
1156 
1157 	data_size = vm_get_snapshot_size(meta);
1158 
1159 	ret = write(data_fd, meta->buffer.buf_start, data_size);
1160 	if (ret != data_size) {
1161 		perror("Failed to write all snapshotted data.");
1162 		return (-1);
1163 	}
1164 
1165 	/* Write metadata. */
1166 	xo_open_instance_h(xop, array_key);
1167 	xo_emit_h(xop, "{:" JSON_SNAPSHOT_REQ_KEY "/%s}\n", meta->dev_name);
1168 	xo_emit_h(xop, "{:" JSON_SIZE_KEY "/%lu}\n", data_size);
1169 	xo_emit_h(xop, "{:" JSON_FILE_OFFSET_KEY "/%lu}\n", *offset);
1170 	xo_close_instance_h(xop, array_key);
1171 
1172 	*offset += data_size;
1173 
1174 	return (0);
1175 }
1176 
1177 static int
1178 vm_snapshot_user_dev(const struct vm_snapshot_dev_info *info,
1179 		     int data_fd, xo_handle_t *xop,
1180 		     struct vm_snapshot_meta *meta, off_t *offset)
1181 {
1182 	int ret;
1183 
1184 	ret = (*info->snapshot_cb)(meta);
1185 	if (ret != 0) {
1186 		fprintf(stderr, "Failed to snapshot %s; ret=%d\r\n",
1187 			meta->dev_name, ret);
1188 		return (ret);
1189 	}
1190 
1191 	ret = vm_snapshot_dev_write_data(data_fd, xop, JSON_DEV_ARR_KEY, meta,
1192 					 offset);
1193 	if (ret != 0)
1194 		return (ret);
1195 
1196 	return (0);
1197 }
1198 
1199 static int
1200 vm_snapshot_user_devs(struct vmctx *ctx, int data_fd, xo_handle_t *xop)
1201 {
1202 	int ret, i;
1203 	off_t offset;
1204 	void *buffer;
1205 	size_t buf_size;
1206 	struct vm_snapshot_meta *meta;
1207 
1208 	buf_size = SNAPSHOT_BUFFER_SIZE;
1209 
1210 	offset = lseek(data_fd, 0, SEEK_CUR);
1211 	if (offset < 0) {
1212 		perror("Failed to get data file current offset.");
1213 		return (-1);
1214 	}
1215 
1216 	buffer = malloc(buf_size);
1217 	if (buffer == NULL) {
1218 		perror("Failed to allocate memory for snapshot buffer");
1219 		ret = ENOSPC;
1220 		goto snapshot_err;
1221 	}
1222 
1223 	meta = &(struct vm_snapshot_meta) {
1224 		.ctx = ctx,
1225 
1226 		.buffer.buf_start = buffer,
1227 		.buffer.buf_size = buf_size,
1228 
1229 		.op = VM_SNAPSHOT_SAVE,
1230 	};
1231 
1232 	xo_open_list_h(xop, JSON_DEV_ARR_KEY);
1233 
1234 	/* Restore other devices that support this feature */
1235 	for (i = 0; i < nitems(snapshot_devs); i++) {
1236 		meta->dev_name = snapshot_devs[i].dev_name;
1237 
1238 		memset(meta->buffer.buf_start, 0, meta->buffer.buf_size);
1239 		meta->buffer.buf = meta->buffer.buf_start;
1240 		meta->buffer.buf_rem = meta->buffer.buf_size;
1241 
1242 		ret = vm_snapshot_user_dev(&snapshot_devs[i], data_fd, xop,
1243 					   meta, &offset);
1244 		if (ret != 0)
1245 			goto snapshot_err;
1246 	}
1247 
1248 	xo_close_list_h(xop, JSON_DEV_ARR_KEY);
1249 
1250 snapshot_err:
1251 	if (buffer != NULL)
1252 		free(buffer);
1253 	return (ret);
1254 }
1255 
1256 void
1257 checkpoint_cpu_add(int vcpu)
1258 {
1259 
1260 	pthread_mutex_lock(&vcpu_lock);
1261 	CPU_SET(vcpu, &vcpus_active);
1262 
1263 	if (checkpoint_active) {
1264 		CPU_SET(vcpu, &vcpus_suspended);
1265 		while (checkpoint_active)
1266 			pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1267 		CPU_CLR(vcpu, &vcpus_suspended);
1268 	}
1269 	pthread_mutex_unlock(&vcpu_lock);
1270 }
1271 
1272 /*
1273  * When a vCPU is suspended for any reason, it calls
1274  * checkpoint_cpu_suspend().  This records that the vCPU is idle.
1275  * Before returning from suspension, checkpoint_cpu_resume() is
1276  * called.  In suspend we note that the vCPU is idle.  In resume we
1277  * pause the vCPU thread until the checkpoint is complete.  The reason
1278  * for the two-step process is that vCPUs might already be stopped in
1279  * the debug server when a checkpoint is requested.  This approach
1280  * allows us to account for and handle those vCPUs.
1281  */
1282 void
1283 checkpoint_cpu_suspend(int vcpu)
1284 {
1285 
1286 	pthread_mutex_lock(&vcpu_lock);
1287 	CPU_SET(vcpu, &vcpus_suspended);
1288 	if (checkpoint_active && CPU_CMP(&vcpus_active, &vcpus_suspended) == 0)
1289 		pthread_cond_signal(&vcpus_idle);
1290 	pthread_mutex_unlock(&vcpu_lock);
1291 }
1292 
1293 void
1294 checkpoint_cpu_resume(int vcpu)
1295 {
1296 
1297 	pthread_mutex_lock(&vcpu_lock);
1298 	while (checkpoint_active)
1299 		pthread_cond_wait(&vcpus_can_run, &vcpu_lock);
1300 	CPU_CLR(vcpu, &vcpus_suspended);
1301 	pthread_mutex_unlock(&vcpu_lock);
1302 }
1303 
1304 static void
1305 vm_vcpu_pause(struct vmctx *ctx)
1306 {
1307 
1308 	pthread_mutex_lock(&vcpu_lock);
1309 	checkpoint_active = true;
1310 	vm_suspend_cpu(ctx, -1);
1311 	while (CPU_CMP(&vcpus_active, &vcpus_suspended) != 0)
1312 		pthread_cond_wait(&vcpus_idle, &vcpu_lock);
1313 	pthread_mutex_unlock(&vcpu_lock);
1314 }
1315 
1316 static void
1317 vm_vcpu_resume(struct vmctx *ctx)
1318 {
1319 
1320 	pthread_mutex_lock(&vcpu_lock);
1321 	checkpoint_active = false;
1322 	pthread_mutex_unlock(&vcpu_lock);
1323 	vm_resume_cpu(ctx, -1);
1324 	pthread_cond_broadcast(&vcpus_can_run);
1325 }
1326 
1327 static int
1328 vm_checkpoint(struct vmctx *ctx, char *checkpoint_file, bool stop_vm)
1329 {
1330 	int fd_checkpoint = 0, kdata_fd = 0;
1331 	int ret = 0;
1332 	int error = 0;
1333 	size_t memsz;
1334 	xo_handle_t *xop = NULL;
1335 	char *meta_filename = NULL;
1336 	char *kdata_filename = NULL;
1337 	FILE *meta_file = NULL;
1338 
1339 	kdata_filename = strcat_extension(checkpoint_file, ".kern");
1340 	if (kdata_filename == NULL) {
1341 		fprintf(stderr, "Failed to construct kernel data filename.\n");
1342 		return (-1);
1343 	}
1344 
1345 	kdata_fd = open(kdata_filename, O_WRONLY | O_CREAT | O_TRUNC, 0700);
1346 	if (kdata_fd < 0) {
1347 		perror("Failed to open kernel data snapshot file.");
1348 		error = -1;
1349 		goto done;
1350 	}
1351 
1352 	fd_checkpoint = open(checkpoint_file, O_RDWR | O_CREAT | O_TRUNC, 0700);
1353 
1354 	if (fd_checkpoint < 0) {
1355 		perror("Failed to create checkpoint file");
1356 		error = -1;
1357 		goto done;
1358 	}
1359 
1360 	meta_filename = strcat_extension(checkpoint_file, ".meta");
1361 	if (meta_filename == NULL) {
1362 		fprintf(stderr, "Failed to construct vm metadata filename.\n");
1363 		goto done;
1364 	}
1365 
1366 	meta_file = fopen(meta_filename, "w");
1367 	if (meta_file == NULL) {
1368 		perror("Failed to open vm metadata snapshot file.");
1369 		goto done;
1370 	}
1371 
1372 	xop = xo_create_to_file(meta_file, XO_STYLE_JSON, XOF_PRETTY);
1373 	if (xop == NULL) {
1374 		perror("Failed to get libxo handle on metadata file.");
1375 		goto done;
1376 	}
1377 
1378 	vm_vcpu_pause(ctx);
1379 
1380 	ret = vm_pause_user_devs(ctx);
1381 	if (ret != 0) {
1382 		fprintf(stderr, "Could not pause devices\r\n");
1383 		error = ret;
1384 		goto done;
1385 	}
1386 
1387 	memsz = vm_snapshot_mem(ctx, fd_checkpoint, 0, true);
1388 	if (memsz == 0) {
1389 		perror("Could not write guest memory to file");
1390 		error = -1;
1391 		goto done;
1392 	}
1393 
1394 	ret = vm_snapshot_basic_metadata(ctx, xop, memsz);
1395 	if (ret != 0) {
1396 		fprintf(stderr, "Failed to snapshot vm basic metadata.\n");
1397 		error = -1;
1398 		goto done;
1399 	}
1400 
1401 
1402 	ret = vm_snapshot_kern_structs(ctx, kdata_fd, xop);
1403 	if (ret != 0) {
1404 		fprintf(stderr, "Failed to snapshot vm kernel data.\n");
1405 		error = -1;
1406 		goto done;
1407 	}
1408 
1409 	ret = vm_snapshot_user_devs(ctx, kdata_fd, xop);
1410 	if (ret != 0) {
1411 		fprintf(stderr, "Failed to snapshot device state.\n");
1412 		error = -1;
1413 		goto done;
1414 	}
1415 
1416 	xo_finish_h(xop);
1417 
1418 	if (stop_vm) {
1419 		vm_destroy(ctx);
1420 		exit(0);
1421 	}
1422 
1423 done:
1424 	ret = vm_resume_user_devs(ctx);
1425 	if (ret != 0)
1426 		fprintf(stderr, "Could not resume devices\r\n");
1427 	vm_vcpu_resume(ctx);
1428 	if (fd_checkpoint > 0)
1429 		close(fd_checkpoint);
1430 	if (meta_filename != NULL)
1431 		free(meta_filename);
1432 	if (kdata_filename != NULL)
1433 		free(kdata_filename);
1434 	if (xop != NULL)
1435 		xo_destroy(xop);
1436 	if (meta_file != NULL)
1437 		fclose(meta_file);
1438 	if (kdata_fd > 0)
1439 		close(kdata_fd);
1440 	return (error);
1441 }
1442 
1443 int
1444 handle_message(struct ipc_message *imsg, struct vmctx *ctx)
1445 {
1446 	int err;
1447 
1448 	switch (imsg->code) {
1449 		case START_CHECKPOINT:
1450 			err = vm_checkpoint(ctx, imsg->data.op.snapshot_filename, false);
1451 			break;
1452 		case START_SUSPEND:
1453 			err = vm_checkpoint(ctx, imsg->data.op.snapshot_filename, true);
1454 			break;
1455 		default:
1456 			EPRINTLN("Unrecognized checkpoint operation\n");
1457 			err = -1;
1458 	}
1459 
1460 	if (err != 0)
1461 		EPRINTLN("Unable to perform the requested operation\n");
1462 
1463 	return (err);
1464 }
1465 
1466 /*
1467  * Listen for commands from bhyvectl
1468  */
1469 void *
1470 checkpoint_thread(void *param)
1471 {
1472 	struct ipc_message imsg;
1473 	struct checkpoint_thread_info *thread_info;
1474 	ssize_t n;
1475 
1476 	pthread_set_name_np(pthread_self(), "checkpoint thread");
1477 	thread_info = (struct checkpoint_thread_info *)param;
1478 
1479 	for (;;) {
1480 		n = recvfrom(thread_info->socket_fd, &imsg, sizeof(imsg), 0, NULL, 0);
1481 
1482 		/*
1483 		 * slight sanity check: see if there's enough data to at
1484 		 * least determine the type of message.
1485 		 */
1486 		if (n >= sizeof(imsg.code))
1487 			handle_message(&imsg, thread_info->ctx);
1488 		else
1489 			EPRINTLN("Failed to receive message: %s\n",
1490 			    n == -1 ? strerror(errno) : "unknown error");
1491 	}
1492 
1493 	return (NULL);
1494 }
1495 
1496 void
1497 init_snapshot(void)
1498 {
1499 	int err;
1500 
1501 	err = pthread_mutex_init(&vcpu_lock, NULL);
1502 	if (err != 0)
1503 		errc(1, err, "checkpoint mutex init");
1504 	err = pthread_cond_init(&vcpus_idle, NULL);
1505 	if (err != 0)
1506 		errc(1, err, "checkpoint cv init (vcpus_idle)");
1507 	err = pthread_cond_init(&vcpus_can_run, NULL);
1508 	if (err != 0)
1509 		errc(1, err, "checkpoint cv init (vcpus_can_run)");
1510 }
1511 
1512 /*
1513  * Create the listening socket for IPC with bhyvectl
1514  */
1515 int
1516 init_checkpoint_thread(struct vmctx *ctx)
1517 {
1518 	struct checkpoint_thread_info *checkpoint_info = NULL;
1519 	struct sockaddr_un addr;
1520 	int socket_fd;
1521 	pthread_t checkpoint_pthread;
1522 	char vmname_buf[MAX_VMNAME];
1523 	int ret, err = 0;
1524 
1525 	memset(&addr, 0, sizeof(addr));
1526 
1527 	socket_fd = socket(PF_UNIX, SOCK_DGRAM, 0);
1528 	if (socket_fd < 0) {
1529 		EPRINTLN("Socket creation failed: %s", strerror(errno));
1530 		err = -1;
1531 		goto fail;
1532 	}
1533 
1534 	addr.sun_family = AF_UNIX;
1535 
1536 	err = vm_get_name(ctx, vmname_buf, MAX_VMNAME - 1);
1537 	if (err != 0) {
1538 		perror("Failed to get VM name");
1539 		goto fail;
1540 	}
1541 
1542 	snprintf(addr.sun_path, sizeof(addr.sun_path), "%s%s",
1543 		 BHYVE_RUN_DIR, vmname_buf);
1544 	addr.sun_len = SUN_LEN(&addr);
1545 	unlink(addr.sun_path);
1546 
1547 	if (bind(socket_fd, (struct sockaddr *)&addr, addr.sun_len) != 0) {
1548 		EPRINTLN("Failed to bind socket \"%s\": %s\n",
1549 		    addr.sun_path, strerror(errno));
1550 		err = -1;
1551 		goto fail;
1552 	}
1553 
1554 	checkpoint_info = calloc(1, sizeof(*checkpoint_info));
1555 	checkpoint_info->ctx = ctx;
1556 	checkpoint_info->socket_fd = socket_fd;
1557 
1558 	ret = pthread_create(&checkpoint_pthread, NULL, checkpoint_thread,
1559 		checkpoint_info);
1560 	if (ret < 0) {
1561 		err = ret;
1562 		goto fail;
1563 	}
1564 
1565 	return (0);
1566 fail:
1567 	free(checkpoint_info);
1568 	if (socket_fd > 0)
1569 		close(socket_fd);
1570 	unlink(addr.sun_path);
1571 
1572 	return (err);
1573 }
1574 
1575 void
1576 vm_snapshot_buf_err(const char *bufname, const enum vm_snapshot_op op)
1577 {
1578 	const char *__op;
1579 
1580 	if (op == VM_SNAPSHOT_SAVE)
1581 		__op = "save";
1582 	else if (op == VM_SNAPSHOT_RESTORE)
1583 		__op = "restore";
1584 	else
1585 		__op = "unknown";
1586 
1587 	fprintf(stderr, "%s: snapshot-%s failed for %s\r\n",
1588 		__func__, __op, bufname);
1589 }
1590 
1591 int
1592 vm_snapshot_buf(volatile void *data, size_t data_size,
1593 		struct vm_snapshot_meta *meta)
1594 {
1595 	struct vm_snapshot_buffer *buffer;
1596 	int op;
1597 
1598 	buffer = &meta->buffer;
1599 	op = meta->op;
1600 
1601 	if (buffer->buf_rem < data_size) {
1602 		fprintf(stderr, "%s: buffer too small\r\n", __func__);
1603 		return (E2BIG);
1604 	}
1605 
1606 	if (op == VM_SNAPSHOT_SAVE)
1607 		memcpy(buffer->buf, (uint8_t *) data, data_size);
1608 	else if (op == VM_SNAPSHOT_RESTORE)
1609 		memcpy((uint8_t *) data, buffer->buf, data_size);
1610 	else
1611 		return (EINVAL);
1612 
1613 	buffer->buf += data_size;
1614 	buffer->buf_rem -= data_size;
1615 
1616 	return (0);
1617 }
1618 
1619 size_t
1620 vm_get_snapshot_size(struct vm_snapshot_meta *meta)
1621 {
1622 	size_t length;
1623 	struct vm_snapshot_buffer *buffer;
1624 
1625 	buffer = &meta->buffer;
1626 
1627 	if (buffer->buf_size < buffer->buf_rem) {
1628 		fprintf(stderr, "%s: Invalid buffer: size = %zu, rem = %zu\r\n",
1629 			__func__, buffer->buf_size, buffer->buf_rem);
1630 		length = 0;
1631 	} else {
1632 		length = buffer->buf_size - buffer->buf_rem;
1633 	}
1634 
1635 	return (length);
1636 }
1637 
1638 int
1639 vm_snapshot_guest2host_addr(void **addrp, size_t len, bool restore_null,
1640 			    struct vm_snapshot_meta *meta)
1641 {
1642 	int ret;
1643 	vm_paddr_t gaddr;
1644 
1645 	if (meta->op == VM_SNAPSHOT_SAVE) {
1646 		gaddr = paddr_host2guest(meta->ctx, *addrp);
1647 		if (gaddr == (vm_paddr_t) -1) {
1648 			if (!restore_null ||
1649 			    (restore_null && (*addrp != NULL))) {
1650 				ret = EFAULT;
1651 				goto done;
1652 			}
1653 		}
1654 
1655 		SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1656 	} else if (meta->op == VM_SNAPSHOT_RESTORE) {
1657 		SNAPSHOT_VAR_OR_LEAVE(gaddr, meta, ret, done);
1658 		if (gaddr == (vm_paddr_t) -1) {
1659 			if (!restore_null) {
1660 				ret = EFAULT;
1661 				goto done;
1662 			}
1663 		}
1664 
1665 		*addrp = paddr_guest2host(meta->ctx, gaddr, len);
1666 	} else {
1667 		ret = EINVAL;
1668 	}
1669 
1670 done:
1671 	return (ret);
1672 }
1673 
1674 int
1675 vm_snapshot_buf_cmp(volatile void *data, size_t data_size,
1676 		    struct vm_snapshot_meta *meta)
1677 {
1678 	struct vm_snapshot_buffer *buffer;
1679 	int op;
1680 	int ret;
1681 
1682 	buffer = &meta->buffer;
1683 	op = meta->op;
1684 
1685 	if (buffer->buf_rem < data_size) {
1686 		fprintf(stderr, "%s: buffer too small\r\n", __func__);
1687 		ret = E2BIG;
1688 		goto done;
1689 	}
1690 
1691 	if (op == VM_SNAPSHOT_SAVE) {
1692 		ret = 0;
1693 		memcpy(buffer->buf, (uint8_t *) data, data_size);
1694 	} else if (op == VM_SNAPSHOT_RESTORE) {
1695 		ret = memcmp((uint8_t *) data, buffer->buf, data_size);
1696 	} else {
1697 		ret = EINVAL;
1698 		goto done;
1699 	}
1700 
1701 	buffer->buf += data_size;
1702 	buffer->buf_rem -= data_size;
1703 
1704 done:
1705 	return (ret);
1706 }
1707