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