]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/vmm/vmm_instruction_emul.c
MFV r267565:
[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
48 #include <machine/vmm.h>
49
50 #include <assert.h>
51 #include <vmmapi.h>
52 #define KASSERT(exp,msg)        assert((exp))
53 #endif  /* _KERNEL */
54
55 #include <machine/vmm_instruction_emul.h>
56 #include <x86/psl.h>
57 #include <x86/specialreg.h>
58
59 /* struct vie_op.op_type */
60 enum {
61         VIE_OP_TYPE_NONE = 0,
62         VIE_OP_TYPE_MOV,
63         VIE_OP_TYPE_MOVSX,
64         VIE_OP_TYPE_MOVZX,
65         VIE_OP_TYPE_AND,
66         VIE_OP_TYPE_OR,
67         VIE_OP_TYPE_TWO_BYTE,
68         VIE_OP_TYPE_LAST
69 };
70
71 /* struct vie_op.op_flags */
72 #define VIE_OP_F_IMM            (1 << 0)        /* immediate operand present */
73 #define VIE_OP_F_IMM8           (1 << 1)        /* 8-bit immediate operand */
74
75 static const struct vie_op two_byte_opcodes[256] = {
76         [0xB6] = {
77                 .op_byte = 0xB6,
78                 .op_type = VIE_OP_TYPE_MOVZX,
79         },
80         [0xBE] = {
81                 .op_byte = 0xBE,
82                 .op_type = VIE_OP_TYPE_MOVSX,
83         },
84 };
85
86 static const struct vie_op one_byte_opcodes[256] = {
87         [0x0F] = {
88                 .op_byte = 0x0F,
89                 .op_type = VIE_OP_TYPE_TWO_BYTE
90         },
91         [0x88] = {
92                 .op_byte = 0x88,
93                 .op_type = VIE_OP_TYPE_MOV,
94         },
95         [0x89] = {
96                 .op_byte = 0x89,
97                 .op_type = VIE_OP_TYPE_MOV,
98         },
99         [0x8A] = {
100                 .op_byte = 0x8A,
101                 .op_type = VIE_OP_TYPE_MOV,
102         },
103         [0x8B] = {
104                 .op_byte = 0x8B,
105                 .op_type = VIE_OP_TYPE_MOV,
106         },
107         [0xC6] = {
108                 /* XXX Group 11 extended opcode - not just MOV */
109                 .op_byte = 0xC6,
110                 .op_type = VIE_OP_TYPE_MOV,
111                 .op_flags = VIE_OP_F_IMM8,
112         },
113         [0xC7] = {
114                 .op_byte = 0xC7,
115                 .op_type = VIE_OP_TYPE_MOV,
116                 .op_flags = VIE_OP_F_IMM,
117         },
118         [0x23] = {
119                 .op_byte = 0x23,
120                 .op_type = VIE_OP_TYPE_AND,
121         },
122         [0x81] = {
123                 /* XXX Group 1 extended opcode - not just AND */
124                 .op_byte = 0x81,
125                 .op_type = VIE_OP_TYPE_AND,
126                 .op_flags = VIE_OP_F_IMM,
127         },
128         [0x83] = {
129                 /* XXX Group 1 extended opcode - not just OR */
130                 .op_byte = 0x83,
131                 .op_type = VIE_OP_TYPE_OR,
132                 .op_flags = VIE_OP_F_IMM8,
133         },
134 };
135
136 /* struct vie.mod */
137 #define VIE_MOD_INDIRECT                0
138 #define VIE_MOD_INDIRECT_DISP8          1
139 #define VIE_MOD_INDIRECT_DISP32         2
140 #define VIE_MOD_DIRECT                  3
141
142 /* struct vie.rm */
143 #define VIE_RM_SIB                      4
144 #define VIE_RM_DISP32                   5
145
146 #define GB                              (1024 * 1024 * 1024)
147
148 static enum vm_reg_name gpr_map[16] = {
149         VM_REG_GUEST_RAX,
150         VM_REG_GUEST_RCX,
151         VM_REG_GUEST_RDX,
152         VM_REG_GUEST_RBX,
153         VM_REG_GUEST_RSP,
154         VM_REG_GUEST_RBP,
155         VM_REG_GUEST_RSI,
156         VM_REG_GUEST_RDI,
157         VM_REG_GUEST_R8,
158         VM_REG_GUEST_R9,
159         VM_REG_GUEST_R10,
160         VM_REG_GUEST_R11,
161         VM_REG_GUEST_R12,
162         VM_REG_GUEST_R13,
163         VM_REG_GUEST_R14,
164         VM_REG_GUEST_R15
165 };
166
167 static uint64_t size2mask[] = {
168         [1] = 0xff,
169         [2] = 0xffff,
170         [4] = 0xffffffff,
171         [8] = 0xffffffffffffffff,
172 };
173
174 static int
175 vie_read_register(void *vm, int vcpuid, enum vm_reg_name reg, uint64_t *rval)
176 {
177         int error;
178
179         error = vm_get_register(vm, vcpuid, reg, rval);
180
181         return (error);
182 }
183
184 static int
185 vie_read_bytereg(void *vm, int vcpuid, struct vie *vie, uint8_t *rval)
186 {
187         uint64_t val;
188         int error, rshift;
189         enum vm_reg_name reg;
190
191         rshift = 0;
192         reg = gpr_map[vie->reg];
193
194         /*
195          * 64-bit mode imposes limitations on accessing legacy byte registers.
196          *
197          * The legacy high-byte registers cannot be addressed if the REX
198          * prefix is present. In this case the values 4, 5, 6 and 7 of the
199          * 'ModRM:reg' field address %spl, %bpl, %sil and %dil respectively.
200          *
201          * If the REX prefix is not present then the values 4, 5, 6 and 7
202          * of the 'ModRM:reg' field address the legacy high-byte registers,
203          * %ah, %ch, %dh and %bh respectively.
204          */
205         if (!vie->rex_present) {
206                 if (vie->reg & 0x4) {
207                         /*
208                          * Obtain the value of %ah by reading %rax and shifting
209                          * right by 8 bits (same for %bh, %ch and %dh).
210                          */
211                         rshift = 8;
212                         reg = gpr_map[vie->reg & 0x3];
213                 }
214         }
215
216         error = vm_get_register(vm, vcpuid, reg, &val);
217         *rval = val >> rshift;
218         return (error);
219 }
220
221 int
222 vie_update_register(void *vm, int vcpuid, enum vm_reg_name reg,
223                     uint64_t val, int size)
224 {
225         int error;
226         uint64_t origval;
227
228         switch (size) {
229         case 1:
230         case 2:
231                 error = vie_read_register(vm, vcpuid, reg, &origval);
232                 if (error)
233                         return (error);
234                 val &= size2mask[size];
235                 val |= origval & ~size2mask[size];
236                 break;
237         case 4:
238                 val &= 0xffffffffUL;
239                 break;
240         case 8:
241                 break;
242         default:
243                 return (EINVAL);
244         }
245
246         error = vm_set_register(vm, vcpuid, reg, val);
247         return (error);
248 }
249
250 /*
251  * The following simplifying assumptions are made during emulation:
252  *
253  * - guest is in 64-bit mode
254  *   - default address size is 64-bits
255  *   - default operand size is 32-bits
256  *
257  * - operand size override is not supported
258  *
259  * - address size override is not supported
260  */
261 static int
262 emulate_mov(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
263             mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
264 {
265         int error, size;
266         enum vm_reg_name reg;
267         uint8_t byte;
268         uint64_t val;
269
270         size = 4;
271         error = EINVAL;
272
273         switch (vie->op.op_byte) {
274         case 0x88:
275                 /*
276                  * MOV byte from reg (ModRM:reg) to mem (ModRM:r/m)
277                  * 88/r:        mov r/m8, r8
278                  * REX + 88/r:  mov r/m8, r8 (%ah, %ch, %dh, %bh not available)
279                  */
280                 size = 1;
281                 error = vie_read_bytereg(vm, vcpuid, vie, &byte);
282                 if (error == 0)
283                         error = memwrite(vm, vcpuid, gpa, byte, size, arg);
284                 break;
285         case 0x89:
286                 /*
287                  * MOV from reg (ModRM:reg) to mem (ModRM:r/m)
288                  * 89/r:        mov r/m32, r32
289                  * REX.W + 89/r mov r/m64, r64
290                  */
291                 if (vie->rex_w)
292                         size = 8;
293                 reg = gpr_map[vie->reg];
294                 error = vie_read_register(vm, vcpuid, reg, &val);
295                 if (error == 0) {
296                         val &= size2mask[size];
297                         error = memwrite(vm, vcpuid, gpa, val, size, arg);
298                 }
299                 break;
300         case 0x8A:
301         case 0x8B:
302                 /*
303                  * MOV from mem (ModRM:r/m) to reg (ModRM:reg)
304                  * 8A/r:        mov r/m8, r8
305                  * REX + 8A/r:  mov r/m8, r8
306                  * 8B/r:        mov r32, r/m32
307                  * REX.W 8B/r:  mov r64, r/m64
308                  */
309                 if (vie->op.op_byte == 0x8A)
310                         size = 1;
311                 else if (vie->rex_w)
312                         size = 8;
313                 error = memread(vm, vcpuid, gpa, &val, size, arg);
314                 if (error == 0) {
315                         reg = gpr_map[vie->reg];
316                         error = vie_update_register(vm, vcpuid, reg, val, size);
317                 }
318                 break;
319         case 0xC6:
320                 /*
321                  * MOV from imm8 to mem (ModRM:r/m)
322                  * C6/0         mov r/m8, imm8
323                  * REX + C6/0   mov r/m8, imm8
324                  */
325                 size = 1;
326                 error = memwrite(vm, vcpuid, gpa, vie->immediate, size, arg);
327                 break;
328         case 0xC7:
329                 /*
330                  * MOV from imm32 to mem (ModRM:r/m)
331                  * C7/0         mov r/m32, imm32
332                  * REX.W + C7/0 mov r/m64, imm32 (sign-extended to 64-bits)
333                  */
334                 val = vie->immediate;           /* already sign-extended */
335
336                 if (vie->rex_w)
337                         size = 8;
338
339                 if (size != 8)
340                         val &= size2mask[size];
341
342                 error = memwrite(vm, vcpuid, gpa, val, size, arg);
343                 break;
344         default:
345                 break;
346         }
347
348         return (error);
349 }
350
351 /*
352  * The following simplifying assumptions are made during emulation:
353  *
354  * - guest is in 64-bit mode
355  *   - default address size is 64-bits
356  *   - default operand size is 32-bits
357  *
358  * - operand size override is not supported
359  *
360  * - address size override is not supported
361  */
362 static int
363 emulate_movx(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
364              mem_region_read_t memread, mem_region_write_t memwrite,
365              void *arg)
366 {
367         int error, size;
368         enum vm_reg_name reg;
369         uint64_t val;
370
371         size = 4;
372         error = EINVAL;
373
374         switch (vie->op.op_byte) {
375         case 0xB6:
376                 /*
377                  * MOV and zero extend byte from mem (ModRM:r/m) to
378                  * reg (ModRM:reg).
379                  *
380                  * 0F B6/r              movzx r/m8, r32
381                  * REX.W + 0F B6/r      movzx r/m8, r64
382                  */
383
384                 /* get the first operand */
385                 error = memread(vm, vcpuid, gpa, &val, 1, arg);
386                 if (error)
387                         break;
388
389                 /* get the second operand */
390                 reg = gpr_map[vie->reg];
391
392                 if (vie->rex_w)
393                         size = 8;
394
395                 /* write the result */
396                 error = vie_update_register(vm, vcpuid, reg, val, size);
397                 break;
398         case 0xBE:
399                 /*
400                  * MOV and sign extend byte from mem (ModRM:r/m) to
401                  * reg (ModRM:reg).
402                  *
403                  * 0F BE/r              movsx r/m8, r32
404                  * REX.W + 0F BE/r      movsx r/m8, r64
405                  */
406
407                 /* get the first operand */
408                 error = memread(vm, vcpuid, gpa, &val, 1, arg);
409                 if (error)
410                         break;
411
412                 /* get the second operand */
413                 reg = gpr_map[vie->reg];
414
415                 if (vie->rex_w)
416                         size = 8;
417
418                 /* sign extend byte */
419                 val = (int8_t)val;
420
421                 /* write the result */
422                 error = vie_update_register(vm, vcpuid, reg, val, size);
423                 break;
424         default:
425                 break;
426         }
427         return (error);
428 }
429
430 static int
431 emulate_and(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
432             mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
433 {
434         int error, size;
435         enum vm_reg_name reg;
436         uint64_t val1, val2;
437
438         size = 4;
439         error = EINVAL;
440
441         switch (vie->op.op_byte) {
442         case 0x23:
443                 /*
444                  * AND reg (ModRM:reg) and mem (ModRM:r/m) and store the
445                  * result in reg.
446                  *
447                  * 23/r         and r32, r/m32
448                  * REX.W + 23/r and r64, r/m64
449                  */
450                 if (vie->rex_w)
451                         size = 8;
452
453                 /* get the first operand */
454                 reg = gpr_map[vie->reg];
455                 error = vie_read_register(vm, vcpuid, reg, &val1);
456                 if (error)
457                         break;
458
459                 /* get the second operand */
460                 error = memread(vm, vcpuid, gpa, &val2, size, arg);
461                 if (error)
462                         break;
463
464                 /* perform the operation and write the result */
465                 val1 &= val2;
466                 error = vie_update_register(vm, vcpuid, reg, val1, size);
467                 break;
468         case 0x81:
469                 /*
470                  * AND mem (ModRM:r/m) with immediate and store the
471                  * result in mem.
472                  *
473                  * 81/          and r/m32, imm32
474                  * REX.W + 81/  and r/m64, imm32 sign-extended to 64
475                  *
476                  * Currently, only the AND operation of the 0x81 opcode
477                  * is implemented (ModRM:reg = b100).
478                  */
479                 if ((vie->reg & 7) != 4)
480                         break;
481
482                 if (vie->rex_w)
483                         size = 8;
484                 
485                 /* get the first operand */
486                 error = memread(vm, vcpuid, gpa, &val1, size, arg);
487                 if (error)
488                         break;
489
490                 /*
491                  * perform the operation with the pre-fetched immediate
492                  * operand and write the result
493                  */
494                 val1 &= vie->immediate;
495                 error = memwrite(vm, vcpuid, gpa, val1, size, arg);
496                 break;
497         default:
498                 break;
499         }
500         return (error);
501 }
502
503 static int
504 emulate_or(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
505             mem_region_read_t memread, mem_region_write_t memwrite, void *arg)
506 {
507         int error, size;
508         uint64_t val1;
509
510         size = 4;
511         error = EINVAL;
512
513         switch (vie->op.op_byte) {
514         case 0x83:
515                 /*
516                  * OR mem (ModRM:r/m) with immediate and store the
517                  * result in mem.
518                  *
519                  * 83/          OR r/m32, imm8 sign-extended to 32
520                  * REX.W + 83/  OR r/m64, imm8 sign-extended to 64
521                  *
522                  * Currently, only the OR operation of the 0x83 opcode
523                  * is implemented (ModRM:reg = b001).
524                  */
525                 if ((vie->reg & 7) != 1)
526                         break;
527
528                 if (vie->rex_w)
529                         size = 8;
530                 
531                 /* get the first operand */
532                 error = memread(vm, vcpuid, gpa, &val1, size, arg);
533                 if (error)
534                         break;
535
536                 /*
537                  * perform the operation with the pre-fetched immediate
538                  * operand and write the result
539                  */
540                 val1 |= vie->immediate;
541                 error = memwrite(vm, vcpuid, gpa, val1, size, arg);
542                 break;
543         default:
544                 break;
545         }
546         return (error);
547 }
548
549 int
550 vmm_emulate_instruction(void *vm, int vcpuid, uint64_t gpa, struct vie *vie,
551                         mem_region_read_t memread, mem_region_write_t memwrite,
552                         void *memarg)
553 {
554         int error;
555
556         if (!vie->decoded)
557                 return (EINVAL);
558
559         switch (vie->op.op_type) {
560         case VIE_OP_TYPE_MOV:
561                 error = emulate_mov(vm, vcpuid, gpa, vie,
562                                     memread, memwrite, memarg);
563                 break;
564         case VIE_OP_TYPE_MOVSX:
565         case VIE_OP_TYPE_MOVZX:
566                 error = emulate_movx(vm, vcpuid, gpa, vie,
567                                      memread, memwrite, memarg);
568                 break;
569         case VIE_OP_TYPE_AND:
570                 error = emulate_and(vm, vcpuid, gpa, vie,
571                                     memread, memwrite, memarg);
572                 break;
573         case VIE_OP_TYPE_OR:
574                 error = emulate_or(vm, vcpuid, gpa, vie,
575                                     memread, memwrite, memarg);
576                 break;
577         default:
578                 error = EINVAL;
579                 break;
580         }
581
582         return (error);
583 }
584
585 int
586 vie_alignment_check(int cpl, int size, uint64_t cr0, uint64_t rf, uint64_t gla)
587 {
588         KASSERT(size == 1 || size == 2 || size == 4 || size == 8,
589             ("%s: invalid size %d", __func__, size));
590         KASSERT(cpl >= 0 && cpl <= 3, ("%s: invalid cpl %d", __func__, cpl));
591
592         if (cpl != 3 || (cr0 & CR0_AM) == 0 || (rf & PSL_AC) == 0)
593                 return (0);
594
595         return ((gla & (size - 1)) ? 1 : 0);
596 }
597
598 int
599 vie_canonical_check(enum vm_cpu_mode cpu_mode, uint64_t gla)
600 {
601         uint64_t mask;
602
603         if (cpu_mode != CPU_MODE_64BIT)
604                 return (0);
605
606         /*
607          * The value of the bit 47 in the 'gla' should be replicated in the
608          * most significant 16 bits.
609          */
610         mask = ~((1UL << 48) - 1);
611         if (gla & (1UL << 47))
612                 return ((gla & mask) != mask);
613         else
614                 return ((gla & mask) != 0);
615 }
616
617 uint64_t
618 vie_size2mask(int size)
619 {
620         KASSERT(size == 1 || size == 2 || size == 4 || size == 8,
621             ("vie_size2mask: invalid size %d", size));
622         return (size2mask[size]);
623 }
624
625 int
626 vie_calculate_gla(enum vm_cpu_mode cpu_mode, enum vm_reg_name seg,
627     struct seg_desc *desc, uint64_t offset, int length, int addrsize,
628     int prot, uint64_t *gla)
629 {
630         uint64_t low_limit, high_limit, segbase;
631         int glasize, type;
632
633         KASSERT(seg >= VM_REG_GUEST_ES && seg <= VM_REG_GUEST_GS,
634             ("%s: invalid segment %d", __func__, seg));
635         KASSERT(length == 1 || length == 2 || length == 4 || length == 8,
636             ("%s: invalid operand size %d", __func__, length));
637         KASSERT((prot & ~(PROT_READ | PROT_WRITE)) == 0,
638             ("%s: invalid prot %#x", __func__, prot));
639
640         if (cpu_mode == CPU_MODE_64BIT) {
641                 KASSERT(addrsize == 4 || addrsize == 8, ("%s: invalid address "
642                     "size %d for cpu_mode %d", __func__, addrsize, cpu_mode));
643                 glasize = 8;
644         } else {
645                 KASSERT(addrsize == 2 || addrsize == 4, ("%s: invalid address "
646                     "size %d for cpu mode %d", __func__, addrsize, cpu_mode));
647                 glasize = 4;
648                 /*
649                  * If the segment selector is loaded with a NULL selector
650                  * then the descriptor is unusable and attempting to use
651                  * it results in a #GP(0).
652                  */
653                 if (SEG_DESC_UNUSABLE(desc))
654                         return (-1);
655
656                 /* 
657                  * The processor generates a #NP exception when a segment
658                  * register is loaded with a selector that points to a
659                  * descriptor that is not present. If this was the case then
660                  * it would have been checked before the VM-exit.
661                  */
662                 KASSERT(SEG_DESC_PRESENT(desc), ("segment %d not present: %#x",
663                     seg, desc->access));
664
665                 /*
666                  * The descriptor type must indicate a code/data segment.
667                  */
668                 type = SEG_DESC_TYPE(desc);
669                 KASSERT(type >= 16 && type <= 31, ("segment %d has invalid "
670                     "descriptor type %#x", seg, type));
671
672                 if (prot & PROT_READ) {
673                         /* #GP on a read access to a exec-only code segment */
674                         if ((type & 0xA) == 0x8)
675                                 return (-1);
676                 }
677
678                 if (prot & PROT_WRITE) {
679                         /*
680                          * #GP on a write access to a code segment or a
681                          * read-only data segment.
682                          */
683                         if (type & 0x8)                 /* code segment */
684                                 return (-1);
685
686                         if ((type & 0xA) == 0)          /* read-only data seg */
687                                 return (-1);
688                 }
689
690                 /*
691                  * 'desc->limit' is fully expanded taking granularity into
692                  * account.
693                  */
694                 if ((type & 0xC) == 0x4) {
695                         /* expand-down data segment */
696                         low_limit = desc->limit + 1;
697                         high_limit = SEG_DESC_DEF32(desc) ? 0xffffffff : 0xffff;
698                 } else {
699                         /* code segment or expand-up data segment */
700                         low_limit = 0;
701                         high_limit = desc->limit;
702                 }
703
704                 while (length > 0) {
705                         offset &= vie_size2mask(addrsize);
706                         if (offset < low_limit || offset > high_limit)
707                                 return (-1);
708                         offset++;
709                         length--;
710                 }
711         }
712
713         /*
714          * In 64-bit mode all segments except %fs and %gs have a segment
715          * base address of 0.
716          */
717         if (cpu_mode == CPU_MODE_64BIT && seg != VM_REG_GUEST_FS &&
718             seg != VM_REG_GUEST_GS) {
719                 segbase = 0;
720         } else {
721                 segbase = desc->base;
722         }
723
724         /*
725          * Truncate 'offset' to the effective address size before adding
726          * it to the segment base.
727          */
728         offset &= vie_size2mask(addrsize);
729         *gla = (segbase + offset) & vie_size2mask(glasize);
730         return (0);
731 }
732
733 #ifdef _KERNEL
734 void
735 vie_init(struct vie *vie)
736 {
737
738         bzero(vie, sizeof(struct vie));
739
740         vie->base_register = VM_REG_LAST;
741         vie->index_register = VM_REG_LAST;
742 }
743
744 static int
745 pf_error_code(int usermode, int prot, int rsvd, uint64_t pte)
746 {
747         int error_code = 0;
748
749         if (pte & PG_V)
750                 error_code |= PGEX_P;
751         if (prot & VM_PROT_WRITE)
752                 error_code |= PGEX_W;
753         if (usermode)
754                 error_code |= PGEX_U;
755         if (rsvd)
756                 error_code |= PGEX_RSV;
757         if (prot & VM_PROT_EXECUTE)
758                 error_code |= PGEX_I;
759
760         return (error_code);
761 }
762
763 static void
764 ptp_release(void **cookie)
765 {
766         if (*cookie != NULL) {
767                 vm_gpa_release(*cookie);
768                 *cookie = NULL;
769         }
770 }
771
772 static void *
773 ptp_hold(struct vm *vm, vm_paddr_t ptpphys, size_t len, void **cookie)
774 {
775         void *ptr;
776
777         ptp_release(cookie);
778         ptr = vm_gpa_hold(vm, ptpphys, len, VM_PROT_RW, cookie);
779         return (ptr);
780 }
781
782 int
783 vmm_gla2gpa(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
784     uint64_t gla, int prot, uint64_t *gpa)
785 {
786         int nlevels, pfcode, ptpshift, ptpindex, retval, usermode, writable;
787         u_int retries;
788         uint64_t *ptpbase, ptpphys, pte, pgsize;
789         uint32_t *ptpbase32, pte32;
790         void *cookie;
791
792         usermode = (paging->cpl == 3 ? 1 : 0);
793         writable = prot & VM_PROT_WRITE;
794         cookie = NULL;
795         retval = 0;
796         retries = 0;
797 restart:
798         ptpphys = paging->cr3;          /* root of the page tables */
799         ptp_release(&cookie);
800         if (retries++ > 0)
801                 maybe_yield();
802
803         if (vie_canonical_check(paging->cpu_mode, gla)) {
804                 /*
805                  * XXX assuming a non-stack reference otherwise a stack fault
806                  * should be generated.
807                  */
808                 vm_inject_gp(vm, vcpuid);
809                 goto fault;
810         }
811
812         if (paging->paging_mode == PAGING_MODE_FLAT) {
813                 *gpa = gla;
814                 goto done;
815         }
816
817         if (paging->paging_mode == PAGING_MODE_32) {
818                 nlevels = 2;
819                 while (--nlevels >= 0) {
820                         /* Zero out the lower 12 bits. */
821                         ptpphys &= ~0xfff;
822
823                         ptpbase32 = ptp_hold(vm, ptpphys, PAGE_SIZE, &cookie);
824
825                         if (ptpbase32 == NULL)
826                                 goto error;
827
828                         ptpshift = PAGE_SHIFT + nlevels * 10;
829                         ptpindex = (gla >> ptpshift) & 0x3FF;
830                         pgsize = 1UL << ptpshift;
831
832                         pte32 = ptpbase32[ptpindex];
833
834                         if ((pte32 & PG_V) == 0 ||
835                             (usermode && (pte32 & PG_U) == 0) ||
836                             (writable && (pte32 & PG_RW) == 0)) {
837                                 pfcode = pf_error_code(usermode, prot, 0,
838                                     pte32);
839                                 vm_inject_pf(vm, vcpuid, pfcode, gla);
840                                 goto fault;
841                         }
842
843                         /*
844                          * Emulate the x86 MMU's management of the accessed
845                          * and dirty flags. While the accessed flag is set
846                          * at every level of the page table, the dirty flag
847                          * is only set at the last level providing the guest
848                          * physical address.
849                          */
850                         if ((pte32 & PG_A) == 0) {
851                                 if (atomic_cmpset_32(&ptpbase32[ptpindex],
852                                     pte32, pte32 | PG_A) == 0) {
853                                         goto restart;
854                                 }
855                         }
856
857                         /* XXX must be ignored if CR4.PSE=0 */
858                         if (nlevels > 0 && (pte32 & PG_PS) != 0)
859                                 break;
860
861                         ptpphys = pte32;
862                 }
863
864                 /* Set the dirty bit in the page table entry if necessary */
865                 if (writable && (pte32 & PG_M) == 0) {
866                         if (atomic_cmpset_32(&ptpbase32[ptpindex],
867                             pte32, pte32 | PG_M) == 0) {
868                                 goto restart;
869                         }
870                 }
871
872                 /* Zero out the lower 'ptpshift' bits */
873                 pte32 >>= ptpshift; pte32 <<= ptpshift;
874                 *gpa = pte32 | (gla & (pgsize - 1));
875                 goto done;
876         }
877
878         if (paging->paging_mode == PAGING_MODE_PAE) {
879                 /* Zero out the lower 5 bits and the upper 32 bits */
880                 ptpphys &= 0xffffffe0UL;
881
882                 ptpbase = ptp_hold(vm, ptpphys, sizeof(*ptpbase) * 4, &cookie);
883                 if (ptpbase == NULL)
884                         goto error;
885
886                 ptpindex = (gla >> 30) & 0x3;
887
888                 pte = ptpbase[ptpindex];
889
890                 if ((pte & PG_V) == 0) {
891                         pfcode = pf_error_code(usermode, prot, 0, pte);
892                         vm_inject_pf(vm, vcpuid, pfcode, gla);
893                         goto fault;
894                 }
895
896                 ptpphys = pte;
897
898                 nlevels = 2;
899         } else
900                 nlevels = 4;
901         while (--nlevels >= 0) {
902                 /* Zero out the lower 12 bits and the upper 12 bits */
903                 ptpphys >>= 12; ptpphys <<= 24; ptpphys >>= 12;
904
905                 ptpbase = ptp_hold(vm, ptpphys, PAGE_SIZE, &cookie);
906                 if (ptpbase == NULL)
907                         goto error;
908
909                 ptpshift = PAGE_SHIFT + nlevels * 9;
910                 ptpindex = (gla >> ptpshift) & 0x1FF;
911                 pgsize = 1UL << ptpshift;
912
913                 pte = ptpbase[ptpindex];
914
915                 if ((pte & PG_V) == 0 ||
916                     (usermode && (pte & PG_U) == 0) ||
917                     (writable && (pte & PG_RW) == 0)) {
918                         pfcode = pf_error_code(usermode, prot, 0, pte);
919                         vm_inject_pf(vm, vcpuid, pfcode, gla);
920                         goto fault;
921                 }
922
923                 /* Set the accessed bit in the page table entry */
924                 if ((pte & PG_A) == 0) {
925                         if (atomic_cmpset_64(&ptpbase[ptpindex],
926                             pte, pte | PG_A) == 0) {
927                                 goto restart;
928                         }
929                 }
930
931                 if (nlevels > 0 && (pte & PG_PS) != 0) {
932                         if (pgsize > 1 * GB) {
933                                 pfcode = pf_error_code(usermode, prot, 1, pte);
934                                 vm_inject_pf(vm, vcpuid, pfcode, gla);
935                                 goto fault;
936                         }
937                         break;
938                 }
939
940                 ptpphys = pte;
941         }
942
943         /* Set the dirty bit in the page table entry if necessary */
944         if (writable && (pte & PG_M) == 0) {
945                 if (atomic_cmpset_64(&ptpbase[ptpindex], pte, pte | PG_M) == 0)
946                         goto restart;
947         }
948
949         /* Zero out the lower 'ptpshift' bits and the upper 12 bits */
950         pte >>= ptpshift; pte <<= (ptpshift + 12); pte >>= 12;
951         *gpa = pte | (gla & (pgsize - 1));
952 done:
953         ptp_release(&cookie);
954         return (retval);
955 error:
956         retval = -1;
957         goto done;
958 fault:
959         retval = 1;
960         goto done;
961 }
962
963 int
964 vmm_fetch_instruction(struct vm *vm, int cpuid, struct vm_guest_paging *paging,
965     uint64_t rip, int inst_length, struct vie *vie)
966 {
967         int n, error, prot;
968         uint64_t gpa, off;
969         void *hpa, *cookie;
970
971         /*
972          * XXX cache previously fetched instructions using 'rip' as the tag
973          */
974
975         prot = VM_PROT_READ | VM_PROT_EXECUTE;
976         if (inst_length > VIE_INST_SIZE)
977                 panic("vmm_fetch_instruction: invalid length %d", inst_length);
978
979         /* Copy the instruction into 'vie' */
980         while (vie->num_valid < inst_length) {
981                 error = vmm_gla2gpa(vm, cpuid, paging, rip, prot, &gpa);
982                 if (error)
983                         return (error);
984
985                 off = gpa & PAGE_MASK;
986                 n = min(inst_length - vie->num_valid, PAGE_SIZE - off);
987
988                 if ((hpa = vm_gpa_hold(vm, gpa, n, prot, &cookie)) == NULL)
989                         break;
990
991                 bcopy(hpa, &vie->inst[vie->num_valid], n);
992
993                 vm_gpa_release(cookie);
994
995                 rip += n;
996                 vie->num_valid += n;
997         }
998
999         if (vie->num_valid == inst_length)
1000                 return (0);
1001         else
1002                 return (-1);
1003 }
1004
1005 static int
1006 vie_peek(struct vie *vie, uint8_t *x)
1007 {
1008
1009         if (vie->num_processed < vie->num_valid) {
1010                 *x = vie->inst[vie->num_processed];
1011                 return (0);
1012         } else
1013                 return (-1);
1014 }
1015
1016 static void
1017 vie_advance(struct vie *vie)
1018 {
1019
1020         vie->num_processed++;
1021 }
1022
1023 static int
1024 decode_rex(struct vie *vie)
1025 {
1026         uint8_t x;
1027
1028         if (vie_peek(vie, &x))
1029                 return (-1);
1030
1031         if (x >= 0x40 && x <= 0x4F) {
1032                 vie->rex_present = 1;
1033
1034                 vie->rex_w = x & 0x8 ? 1 : 0;
1035                 vie->rex_r = x & 0x4 ? 1 : 0;
1036                 vie->rex_x = x & 0x2 ? 1 : 0;
1037                 vie->rex_b = x & 0x1 ? 1 : 0;
1038
1039                 vie_advance(vie);
1040         }
1041
1042         return (0);
1043 }
1044
1045 static int
1046 decode_two_byte_opcode(struct vie *vie)
1047 {
1048         uint8_t x;
1049
1050         if (vie_peek(vie, &x))
1051                 return (-1);
1052
1053         vie->op = two_byte_opcodes[x];
1054
1055         if (vie->op.op_type == VIE_OP_TYPE_NONE)
1056                 return (-1);
1057
1058         vie_advance(vie);
1059         return (0);
1060 }
1061
1062 static int
1063 decode_opcode(struct vie *vie)
1064 {
1065         uint8_t x;
1066
1067         if (vie_peek(vie, &x))
1068                 return (-1);
1069
1070         vie->op = one_byte_opcodes[x];
1071
1072         if (vie->op.op_type == VIE_OP_TYPE_NONE)
1073                 return (-1);
1074
1075         vie_advance(vie);
1076
1077         if (vie->op.op_type == VIE_OP_TYPE_TWO_BYTE)
1078                 return (decode_two_byte_opcode(vie));
1079
1080         return (0);
1081 }
1082
1083 static int
1084 decode_modrm(struct vie *vie, enum vm_cpu_mode cpu_mode)
1085 {
1086         uint8_t x;
1087
1088         if (vie_peek(vie, &x))
1089                 return (-1);
1090
1091         vie->mod = (x >> 6) & 0x3;
1092         vie->rm =  (x >> 0) & 0x7;
1093         vie->reg = (x >> 3) & 0x7;
1094
1095         /*
1096          * A direct addressing mode makes no sense in the context of an EPT
1097          * fault. There has to be a memory access involved to cause the
1098          * EPT fault.
1099          */
1100         if (vie->mod == VIE_MOD_DIRECT)
1101                 return (-1);
1102
1103         if ((vie->mod == VIE_MOD_INDIRECT && vie->rm == VIE_RM_DISP32) ||
1104             (vie->mod != VIE_MOD_DIRECT && vie->rm == VIE_RM_SIB)) {
1105                 /*
1106                  * Table 2-5: Special Cases of REX Encodings
1107                  *
1108                  * mod=0, r/m=5 is used in the compatibility mode to
1109                  * indicate a disp32 without a base register.
1110                  *
1111                  * mod!=3, r/m=4 is used in the compatibility mode to
1112                  * indicate that the SIB byte is present.
1113                  *
1114                  * The 'b' bit in the REX prefix is don't care in
1115                  * this case.
1116                  */
1117         } else {
1118                 vie->rm |= (vie->rex_b << 3);
1119         }
1120
1121         vie->reg |= (vie->rex_r << 3);
1122
1123         /* SIB */
1124         if (vie->mod != VIE_MOD_DIRECT && vie->rm == VIE_RM_SIB)
1125                 goto done;
1126
1127         vie->base_register = gpr_map[vie->rm];
1128
1129         switch (vie->mod) {
1130         case VIE_MOD_INDIRECT_DISP8:
1131                 vie->disp_bytes = 1;
1132                 break;
1133         case VIE_MOD_INDIRECT_DISP32:
1134                 vie->disp_bytes = 4;
1135                 break;
1136         case VIE_MOD_INDIRECT:
1137                 if (vie->rm == VIE_RM_DISP32) {
1138                         vie->disp_bytes = 4;
1139                         /*
1140                          * Table 2-7. RIP-Relative Addressing
1141                          *
1142                          * In 64-bit mode mod=00 r/m=101 implies [rip] + disp32
1143                          * whereas in compatibility mode it just implies disp32.
1144                          */
1145
1146                         if (cpu_mode == CPU_MODE_64BIT)
1147                                 vie->base_register = VM_REG_GUEST_RIP;
1148                         else
1149                                 vie->base_register = VM_REG_LAST;
1150                 }
1151                 break;
1152         }
1153
1154 done:
1155         vie_advance(vie);
1156
1157         return (0);
1158 }
1159
1160 static int
1161 decode_sib(struct vie *vie)
1162 {
1163         uint8_t x;
1164
1165         /* Proceed only if SIB byte is present */
1166         if (vie->mod == VIE_MOD_DIRECT || vie->rm != VIE_RM_SIB)
1167                 return (0);
1168
1169         if (vie_peek(vie, &x))
1170                 return (-1);
1171
1172         /* De-construct the SIB byte */
1173         vie->ss = (x >> 6) & 0x3;
1174         vie->index = (x >> 3) & 0x7;
1175         vie->base = (x >> 0) & 0x7;
1176
1177         /* Apply the REX prefix modifiers */
1178         vie->index |= vie->rex_x << 3;
1179         vie->base |= vie->rex_b << 3;
1180
1181         switch (vie->mod) {
1182         case VIE_MOD_INDIRECT_DISP8:
1183                 vie->disp_bytes = 1;
1184                 break;
1185         case VIE_MOD_INDIRECT_DISP32:
1186                 vie->disp_bytes = 4;
1187                 break;
1188         }
1189
1190         if (vie->mod == VIE_MOD_INDIRECT &&
1191             (vie->base == 5 || vie->base == 13)) {
1192                 /*
1193                  * Special case when base register is unused if mod = 0
1194                  * and base = %rbp or %r13.
1195                  *
1196                  * Documented in:
1197                  * Table 2-3: 32-bit Addressing Forms with the SIB Byte
1198                  * Table 2-5: Special Cases of REX Encodings
1199                  */
1200                 vie->disp_bytes = 4;
1201         } else {
1202                 vie->base_register = gpr_map[vie->base];
1203         }
1204
1205         /*
1206          * All encodings of 'index' are valid except for %rsp (4).
1207          *
1208          * Documented in:
1209          * Table 2-3: 32-bit Addressing Forms with the SIB Byte
1210          * Table 2-5: Special Cases of REX Encodings
1211          */
1212         if (vie->index != 4)
1213                 vie->index_register = gpr_map[vie->index];
1214
1215         /* 'scale' makes sense only in the context of an index register */
1216         if (vie->index_register < VM_REG_LAST)
1217                 vie->scale = 1 << vie->ss;
1218
1219         vie_advance(vie);
1220
1221         return (0);
1222 }
1223
1224 static int
1225 decode_displacement(struct vie *vie)
1226 {
1227         int n, i;
1228         uint8_t x;
1229
1230         union {
1231                 char    buf[4];
1232                 int8_t  signed8;
1233                 int32_t signed32;
1234         } u;
1235
1236         if ((n = vie->disp_bytes) == 0)
1237                 return (0);
1238
1239         if (n != 1 && n != 4)
1240                 panic("decode_displacement: invalid disp_bytes %d", n);
1241
1242         for (i = 0; i < n; i++) {
1243                 if (vie_peek(vie, &x))
1244                         return (-1);
1245
1246                 u.buf[i] = x;
1247                 vie_advance(vie);
1248         }
1249
1250         if (n == 1)
1251                 vie->displacement = u.signed8;          /* sign-extended */
1252         else
1253                 vie->displacement = u.signed32;         /* sign-extended */
1254
1255         return (0);
1256 }
1257
1258 static int
1259 decode_immediate(struct vie *vie)
1260 {
1261         int i, n;
1262         uint8_t x;
1263         union {
1264                 char    buf[4];
1265                 int8_t  signed8;
1266                 int32_t signed32;
1267         } u;
1268
1269         /* Figure out immediate operand size (if any) */
1270         if (vie->op.op_flags & VIE_OP_F_IMM)
1271                 vie->imm_bytes = 4;
1272         else if (vie->op.op_flags & VIE_OP_F_IMM8)
1273                 vie->imm_bytes = 1;
1274
1275         if ((n = vie->imm_bytes) == 0)
1276                 return (0);
1277
1278         if (n != 1 && n != 4)
1279                 panic("decode_immediate: invalid imm_bytes %d", n);
1280
1281         for (i = 0; i < n; i++) {
1282                 if (vie_peek(vie, &x))
1283                         return (-1);
1284
1285                 u.buf[i] = x;
1286                 vie_advance(vie);
1287         }
1288         
1289         if (n == 1)
1290                 vie->immediate = u.signed8;             /* sign-extended */
1291         else
1292                 vie->immediate = u.signed32;            /* sign-extended */
1293
1294         return (0);
1295 }
1296
1297 /*
1298  * Verify that all the bytes in the instruction buffer were consumed.
1299  */
1300 static int
1301 verify_inst_length(struct vie *vie)
1302 {
1303
1304         if (vie->num_processed == vie->num_valid)
1305                 return (0);
1306         else
1307                 return (-1);
1308 }
1309
1310 /*
1311  * Verify that the 'guest linear address' provided as collateral of the nested
1312  * page table fault matches with our instruction decoding.
1313  */
1314 static int
1315 verify_gla(struct vm *vm, int cpuid, uint64_t gla, struct vie *vie)
1316 {
1317         int error;
1318         uint64_t base, idx;
1319
1320         /* Skip 'gla' verification */
1321         if (gla == VIE_INVALID_GLA)
1322                 return (0);
1323
1324         base = 0;
1325         if (vie->base_register != VM_REG_LAST) {
1326                 error = vm_get_register(vm, cpuid, vie->base_register, &base);
1327                 if (error) {
1328                         printf("verify_gla: error %d getting base reg %d\n",
1329                                 error, vie->base_register);
1330                         return (-1);
1331                 }
1332
1333                 /*
1334                  * RIP-relative addressing starts from the following
1335                  * instruction
1336                  */
1337                 if (vie->base_register == VM_REG_GUEST_RIP)
1338                         base += vie->num_valid;
1339         }
1340
1341         idx = 0;
1342         if (vie->index_register != VM_REG_LAST) {
1343                 error = vm_get_register(vm, cpuid, vie->index_register, &idx);
1344                 if (error) {
1345                         printf("verify_gla: error %d getting index reg %d\n",
1346                                 error, vie->index_register);
1347                         return (-1);
1348                 }
1349         }
1350
1351         if (base + vie->scale * idx + vie->displacement != gla) {
1352                 printf("verify_gla mismatch: "
1353                        "base(0x%0lx), scale(%d), index(0x%0lx), "
1354                        "disp(0x%0lx), gla(0x%0lx)\n",
1355                        base, vie->scale, idx, vie->displacement, gla);
1356                 return (-1);
1357         }
1358
1359         return (0);
1360 }
1361
1362 int
1363 vmm_decode_instruction(struct vm *vm, int cpuid, uint64_t gla,
1364                        enum vm_cpu_mode cpu_mode, struct vie *vie)
1365 {
1366
1367         if (cpu_mode == CPU_MODE_64BIT) {
1368                 if (decode_rex(vie))
1369                         return (-1);
1370         }
1371
1372         if (decode_opcode(vie))
1373                 return (-1);
1374
1375         if (decode_modrm(vie, cpu_mode))
1376                 return (-1);
1377
1378         if (decode_sib(vie))
1379                 return (-1);
1380
1381         if (decode_displacement(vie))
1382                 return (-1);
1383         
1384         if (decode_immediate(vie))
1385                 return (-1);
1386
1387         if (verify_inst_length(vie))
1388                 return (-1);
1389
1390         if (verify_gla(vm, cpuid, gla, vie))
1391                 return (-1);
1392
1393         vie->decoded = 1;       /* success */
1394
1395         return (0);
1396 }
1397 #endif  /* _KERNEL */