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