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