xref: /freebsd/sys/amd64/vmm/vmm_instruction_emul.c (revision 43a5ec4eb41567cc92586503212743d89686d78f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012 Sandvine, Inc.
5  * Copyright (c) 2012 NetApp, Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #ifdef _KERNEL
36 #include <sys/param.h>
37 #include <sys/pcpu.h>
38 #include <sys/systm.h>
39 #include <sys/proc.h>
40 
41 #include <vm/vm.h>
42 #include <vm/pmap.h>
43 
44 #include <machine/vmparam.h>
45 #include <machine/vmm.h>
46 #else	/* !_KERNEL */
47 #include <sys/types.h>
48 #include <sys/errno.h>
49 #include <sys/_iovec.h>
50 
51 #include <machine/vmm.h>
52 
53 #include <err.h>
54 #include <assert.h>
55 #include <stdbool.h>
56 #include <stddef.h>
57 #include <stdio.h>
58 #include <string.h>
59 #include <strings.h>
60 #include <vmmapi.h>
61 #define	KASSERT(exp,msg)	assert((exp))
62 #define	panic(...)		errx(4, __VA_ARGS__)
63 #endif	/* _KERNEL */
64 
65 #include <machine/vmm_instruction_emul.h>
66 #include <x86/psl.h>
67 #include <x86/specialreg.h>
68 
69 /* struct vie_op.op_type */
70 enum {
71 	VIE_OP_TYPE_NONE = 0,
72 	VIE_OP_TYPE_MOV,
73 	VIE_OP_TYPE_MOVSX,
74 	VIE_OP_TYPE_MOVZX,
75 	VIE_OP_TYPE_AND,
76 	VIE_OP_TYPE_OR,
77 	VIE_OP_TYPE_SUB,
78 	VIE_OP_TYPE_TWO_BYTE,
79 	VIE_OP_TYPE_PUSH,
80 	VIE_OP_TYPE_CMP,
81 	VIE_OP_TYPE_POP,
82 	VIE_OP_TYPE_MOVS,
83 	VIE_OP_TYPE_GROUP1,
84 	VIE_OP_TYPE_STOS,
85 	VIE_OP_TYPE_BITTEST,
86 	VIE_OP_TYPE_TWOB_GRP15,
87 	VIE_OP_TYPE_ADD,
88 	VIE_OP_TYPE_TEST,
89 	VIE_OP_TYPE_BEXTR,
90 	VIE_OP_TYPE_LAST
91 };
92 
93 /* struct vie_op.op_flags */
94 #define	VIE_OP_F_IMM		(1 << 0)  /* 16/32-bit immediate operand */
95 #define	VIE_OP_F_IMM8		(1 << 1)  /* 8-bit immediate operand */
96 #define	VIE_OP_F_MOFFSET	(1 << 2)  /* 16/32/64-bit immediate moffset */
97 #define	VIE_OP_F_NO_MODRM	(1 << 3)
98 #define	VIE_OP_F_NO_GLA_VERIFICATION (1 << 4)
99 
100 static const struct vie_op three_byte_opcodes_0f38[256] = {
101 	[0xF7] = {
102 		.op_byte = 0xF7,
103 		.op_type = VIE_OP_TYPE_BEXTR,
104 	},
105 };
106 
107 static const struct vie_op two_byte_opcodes[256] = {
108 	[0xAE] = {
109 		.op_byte = 0xAE,
110 		.op_type = VIE_OP_TYPE_TWOB_GRP15,
111 	},
112 	[0xB6] = {
113 		.op_byte = 0xB6,
114 		.op_type = VIE_OP_TYPE_MOVZX,
115 	},
116 	[0xB7] = {
117 		.op_byte = 0xB7,
118 		.op_type = VIE_OP_TYPE_MOVZX,
119 	},
120 	[0xBA] = {
121 		.op_byte = 0xBA,
122 		.op_type = VIE_OP_TYPE_BITTEST,
123 		.op_flags = VIE_OP_F_IMM8,
124 	},
125 	[0xBE] = {
126 		.op_byte = 0xBE,
127 		.op_type = VIE_OP_TYPE_MOVSX,
128 	},
129 };
130 
131 static const struct vie_op one_byte_opcodes[256] = {
132 	[0x03] = {
133 		.op_byte = 0x03,
134 		.op_type = VIE_OP_TYPE_ADD,
135 	},
136 	[0x0F] = {
137 		.op_byte = 0x0F,
138 		.op_type = VIE_OP_TYPE_TWO_BYTE
139 	},
140 	[0x0B] = {
141 		.op_byte = 0x0B,
142 		.op_type = VIE_OP_TYPE_OR,
143 	},
144 	[0x2B] = {
145 		.op_byte = 0x2B,
146 		.op_type = VIE_OP_TYPE_SUB,
147 	},
148 	[0x39] = {
149 		.op_byte = 0x39,
150 		.op_type = VIE_OP_TYPE_CMP,
151 	},
152 	[0x3B] = {
153 		.op_byte = 0x3B,
154 		.op_type = VIE_OP_TYPE_CMP,
155 	},
156 	[0x88] = {
157 		.op_byte = 0x88,
158 		.op_type = VIE_OP_TYPE_MOV,
159 	},
160 	[0x89] = {
161 		.op_byte = 0x89,
162 		.op_type = VIE_OP_TYPE_MOV,
163 	},
164 	[0x8A] = {
165 		.op_byte = 0x8A,
166 		.op_type = VIE_OP_TYPE_MOV,
167 	},
168 	[0x8B] = {
169 		.op_byte = 0x8B,
170 		.op_type = VIE_OP_TYPE_MOV,
171 	},
172 	[0xA1] = {
173 		.op_byte = 0xA1,
174 		.op_type = VIE_OP_TYPE_MOV,
175 		.op_flags = VIE_OP_F_MOFFSET | VIE_OP_F_NO_MODRM,
176 	},
177 	[0xA3] = {
178 		.op_byte = 0xA3,
179 		.op_type = VIE_OP_TYPE_MOV,
180 		.op_flags = VIE_OP_F_MOFFSET | VIE_OP_F_NO_MODRM,
181 	},
182 	[0xA4] = {
183 		.op_byte = 0xA4,
184 		.op_type = VIE_OP_TYPE_MOVS,
185 		.op_flags = VIE_OP_F_NO_MODRM | VIE_OP_F_NO_GLA_VERIFICATION
186 	},
187 	[0xA5] = {
188 		.op_byte = 0xA5,
189 		.op_type = VIE_OP_TYPE_MOVS,
190 		.op_flags = VIE_OP_F_NO_MODRM | VIE_OP_F_NO_GLA_VERIFICATION
191 	},
192 	[0xAA] = {
193 		.op_byte = 0xAA,
194 		.op_type = VIE_OP_TYPE_STOS,
195 		.op_flags = VIE_OP_F_NO_MODRM | VIE_OP_F_NO_GLA_VERIFICATION
196 	},
197 	[0xAB] = {
198 		.op_byte = 0xAB,
199 		.op_type = VIE_OP_TYPE_STOS,
200 		.op_flags = VIE_OP_F_NO_MODRM | VIE_OP_F_NO_GLA_VERIFICATION
201 	},
202 	[0xC6] = {
203 		/* XXX Group 11 extended opcode - not just MOV */
204 		.op_byte = 0xC6,
205 		.op_type = VIE_OP_TYPE_MOV,
206 		.op_flags = VIE_OP_F_IMM8,
207 	},
208 	[0xC7] = {
209 		.op_byte = 0xC7,
210 		.op_type = VIE_OP_TYPE_MOV,
211 		.op_flags = VIE_OP_F_IMM,
212 	},
213 	[0x23] = {
214 		.op_byte = 0x23,
215 		.op_type = VIE_OP_TYPE_AND,
216 	},
217 	[0x80] = {
218 		/* Group 1 extended opcode */
219 		.op_byte = 0x80,
220 		.op_type = VIE_OP_TYPE_GROUP1,
221 		.op_flags = VIE_OP_F_IMM8,
222 	},
223 	[0x81] = {
224 		/* Group 1 extended opcode */
225 		.op_byte = 0x81,
226 		.op_type = VIE_OP_TYPE_GROUP1,
227 		.op_flags = VIE_OP_F_IMM,
228 	},
229 	[0x83] = {
230 		/* Group 1 extended opcode */
231 		.op_byte = 0x83,
232 		.op_type = VIE_OP_TYPE_GROUP1,
233 		.op_flags = VIE_OP_F_IMM8,
234 	},
235 	[0x8F] = {
236 		/* XXX Group 1A extended opcode - not just POP */
237 		.op_byte = 0x8F,
238 		.op_type = VIE_OP_TYPE_POP,
239 	},
240 	[0xF7] = {
241 		/* XXX Group 3 extended opcode - not just TEST */
242 		.op_byte = 0xF7,
243 		.op_type = VIE_OP_TYPE_TEST,
244 		.op_flags = VIE_OP_F_IMM,
245 	},
246 	[0xFF] = {
247 		/* XXX Group 5 extended opcode - not just PUSH */
248 		.op_byte = 0xFF,
249 		.op_type = VIE_OP_TYPE_PUSH,
250 	}
251 };
252 
253 /* struct vie.mod */
254 #define	VIE_MOD_INDIRECT		0
255 #define	VIE_MOD_INDIRECT_DISP8		1
256 #define	VIE_MOD_INDIRECT_DISP32		2
257 #define	VIE_MOD_DIRECT			3
258 
259 /* struct vie.rm */
260 #define	VIE_RM_SIB			4
261 #define	VIE_RM_DISP32			5
262 
263 #define	GB				(1024 * 1024 * 1024)
264 
265 static enum vm_reg_name gpr_map[16] = {
266 	VM_REG_GUEST_RAX,
267 	VM_REG_GUEST_RCX,
268 	VM_REG_GUEST_RDX,
269 	VM_REG_GUEST_RBX,
270 	VM_REG_GUEST_RSP,
271 	VM_REG_GUEST_RBP,
272 	VM_REG_GUEST_RSI,
273 	VM_REG_GUEST_RDI,
274 	VM_REG_GUEST_R8,
275 	VM_REG_GUEST_R9,
276 	VM_REG_GUEST_R10,
277 	VM_REG_GUEST_R11,
278 	VM_REG_GUEST_R12,
279 	VM_REG_GUEST_R13,
280 	VM_REG_GUEST_R14,
281 	VM_REG_GUEST_R15
282 };
283 
284 static uint64_t size2mask[] = {
285 	[1] = 0xff,
286 	[2] = 0xffff,
287 	[4] = 0xffffffff,
288 	[8] = 0xffffffffffffffff,
289 };
290 
291 static int
292 vie_read_register(void *vm, int vcpuid, enum vm_reg_name reg, uint64_t *rval)
293 {
294 	int error;
295 
296 	error = vm_get_register(vm, vcpuid, reg, rval);
297 
298 	return (error);
299 }
300 
301 static void
302 vie_calc_bytereg(struct vie *vie, enum vm_reg_name *reg, int *lhbr)
303 {
304 	*lhbr = 0;
305 	*reg = gpr_map[vie->reg];
306 
307 	/*
308 	 * 64-bit mode imposes limitations on accessing legacy high byte
309 	 * registers (lhbr).
310 	 *
311 	 * The legacy high-byte registers cannot be addressed if the REX
312 	 * prefix is present. In this case the values 4, 5, 6 and 7 of the
313 	 * 'ModRM:reg' field address %spl, %bpl, %sil and %dil respectively.
314 	 *
315 	 * If the REX prefix is not present then the values 4, 5, 6 and 7
316 	 * of the 'ModRM:reg' field address the legacy high-byte registers,
317 	 * %ah, %ch, %dh and %bh respectively.
318 	 */
319 	if (!vie->rex_present) {
320 		if (vie->reg & 0x4) {
321 			*lhbr = 1;
322 			*reg = gpr_map[vie->reg & 0x3];
323 		}
324 	}
325 }
326 
327 static int
328 vie_read_bytereg(void *vm, int vcpuid, struct vie *vie, uint8_t *rval)
329 {
330 	uint64_t val;
331 	int error, lhbr;
332 	enum vm_reg_name reg;
333 
334 	vie_calc_bytereg(vie, &reg, &lhbr);
335 	error = vm_get_register(vm, vcpuid, reg, &val);
336 
337 	/*
338 	 * To obtain the value of a legacy high byte register shift the
339 	 * base register right by 8 bits (%ah = %rax >> 8).
340 	 */
341 	if (lhbr)
342 		*rval = val >> 8;
343 	else
344 		*rval = val;
345 	return (error);
346 }
347 
348 static int
349 vie_write_bytereg(void *vm, int vcpuid, struct vie *vie, uint8_t byte)
350 {
351 	uint64_t origval, val, mask;
352 	int error, lhbr;
353 	enum vm_reg_name reg;
354 
355 	vie_calc_bytereg(vie, &reg, &lhbr);
356 	error = vm_get_register(vm, vcpuid, reg, &origval);
357 	if (error == 0) {
358 		val = byte;
359 		mask = 0xff;
360 		if (lhbr) {
361 			/*
362 			 * Shift left by 8 to store 'byte' in a legacy high
363 			 * byte register.
364 			 */
365 			val <<= 8;
366 			mask <<= 8;
367 		}
368 		val |= origval & ~mask;
369 		error = vm_set_register(vm, vcpuid, reg, val);
370 	}
371 	return (error);
372 }
373 
374 int
375 vie_update_register(void *vm, int vcpuid, enum vm_reg_name reg,
376 		    uint64_t val, int size)
377 {
378 	int error;
379 	uint64_t origval;
380 
381 	switch (size) {
382 	case 1:
383 	case 2:
384 		error = vie_read_register(vm, vcpuid, reg, &origval);
385 		if (error)
386 			return (error);
387 		val &= size2mask[size];
388 		val |= origval & ~size2mask[size];
389 		break;
390 	case 4:
391 		val &= 0xffffffffUL;
392 		break;
393 	case 8:
394 		break;
395 	default:
396 		return (EINVAL);
397 	}
398 
399 	error = vm_set_register(vm, vcpuid, reg, val);
400 	return (error);
401 }
402 
403 #define	RFLAGS_STATUS_BITS    (PSL_C | PSL_PF | PSL_AF | PSL_Z | PSL_N | PSL_V)
404 
405 /*
406  * Return the status flags that would result from doing (x - y).
407  */
408 #define	GETCC(sz)							\
409 static u_long								\
410 getcc##sz(uint##sz##_t x, uint##sz##_t y)				\
411 {									\
412 	u_long rflags;							\
413 									\
414 	__asm __volatile("sub %2,%1; pushfq; popq %0" :			\
415 	    "=r" (rflags), "+r" (x) : "m" (y));				\
416 	return (rflags);						\
417 } struct __hack
418 
419 GETCC(8);
420 GETCC(16);
421 GETCC(32);
422 GETCC(64);
423 
424 static u_long
425 getcc(int opsize, uint64_t x, uint64_t y)
426 {
427 	KASSERT(opsize == 1 || opsize == 2 || opsize == 4 || opsize == 8,
428 	    ("getcc: invalid operand size %d", opsize));
429 
430 	if (opsize == 1)
431 		return (getcc8(x, y));
432 	else if (opsize == 2)
433 		return (getcc16(x, y));
434 	else if (opsize == 4)
435 		return (getcc32(x, y));
436 	else
437 		return (getcc64(x, y));
438 }
439 
440 /*
441  * Macro creation of functions getaddflags{8,16,32,64}
442  */
443 #define	GETADDFLAGS(sz)							\
444 static u_long								\
445 getaddflags##sz(uint##sz##_t x, uint##sz##_t y)				\
446 {									\
447 	u_long rflags;							\
448 									\
449 	__asm __volatile("add %2,%1; pushfq; popq %0" :			\
450 	    "=r" (rflags), "+r" (x) : "m" (y));				\
451 	return (rflags);						\
452 } struct __hack
453 
454 GETADDFLAGS(8);
455 GETADDFLAGS(16);
456 GETADDFLAGS(32);
457 GETADDFLAGS(64);
458 
459 static u_long
460 getaddflags(int opsize, uint64_t x, uint64_t y)
461 {
462 	KASSERT(opsize == 1 || opsize == 2 || opsize == 4 || opsize == 8,
463 	    ("getaddflags: invalid operand size %d", opsize));
464 
465 	if (opsize == 1)
466 		return (getaddflags8(x, y));
467 	else if (opsize == 2)
468 		return (getaddflags16(x, y));
469 	else if (opsize == 4)
470 		return (getaddflags32(x, y));
471 	else
472 		return (getaddflags64(x, y));
473 }
474 
475 /*
476  * Return the status flags that would result from doing (x & y).
477  */
478 #define	GETANDFLAGS(sz)							\
479 static u_long								\
480 getandflags##sz(uint##sz##_t x, uint##sz##_t y)				\
481 {									\
482 	u_long rflags;							\
483 									\
484 	__asm __volatile("and %2,%1; pushfq; popq %0" :			\
485 	    "=r" (rflags), "+r" (x) : "m" (y));				\
486 	return (rflags);						\
487 } struct __hack
488 
489 GETANDFLAGS(8);
490 GETANDFLAGS(16);
491 GETANDFLAGS(32);
492 GETANDFLAGS(64);
493 
494 static u_long
495 getandflags(int opsize, uint64_t x, uint64_t y)
496 {
497 	KASSERT(opsize == 1 || opsize == 2 || opsize == 4 || opsize == 8,
498 	    ("getandflags: invalid operand size %d", opsize));
499 
500 	if (opsize == 1)
501 		return (getandflags8(x, y));
502 	else if (opsize == 2)
503 		return (getandflags16(x, y));
504 	else if (opsize == 4)
505 		return (getandflags32(x, y));
506 	else
507 		return (getandflags64(x, y));
508 }
509 
510 static int
511 emulate_mov(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
512 	    mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
513 {
514 	int error, size;
515 	enum vm_reg_name reg;
516 	uint8_t byte;
517 	uint64_t val;
518 
519 	size = vie->opsize;
520 	error = EINVAL;
521 
522 	switch (vie->op.op_byte) {
523 	case 0x88:
524 		/*
525 		 * MOV byte from reg (ModRM:reg) to mem (ModRM:r/m)
526 		 * 88/r:	mov r/m8, r8
527 		 * REX + 88/r:	mov r/m8, r8 (%ah, %ch, %dh, %bh not available)
528 		 */
529 		size = 1;	/* override for byte operation */
530 		error = vie_read_bytereg(vm, vcpuid, vie, &byte);
531 		if (error == 0)
532 			error = memwrite(vm, vcpuid, gpa, byte, size, arg);
533 		break;
534 	case 0x89:
535 		/*
536 		 * MOV from reg (ModRM:reg) to mem (ModRM:r/m)
537 		 * 89/r:	mov r/m16, r16
538 		 * 89/r:	mov r/m32, r32
539 		 * REX.W + 89/r	mov r/m64, r64
540 		 */
541 		reg = gpr_map[vie->reg];
542 		error = vie_read_register(vm, vcpuid, reg, &val);
543 		if (error == 0) {
544 			val &= size2mask[size];
545 			error = memwrite(vm, vcpuid, gpa, val, size, arg);
546 		}
547 		break;
548 	case 0x8A:
549 		/*
550 		 * MOV byte from mem (ModRM:r/m) to reg (ModRM:reg)
551 		 * 8A/r:	mov r8, r/m8
552 		 * REX + 8A/r:	mov r8, r/m8
553 		 */
554 		size = 1;	/* override for byte operation */
555 		error = memread(vm, vcpuid, gpa, &val, size, arg);
556 		if (error == 0)
557 			error = vie_write_bytereg(vm, vcpuid, vie, val);
558 		break;
559 	case 0x8B:
560 		/*
561 		 * MOV from mem (ModRM:r/m) to reg (ModRM:reg)
562 		 * 8B/r:	mov r16, r/m16
563 		 * 8B/r:	mov r32, r/m32
564 		 * REX.W 8B/r:	mov r64, r/m64
565 		 */
566 		error = memread(vm, vcpuid, gpa, &val, size, arg);
567 		if (error == 0) {
568 			reg = gpr_map[vie->reg];
569 			error = vie_update_register(vm, vcpuid, reg, val, size);
570 		}
571 		break;
572 	case 0xA1:
573 		/*
574 		 * MOV from seg:moffset to AX/EAX/RAX
575 		 * A1:		mov AX, moffs16
576 		 * A1:		mov EAX, moffs32
577 		 * REX.W + A1:	mov RAX, moffs64
578 		 */
579 		error = memread(vm, vcpuid, gpa, &val, size, arg);
580 		if (error == 0) {
581 			reg = VM_REG_GUEST_RAX;
582 			error = vie_update_register(vm, vcpuid, reg, val, size);
583 		}
584 		break;
585 	case 0xA3:
586 		/*
587 		 * MOV from AX/EAX/RAX to seg:moffset
588 		 * A3:		mov moffs16, AX
589 		 * A3:		mov moffs32, EAX
590 		 * REX.W + A3:	mov moffs64, RAX
591 		 */
592 		error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RAX, &val);
593 		if (error == 0) {
594 			val &= size2mask[size];
595 			error = memwrite(vm, vcpuid, gpa, val, size, arg);
596 		}
597 		break;
598 	case 0xC6:
599 		/*
600 		 * MOV from imm8 to mem (ModRM:r/m)
601 		 * C6/0		mov r/m8, imm8
602 		 * REX + C6/0	mov r/m8, imm8
603 		 */
604 		size = 1;	/* override for byte operation */
605 		error = memwrite(vm, vcpuid, gpa, vie->immediate, size, arg);
606 		break;
607 	case 0xC7:
608 		/*
609 		 * MOV from imm16/imm32 to mem (ModRM:r/m)
610 		 * C7/0		mov r/m16, imm16
611 		 * C7/0		mov r/m32, imm32
612 		 * REX.W + C7/0	mov r/m64, imm32 (sign-extended to 64-bits)
613 		 */
614 		val = vie->immediate & size2mask[size];
615 		error = memwrite(vm, vcpuid, gpa, val, size, arg);
616 		break;
617 	default:
618 		break;
619 	}
620 
621 	return (error);
622 }
623 
624 static int
625 emulate_movx(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
626 	     mem_region_read_t memread, mem_region_write_t memwrite,
627 	     void *arg)
628 {
629 	int error, size;
630 	enum vm_reg_name reg;
631 	uint64_t val;
632 
633 	size = vie->opsize;
634 	error = EINVAL;
635 
636 	switch (vie->op.op_byte) {
637 	case 0xB6:
638 		/*
639 		 * MOV and zero extend byte from mem (ModRM:r/m) to
640 		 * reg (ModRM:reg).
641 		 *
642 		 * 0F B6/r		movzx r16, r/m8
643 		 * 0F B6/r		movzx r32, r/m8
644 		 * REX.W + 0F B6/r	movzx r64, r/m8
645 		 */
646 
647 		/* get the first operand */
648 		error = memread(vm, vcpuid, gpa, &val, 1, arg);
649 		if (error)
650 			break;
651 
652 		/* get the second operand */
653 		reg = gpr_map[vie->reg];
654 
655 		/* zero-extend byte */
656 		val = (uint8_t)val;
657 
658 		/* write the result */
659 		error = vie_update_register(vm, vcpuid, reg, val, size);
660 		break;
661 	case 0xB7:
662 		/*
663 		 * MOV and zero extend word from mem (ModRM:r/m) to
664 		 * reg (ModRM:reg).
665 		 *
666 		 * 0F B7/r		movzx r32, r/m16
667 		 * REX.W + 0F B7/r	movzx r64, r/m16
668 		 */
669 		error = memread(vm, vcpuid, gpa, &val, 2, arg);
670 		if (error)
671 			return (error);
672 
673 		reg = gpr_map[vie->reg];
674 
675 		/* zero-extend word */
676 		val = (uint16_t)val;
677 
678 		error = vie_update_register(vm, vcpuid, reg, val, size);
679 		break;
680 	case 0xBE:
681 		/*
682 		 * MOV and sign extend byte from mem (ModRM:r/m) to
683 		 * reg (ModRM:reg).
684 		 *
685 		 * 0F BE/r		movsx r16, r/m8
686 		 * 0F BE/r		movsx r32, r/m8
687 		 * REX.W + 0F BE/r	movsx r64, r/m8
688 		 */
689 
690 		/* get the first operand */
691 		error = memread(vm, vcpuid, gpa, &val, 1, arg);
692 		if (error)
693 			break;
694 
695 		/* get the second operand */
696 		reg = gpr_map[vie->reg];
697 
698 		/* sign extend byte */
699 		val = (int8_t)val;
700 
701 		/* write the result */
702 		error = vie_update_register(vm, vcpuid, reg, val, size);
703 		break;
704 	default:
705 		break;
706 	}
707 	return (error);
708 }
709 
710 /*
711  * Helper function to calculate and validate a linear address.
712  */
713 static int
714 get_gla(void *vm, int vcpuid, struct vie *vie, struct vm_guest_paging *paging,
715     int opsize, int addrsize, int prot, enum vm_reg_name seg,
716     enum vm_reg_name gpr, uint64_t *gla, int *fault)
717 {
718 	struct seg_desc desc;
719 	uint64_t cr0, val, rflags;
720 	int error;
721 
722 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_CR0, &cr0);
723 	KASSERT(error == 0, ("%s: error %d getting cr0", __func__, error));
724 
725 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
726 	KASSERT(error == 0, ("%s: error %d getting rflags", __func__, error));
727 
728 	error = vm_get_seg_desc(vm, vcpuid, seg, &desc);
729 	KASSERT(error == 0, ("%s: error %d getting segment descriptor %d",
730 	    __func__, error, seg));
731 
732 	error = vie_read_register(vm, vcpuid, gpr, &val);
733 	KASSERT(error == 0, ("%s: error %d getting register %d", __func__,
734 	    error, gpr));
735 
736 	if (vie_calculate_gla(paging->cpu_mode, seg, &desc, val, opsize,
737 	    addrsize, prot, gla)) {
738 		if (seg == VM_REG_GUEST_SS)
739 			vm_inject_ss(vm, vcpuid, 0);
740 		else
741 			vm_inject_gp(vm, vcpuid);
742 		goto guest_fault;
743 	}
744 
745 	if (vie_canonical_check(paging->cpu_mode, *gla)) {
746 		if (seg == VM_REG_GUEST_SS)
747 			vm_inject_ss(vm, vcpuid, 0);
748 		else
749 			vm_inject_gp(vm, vcpuid);
750 		goto guest_fault;
751 	}
752 
753 	if (vie_alignment_check(paging->cpl, opsize, cr0, rflags, *gla)) {
754 		vm_inject_ac(vm, vcpuid, 0);
755 		goto guest_fault;
756 	}
757 
758 	*fault = 0;
759 	return (0);
760 
761 guest_fault:
762 	*fault = 1;
763 	return (0);
764 }
765 
766 static int
767 emulate_movs(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
768     struct vm_guest_paging *paging, mem_region_read_t memread,
769     mem_region_write_t memwrite, void *arg)
770 {
771 #ifdef _KERNEL
772 	struct vm_copyinfo copyinfo[2];
773 #else
774 	struct iovec copyinfo[2];
775 #endif
776 	uint64_t dstaddr, srcaddr, dstgpa, srcgpa, val;
777 	uint64_t rcx, rdi, rsi, rflags;
778 	int error, fault, opsize, seg, repeat;
779 
780 	opsize = (vie->op.op_byte == 0xA4) ? 1 : vie->opsize;
781 	val = 0;
782 	error = 0;
783 
784 	/*
785 	 * XXX although the MOVS instruction is only supposed to be used with
786 	 * the "rep" prefix some guests like FreeBSD will use "repnz" instead.
787 	 *
788 	 * Empirically the "repnz" prefix has identical behavior to "rep"
789 	 * and the zero flag does not make a difference.
790 	 */
791 	repeat = vie->repz_present | vie->repnz_present;
792 
793 	if (repeat) {
794 		error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RCX, &rcx);
795 		KASSERT(!error, ("%s: error %d getting rcx", __func__, error));
796 
797 		/*
798 		 * The count register is %rcx, %ecx or %cx depending on the
799 		 * address size of the instruction.
800 		 */
801 		if ((rcx & vie_size2mask(vie->addrsize)) == 0) {
802 			error = 0;
803 			goto done;
804 		}
805 	}
806 
807 	/*
808 	 *	Source		Destination	Comments
809 	 *	--------------------------------------------
810 	 * (1)  memory		memory		n/a
811 	 * (2)  memory		mmio		emulated
812 	 * (3)  mmio		memory		emulated
813 	 * (4)  mmio		mmio		emulated
814 	 *
815 	 * At this point we don't have sufficient information to distinguish
816 	 * between (2), (3) and (4). We use 'vm_copy_setup()' to tease this
817 	 * out because it will succeed only when operating on regular memory.
818 	 *
819 	 * XXX the emulation doesn't properly handle the case where 'gpa'
820 	 * is straddling the boundary between the normal memory and MMIO.
821 	 */
822 
823 	seg = vie->segment_override ? vie->segment_register : VM_REG_GUEST_DS;
824 	error = get_gla(vm, vcpuid, vie, paging, opsize, vie->addrsize,
825 	    PROT_READ, seg, VM_REG_GUEST_RSI, &srcaddr, &fault);
826 	if (error || fault)
827 		goto done;
828 
829 	error = vm_copy_setup(vm, vcpuid, paging, srcaddr, opsize, PROT_READ,
830 	    copyinfo, nitems(copyinfo), &fault);
831 	if (error == 0) {
832 		if (fault)
833 			goto done;	/* Resume guest to handle fault */
834 
835 		/*
836 		 * case (2): read from system memory and write to mmio.
837 		 */
838 		vm_copyin(vm, vcpuid, copyinfo, &val, opsize);
839 		vm_copy_teardown(vm, vcpuid, copyinfo, nitems(copyinfo));
840 		error = memwrite(vm, vcpuid, gpa, val, opsize, arg);
841 		if (error)
842 			goto done;
843 	} else {
844 		/*
845 		 * 'vm_copy_setup()' is expected to fail for cases (3) and (4)
846 		 * if 'srcaddr' is in the mmio space.
847 		 */
848 
849 		error = get_gla(vm, vcpuid, vie, paging, opsize, vie->addrsize,
850 		    PROT_WRITE, VM_REG_GUEST_ES, VM_REG_GUEST_RDI, &dstaddr,
851 		    &fault);
852 		if (error || fault)
853 			goto done;
854 
855 		error = vm_copy_setup(vm, vcpuid, paging, dstaddr, opsize,
856 		    PROT_WRITE, copyinfo, nitems(copyinfo), &fault);
857 		if (error == 0) {
858 			if (fault)
859 				goto done;    /* Resume guest to handle fault */
860 
861 			/*
862 			 * case (3): read from MMIO and write to system memory.
863 			 *
864 			 * A MMIO read can have side-effects so we
865 			 * commit to it only after vm_copy_setup() is
866 			 * successful. If a page-fault needs to be
867 			 * injected into the guest then it will happen
868 			 * before the MMIO read is attempted.
869 			 */
870 			error = memread(vm, vcpuid, gpa, &val, opsize, arg);
871 			if (error)
872 				goto done;
873 
874 			vm_copyout(vm, vcpuid, &val, copyinfo, opsize);
875 			vm_copy_teardown(vm, vcpuid, copyinfo, nitems(copyinfo));
876 		} else {
877 			/*
878 			 * Case (4): read from and write to mmio.
879 			 *
880 			 * Commit to the MMIO read/write (with potential
881 			 * side-effects) only after we are sure that the
882 			 * instruction is not going to be restarted due
883 			 * to address translation faults.
884 			 */
885 			error = vm_gla2gpa(vm, vcpuid, paging, srcaddr,
886 			    PROT_READ, &srcgpa, &fault);
887 			if (error || fault)
888 				goto done;
889 
890 			error = vm_gla2gpa(vm, vcpuid, paging, dstaddr,
891 			   PROT_WRITE, &dstgpa, &fault);
892 			if (error || fault)
893 				goto done;
894 
895 			error = memread(vm, vcpuid, srcgpa, &val, opsize, arg);
896 			if (error)
897 				goto done;
898 
899 			error = memwrite(vm, vcpuid, dstgpa, val, opsize, arg);
900 			if (error)
901 				goto done;
902 		}
903 	}
904 
905 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RSI, &rsi);
906 	KASSERT(error == 0, ("%s: error %d getting rsi", __func__, error));
907 
908 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RDI, &rdi);
909 	KASSERT(error == 0, ("%s: error %d getting rdi", __func__, error));
910 
911 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
912 	KASSERT(error == 0, ("%s: error %d getting rflags", __func__, error));
913 
914 	if (rflags & PSL_D) {
915 		rsi -= opsize;
916 		rdi -= opsize;
917 	} else {
918 		rsi += opsize;
919 		rdi += opsize;
920 	}
921 
922 	error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RSI, rsi,
923 	    vie->addrsize);
924 	KASSERT(error == 0, ("%s: error %d updating rsi", __func__, error));
925 
926 	error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RDI, rdi,
927 	    vie->addrsize);
928 	KASSERT(error == 0, ("%s: error %d updating rdi", __func__, error));
929 
930 	if (repeat) {
931 		rcx = rcx - 1;
932 		error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RCX,
933 		    rcx, vie->addrsize);
934 		KASSERT(!error, ("%s: error %d updating rcx", __func__, error));
935 
936 		/*
937 		 * Repeat the instruction if the count register is not zero.
938 		 */
939 		if ((rcx & vie_size2mask(vie->addrsize)) != 0)
940 			vm_restart_instruction(vm, vcpuid);
941 	}
942 done:
943 	KASSERT(error == 0 || error == EFAULT, ("%s: unexpected error %d",
944 	    __func__, error));
945 	return (error);
946 }
947 
948 static int
949 emulate_stos(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
950     struct vm_guest_paging *paging, mem_region_read_t memread,
951     mem_region_write_t memwrite, void *arg)
952 {
953 	int error, opsize, repeat;
954 	uint64_t val;
955 	uint64_t rcx, rdi, rflags;
956 
957 	opsize = (vie->op.op_byte == 0xAA) ? 1 : vie->opsize;
958 	repeat = vie->repz_present | vie->repnz_present;
959 
960 	if (repeat) {
961 		error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RCX, &rcx);
962 		KASSERT(!error, ("%s: error %d getting rcx", __func__, error));
963 
964 		/*
965 		 * The count register is %rcx, %ecx or %cx depending on the
966 		 * address size of the instruction.
967 		 */
968 		if ((rcx & vie_size2mask(vie->addrsize)) == 0)
969 			return (0);
970 	}
971 
972 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RAX, &val);
973 	KASSERT(!error, ("%s: error %d getting rax", __func__, error));
974 
975 	error = memwrite(vm, vcpuid, gpa, val, opsize, arg);
976 	if (error)
977 		return (error);
978 
979 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RDI, &rdi);
980 	KASSERT(error == 0, ("%s: error %d getting rdi", __func__, error));
981 
982 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
983 	KASSERT(error == 0, ("%s: error %d getting rflags", __func__, error));
984 
985 	if (rflags & PSL_D)
986 		rdi -= opsize;
987 	else
988 		rdi += opsize;
989 
990 	error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RDI, rdi,
991 	    vie->addrsize);
992 	KASSERT(error == 0, ("%s: error %d updating rdi", __func__, error));
993 
994 	if (repeat) {
995 		rcx = rcx - 1;
996 		error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RCX,
997 		    rcx, vie->addrsize);
998 		KASSERT(!error, ("%s: error %d updating rcx", __func__, error));
999 
1000 		/*
1001 		 * Repeat the instruction if the count register is not zero.
1002 		 */
1003 		if ((rcx & vie_size2mask(vie->addrsize)) != 0)
1004 			vm_restart_instruction(vm, vcpuid);
1005 	}
1006 
1007 	return (0);
1008 }
1009 
1010 static int
1011 emulate_and(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1012 	    mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
1013 {
1014 	int error, size;
1015 	enum vm_reg_name reg;
1016 	uint64_t result, rflags, rflags2, val1, val2;
1017 
1018 	size = vie->opsize;
1019 	error = EINVAL;
1020 
1021 	switch (vie->op.op_byte) {
1022 	case 0x23:
1023 		/*
1024 		 * AND reg (ModRM:reg) and mem (ModRM:r/m) and store the
1025 		 * result in reg.
1026 		 *
1027 		 * 23/r		and r16, r/m16
1028 		 * 23/r		and r32, r/m32
1029 		 * REX.W + 23/r	and r64, r/m64
1030 		 */
1031 
1032 		/* get the first operand */
1033 		reg = gpr_map[vie->reg];
1034 		error = vie_read_register(vm, vcpuid, reg, &val1);
1035 		if (error)
1036 			break;
1037 
1038 		/* get the second operand */
1039 		error = memread(vm, vcpuid, gpa, &val2, size, arg);
1040 		if (error)
1041 			break;
1042 
1043 		/* perform the operation and write the result */
1044 		result = val1 & val2;
1045 		error = vie_update_register(vm, vcpuid, reg, result, size);
1046 		break;
1047 	case 0x81:
1048 	case 0x83:
1049 		/*
1050 		 * AND mem (ModRM:r/m) with immediate and store the
1051 		 * result in mem.
1052 		 *
1053 		 * 81 /4		and r/m16, imm16
1054 		 * 81 /4		and r/m32, imm32
1055 		 * REX.W + 81 /4	and r/m64, imm32 sign-extended to 64
1056 		 *
1057 		 * 83 /4		and r/m16, imm8 sign-extended to 16
1058 		 * 83 /4		and r/m32, imm8 sign-extended to 32
1059 		 * REX.W + 83/4		and r/m64, imm8 sign-extended to 64
1060 		 */
1061 
1062 		/* get the first operand */
1063                 error = memread(vm, vcpuid, gpa, &val1, size, arg);
1064                 if (error)
1065 			break;
1066 
1067                 /*
1068 		 * perform the operation with the pre-fetched immediate
1069 		 * operand and write the result
1070 		 */
1071                 result = val1 & vie->immediate;
1072                 error = memwrite(vm, vcpuid, gpa, result, size, arg);
1073 		break;
1074 	default:
1075 		break;
1076 	}
1077 	if (error)
1078 		return (error);
1079 
1080 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
1081 	if (error)
1082 		return (error);
1083 
1084 	/*
1085 	 * OF and CF are cleared; the SF, ZF and PF flags are set according
1086 	 * to the result; AF is undefined.
1087 	 *
1088 	 * The updated status flags are obtained by subtracting 0 from 'result'.
1089 	 */
1090 	rflags2 = getcc(size, result, 0);
1091 	rflags &= ~RFLAGS_STATUS_BITS;
1092 	rflags |= rflags2 & (PSL_PF | PSL_Z | PSL_N);
1093 
1094 	error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, rflags, 8);
1095 	return (error);
1096 }
1097 
1098 static int
1099 emulate_or(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1100 	    mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
1101 {
1102 	int error, size;
1103 	enum vm_reg_name reg;
1104 	uint64_t result, rflags, rflags2, val1, val2;
1105 
1106 	size = vie->opsize;
1107 	error = EINVAL;
1108 
1109 	switch (vie->op.op_byte) {
1110 	case 0x0B:
1111 		/*
1112 		 * OR reg (ModRM:reg) and mem (ModRM:r/m) and store the
1113 		 * result in reg.
1114 		 *
1115 		 * 0b/r         or r16, r/m16
1116 		 * 0b/r         or r32, r/m32
1117 		 * REX.W + 0b/r or r64, r/m64
1118 		 */
1119 
1120 		/* get the first operand */
1121 		reg = gpr_map[vie->reg];
1122 		error = vie_read_register(vm, vcpuid, reg, &val1);
1123 		if (error)
1124 			break;
1125 
1126 		/* get the second operand */
1127 		error = memread(vm, vcpuid, gpa, &val2, size, arg);
1128 		if (error)
1129 			break;
1130 
1131 		/* perform the operation and write the result */
1132 		result = val1 | val2;
1133 		error = vie_update_register(vm, vcpuid, reg, result, size);
1134 		break;
1135 	case 0x81:
1136 	case 0x83:
1137 		/*
1138 		 * OR mem (ModRM:r/m) with immediate and store the
1139 		 * result in mem.
1140 		 *
1141 		 * 81 /1		or r/m16, imm16
1142 		 * 81 /1		or r/m32, imm32
1143 		 * REX.W + 81 /1	or r/m64, imm32 sign-extended to 64
1144 		 *
1145 		 * 83 /1		or r/m16, imm8 sign-extended to 16
1146 		 * 83 /1		or r/m32, imm8 sign-extended to 32
1147 		 * REX.W + 83/1		or r/m64, imm8 sign-extended to 64
1148 		 */
1149 
1150 		/* get the first operand */
1151                 error = memread(vm, vcpuid, gpa, &val1, size, arg);
1152                 if (error)
1153 			break;
1154 
1155                 /*
1156 		 * perform the operation with the pre-fetched immediate
1157 		 * operand and write the result
1158 		 */
1159                 result = val1 | vie->immediate;
1160                 error = memwrite(vm, vcpuid, gpa, result, size, arg);
1161 		break;
1162 	default:
1163 		break;
1164 	}
1165 	if (error)
1166 		return (error);
1167 
1168 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
1169 	if (error)
1170 		return (error);
1171 
1172 	/*
1173 	 * OF and CF are cleared; the SF, ZF and PF flags are set according
1174 	 * to the result; AF is undefined.
1175 	 *
1176 	 * The updated status flags are obtained by subtracting 0 from 'result'.
1177 	 */
1178 	rflags2 = getcc(size, result, 0);
1179 	rflags &= ~RFLAGS_STATUS_BITS;
1180 	rflags |= rflags2 & (PSL_PF | PSL_Z | PSL_N);
1181 
1182 	error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, rflags, 8);
1183 	return (error);
1184 }
1185 
1186 static int
1187 emulate_cmp(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1188 	    mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
1189 {
1190 	int error, size;
1191 	uint64_t regop, memop, op1, op2, rflags, rflags2;
1192 	enum vm_reg_name reg;
1193 
1194 	size = vie->opsize;
1195 	switch (vie->op.op_byte) {
1196 	case 0x39:
1197 	case 0x3B:
1198 		/*
1199 		 * 39/r		CMP r/m16, r16
1200 		 * 39/r		CMP r/m32, r32
1201 		 * REX.W 39/r	CMP r/m64, r64
1202 		 *
1203 		 * 3B/r		CMP r16, r/m16
1204 		 * 3B/r		CMP r32, r/m32
1205 		 * REX.W + 3B/r	CMP r64, r/m64
1206 		 *
1207 		 * Compare the first operand with the second operand and
1208 		 * set status flags in EFLAGS register. The comparison is
1209 		 * performed by subtracting the second operand from the first
1210 		 * operand and then setting the status flags.
1211 		 */
1212 
1213 		/* Get the register operand */
1214 		reg = gpr_map[vie->reg];
1215 		error = vie_read_register(vm, vcpuid, reg, &regop);
1216 		if (error)
1217 			return (error);
1218 
1219 		/* Get the memory operand */
1220 		error = memread(vm, vcpuid, gpa, &memop, size, arg);
1221 		if (error)
1222 			return (error);
1223 
1224 		if (vie->op.op_byte == 0x3B) {
1225 			op1 = regop;
1226 			op2 = memop;
1227 		} else {
1228 			op1 = memop;
1229 			op2 = regop;
1230 		}
1231 		rflags2 = getcc(size, op1, op2);
1232 		break;
1233 	case 0x80:
1234 	case 0x81:
1235 	case 0x83:
1236 		/*
1237 		 * 80 /7		cmp r/m8, imm8
1238 		 * REX + 80 /7		cmp r/m8, imm8
1239 		 *
1240 		 * 81 /7		cmp r/m16, imm16
1241 		 * 81 /7		cmp r/m32, imm32
1242 		 * REX.W + 81 /7	cmp r/m64, imm32 sign-extended to 64
1243 		 *
1244 		 * 83 /7		cmp r/m16, imm8 sign-extended to 16
1245 		 * 83 /7		cmp r/m32, imm8 sign-extended to 32
1246 		 * REX.W + 83 /7	cmp r/m64, imm8 sign-extended to 64
1247 		 *
1248 		 * Compare mem (ModRM:r/m) with immediate and set
1249 		 * status flags according to the results.  The
1250 		 * comparison is performed by subtracting the
1251 		 * immediate from the first operand and then setting
1252 		 * the status flags.
1253 		 *
1254 		 */
1255 		if (vie->op.op_byte == 0x80)
1256 			size = 1;
1257 
1258 		/* get the first operand */
1259                 error = memread(vm, vcpuid, gpa, &op1, size, arg);
1260 		if (error)
1261 			return (error);
1262 
1263 		rflags2 = getcc(size, op1, vie->immediate);
1264 		break;
1265 	default:
1266 		return (EINVAL);
1267 	}
1268 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
1269 	if (error)
1270 		return (error);
1271 	rflags &= ~RFLAGS_STATUS_BITS;
1272 	rflags |= rflags2 & RFLAGS_STATUS_BITS;
1273 
1274 	error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, rflags, 8);
1275 	return (error);
1276 }
1277 
1278 static int
1279 emulate_test(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1280     mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
1281 {
1282 	int error, size;
1283 	uint64_t op1, rflags, rflags2;
1284 
1285 	size = vie->opsize;
1286 	error = EINVAL;
1287 
1288 	switch (vie->op.op_byte) {
1289 	case 0xF7:
1290 		/*
1291 		 * F7 /0		test r/m16, imm16
1292 		 * F7 /0		test r/m32, imm32
1293 		 * REX.W + F7 /0	test r/m64, imm32 sign-extended to 64
1294 		 *
1295 		 * Test mem (ModRM:r/m) with immediate and set status
1296 		 * flags according to the results.  The comparison is
1297 		 * performed by anding the immediate from the first
1298 		 * operand and then setting the status flags.
1299 		 */
1300 		if ((vie->reg & 7) != 0)
1301 			return (EINVAL);
1302 
1303 		error = memread(vm, vcpuid, gpa, &op1, size, arg);
1304 		if (error)
1305 			return (error);
1306 
1307 		rflags2 = getandflags(size, op1, vie->immediate);
1308 		break;
1309 	default:
1310 		return (EINVAL);
1311 	}
1312 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
1313 	if (error)
1314 		return (error);
1315 
1316 	/*
1317 	 * OF and CF are cleared; the SF, ZF and PF flags are set according
1318 	 * to the result; AF is undefined.
1319 	 */
1320 	rflags &= ~RFLAGS_STATUS_BITS;
1321 	rflags |= rflags2 & (PSL_PF | PSL_Z | PSL_N);
1322 
1323 	error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, rflags, 8);
1324 	return (error);
1325 }
1326 
1327 static int
1328 emulate_bextr(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1329     struct vm_guest_paging *paging, mem_region_read_t memread,
1330     mem_region_write_t memwrite, void *arg)
1331 {
1332 	uint64_t src1, src2, dst, rflags;
1333 	unsigned start, len;
1334 	int error, size;
1335 
1336 	size = vie->opsize;
1337 	error = EINVAL;
1338 
1339 	/*
1340 	 * VEX.LZ.0F38.W0 F7 /r		BEXTR r32a, r/m32, r32b
1341 	 * VEX.LZ.0F38.W1 F7 /r		BEXTR r64a, r/m64, r64b
1342 	 *
1343 	 * Destination operand is ModRM:reg.  Source operands are ModRM:r/m and
1344 	 * Vex.vvvv.
1345 	 *
1346 	 * Operand size is always 32-bit if not in 64-bit mode (W1 is ignored).
1347 	 */
1348 	if (size != 4 && paging->cpu_mode != CPU_MODE_64BIT)
1349 		size = 4;
1350 
1351 	/*
1352 	 * Extracts contiguous bits from the first /source/ operand (second
1353 	 * operand) using an index and length specified in the second /source/
1354 	 * operand (third operand).
1355 	 */
1356 	error = memread(vm, vcpuid, gpa, &src1, size, arg);
1357 	if (error)
1358 		return (error);
1359 	error = vie_read_register(vm, vcpuid, gpr_map[vie->vex_reg], &src2);
1360 	if (error)
1361 		return (error);
1362 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
1363 	if (error)
1364 		return (error);
1365 
1366 	start = (src2 & 0xff);
1367 	len = (src2 & 0xff00) >> 8;
1368 
1369 	/* If no bits are extracted, the destination register is cleared. */
1370 	dst = 0;
1371 
1372 	/* If START exceeds the operand size, no bits are extracted. */
1373 	if (start > size * 8)
1374 		goto done;
1375 	/* Length is bounded by both the destination size and start offset. */
1376 	if (start + len > size * 8)
1377 		len = (size * 8) - start;
1378 	if (len == 0)
1379 		goto done;
1380 
1381 	if (start > 0)
1382 		src1 = (src1 >> start);
1383 	if (len < 64)
1384 		src1 = src1 & ((1ull << len) - 1);
1385 	dst = src1;
1386 
1387 done:
1388 	error = vie_update_register(vm, vcpuid, gpr_map[vie->reg], dst, size);
1389 	if (error)
1390 		return (error);
1391 
1392 	/*
1393 	 * AMD: OF, CF cleared; SF/AF/PF undefined; ZF set by result.
1394 	 * Intel: ZF is set by result; AF/SF/PF undefined; all others cleared.
1395 	 */
1396 	rflags &= ~RFLAGS_STATUS_BITS;
1397 	if (dst == 0)
1398 		rflags |= PSL_Z;
1399 	error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, rflags,
1400 	    8);
1401 	return (error);
1402 }
1403 
1404 static int
1405 emulate_add(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1406 	    mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
1407 {
1408 	int error, size;
1409 	uint64_t nval, rflags, rflags2, val1, val2;
1410 	enum vm_reg_name reg;
1411 
1412 	size = vie->opsize;
1413 	error = EINVAL;
1414 
1415 	switch (vie->op.op_byte) {
1416 	case 0x03:
1417 		/*
1418 		 * ADD r/m to r and store the result in r
1419 		 *
1420 		 * 03/r            ADD r16, r/m16
1421 		 * 03/r            ADD r32, r/m32
1422 		 * REX.W + 03/r    ADD r64, r/m64
1423 		 */
1424 
1425 		/* get the first operand */
1426 		reg = gpr_map[vie->reg];
1427 		error = vie_read_register(vm, vcpuid, reg, &val1);
1428 		if (error)
1429 			break;
1430 
1431 		/* get the second operand */
1432 		error = memread(vm, vcpuid, gpa, &val2, size, arg);
1433 		if (error)
1434 			break;
1435 
1436 		/* perform the operation and write the result */
1437 		nval = val1 + val2;
1438 		error = vie_update_register(vm, vcpuid, reg, nval, size);
1439 		break;
1440 	default:
1441 		break;
1442 	}
1443 
1444 	if (!error) {
1445 		rflags2 = getaddflags(size, val1, val2);
1446 		error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS,
1447 		    &rflags);
1448 		if (error)
1449 			return (error);
1450 
1451 		rflags &= ~RFLAGS_STATUS_BITS;
1452 		rflags |= rflags2 & RFLAGS_STATUS_BITS;
1453 		error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RFLAGS,
1454 		    rflags, 8);
1455 	}
1456 
1457 	return (error);
1458 }
1459 
1460 static int
1461 emulate_sub(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1462 	    mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
1463 {
1464 	int error, size;
1465 	uint64_t nval, rflags, rflags2, val1, val2;
1466 	enum vm_reg_name reg;
1467 
1468 	size = vie->opsize;
1469 	error = EINVAL;
1470 
1471 	switch (vie->op.op_byte) {
1472 	case 0x2B:
1473 		/*
1474 		 * SUB r/m from r and store the result in r
1475 		 *
1476 		 * 2B/r            SUB r16, r/m16
1477 		 * 2B/r            SUB r32, r/m32
1478 		 * REX.W + 2B/r    SUB r64, r/m64
1479 		 */
1480 
1481 		/* get the first operand */
1482 		reg = gpr_map[vie->reg];
1483 		error = vie_read_register(vm, vcpuid, reg, &val1);
1484 		if (error)
1485 			break;
1486 
1487 		/* get the second operand */
1488 		error = memread(vm, vcpuid, gpa, &val2, size, arg);
1489 		if (error)
1490 			break;
1491 
1492 		/* perform the operation and write the result */
1493 		nval = val1 - val2;
1494 		error = vie_update_register(vm, vcpuid, reg, nval, size);
1495 		break;
1496 	default:
1497 		break;
1498 	}
1499 
1500 	if (!error) {
1501 		rflags2 = getcc(size, val1, val2);
1502 		error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS,
1503 		    &rflags);
1504 		if (error)
1505 			return (error);
1506 
1507 		rflags &= ~RFLAGS_STATUS_BITS;
1508 		rflags |= rflags2 & RFLAGS_STATUS_BITS;
1509 		error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RFLAGS,
1510 		    rflags, 8);
1511 	}
1512 
1513 	return (error);
1514 }
1515 
1516 static int
1517 emulate_stack_op(void *vm, int vcpuid, uint64_t mmio_gpa, struct vie *vie,
1518     struct vm_guest_paging *paging, mem_region_read_t memread,
1519     mem_region_write_t memwrite, void *arg)
1520 {
1521 #ifdef _KERNEL
1522 	struct vm_copyinfo copyinfo[2];
1523 #else
1524 	struct iovec copyinfo[2];
1525 #endif
1526 	struct seg_desc ss_desc;
1527 	uint64_t cr0, rflags, rsp, stack_gla, val;
1528 	int error, fault, size, stackaddrsize, pushop;
1529 
1530 	val = 0;
1531 	size = vie->opsize;
1532 	pushop = (vie->op.op_type == VIE_OP_TYPE_PUSH) ? 1 : 0;
1533 
1534 	/*
1535 	 * From "Address-Size Attributes for Stack Accesses", Intel SDL, Vol 1
1536 	 */
1537 	if (paging->cpu_mode == CPU_MODE_REAL) {
1538 		stackaddrsize = 2;
1539 	} else if (paging->cpu_mode == CPU_MODE_64BIT) {
1540 		/*
1541 		 * "Stack Manipulation Instructions in 64-bit Mode", SDM, Vol 3
1542 		 * - Stack pointer size is always 64-bits.
1543 		 * - PUSH/POP of 32-bit values is not possible in 64-bit mode.
1544 		 * - 16-bit PUSH/POP is supported by using the operand size
1545 		 *   override prefix (66H).
1546 		 */
1547 		stackaddrsize = 8;
1548 		size = vie->opsize_override ? 2 : 8;
1549 	} else {
1550 		/*
1551 		 * In protected or compatibility mode the 'B' flag in the
1552 		 * stack-segment descriptor determines the size of the
1553 		 * stack pointer.
1554 		 */
1555 		error = vm_get_seg_desc(vm, vcpuid, VM_REG_GUEST_SS, &ss_desc);
1556 		KASSERT(error == 0, ("%s: error %d getting SS descriptor",
1557 		    __func__, error));
1558 		if (SEG_DESC_DEF32(ss_desc.access))
1559 			stackaddrsize = 4;
1560 		else
1561 			stackaddrsize = 2;
1562 	}
1563 
1564 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_CR0, &cr0);
1565 	KASSERT(error == 0, ("%s: error %d getting cr0", __func__, error));
1566 
1567 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
1568 	KASSERT(error == 0, ("%s: error %d getting rflags", __func__, error));
1569 
1570 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RSP, &rsp);
1571 	KASSERT(error == 0, ("%s: error %d getting rsp", __func__, error));
1572 	if (pushop) {
1573 		rsp -= size;
1574 	}
1575 
1576 	if (vie_calculate_gla(paging->cpu_mode, VM_REG_GUEST_SS, &ss_desc,
1577 	    rsp, size, stackaddrsize, pushop ? PROT_WRITE : PROT_READ,
1578 	    &stack_gla)) {
1579 		vm_inject_ss(vm, vcpuid, 0);
1580 		return (0);
1581 	}
1582 
1583 	if (vie_canonical_check(paging->cpu_mode, stack_gla)) {
1584 		vm_inject_ss(vm, vcpuid, 0);
1585 		return (0);
1586 	}
1587 
1588 	if (vie_alignment_check(paging->cpl, size, cr0, rflags, stack_gla)) {
1589 		vm_inject_ac(vm, vcpuid, 0);
1590 		return (0);
1591 	}
1592 
1593 	error = vm_copy_setup(vm, vcpuid, paging, stack_gla, size,
1594 	    pushop ? PROT_WRITE : PROT_READ, copyinfo, nitems(copyinfo),
1595 	    &fault);
1596 	if (error || fault)
1597 		return (error);
1598 
1599 	if (pushop) {
1600 		error = memread(vm, vcpuid, mmio_gpa, &val, size, arg);
1601 		if (error == 0)
1602 			vm_copyout(vm, vcpuid, &val, copyinfo, size);
1603 	} else {
1604 		vm_copyin(vm, vcpuid, copyinfo, &val, size);
1605 		error = memwrite(vm, vcpuid, mmio_gpa, val, size, arg);
1606 		rsp += size;
1607 	}
1608 	vm_copy_teardown(vm, vcpuid, copyinfo, nitems(copyinfo));
1609 
1610 	if (error == 0) {
1611 		error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RSP, rsp,
1612 		    stackaddrsize);
1613 		KASSERT(error == 0, ("error %d updating rsp", error));
1614 	}
1615 	return (error);
1616 }
1617 
1618 static int
1619 emulate_push(void *vm, int vcpuid, uint64_t mmio_gpa, struct vie *vie,
1620     struct vm_guest_paging *paging, mem_region_read_t memread,
1621     mem_region_write_t memwrite, void *arg)
1622 {
1623 	int error;
1624 
1625 	/*
1626 	 * Table A-6, "Opcode Extensions", Intel SDM, Vol 2.
1627 	 *
1628 	 * PUSH is part of the group 5 extended opcodes and is identified
1629 	 * by ModRM:reg = b110.
1630 	 */
1631 	if ((vie->reg & 7) != 6)
1632 		return (EINVAL);
1633 
1634 	error = emulate_stack_op(vm, vcpuid, mmio_gpa, vie, paging, memread,
1635 	    memwrite, arg);
1636 	return (error);
1637 }
1638 
1639 static int
1640 emulate_pop(void *vm, int vcpuid, uint64_t mmio_gpa, struct vie *vie,
1641     struct vm_guest_paging *paging, mem_region_read_t memread,
1642     mem_region_write_t memwrite, void *arg)
1643 {
1644 	int error;
1645 
1646 	/*
1647 	 * Table A-6, "Opcode Extensions", Intel SDM, Vol 2.
1648 	 *
1649 	 * POP is part of the group 1A extended opcodes and is identified
1650 	 * by ModRM:reg = b000.
1651 	 */
1652 	if ((vie->reg & 7) != 0)
1653 		return (EINVAL);
1654 
1655 	error = emulate_stack_op(vm, vcpuid, mmio_gpa, vie, paging, memread,
1656 	    memwrite, arg);
1657 	return (error);
1658 }
1659 
1660 static int
1661 emulate_group1(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1662     struct vm_guest_paging *paging, mem_region_read_t memread,
1663     mem_region_write_t memwrite, void *memarg)
1664 {
1665 	int error;
1666 
1667 	switch (vie->reg & 7) {
1668 	case 0x1:	/* OR */
1669 		error = emulate_or(vm, vcpuid, gpa, vie,
1670 		    memread, memwrite, memarg);
1671 		break;
1672 	case 0x4:	/* AND */
1673 		error = emulate_and(vm, vcpuid, gpa, vie,
1674 		    memread, memwrite, memarg);
1675 		break;
1676 	case 0x7:	/* CMP */
1677 		error = emulate_cmp(vm, vcpuid, gpa, vie,
1678 		    memread, memwrite, memarg);
1679 		break;
1680 	default:
1681 		error = EINVAL;
1682 		break;
1683 	}
1684 
1685 	return (error);
1686 }
1687 
1688 static int
1689 emulate_bittest(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1690     mem_region_read_t memread, mem_region_write_t memwrite, void *memarg)
1691 {
1692 	uint64_t val, rflags;
1693 	int error, bitmask, bitoff;
1694 
1695 	/*
1696 	 * 0F BA is a Group 8 extended opcode.
1697 	 *
1698 	 * Currently we only emulate the 'Bit Test' instruction which is
1699 	 * identified by a ModR/M:reg encoding of 100b.
1700 	 */
1701 	if ((vie->reg & 7) != 4)
1702 		return (EINVAL);
1703 
1704 	error = vie_read_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, &rflags);
1705 	KASSERT(error == 0, ("%s: error %d getting rflags", __func__, error));
1706 
1707 	error = memread(vm, vcpuid, gpa, &val, vie->opsize, memarg);
1708 	if (error)
1709 		return (error);
1710 
1711 	/*
1712 	 * Intel SDM, Vol 2, Table 3-2:
1713 	 * "Range of Bit Positions Specified by Bit Offset Operands"
1714 	 */
1715 	bitmask = vie->opsize * 8 - 1;
1716 	bitoff = vie->immediate & bitmask;
1717 
1718 	/* Copy the bit into the Carry flag in %rflags */
1719 	if (val & (1UL << bitoff))
1720 		rflags |= PSL_C;
1721 	else
1722 		rflags &= ~PSL_C;
1723 
1724 	error = vie_update_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, rflags, 8);
1725 	KASSERT(error == 0, ("%s: error %d updating rflags", __func__, error));
1726 
1727 	return (0);
1728 }
1729 
1730 static int
1731 emulate_twob_group15(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1732     mem_region_read_t memread, mem_region_write_t memwrite, void *memarg)
1733 {
1734 	int error;
1735 	uint64_t buf;
1736 
1737 	switch (vie->reg & 7) {
1738 	case 0x7:	/* CLFLUSH, CLFLUSHOPT, and SFENCE */
1739 		if (vie->mod == 0x3) {
1740 			/*
1741 			 * SFENCE.  Ignore it, VM exit provides enough
1742 			 * barriers on its own.
1743 			 */
1744 			error = 0;
1745 		} else {
1746 			/*
1747 			 * CLFLUSH, CLFLUSHOPT.  Only check for access
1748 			 * rights.
1749 			 */
1750 			error = memread(vm, vcpuid, gpa, &buf, 1, memarg);
1751 		}
1752 		break;
1753 	default:
1754 		error = EINVAL;
1755 		break;
1756 	}
1757 
1758 	return (error);
1759 }
1760 
1761 int
1762 vmm_emulate_instruction(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
1763     struct vm_guest_paging *paging, mem_region_read_t memread,
1764     mem_region_write_t memwrite, void *memarg)
1765 {
1766 	int error;
1767 
1768 	if (!vie->decoded)
1769 		return (EINVAL);
1770 
1771 	switch (vie->op.op_type) {
1772 	case VIE_OP_TYPE_GROUP1:
1773 		error = emulate_group1(vm, vcpuid, gpa, vie, paging, memread,
1774 		    memwrite, memarg);
1775 		break;
1776 	case VIE_OP_TYPE_POP:
1777 		error = emulate_pop(vm, vcpuid, gpa, vie, paging, memread,
1778 		    memwrite, memarg);
1779 		break;
1780 	case VIE_OP_TYPE_PUSH:
1781 		error = emulate_push(vm, vcpuid, gpa, vie, paging, memread,
1782 		    memwrite, memarg);
1783 		break;
1784 	case VIE_OP_TYPE_CMP:
1785 		error = emulate_cmp(vm, vcpuid, gpa, vie,
1786 				    memread, memwrite, memarg);
1787 		break;
1788 	case VIE_OP_TYPE_MOV:
1789 		error = emulate_mov(vm, vcpuid, gpa, vie,
1790 				    memread, memwrite, memarg);
1791 		break;
1792 	case VIE_OP_TYPE_MOVSX:
1793 	case VIE_OP_TYPE_MOVZX:
1794 		error = emulate_movx(vm, vcpuid, gpa, vie,
1795 				     memread, memwrite, memarg);
1796 		break;
1797 	case VIE_OP_TYPE_MOVS:
1798 		error = emulate_movs(vm, vcpuid, gpa, vie, paging, memread,
1799 		    memwrite, memarg);
1800 		break;
1801 	case VIE_OP_TYPE_STOS:
1802 		error = emulate_stos(vm, vcpuid, gpa, vie, paging, memread,
1803 		    memwrite, memarg);
1804 		break;
1805 	case VIE_OP_TYPE_AND:
1806 		error = emulate_and(vm, vcpuid, gpa, vie,
1807 				    memread, memwrite, memarg);
1808 		break;
1809 	case VIE_OP_TYPE_OR:
1810 		error = emulate_or(vm, vcpuid, gpa, vie,
1811 				    memread, memwrite, memarg);
1812 		break;
1813 	case VIE_OP_TYPE_SUB:
1814 		error = emulate_sub(vm, vcpuid, gpa, vie,
1815 				    memread, memwrite, memarg);
1816 		break;
1817 	case VIE_OP_TYPE_BITTEST:
1818 		error = emulate_bittest(vm, vcpuid, gpa, vie,
1819 		    memread, memwrite, memarg);
1820 		break;
1821 	case VIE_OP_TYPE_TWOB_GRP15:
1822 		error = emulate_twob_group15(vm, vcpuid, gpa, vie,
1823 		    memread, memwrite, memarg);
1824 		break;
1825 	case VIE_OP_TYPE_ADD:
1826 		error = emulate_add(vm, vcpuid, gpa, vie, memread,
1827 		    memwrite, memarg);
1828 		break;
1829 	case VIE_OP_TYPE_TEST:
1830 		error = emulate_test(vm, vcpuid, gpa, vie,
1831 		    memread, memwrite, memarg);
1832 		break;
1833 	case VIE_OP_TYPE_BEXTR:
1834 		error = emulate_bextr(vm, vcpuid, gpa, vie, paging,
1835 		    memread, memwrite, memarg);
1836 		break;
1837 	default:
1838 		error = EINVAL;
1839 		break;
1840 	}
1841 
1842 	return (error);
1843 }
1844 
1845 int
1846 vie_alignment_check(int cpl, int size, uint64_t cr0, uint64_t rf, uint64_t gla)
1847 {
1848 	KASSERT(size == 1 || size == 2 || size == 4 || size == 8,
1849 	    ("%s: invalid size %d", __func__, size));
1850 	KASSERT(cpl >= 0 && cpl <= 3, ("%s: invalid cpl %d", __func__, cpl));
1851 
1852 	if (cpl != 3 || (cr0 & CR0_AM) == 0 || (rf & PSL_AC) == 0)
1853 		return (0);
1854 
1855 	return ((gla & (size - 1)) ? 1 : 0);
1856 }
1857 
1858 int
1859 vie_canonical_check(enum vm_cpu_mode cpu_mode, uint64_t gla)
1860 {
1861 	uint64_t mask;
1862 
1863 	if (cpu_mode != CPU_MODE_64BIT)
1864 		return (0);
1865 
1866 	/*
1867 	 * The value of the bit 47 in the 'gla' should be replicated in the
1868 	 * most significant 16 bits.
1869 	 */
1870 	mask = ~((1UL << 48) - 1);
1871 	if (gla & (1UL << 47))
1872 		return ((gla & mask) != mask);
1873 	else
1874 		return ((gla & mask) != 0);
1875 }
1876 
1877 uint64_t
1878 vie_size2mask(int size)
1879 {
1880 	KASSERT(size == 1 || size == 2 || size == 4 || size == 8,
1881 	    ("vie_size2mask: invalid size %d", size));
1882 	return (size2mask[size]);
1883 }
1884 
1885 int
1886 vie_calculate_gla(enum vm_cpu_mode cpu_mode, enum vm_reg_name seg,
1887     struct seg_desc *desc, uint64_t offset, int length, int addrsize,
1888     int prot, uint64_t *gla)
1889 {
1890 	uint64_t firstoff, low_limit, high_limit, segbase;
1891 	int glasize, type;
1892 
1893 	KASSERT(seg >= VM_REG_GUEST_ES && seg <= VM_REG_GUEST_GS,
1894 	    ("%s: invalid segment %d", __func__, seg));
1895 	KASSERT(length == 1 || length == 2 || length == 4 || length == 8,
1896 	    ("%s: invalid operand size %d", __func__, length));
1897 	KASSERT((prot & ~(PROT_READ | PROT_WRITE)) == 0,
1898 	    ("%s: invalid prot %#x", __func__, prot));
1899 
1900 	firstoff = offset;
1901 	if (cpu_mode == CPU_MODE_64BIT) {
1902 		KASSERT(addrsize == 4 || addrsize == 8, ("%s: invalid address "
1903 		    "size %d for cpu_mode %d", __func__, addrsize, cpu_mode));
1904 		glasize = 8;
1905 	} else {
1906 		KASSERT(addrsize == 2 || addrsize == 4, ("%s: invalid address "
1907 		    "size %d for cpu mode %d", __func__, addrsize, cpu_mode));
1908 		glasize = 4;
1909 		/*
1910 		 * If the segment selector is loaded with a NULL selector
1911 		 * then the descriptor is unusable and attempting to use
1912 		 * it results in a #GP(0).
1913 		 */
1914 		if (SEG_DESC_UNUSABLE(desc->access))
1915 			return (-1);
1916 
1917 		/*
1918 		 * The processor generates a #NP exception when a segment
1919 		 * register is loaded with a selector that points to a
1920 		 * descriptor that is not present. If this was the case then
1921 		 * it would have been checked before the VM-exit.
1922 		 */
1923 		KASSERT(SEG_DESC_PRESENT(desc->access),
1924 		    ("segment %d not present: %#x", seg, desc->access));
1925 
1926 		/*
1927 		 * The descriptor type must indicate a code/data segment.
1928 		 */
1929 		type = SEG_DESC_TYPE(desc->access);
1930 		KASSERT(type >= 16 && type <= 31, ("segment %d has invalid "
1931 		    "descriptor type %#x", seg, type));
1932 
1933 		if (prot & PROT_READ) {
1934 			/* #GP on a read access to a exec-only code segment */
1935 			if ((type & 0xA) == 0x8)
1936 				return (-1);
1937 		}
1938 
1939 		if (prot & PROT_WRITE) {
1940 			/*
1941 			 * #GP on a write access to a code segment or a
1942 			 * read-only data segment.
1943 			 */
1944 			if (type & 0x8)			/* code segment */
1945 				return (-1);
1946 
1947 			if ((type & 0xA) == 0)		/* read-only data seg */
1948 				return (-1);
1949 		}
1950 
1951 		/*
1952 		 * 'desc->limit' is fully expanded taking granularity into
1953 		 * account.
1954 		 */
1955 		if ((type & 0xC) == 0x4) {
1956 			/* expand-down data segment */
1957 			low_limit = desc->limit + 1;
1958 			high_limit = SEG_DESC_DEF32(desc->access) ?
1959 			    0xffffffff : 0xffff;
1960 		} else {
1961 			/* code segment or expand-up data segment */
1962 			low_limit = 0;
1963 			high_limit = desc->limit;
1964 		}
1965 
1966 		while (length > 0) {
1967 			offset &= vie_size2mask(addrsize);
1968 			if (offset < low_limit || offset > high_limit)
1969 				return (-1);
1970 			offset++;
1971 			length--;
1972 		}
1973 	}
1974 
1975 	/*
1976 	 * In 64-bit mode all segments except %fs and %gs have a segment
1977 	 * base address of 0.
1978 	 */
1979 	if (cpu_mode == CPU_MODE_64BIT && seg != VM_REG_GUEST_FS &&
1980 	    seg != VM_REG_GUEST_GS) {
1981 		segbase = 0;
1982 	} else {
1983 		segbase = desc->base;
1984 	}
1985 
1986 	/*
1987 	 * Truncate 'firstoff' to the effective address size before adding
1988 	 * it to the segment base.
1989 	 */
1990 	firstoff &= vie_size2mask(addrsize);
1991 	*gla = (segbase + firstoff) & vie_size2mask(glasize);
1992 	return (0);
1993 }
1994 
1995 /*
1996  * Prepare a partially decoded vie for a 2nd attempt.
1997  */
1998 void
1999 vie_restart(struct vie *vie)
2000 {
2001 	_Static_assert(
2002 	    offsetof(struct vie, inst) < offsetof(struct vie, vie_startzero) &&
2003 	    offsetof(struct vie, num_valid) < offsetof(struct vie, vie_startzero),
2004 	    "restart should not erase instruction length or contents");
2005 
2006 	memset((char *)vie + offsetof(struct vie, vie_startzero), 0,
2007 	    sizeof(*vie) - offsetof(struct vie, vie_startzero));
2008 
2009 	vie->base_register = VM_REG_LAST;
2010 	vie->index_register = VM_REG_LAST;
2011 	vie->segment_register = VM_REG_LAST;
2012 }
2013 
2014 void
2015 vie_init(struct vie *vie, const char *inst_bytes, int inst_length)
2016 {
2017 	KASSERT(inst_length >= 0 && inst_length <= VIE_INST_SIZE,
2018 	    ("%s: invalid instruction length (%d)", __func__, inst_length));
2019 
2020 	vie_restart(vie);
2021 	memset(vie->inst, 0, sizeof(vie->inst));
2022 	if (inst_length != 0)
2023 		memcpy(vie->inst, inst_bytes, inst_length);
2024 	vie->num_valid = inst_length;
2025 }
2026 
2027 #ifdef _KERNEL
2028 static int
2029 pf_error_code(int usermode, int prot, int rsvd, uint64_t pte)
2030 {
2031 	int error_code = 0;
2032 
2033 	if (pte & PG_V)
2034 		error_code |= PGEX_P;
2035 	if (prot & VM_PROT_WRITE)
2036 		error_code |= PGEX_W;
2037 	if (usermode)
2038 		error_code |= PGEX_U;
2039 	if (rsvd)
2040 		error_code |= PGEX_RSV;
2041 	if (prot & VM_PROT_EXECUTE)
2042 		error_code |= PGEX_I;
2043 
2044 	return (error_code);
2045 }
2046 
2047 static void
2048 ptp_release(void **cookie)
2049 {
2050 	if (*cookie != NULL) {
2051 		vm_gpa_release(*cookie);
2052 		*cookie = NULL;
2053 	}
2054 }
2055 
2056 static void *
2057 ptp_hold(struct vm *vm, int vcpu, vm_paddr_t ptpphys, size_t len, void **cookie)
2058 {
2059 	void *ptr;
2060 
2061 	ptp_release(cookie);
2062 	ptr = vm_gpa_hold(vm, vcpu, ptpphys, len, VM_PROT_RW, cookie);
2063 	return (ptr);
2064 }
2065 
2066 static int
2067 _vm_gla2gpa(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2068     uint64_t gla, int prot, uint64_t *gpa, int *guest_fault, bool check_only)
2069 {
2070 	int nlevels, pfcode, ptpshift, ptpindex, retval, usermode, writable;
2071 	u_int retries;
2072 	uint64_t *ptpbase, ptpphys, pte, pgsize;
2073 	uint32_t *ptpbase32, pte32;
2074 	void *cookie;
2075 
2076 	*guest_fault = 0;
2077 
2078 	usermode = (paging->cpl == 3 ? 1 : 0);
2079 	writable = prot & VM_PROT_WRITE;
2080 	cookie = NULL;
2081 	retval = 0;
2082 	retries = 0;
2083 restart:
2084 	ptpphys = paging->cr3;		/* root of the page tables */
2085 	ptp_release(&cookie);
2086 	if (retries++ > 0)
2087 		maybe_yield();
2088 
2089 	if (vie_canonical_check(paging->cpu_mode, gla)) {
2090 		/*
2091 		 * XXX assuming a non-stack reference otherwise a stack fault
2092 		 * should be generated.
2093 		 */
2094 		if (!check_only)
2095 			vm_inject_gp(vm, vcpuid);
2096 		goto fault;
2097 	}
2098 
2099 	if (paging->paging_mode == PAGING_MODE_FLAT) {
2100 		*gpa = gla;
2101 		goto done;
2102 	}
2103 
2104 	if (paging->paging_mode == PAGING_MODE_32) {
2105 		nlevels = 2;
2106 		while (--nlevels >= 0) {
2107 			/* Zero out the lower 12 bits. */
2108 			ptpphys &= ~0xfff;
2109 
2110 			ptpbase32 = ptp_hold(vm, vcpuid, ptpphys, PAGE_SIZE,
2111 			    &cookie);
2112 
2113 			if (ptpbase32 == NULL)
2114 				goto error;
2115 
2116 			ptpshift = PAGE_SHIFT + nlevels * 10;
2117 			ptpindex = (gla >> ptpshift) & 0x3FF;
2118 			pgsize = 1UL << ptpshift;
2119 
2120 			pte32 = ptpbase32[ptpindex];
2121 
2122 			if ((pte32 & PG_V) == 0 ||
2123 			    (usermode && (pte32 & PG_U) == 0) ||
2124 			    (writable && (pte32 & PG_RW) == 0)) {
2125 				if (!check_only) {
2126 					pfcode = pf_error_code(usermode, prot, 0,
2127 					    pte32);
2128 					vm_inject_pf(vm, vcpuid, pfcode, gla);
2129 				}
2130 				goto fault;
2131 			}
2132 
2133 			/*
2134 			 * Emulate the x86 MMU's management of the accessed
2135 			 * and dirty flags. While the accessed flag is set
2136 			 * at every level of the page table, the dirty flag
2137 			 * is only set at the last level providing the guest
2138 			 * physical address.
2139 			 */
2140 			if (!check_only && (pte32 & PG_A) == 0) {
2141 				if (atomic_cmpset_32(&ptpbase32[ptpindex],
2142 				    pte32, pte32 | PG_A) == 0) {
2143 					goto restart;
2144 				}
2145 			}
2146 
2147 			/* XXX must be ignored if CR4.PSE=0 */
2148 			if (nlevels > 0 && (pte32 & PG_PS) != 0)
2149 				break;
2150 
2151 			ptpphys = pte32;
2152 		}
2153 
2154 		/* Set the dirty bit in the page table entry if necessary */
2155 		if (!check_only && writable && (pte32 & PG_M) == 0) {
2156 			if (atomic_cmpset_32(&ptpbase32[ptpindex],
2157 			    pte32, pte32 | PG_M) == 0) {
2158 				goto restart;
2159 			}
2160 		}
2161 
2162 		/* Zero out the lower 'ptpshift' bits */
2163 		pte32 >>= ptpshift; pte32 <<= ptpshift;
2164 		*gpa = pte32 | (gla & (pgsize - 1));
2165 		goto done;
2166 	}
2167 
2168 	if (paging->paging_mode == PAGING_MODE_PAE) {
2169 		/* Zero out the lower 5 bits and the upper 32 bits */
2170 		ptpphys &= 0xffffffe0UL;
2171 
2172 		ptpbase = ptp_hold(vm, vcpuid, ptpphys, sizeof(*ptpbase) * 4,
2173 		    &cookie);
2174 		if (ptpbase == NULL)
2175 			goto error;
2176 
2177 		ptpindex = (gla >> 30) & 0x3;
2178 
2179 		pte = ptpbase[ptpindex];
2180 
2181 		if ((pte & PG_V) == 0) {
2182 			if (!check_only) {
2183 				pfcode = pf_error_code(usermode, prot, 0, pte);
2184 				vm_inject_pf(vm, vcpuid, pfcode, gla);
2185 			}
2186 			goto fault;
2187 		}
2188 
2189 		ptpphys = pte;
2190 
2191 		nlevels = 2;
2192 	} else if (paging->paging_mode == PAGING_MODE_64_LA57) {
2193 		nlevels = 5;
2194 	} else {
2195 		nlevels = 4;
2196 	}
2197 
2198 	while (--nlevels >= 0) {
2199 		/* Zero out the lower 12 bits and the upper 12 bits */
2200 		ptpphys >>= 12; ptpphys <<= 24; ptpphys >>= 12;
2201 
2202 		ptpbase = ptp_hold(vm, vcpuid, ptpphys, PAGE_SIZE, &cookie);
2203 		if (ptpbase == NULL)
2204 			goto error;
2205 
2206 		ptpshift = PAGE_SHIFT + nlevels * 9;
2207 		ptpindex = (gla >> ptpshift) & 0x1FF;
2208 		pgsize = 1UL << ptpshift;
2209 
2210 		pte = ptpbase[ptpindex];
2211 
2212 		if ((pte & PG_V) == 0 ||
2213 		    (usermode && (pte & PG_U) == 0) ||
2214 		    (writable && (pte & PG_RW) == 0)) {
2215 			if (!check_only) {
2216 				pfcode = pf_error_code(usermode, prot, 0, pte);
2217 				vm_inject_pf(vm, vcpuid, pfcode, gla);
2218 			}
2219 			goto fault;
2220 		}
2221 
2222 		/* Set the accessed bit in the page table entry */
2223 		if (!check_only && (pte & PG_A) == 0) {
2224 			if (atomic_cmpset_64(&ptpbase[ptpindex],
2225 			    pte, pte | PG_A) == 0) {
2226 				goto restart;
2227 			}
2228 		}
2229 
2230 		if (nlevels > 0 && (pte & PG_PS) != 0) {
2231 			if (pgsize > 1 * GB) {
2232 				if (!check_only) {
2233 					pfcode = pf_error_code(usermode, prot, 1,
2234 					    pte);
2235 					vm_inject_pf(vm, vcpuid, pfcode, gla);
2236 				}
2237 				goto fault;
2238 			}
2239 			break;
2240 		}
2241 
2242 		ptpphys = pte;
2243 	}
2244 
2245 	/* Set the dirty bit in the page table entry if necessary */
2246 	if (!check_only && writable && (pte & PG_M) == 0) {
2247 		if (atomic_cmpset_64(&ptpbase[ptpindex], pte, pte | PG_M) == 0)
2248 			goto restart;
2249 	}
2250 
2251 	/* Zero out the lower 'ptpshift' bits and the upper 12 bits */
2252 	pte >>= ptpshift; pte <<= (ptpshift + 12); pte >>= 12;
2253 	*gpa = pte | (gla & (pgsize - 1));
2254 done:
2255 	ptp_release(&cookie);
2256 	KASSERT(retval == 0 || retval == EFAULT, ("%s: unexpected retval %d",
2257 	    __func__, retval));
2258 	return (retval);
2259 error:
2260 	retval = EFAULT;
2261 	goto done;
2262 fault:
2263 	*guest_fault = 1;
2264 	goto done;
2265 }
2266 
2267 int
2268 vm_gla2gpa(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2269     uint64_t gla, int prot, uint64_t *gpa, int *guest_fault)
2270 {
2271 
2272 	return (_vm_gla2gpa(vm, vcpuid, paging, gla, prot, gpa, guest_fault,
2273 	    false));
2274 }
2275 
2276 int
2277 vm_gla2gpa_nofault(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2278     uint64_t gla, int prot, uint64_t *gpa, int *guest_fault)
2279 {
2280 
2281 	return (_vm_gla2gpa(vm, vcpuid, paging, gla, prot, gpa, guest_fault,
2282 	    true));
2283 }
2284 
2285 int
2286 vmm_fetch_instruction(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2287     uint64_t rip, int inst_length, struct vie *vie, int *faultptr)
2288 {
2289 	struct vm_copyinfo copyinfo[2];
2290 	int error, prot;
2291 
2292 	if (inst_length > VIE_INST_SIZE)
2293 		panic("vmm_fetch_instruction: invalid length %d", inst_length);
2294 
2295 	prot = PROT_READ | PROT_EXEC;
2296 	error = vm_copy_setup(vm, vcpuid, paging, rip, inst_length, prot,
2297 	    copyinfo, nitems(copyinfo), faultptr);
2298 	if (error || *faultptr)
2299 		return (error);
2300 
2301 	vm_copyin(vm, vcpuid, copyinfo, vie->inst, inst_length);
2302 	vm_copy_teardown(vm, vcpuid, copyinfo, nitems(copyinfo));
2303 	vie->num_valid = inst_length;
2304 	return (0);
2305 }
2306 #endif	/* _KERNEL */
2307 
2308 static int
2309 vie_peek(struct vie *vie, uint8_t *x)
2310 {
2311 
2312 	if (vie->num_processed < vie->num_valid) {
2313 		*x = vie->inst[vie->num_processed];
2314 		return (0);
2315 	} else
2316 		return (-1);
2317 }
2318 
2319 static void
2320 vie_advance(struct vie *vie)
2321 {
2322 
2323 	vie->num_processed++;
2324 }
2325 
2326 static bool
2327 segment_override(uint8_t x, int *seg)
2328 {
2329 
2330 	switch (x) {
2331 	case 0x2E:
2332 		*seg = VM_REG_GUEST_CS;
2333 		break;
2334 	case 0x36:
2335 		*seg = VM_REG_GUEST_SS;
2336 		break;
2337 	case 0x3E:
2338 		*seg = VM_REG_GUEST_DS;
2339 		break;
2340 	case 0x26:
2341 		*seg = VM_REG_GUEST_ES;
2342 		break;
2343 	case 0x64:
2344 		*seg = VM_REG_GUEST_FS;
2345 		break;
2346 	case 0x65:
2347 		*seg = VM_REG_GUEST_GS;
2348 		break;
2349 	default:
2350 		return (false);
2351 	}
2352 	return (true);
2353 }
2354 
2355 static int
2356 decode_prefixes(struct vie *vie, enum vm_cpu_mode cpu_mode, int cs_d)
2357 {
2358 	uint8_t x;
2359 
2360 	while (1) {
2361 		if (vie_peek(vie, &x))
2362 			return (-1);
2363 
2364 		if (x == 0x66)
2365 			vie->opsize_override = 1;
2366 		else if (x == 0x67)
2367 			vie->addrsize_override = 1;
2368 		else if (x == 0xF3)
2369 			vie->repz_present = 1;
2370 		else if (x == 0xF2)
2371 			vie->repnz_present = 1;
2372 		else if (segment_override(x, &vie->segment_register))
2373 			vie->segment_override = 1;
2374 		else
2375 			break;
2376 
2377 		vie_advance(vie);
2378 	}
2379 
2380 	/*
2381 	 * From section 2.2.1, "REX Prefixes", Intel SDM Vol 2:
2382 	 * - Only one REX prefix is allowed per instruction.
2383 	 * - The REX prefix must immediately precede the opcode byte or the
2384 	 *   escape opcode byte.
2385 	 * - If an instruction has a mandatory prefix (0x66, 0xF2 or 0xF3)
2386 	 *   the mandatory prefix must come before the REX prefix.
2387 	 */
2388 	if (cpu_mode == CPU_MODE_64BIT && x >= 0x40 && x <= 0x4F) {
2389 		vie->rex_present = 1;
2390 		vie->rex_w = x & 0x8 ? 1 : 0;
2391 		vie->rex_r = x & 0x4 ? 1 : 0;
2392 		vie->rex_x = x & 0x2 ? 1 : 0;
2393 		vie->rex_b = x & 0x1 ? 1 : 0;
2394 		vie_advance(vie);
2395 	}
2396 
2397 	/*
2398 	 * § 2.3.5, "The VEX Prefix", SDM Vol 2.
2399 	 */
2400 	if ((cpu_mode == CPU_MODE_64BIT || cpu_mode == CPU_MODE_COMPATIBILITY)
2401 	    && x == 0xC4) {
2402 		const struct vie_op *optab;
2403 
2404 		/* 3-byte VEX prefix. */
2405 		vie->vex_present = 1;
2406 
2407 		vie_advance(vie);
2408 		if (vie_peek(vie, &x))
2409 			return (-1);
2410 
2411 		/*
2412 		 * 2nd byte: [R', X', B', mmmmm[4:0]].  Bits are inverted
2413 		 * relative to REX encoding.
2414 		 */
2415 		vie->rex_r = x & 0x80 ? 0 : 1;
2416 		vie->rex_x = x & 0x40 ? 0 : 1;
2417 		vie->rex_b = x & 0x20 ? 0 : 1;
2418 
2419 		switch (x & 0x1F) {
2420 		case 0x2:
2421 			/* 0F 38. */
2422 			optab = three_byte_opcodes_0f38;
2423 			break;
2424 		case 0x1:
2425 			/* 0F class - nothing handled here yet. */
2426 			/* FALLTHROUGH */
2427 		case 0x3:
2428 			/* 0F 3A class - nothing handled here yet. */
2429 			/* FALLTHROUGH */
2430 		default:
2431 			/* Reserved (#UD). */
2432 			return (-1);
2433 		}
2434 
2435 		vie_advance(vie);
2436 		if (vie_peek(vie, &x))
2437 			return (-1);
2438 
2439 		/* 3rd byte: [W, vvvv[6:3], L, pp[1:0]]. */
2440 		vie->rex_w = x & 0x80 ? 1 : 0;
2441 
2442 		vie->vex_reg = ((~(unsigned)x & 0x78u) >> 3);
2443 		vie->vex_l = !!(x & 0x4);
2444 		vie->vex_pp = (x & 0x3);
2445 
2446 		/* PP: 1=66 2=F3 3=F2 prefixes. */
2447 		switch (vie->vex_pp) {
2448 		case 0x1:
2449 			vie->opsize_override = 1;
2450 			break;
2451 		case 0x2:
2452 			vie->repz_present = 1;
2453 			break;
2454 		case 0x3:
2455 			vie->repnz_present = 1;
2456 			break;
2457 		}
2458 
2459 		vie_advance(vie);
2460 
2461 		/* Opcode, sans literal prefix prefix. */
2462 		if (vie_peek(vie, &x))
2463 			return (-1);
2464 
2465 		vie->op = optab[x];
2466 		if (vie->op.op_type == VIE_OP_TYPE_NONE)
2467 			return (-1);
2468 
2469 		vie_advance(vie);
2470 	}
2471 
2472 	/*
2473 	 * Section "Operand-Size And Address-Size Attributes", Intel SDM, Vol 1
2474 	 */
2475 	if (cpu_mode == CPU_MODE_64BIT) {
2476 		/*
2477 		 * Default address size is 64-bits and default operand size
2478 		 * is 32-bits.
2479 		 */
2480 		vie->addrsize = vie->addrsize_override ? 4 : 8;
2481 		if (vie->rex_w)
2482 			vie->opsize = 8;
2483 		else if (vie->opsize_override)
2484 			vie->opsize = 2;
2485 		else
2486 			vie->opsize = 4;
2487 	} else if (cs_d) {
2488 		/* Default address and operand sizes are 32-bits */
2489 		vie->addrsize = vie->addrsize_override ? 2 : 4;
2490 		vie->opsize = vie->opsize_override ? 2 : 4;
2491 	} else {
2492 		/* Default address and operand sizes are 16-bits */
2493 		vie->addrsize = vie->addrsize_override ? 4 : 2;
2494 		vie->opsize = vie->opsize_override ? 4 : 2;
2495 	}
2496 	return (0);
2497 }
2498 
2499 static int
2500 decode_two_byte_opcode(struct vie *vie)
2501 {
2502 	uint8_t x;
2503 
2504 	if (vie_peek(vie, &x))
2505 		return (-1);
2506 
2507 	vie->op = two_byte_opcodes[x];
2508 
2509 	if (vie->op.op_type == VIE_OP_TYPE_NONE)
2510 		return (-1);
2511 
2512 	vie_advance(vie);
2513 	return (0);
2514 }
2515 
2516 static int
2517 decode_opcode(struct vie *vie)
2518 {
2519 	uint8_t x;
2520 
2521 	if (vie_peek(vie, &x))
2522 		return (-1);
2523 
2524 	/* Already did this via VEX prefix. */
2525 	if (vie->op.op_type != VIE_OP_TYPE_NONE)
2526 		return (0);
2527 
2528 	vie->op = one_byte_opcodes[x];
2529 
2530 	if (vie->op.op_type == VIE_OP_TYPE_NONE)
2531 		return (-1);
2532 
2533 	vie_advance(vie);
2534 
2535 	if (vie->op.op_type == VIE_OP_TYPE_TWO_BYTE)
2536 		return (decode_two_byte_opcode(vie));
2537 
2538 	return (0);
2539 }
2540 
2541 static int
2542 decode_modrm(struct vie *vie, enum vm_cpu_mode cpu_mode)
2543 {
2544 	uint8_t x;
2545 
2546 	if (vie->op.op_flags & VIE_OP_F_NO_MODRM)
2547 		return (0);
2548 
2549 	if (cpu_mode == CPU_MODE_REAL)
2550 		return (-1);
2551 
2552 	if (vie_peek(vie, &x))
2553 		return (-1);
2554 
2555 	vie->mod = (x >> 6) & 0x3;
2556 	vie->rm =  (x >> 0) & 0x7;
2557 	vie->reg = (x >> 3) & 0x7;
2558 
2559 	/*
2560 	 * A direct addressing mode makes no sense in the context of an EPT
2561 	 * fault. There has to be a memory access involved to cause the
2562 	 * EPT fault.
2563 	 */
2564 	if (vie->mod == VIE_MOD_DIRECT)
2565 		return (-1);
2566 
2567 	if ((vie->mod == VIE_MOD_INDIRECT && vie->rm == VIE_RM_DISP32) ||
2568 	    (vie->mod != VIE_MOD_DIRECT && vie->rm == VIE_RM_SIB)) {
2569 		/*
2570 		 * Table 2-5: Special Cases of REX Encodings
2571 		 *
2572 		 * mod=0, r/m=5 is used in the compatibility mode to
2573 		 * indicate a disp32 without a base register.
2574 		 *
2575 		 * mod!=3, r/m=4 is used in the compatibility mode to
2576 		 * indicate that the SIB byte is present.
2577 		 *
2578 		 * The 'b' bit in the REX prefix is don't care in
2579 		 * this case.
2580 		 */
2581 	} else {
2582 		vie->rm |= (vie->rex_b << 3);
2583 	}
2584 
2585 	vie->reg |= (vie->rex_r << 3);
2586 
2587 	/* SIB */
2588 	if (vie->mod != VIE_MOD_DIRECT && vie->rm == VIE_RM_SIB)
2589 		goto done;
2590 
2591 	vie->base_register = gpr_map[vie->rm];
2592 
2593 	switch (vie->mod) {
2594 	case VIE_MOD_INDIRECT_DISP8:
2595 		vie->disp_bytes = 1;
2596 		break;
2597 	case VIE_MOD_INDIRECT_DISP32:
2598 		vie->disp_bytes = 4;
2599 		break;
2600 	case VIE_MOD_INDIRECT:
2601 		if (vie->rm == VIE_RM_DISP32) {
2602 			vie->disp_bytes = 4;
2603 			/*
2604 			 * Table 2-7. RIP-Relative Addressing
2605 			 *
2606 			 * In 64-bit mode mod=00 r/m=101 implies [rip] + disp32
2607 			 * whereas in compatibility mode it just implies disp32.
2608 			 */
2609 
2610 			if (cpu_mode == CPU_MODE_64BIT)
2611 				vie->base_register = VM_REG_GUEST_RIP;
2612 			else
2613 				vie->base_register = VM_REG_LAST;
2614 		}
2615 		break;
2616 	}
2617 
2618 done:
2619 	vie_advance(vie);
2620 
2621 	return (0);
2622 }
2623 
2624 static int
2625 decode_sib(struct vie *vie)
2626 {
2627 	uint8_t x;
2628 
2629 	/* Proceed only if SIB byte is present */
2630 	if (vie->mod == VIE_MOD_DIRECT || vie->rm != VIE_RM_SIB)
2631 		return (0);
2632 
2633 	if (vie_peek(vie, &x))
2634 		return (-1);
2635 
2636 	/* De-construct the SIB byte */
2637 	vie->ss = (x >> 6) & 0x3;
2638 	vie->index = (x >> 3) & 0x7;
2639 	vie->base = (x >> 0) & 0x7;
2640 
2641 	/* Apply the REX prefix modifiers */
2642 	vie->index |= vie->rex_x << 3;
2643 	vie->base |= vie->rex_b << 3;
2644 
2645 	switch (vie->mod) {
2646 	case VIE_MOD_INDIRECT_DISP8:
2647 		vie->disp_bytes = 1;
2648 		break;
2649 	case VIE_MOD_INDIRECT_DISP32:
2650 		vie->disp_bytes = 4;
2651 		break;
2652 	}
2653 
2654 	if (vie->mod == VIE_MOD_INDIRECT &&
2655 	    (vie->base == 5 || vie->base == 13)) {
2656 		/*
2657 		 * Special case when base register is unused if mod = 0
2658 		 * and base = %rbp or %r13.
2659 		 *
2660 		 * Documented in:
2661 		 * Table 2-3: 32-bit Addressing Forms with the SIB Byte
2662 		 * Table 2-5: Special Cases of REX Encodings
2663 		 */
2664 		vie->disp_bytes = 4;
2665 	} else {
2666 		vie->base_register = gpr_map[vie->base];
2667 	}
2668 
2669 	/*
2670 	 * All encodings of 'index' are valid except for %rsp (4).
2671 	 *
2672 	 * Documented in:
2673 	 * Table 2-3: 32-bit Addressing Forms with the SIB Byte
2674 	 * Table 2-5: Special Cases of REX Encodings
2675 	 */
2676 	if (vie->index != 4)
2677 		vie->index_register = gpr_map[vie->index];
2678 
2679 	/* 'scale' makes sense only in the context of an index register */
2680 	if (vie->index_register < VM_REG_LAST)
2681 		vie->scale = 1 << vie->ss;
2682 
2683 	vie_advance(vie);
2684 
2685 	return (0);
2686 }
2687 
2688 static int
2689 decode_displacement(struct vie *vie)
2690 {
2691 	int n, i;
2692 	uint8_t x;
2693 
2694 	union {
2695 		char	buf[4];
2696 		int8_t	signed8;
2697 		int32_t	signed32;
2698 	} u;
2699 
2700 	if ((n = vie->disp_bytes) == 0)
2701 		return (0);
2702 
2703 	if (n != 1 && n != 4)
2704 		panic("decode_displacement: invalid disp_bytes %d", n);
2705 
2706 	for (i = 0; i < n; i++) {
2707 		if (vie_peek(vie, &x))
2708 			return (-1);
2709 
2710 		u.buf[i] = x;
2711 		vie_advance(vie);
2712 	}
2713 
2714 	if (n == 1)
2715 		vie->displacement = u.signed8;		/* sign-extended */
2716 	else
2717 		vie->displacement = u.signed32;		/* sign-extended */
2718 
2719 	return (0);
2720 }
2721 
2722 static int
2723 decode_immediate(struct vie *vie)
2724 {
2725 	int i, n;
2726 	uint8_t x;
2727 	union {
2728 		char	buf[4];
2729 		int8_t	signed8;
2730 		int16_t	signed16;
2731 		int32_t	signed32;
2732 	} u;
2733 
2734 	/* Figure out immediate operand size (if any) */
2735 	if (vie->op.op_flags & VIE_OP_F_IMM) {
2736 		/*
2737 		 * Section 2.2.1.5 "Immediates", Intel SDM:
2738 		 * In 64-bit mode the typical size of immediate operands
2739 		 * remains 32-bits. When the operand size if 64-bits, the
2740 		 * processor sign-extends all immediates to 64-bits prior
2741 		 * to their use.
2742 		 */
2743 		if (vie->opsize == 4 || vie->opsize == 8)
2744 			vie->imm_bytes = 4;
2745 		else
2746 			vie->imm_bytes = 2;
2747 	} else if (vie->op.op_flags & VIE_OP_F_IMM8) {
2748 		vie->imm_bytes = 1;
2749 	}
2750 
2751 	if ((n = vie->imm_bytes) == 0)
2752 		return (0);
2753 
2754 	KASSERT(n == 1 || n == 2 || n == 4,
2755 	    ("%s: invalid number of immediate bytes: %d", __func__, n));
2756 
2757 	for (i = 0; i < n; i++) {
2758 		if (vie_peek(vie, &x))
2759 			return (-1);
2760 
2761 		u.buf[i] = x;
2762 		vie_advance(vie);
2763 	}
2764 
2765 	/* sign-extend the immediate value before use */
2766 	if (n == 1)
2767 		vie->immediate = u.signed8;
2768 	else if (n == 2)
2769 		vie->immediate = u.signed16;
2770 	else
2771 		vie->immediate = u.signed32;
2772 
2773 	return (0);
2774 }
2775 
2776 static int
2777 decode_moffset(struct vie *vie)
2778 {
2779 	int i, n;
2780 	uint8_t x;
2781 	union {
2782 		char	buf[8];
2783 		uint64_t u64;
2784 	} u;
2785 
2786 	if ((vie->op.op_flags & VIE_OP_F_MOFFSET) == 0)
2787 		return (0);
2788 
2789 	/*
2790 	 * Section 2.2.1.4, "Direct Memory-Offset MOVs", Intel SDM:
2791 	 * The memory offset size follows the address-size of the instruction.
2792 	 */
2793 	n = vie->addrsize;
2794 	KASSERT(n == 2 || n == 4 || n == 8, ("invalid moffset bytes: %d", n));
2795 
2796 	u.u64 = 0;
2797 	for (i = 0; i < n; i++) {
2798 		if (vie_peek(vie, &x))
2799 			return (-1);
2800 
2801 		u.buf[i] = x;
2802 		vie_advance(vie);
2803 	}
2804 	vie->displacement = u.u64;
2805 	return (0);
2806 }
2807 
2808 #ifdef _KERNEL
2809 /*
2810  * Verify that the 'guest linear address' provided as collateral of the nested
2811  * page table fault matches with our instruction decoding.
2812  */
2813 static int
2814 verify_gla(struct vm *vm, int cpuid, uint64_t gla, struct vie *vie,
2815     enum vm_cpu_mode cpu_mode)
2816 {
2817 	int error;
2818 	uint64_t base, segbase, idx, gla2;
2819 	enum vm_reg_name seg;
2820 	struct seg_desc desc;
2821 
2822 	/* Skip 'gla' verification */
2823 	if (gla == VIE_INVALID_GLA)
2824 		return (0);
2825 
2826 	base = 0;
2827 	if (vie->base_register != VM_REG_LAST) {
2828 		error = vm_get_register(vm, cpuid, vie->base_register, &base);
2829 		if (error) {
2830 			printf("verify_gla: error %d getting base reg %d\n",
2831 				error, vie->base_register);
2832 			return (-1);
2833 		}
2834 
2835 		/*
2836 		 * RIP-relative addressing starts from the following
2837 		 * instruction
2838 		 */
2839 		if (vie->base_register == VM_REG_GUEST_RIP)
2840 			base += vie->num_processed;
2841 	}
2842 
2843 	idx = 0;
2844 	if (vie->index_register != VM_REG_LAST) {
2845 		error = vm_get_register(vm, cpuid, vie->index_register, &idx);
2846 		if (error) {
2847 			printf("verify_gla: error %d getting index reg %d\n",
2848 				error, vie->index_register);
2849 			return (-1);
2850 		}
2851 	}
2852 
2853 	/*
2854 	 * From "Specifying a Segment Selector", Intel SDM, Vol 1
2855 	 *
2856 	 * In 64-bit mode, segmentation is generally (but not
2857 	 * completely) disabled.  The exceptions are the FS and GS
2858 	 * segments.
2859 	 *
2860 	 * In legacy IA-32 mode, when the ESP or EBP register is used
2861 	 * as the base, the SS segment is the default segment.  For
2862 	 * other data references, except when relative to stack or
2863 	 * string destination the DS segment is the default.  These
2864 	 * can be overridden to allow other segments to be accessed.
2865 	 */
2866 	if (vie->segment_override)
2867 		seg = vie->segment_register;
2868 	else if (vie->base_register == VM_REG_GUEST_RSP ||
2869 	    vie->base_register == VM_REG_GUEST_RBP)
2870 		seg = VM_REG_GUEST_SS;
2871 	else
2872 		seg = VM_REG_GUEST_DS;
2873 	if (cpu_mode == CPU_MODE_64BIT && seg != VM_REG_GUEST_FS &&
2874 	    seg != VM_REG_GUEST_GS) {
2875 		segbase = 0;
2876 	} else {
2877 		error = vm_get_seg_desc(vm, cpuid, seg, &desc);
2878 		if (error) {
2879 			printf("verify_gla: error %d getting segment"
2880 			       " descriptor %d", error,
2881 			       vie->segment_register);
2882 			return (-1);
2883 		}
2884 		segbase = desc.base;
2885 	}
2886 
2887 	gla2 = segbase + base + vie->scale * idx + vie->displacement;
2888 	gla2 &= size2mask[vie->addrsize];
2889 	if (gla != gla2) {
2890 		printf("verify_gla mismatch: segbase(0x%0lx)"
2891 		       "base(0x%0lx), scale(%d), index(0x%0lx), "
2892 		       "disp(0x%0lx), gla(0x%0lx), gla2(0x%0lx)\n",
2893 		       segbase, base, vie->scale, idx, vie->displacement,
2894 		       gla, gla2);
2895 		return (-1);
2896 	}
2897 
2898 	return (0);
2899 }
2900 #endif	/* _KERNEL */
2901 
2902 int
2903 #ifdef _KERNEL
2904 vmm_decode_instruction(struct vm *vm, int cpuid, uint64_t gla,
2905 		       enum vm_cpu_mode cpu_mode, int cs_d, struct vie *vie)
2906 #else
2907 vmm_decode_instruction(enum vm_cpu_mode cpu_mode, int cs_d, struct vie *vie)
2908 #endif
2909 {
2910 
2911 	if (decode_prefixes(vie, cpu_mode, cs_d))
2912 		return (-1);
2913 
2914 	if (decode_opcode(vie))
2915 		return (-1);
2916 
2917 	if (decode_modrm(vie, cpu_mode))
2918 		return (-1);
2919 
2920 	if (decode_sib(vie))
2921 		return (-1);
2922 
2923 	if (decode_displacement(vie))
2924 		return (-1);
2925 
2926 	if (decode_immediate(vie))
2927 		return (-1);
2928 
2929 	if (decode_moffset(vie))
2930 		return (-1);
2931 
2932 #ifdef _KERNEL
2933 	if ((vie->op.op_flags & VIE_OP_F_NO_GLA_VERIFICATION) == 0) {
2934 		if (verify_gla(vm, cpuid, gla, vie, cpu_mode))
2935 			return (-1);
2936 	}
2937 #endif
2938 
2939 	vie->decoded = 1;	/* success */
2940 
2941 	return (0);
2942 }
2943