xref: /openbmc/linux/arch/x86/kvm/emulate.c (revision 3db55767)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /******************************************************************************
3  * emulate.c
4  *
5  * Generic x86 (32-bit and 64-bit) instruction decoder and emulator.
6  *
7  * Copyright (c) 2005 Keir Fraser
8  *
9  * Linux coding style, mod r/m decoder, segment base fixes, real-mode
10  * privileged instructions:
11  *
12  * Copyright (C) 2006 Qumranet
13  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
14  *
15  *   Avi Kivity <avi@qumranet.com>
16  *   Yaniv Kamay <yaniv@qumranet.com>
17  *
18  * From: xen-unstable 10676:af9809f51f81a3c43f276f00c81a52ef558afda4
19  */
20 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
21 
22 #include <linux/kvm_host.h>
23 #include "kvm_cache_regs.h"
24 #include "kvm_emulate.h"
25 #include <linux/stringify.h>
26 #include <asm/debugreg.h>
27 #include <asm/nospec-branch.h>
28 #include <asm/ibt.h>
29 
30 #include "x86.h"
31 #include "tss.h"
32 #include "mmu.h"
33 #include "pmu.h"
34 
35 /*
36  * Operand types
37  */
38 #define OpNone             0ull
39 #define OpImplicit         1ull  /* No generic decode */
40 #define OpReg              2ull  /* Register */
41 #define OpMem              3ull  /* Memory */
42 #define OpAcc              4ull  /* Accumulator: AL/AX/EAX/RAX */
43 #define OpDI               5ull  /* ES:DI/EDI/RDI */
44 #define OpMem64            6ull  /* Memory, 64-bit */
45 #define OpImmUByte         7ull  /* Zero-extended 8-bit immediate */
46 #define OpDX               8ull  /* DX register */
47 #define OpCL               9ull  /* CL register (for shifts) */
48 #define OpImmByte         10ull  /* 8-bit sign extended immediate */
49 #define OpOne             11ull  /* Implied 1 */
50 #define OpImm             12ull  /* Sign extended up to 32-bit immediate */
51 #define OpMem16           13ull  /* Memory operand (16-bit). */
52 #define OpMem32           14ull  /* Memory operand (32-bit). */
53 #define OpImmU            15ull  /* Immediate operand, zero extended */
54 #define OpSI              16ull  /* SI/ESI/RSI */
55 #define OpImmFAddr        17ull  /* Immediate far address */
56 #define OpMemFAddr        18ull  /* Far address in memory */
57 #define OpImmU16          19ull  /* Immediate operand, 16 bits, zero extended */
58 #define OpES              20ull  /* ES */
59 #define OpCS              21ull  /* CS */
60 #define OpSS              22ull  /* SS */
61 #define OpDS              23ull  /* DS */
62 #define OpFS              24ull  /* FS */
63 #define OpGS              25ull  /* GS */
64 #define OpMem8            26ull  /* 8-bit zero extended memory operand */
65 #define OpImm64           27ull  /* Sign extended 16/32/64-bit immediate */
66 #define OpXLat            28ull  /* memory at BX/EBX/RBX + zero-extended AL */
67 #define OpAccLo           29ull  /* Low part of extended acc (AX/AX/EAX/RAX) */
68 #define OpAccHi           30ull  /* High part of extended acc (-/DX/EDX/RDX) */
69 
70 #define OpBits             5  /* Width of operand field */
71 #define OpMask             ((1ull << OpBits) - 1)
72 
73 /*
74  * Opcode effective-address decode tables.
75  * Note that we only emulate instructions that have at least one memory
76  * operand (excluding implicit stack references). We assume that stack
77  * references and instruction fetches will never occur in special memory
78  * areas that require emulation. So, for example, 'mov <imm>,<reg>' need
79  * not be handled.
80  */
81 
82 /* Operand sizes: 8-bit operands or specified/overridden size. */
83 #define ByteOp      (1<<0)	/* 8-bit operands. */
84 /* Destination operand type. */
85 #define DstShift    1
86 #define ImplicitOps (OpImplicit << DstShift)
87 #define DstReg      (OpReg << DstShift)
88 #define DstMem      (OpMem << DstShift)
89 #define DstAcc      (OpAcc << DstShift)
90 #define DstDI       (OpDI << DstShift)
91 #define DstMem64    (OpMem64 << DstShift)
92 #define DstMem16    (OpMem16 << DstShift)
93 #define DstImmUByte (OpImmUByte << DstShift)
94 #define DstDX       (OpDX << DstShift)
95 #define DstAccLo    (OpAccLo << DstShift)
96 #define DstMask     (OpMask << DstShift)
97 /* Source operand type. */
98 #define SrcShift    6
99 #define SrcNone     (OpNone << SrcShift)
100 #define SrcReg      (OpReg << SrcShift)
101 #define SrcMem      (OpMem << SrcShift)
102 #define SrcMem16    (OpMem16 << SrcShift)
103 #define SrcMem32    (OpMem32 << SrcShift)
104 #define SrcImm      (OpImm << SrcShift)
105 #define SrcImmByte  (OpImmByte << SrcShift)
106 #define SrcOne      (OpOne << SrcShift)
107 #define SrcImmUByte (OpImmUByte << SrcShift)
108 #define SrcImmU     (OpImmU << SrcShift)
109 #define SrcSI       (OpSI << SrcShift)
110 #define SrcXLat     (OpXLat << SrcShift)
111 #define SrcImmFAddr (OpImmFAddr << SrcShift)
112 #define SrcMemFAddr (OpMemFAddr << SrcShift)
113 #define SrcAcc      (OpAcc << SrcShift)
114 #define SrcImmU16   (OpImmU16 << SrcShift)
115 #define SrcImm64    (OpImm64 << SrcShift)
116 #define SrcDX       (OpDX << SrcShift)
117 #define SrcMem8     (OpMem8 << SrcShift)
118 #define SrcAccHi    (OpAccHi << SrcShift)
119 #define SrcMask     (OpMask << SrcShift)
120 #define BitOp       (1<<11)
121 #define MemAbs      (1<<12)      /* Memory operand is absolute displacement */
122 #define String      (1<<13)     /* String instruction (rep capable) */
123 #define Stack       (1<<14)     /* Stack instruction (push/pop) */
124 #define GroupMask   (7<<15)     /* Opcode uses one of the group mechanisms */
125 #define Group       (1<<15)     /* Bits 3:5 of modrm byte extend opcode */
126 #define GroupDual   (2<<15)     /* Alternate decoding of mod == 3 */
127 #define Prefix      (3<<15)     /* Instruction varies with 66/f2/f3 prefix */
128 #define RMExt       (4<<15)     /* Opcode extension in ModRM r/m if mod == 3 */
129 #define Escape      (5<<15)     /* Escape to coprocessor instruction */
130 #define InstrDual   (6<<15)     /* Alternate instruction decoding of mod == 3 */
131 #define ModeDual    (7<<15)     /* Different instruction for 32/64 bit */
132 #define Sse         (1<<18)     /* SSE Vector instruction */
133 /* Generic ModRM decode. */
134 #define ModRM       (1<<19)
135 /* Destination is only written; never read. */
136 #define Mov         (1<<20)
137 /* Misc flags */
138 #define Prot        (1<<21) /* instruction generates #UD if not in prot-mode */
139 #define EmulateOnUD (1<<22) /* Emulate if unsupported by the host */
140 #define NoAccess    (1<<23) /* Don't access memory (lea/invlpg/verr etc) */
141 #define Op3264      (1<<24) /* Operand is 64b in long mode, 32b otherwise */
142 #define Undefined   (1<<25) /* No Such Instruction */
143 #define Lock        (1<<26) /* lock prefix is allowed for the instruction */
144 #define Priv        (1<<27) /* instruction generates #GP if current CPL != 0 */
145 #define No64	    (1<<28)
146 #define PageTable   (1 << 29)   /* instruction used to write page table */
147 #define NotImpl     (1 << 30)   /* instruction is not implemented */
148 /* Source 2 operand type */
149 #define Src2Shift   (31)
150 #define Src2None    (OpNone << Src2Shift)
151 #define Src2Mem     (OpMem << Src2Shift)
152 #define Src2CL      (OpCL << Src2Shift)
153 #define Src2ImmByte (OpImmByte << Src2Shift)
154 #define Src2One     (OpOne << Src2Shift)
155 #define Src2Imm     (OpImm << Src2Shift)
156 #define Src2ES      (OpES << Src2Shift)
157 #define Src2CS      (OpCS << Src2Shift)
158 #define Src2SS      (OpSS << Src2Shift)
159 #define Src2DS      (OpDS << Src2Shift)
160 #define Src2FS      (OpFS << Src2Shift)
161 #define Src2GS      (OpGS << Src2Shift)
162 #define Src2Mask    (OpMask << Src2Shift)
163 #define Mmx         ((u64)1 << 40)  /* MMX Vector instruction */
164 #define AlignMask   ((u64)7 << 41)
165 #define Aligned     ((u64)1 << 41)  /* Explicitly aligned (e.g. MOVDQA) */
166 #define Unaligned   ((u64)2 << 41)  /* Explicitly unaligned (e.g. MOVDQU) */
167 #define Avx         ((u64)3 << 41)  /* Advanced Vector Extensions */
168 #define Aligned16   ((u64)4 << 41)  /* Aligned to 16 byte boundary (e.g. FXSAVE) */
169 #define Fastop      ((u64)1 << 44)  /* Use opcode::u.fastop */
170 #define NoWrite     ((u64)1 << 45)  /* No writeback */
171 #define SrcWrite    ((u64)1 << 46)  /* Write back src operand */
172 #define NoMod	    ((u64)1 << 47)  /* Mod field is ignored */
173 #define Intercept   ((u64)1 << 48)  /* Has valid intercept field */
174 #define CheckPerm   ((u64)1 << 49)  /* Has valid check_perm field */
175 #define PrivUD      ((u64)1 << 51)  /* #UD instead of #GP on CPL > 0 */
176 #define NearBranch  ((u64)1 << 52)  /* Near branches */
177 #define No16	    ((u64)1 << 53)  /* No 16 bit operand */
178 #define IncSP       ((u64)1 << 54)  /* SP is incremented before ModRM calc */
179 #define TwoMemOp    ((u64)1 << 55)  /* Instruction has two memory operand */
180 #define IsBranch    ((u64)1 << 56)  /* Instruction is considered a branch. */
181 
182 #define DstXacc     (DstAccLo | SrcAccHi | SrcWrite)
183 
184 #define X2(x...) x, x
185 #define X3(x...) X2(x), x
186 #define X4(x...) X2(x), X2(x)
187 #define X5(x...) X4(x), x
188 #define X6(x...) X4(x), X2(x)
189 #define X7(x...) X4(x), X3(x)
190 #define X8(x...) X4(x), X4(x)
191 #define X16(x...) X8(x), X8(x)
192 
193 struct opcode {
194 	u64 flags;
195 	u8 intercept;
196 	u8 pad[7];
197 	union {
198 		int (*execute)(struct x86_emulate_ctxt *ctxt);
199 		const struct opcode *group;
200 		const struct group_dual *gdual;
201 		const struct gprefix *gprefix;
202 		const struct escape *esc;
203 		const struct instr_dual *idual;
204 		const struct mode_dual *mdual;
205 		void (*fastop)(struct fastop *fake);
206 	} u;
207 	int (*check_perm)(struct x86_emulate_ctxt *ctxt);
208 };
209 
210 struct group_dual {
211 	struct opcode mod012[8];
212 	struct opcode mod3[8];
213 };
214 
215 struct gprefix {
216 	struct opcode pfx_no;
217 	struct opcode pfx_66;
218 	struct opcode pfx_f2;
219 	struct opcode pfx_f3;
220 };
221 
222 struct escape {
223 	struct opcode op[8];
224 	struct opcode high[64];
225 };
226 
227 struct instr_dual {
228 	struct opcode mod012;
229 	struct opcode mod3;
230 };
231 
232 struct mode_dual {
233 	struct opcode mode32;
234 	struct opcode mode64;
235 };
236 
237 #define EFLG_RESERVED_ZEROS_MASK 0xffc0802a
238 
239 enum x86_transfer_type {
240 	X86_TRANSFER_NONE,
241 	X86_TRANSFER_CALL_JMP,
242 	X86_TRANSFER_RET,
243 	X86_TRANSFER_TASK_SWITCH,
244 };
245 
246 static void writeback_registers(struct x86_emulate_ctxt *ctxt)
247 {
248 	unsigned long dirty = ctxt->regs_dirty;
249 	unsigned reg;
250 
251 	for_each_set_bit(reg, &dirty, NR_EMULATOR_GPRS)
252 		ctxt->ops->write_gpr(ctxt, reg, ctxt->_regs[reg]);
253 }
254 
255 static void invalidate_registers(struct x86_emulate_ctxt *ctxt)
256 {
257 	ctxt->regs_dirty = 0;
258 	ctxt->regs_valid = 0;
259 }
260 
261 /*
262  * These EFLAGS bits are restored from saved value during emulation, and
263  * any changes are written back to the saved value after emulation.
264  */
265 #define EFLAGS_MASK (X86_EFLAGS_OF|X86_EFLAGS_SF|X86_EFLAGS_ZF|X86_EFLAGS_AF|\
266 		     X86_EFLAGS_PF|X86_EFLAGS_CF)
267 
268 #ifdef CONFIG_X86_64
269 #define ON64(x) x
270 #else
271 #define ON64(x)
272 #endif
273 
274 /*
275  * fastop functions have a special calling convention:
276  *
277  * dst:    rax        (in/out)
278  * src:    rdx        (in/out)
279  * src2:   rcx        (in)
280  * flags:  rflags     (in/out)
281  * ex:     rsi        (in:fastop pointer, out:zero if exception)
282  *
283  * Moreover, they are all exactly FASTOP_SIZE bytes long, so functions for
284  * different operand sizes can be reached by calculation, rather than a jump
285  * table (which would be bigger than the code).
286  *
287  * The 16 byte alignment, considering 5 bytes for the RET thunk, 3 for ENDBR
288  * and 1 for the straight line speculation INT3, leaves 7 bytes for the
289  * body of the function.  Currently none is larger than 4.
290  */
291 static int fastop(struct x86_emulate_ctxt *ctxt, fastop_t fop);
292 
293 #define FASTOP_SIZE	16
294 
295 #define __FOP_FUNC(name) \
296 	".align " __stringify(FASTOP_SIZE) " \n\t" \
297 	".type " name ", @function \n\t" \
298 	name ":\n\t" \
299 	ASM_ENDBR \
300 	IBT_NOSEAL(name)
301 
302 #define FOP_FUNC(name) \
303 	__FOP_FUNC(#name)
304 
305 #define __FOP_RET(name) \
306 	"11: " ASM_RET \
307 	".size " name ", .-" name "\n\t"
308 
309 #define FOP_RET(name) \
310 	__FOP_RET(#name)
311 
312 #define __FOP_START(op, align) \
313 	extern void em_##op(struct fastop *fake); \
314 	asm(".pushsection .text, \"ax\" \n\t" \
315 	    ".global em_" #op " \n\t" \
316 	    ".align " __stringify(align) " \n\t" \
317 	    "em_" #op ":\n\t"
318 
319 #define FOP_START(op) __FOP_START(op, FASTOP_SIZE)
320 
321 #define FOP_END \
322 	    ".popsection")
323 
324 #define __FOPNOP(name) \
325 	__FOP_FUNC(name) \
326 	__FOP_RET(name)
327 
328 #define FOPNOP() \
329 	__FOPNOP(__stringify(__UNIQUE_ID(nop)))
330 
331 #define FOP1E(op,  dst) \
332 	__FOP_FUNC(#op "_" #dst) \
333 	"10: " #op " %" #dst " \n\t" \
334 	__FOP_RET(#op "_" #dst)
335 
336 #define FOP1EEX(op,  dst) \
337 	FOP1E(op, dst) _ASM_EXTABLE_TYPE_REG(10b, 11b, EX_TYPE_ZERO_REG, %%esi)
338 
339 #define FASTOP1(op) \
340 	FOP_START(op) \
341 	FOP1E(op##b, al) \
342 	FOP1E(op##w, ax) \
343 	FOP1E(op##l, eax) \
344 	ON64(FOP1E(op##q, rax))	\
345 	FOP_END
346 
347 /* 1-operand, using src2 (for MUL/DIV r/m) */
348 #define FASTOP1SRC2(op, name) \
349 	FOP_START(name) \
350 	FOP1E(op, cl) \
351 	FOP1E(op, cx) \
352 	FOP1E(op, ecx) \
353 	ON64(FOP1E(op, rcx)) \
354 	FOP_END
355 
356 /* 1-operand, using src2 (for MUL/DIV r/m), with exceptions */
357 #define FASTOP1SRC2EX(op, name) \
358 	FOP_START(name) \
359 	FOP1EEX(op, cl) \
360 	FOP1EEX(op, cx) \
361 	FOP1EEX(op, ecx) \
362 	ON64(FOP1EEX(op, rcx)) \
363 	FOP_END
364 
365 #define FOP2E(op,  dst, src)	   \
366 	__FOP_FUNC(#op "_" #dst "_" #src) \
367 	#op " %" #src ", %" #dst " \n\t" \
368 	__FOP_RET(#op "_" #dst "_" #src)
369 
370 #define FASTOP2(op) \
371 	FOP_START(op) \
372 	FOP2E(op##b, al, dl) \
373 	FOP2E(op##w, ax, dx) \
374 	FOP2E(op##l, eax, edx) \
375 	ON64(FOP2E(op##q, rax, rdx)) \
376 	FOP_END
377 
378 /* 2 operand, word only */
379 #define FASTOP2W(op) \
380 	FOP_START(op) \
381 	FOPNOP() \
382 	FOP2E(op##w, ax, dx) \
383 	FOP2E(op##l, eax, edx) \
384 	ON64(FOP2E(op##q, rax, rdx)) \
385 	FOP_END
386 
387 /* 2 operand, src is CL */
388 #define FASTOP2CL(op) \
389 	FOP_START(op) \
390 	FOP2E(op##b, al, cl) \
391 	FOP2E(op##w, ax, cl) \
392 	FOP2E(op##l, eax, cl) \
393 	ON64(FOP2E(op##q, rax, cl)) \
394 	FOP_END
395 
396 /* 2 operand, src and dest are reversed */
397 #define FASTOP2R(op, name) \
398 	FOP_START(name) \
399 	FOP2E(op##b, dl, al) \
400 	FOP2E(op##w, dx, ax) \
401 	FOP2E(op##l, edx, eax) \
402 	ON64(FOP2E(op##q, rdx, rax)) \
403 	FOP_END
404 
405 #define FOP3E(op,  dst, src, src2) \
406 	__FOP_FUNC(#op "_" #dst "_" #src "_" #src2) \
407 	#op " %" #src2 ", %" #src ", %" #dst " \n\t"\
408 	__FOP_RET(#op "_" #dst "_" #src "_" #src2)
409 
410 /* 3-operand, word-only, src2=cl */
411 #define FASTOP3WCL(op) \
412 	FOP_START(op) \
413 	FOPNOP() \
414 	FOP3E(op##w, ax, dx, cl) \
415 	FOP3E(op##l, eax, edx, cl) \
416 	ON64(FOP3E(op##q, rax, rdx, cl)) \
417 	FOP_END
418 
419 /* Special case for SETcc - 1 instruction per cc */
420 #define FOP_SETCC(op) \
421 	FOP_FUNC(op) \
422 	#op " %al \n\t" \
423 	FOP_RET(op)
424 
425 FOP_START(setcc)
426 FOP_SETCC(seto)
427 FOP_SETCC(setno)
428 FOP_SETCC(setc)
429 FOP_SETCC(setnc)
430 FOP_SETCC(setz)
431 FOP_SETCC(setnz)
432 FOP_SETCC(setbe)
433 FOP_SETCC(setnbe)
434 FOP_SETCC(sets)
435 FOP_SETCC(setns)
436 FOP_SETCC(setp)
437 FOP_SETCC(setnp)
438 FOP_SETCC(setl)
439 FOP_SETCC(setnl)
440 FOP_SETCC(setle)
441 FOP_SETCC(setnle)
442 FOP_END;
443 
444 FOP_START(salc)
445 FOP_FUNC(salc)
446 "pushf; sbb %al, %al; popf \n\t"
447 FOP_RET(salc)
448 FOP_END;
449 
450 /*
451  * XXX: inoutclob user must know where the argument is being expanded.
452  *      Using asm goto would allow us to remove _fault.
453  */
454 #define asm_safe(insn, inoutclob...) \
455 ({ \
456 	int _fault = 0; \
457  \
458 	asm volatile("1:" insn "\n" \
459 	             "2:\n" \
460 		     _ASM_EXTABLE_TYPE_REG(1b, 2b, EX_TYPE_ONE_REG, %[_fault]) \
461 	             : [_fault] "+r"(_fault) inoutclob ); \
462  \
463 	_fault ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE; \
464 })
465 
466 static int emulator_check_intercept(struct x86_emulate_ctxt *ctxt,
467 				    enum x86_intercept intercept,
468 				    enum x86_intercept_stage stage)
469 {
470 	struct x86_instruction_info info = {
471 		.intercept  = intercept,
472 		.rep_prefix = ctxt->rep_prefix,
473 		.modrm_mod  = ctxt->modrm_mod,
474 		.modrm_reg  = ctxt->modrm_reg,
475 		.modrm_rm   = ctxt->modrm_rm,
476 		.src_val    = ctxt->src.val64,
477 		.dst_val    = ctxt->dst.val64,
478 		.src_bytes  = ctxt->src.bytes,
479 		.dst_bytes  = ctxt->dst.bytes,
480 		.ad_bytes   = ctxt->ad_bytes,
481 		.next_rip   = ctxt->eip,
482 	};
483 
484 	return ctxt->ops->intercept(ctxt, &info, stage);
485 }
486 
487 static void assign_masked(ulong *dest, ulong src, ulong mask)
488 {
489 	*dest = (*dest & ~mask) | (src & mask);
490 }
491 
492 static void assign_register(unsigned long *reg, u64 val, int bytes)
493 {
494 	/* The 4-byte case *is* correct: in 64-bit mode we zero-extend. */
495 	switch (bytes) {
496 	case 1:
497 		*(u8 *)reg = (u8)val;
498 		break;
499 	case 2:
500 		*(u16 *)reg = (u16)val;
501 		break;
502 	case 4:
503 		*reg = (u32)val;
504 		break;	/* 64b: zero-extend */
505 	case 8:
506 		*reg = val;
507 		break;
508 	}
509 }
510 
511 static inline unsigned long ad_mask(struct x86_emulate_ctxt *ctxt)
512 {
513 	return (1UL << (ctxt->ad_bytes << 3)) - 1;
514 }
515 
516 static ulong stack_mask(struct x86_emulate_ctxt *ctxt)
517 {
518 	u16 sel;
519 	struct desc_struct ss;
520 
521 	if (ctxt->mode == X86EMUL_MODE_PROT64)
522 		return ~0UL;
523 	ctxt->ops->get_segment(ctxt, &sel, &ss, NULL, VCPU_SREG_SS);
524 	return ~0U >> ((ss.d ^ 1) * 16);  /* d=0: 0xffff; d=1: 0xffffffff */
525 }
526 
527 static int stack_size(struct x86_emulate_ctxt *ctxt)
528 {
529 	return (__fls(stack_mask(ctxt)) + 1) >> 3;
530 }
531 
532 /* Access/update address held in a register, based on addressing mode. */
533 static inline unsigned long
534 address_mask(struct x86_emulate_ctxt *ctxt, unsigned long reg)
535 {
536 	if (ctxt->ad_bytes == sizeof(unsigned long))
537 		return reg;
538 	else
539 		return reg & ad_mask(ctxt);
540 }
541 
542 static inline unsigned long
543 register_address(struct x86_emulate_ctxt *ctxt, int reg)
544 {
545 	return address_mask(ctxt, reg_read(ctxt, reg));
546 }
547 
548 static void masked_increment(ulong *reg, ulong mask, int inc)
549 {
550 	assign_masked(reg, *reg + inc, mask);
551 }
552 
553 static inline void
554 register_address_increment(struct x86_emulate_ctxt *ctxt, int reg, int inc)
555 {
556 	ulong *preg = reg_rmw(ctxt, reg);
557 
558 	assign_register(preg, *preg + inc, ctxt->ad_bytes);
559 }
560 
561 static void rsp_increment(struct x86_emulate_ctxt *ctxt, int inc)
562 {
563 	masked_increment(reg_rmw(ctxt, VCPU_REGS_RSP), stack_mask(ctxt), inc);
564 }
565 
566 static u32 desc_limit_scaled(struct desc_struct *desc)
567 {
568 	u32 limit = get_desc_limit(desc);
569 
570 	return desc->g ? (limit << 12) | 0xfff : limit;
571 }
572 
573 static unsigned long seg_base(struct x86_emulate_ctxt *ctxt, int seg)
574 {
575 	if (ctxt->mode == X86EMUL_MODE_PROT64 && seg < VCPU_SREG_FS)
576 		return 0;
577 
578 	return ctxt->ops->get_cached_segment_base(ctxt, seg);
579 }
580 
581 static int emulate_exception(struct x86_emulate_ctxt *ctxt, int vec,
582 			     u32 error, bool valid)
583 {
584 	if (KVM_EMULATOR_BUG_ON(vec > 0x1f, ctxt))
585 		return X86EMUL_UNHANDLEABLE;
586 
587 	ctxt->exception.vector = vec;
588 	ctxt->exception.error_code = error;
589 	ctxt->exception.error_code_valid = valid;
590 	return X86EMUL_PROPAGATE_FAULT;
591 }
592 
593 static int emulate_db(struct x86_emulate_ctxt *ctxt)
594 {
595 	return emulate_exception(ctxt, DB_VECTOR, 0, false);
596 }
597 
598 static int emulate_gp(struct x86_emulate_ctxt *ctxt, int err)
599 {
600 	return emulate_exception(ctxt, GP_VECTOR, err, true);
601 }
602 
603 static int emulate_ss(struct x86_emulate_ctxt *ctxt, int err)
604 {
605 	return emulate_exception(ctxt, SS_VECTOR, err, true);
606 }
607 
608 static int emulate_ud(struct x86_emulate_ctxt *ctxt)
609 {
610 	return emulate_exception(ctxt, UD_VECTOR, 0, false);
611 }
612 
613 static int emulate_ts(struct x86_emulate_ctxt *ctxt, int err)
614 {
615 	return emulate_exception(ctxt, TS_VECTOR, err, true);
616 }
617 
618 static int emulate_de(struct x86_emulate_ctxt *ctxt)
619 {
620 	return emulate_exception(ctxt, DE_VECTOR, 0, false);
621 }
622 
623 static int emulate_nm(struct x86_emulate_ctxt *ctxt)
624 {
625 	return emulate_exception(ctxt, NM_VECTOR, 0, false);
626 }
627 
628 static u16 get_segment_selector(struct x86_emulate_ctxt *ctxt, unsigned seg)
629 {
630 	u16 selector;
631 	struct desc_struct desc;
632 
633 	ctxt->ops->get_segment(ctxt, &selector, &desc, NULL, seg);
634 	return selector;
635 }
636 
637 static void set_segment_selector(struct x86_emulate_ctxt *ctxt, u16 selector,
638 				 unsigned seg)
639 {
640 	u16 dummy;
641 	u32 base3;
642 	struct desc_struct desc;
643 
644 	ctxt->ops->get_segment(ctxt, &dummy, &desc, &base3, seg);
645 	ctxt->ops->set_segment(ctxt, selector, &desc, base3, seg);
646 }
647 
648 static inline u8 ctxt_virt_addr_bits(struct x86_emulate_ctxt *ctxt)
649 {
650 	return (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_LA57) ? 57 : 48;
651 }
652 
653 static inline bool emul_is_noncanonical_address(u64 la,
654 						struct x86_emulate_ctxt *ctxt)
655 {
656 	return !__is_canonical_address(la, ctxt_virt_addr_bits(ctxt));
657 }
658 
659 /*
660  * x86 defines three classes of vector instructions: explicitly
661  * aligned, explicitly unaligned, and the rest, which change behaviour
662  * depending on whether they're AVX encoded or not.
663  *
664  * Also included is CMPXCHG16B which is not a vector instruction, yet it is
665  * subject to the same check.  FXSAVE and FXRSTOR are checked here too as their
666  * 512 bytes of data must be aligned to a 16 byte boundary.
667  */
668 static unsigned insn_alignment(struct x86_emulate_ctxt *ctxt, unsigned size)
669 {
670 	u64 alignment = ctxt->d & AlignMask;
671 
672 	if (likely(size < 16))
673 		return 1;
674 
675 	switch (alignment) {
676 	case Unaligned:
677 	case Avx:
678 		return 1;
679 	case Aligned16:
680 		return 16;
681 	case Aligned:
682 	default:
683 		return size;
684 	}
685 }
686 
687 static __always_inline int __linearize(struct x86_emulate_ctxt *ctxt,
688 				       struct segmented_address addr,
689 				       unsigned *max_size, unsigned size,
690 				       bool write, bool fetch,
691 				       enum x86emul_mode mode, ulong *linear)
692 {
693 	struct desc_struct desc;
694 	bool usable;
695 	ulong la;
696 	u32 lim;
697 	u16 sel;
698 	u8  va_bits;
699 
700 	la = seg_base(ctxt, addr.seg) + addr.ea;
701 	*max_size = 0;
702 	switch (mode) {
703 	case X86EMUL_MODE_PROT64:
704 		*linear = la;
705 		va_bits = ctxt_virt_addr_bits(ctxt);
706 		if (!__is_canonical_address(la, va_bits))
707 			goto bad;
708 
709 		*max_size = min_t(u64, ~0u, (1ull << va_bits) - la);
710 		if (size > *max_size)
711 			goto bad;
712 		break;
713 	default:
714 		*linear = la = (u32)la;
715 		usable = ctxt->ops->get_segment(ctxt, &sel, &desc, NULL,
716 						addr.seg);
717 		if (!usable)
718 			goto bad;
719 		/* code segment in protected mode or read-only data segment */
720 		if ((((ctxt->mode != X86EMUL_MODE_REAL) && (desc.type & 8))
721 					|| !(desc.type & 2)) && write)
722 			goto bad;
723 		/* unreadable code segment */
724 		if (!fetch && (desc.type & 8) && !(desc.type & 2))
725 			goto bad;
726 		lim = desc_limit_scaled(&desc);
727 		if (!(desc.type & 8) && (desc.type & 4)) {
728 			/* expand-down segment */
729 			if (addr.ea <= lim)
730 				goto bad;
731 			lim = desc.d ? 0xffffffff : 0xffff;
732 		}
733 		if (addr.ea > lim)
734 			goto bad;
735 		if (lim == 0xffffffff)
736 			*max_size = ~0u;
737 		else {
738 			*max_size = (u64)lim + 1 - addr.ea;
739 			if (size > *max_size)
740 				goto bad;
741 		}
742 		break;
743 	}
744 	if (la & (insn_alignment(ctxt, size) - 1))
745 		return emulate_gp(ctxt, 0);
746 	return X86EMUL_CONTINUE;
747 bad:
748 	if (addr.seg == VCPU_SREG_SS)
749 		return emulate_ss(ctxt, 0);
750 	else
751 		return emulate_gp(ctxt, 0);
752 }
753 
754 static int linearize(struct x86_emulate_ctxt *ctxt,
755 		     struct segmented_address addr,
756 		     unsigned size, bool write,
757 		     ulong *linear)
758 {
759 	unsigned max_size;
760 	return __linearize(ctxt, addr, &max_size, size, write, false,
761 			   ctxt->mode, linear);
762 }
763 
764 static inline int assign_eip(struct x86_emulate_ctxt *ctxt, ulong dst)
765 {
766 	ulong linear;
767 	int rc;
768 	unsigned max_size;
769 	struct segmented_address addr = { .seg = VCPU_SREG_CS,
770 					   .ea = dst };
771 
772 	if (ctxt->op_bytes != sizeof(unsigned long))
773 		addr.ea = dst & ((1UL << (ctxt->op_bytes << 3)) - 1);
774 	rc = __linearize(ctxt, addr, &max_size, 1, false, true, ctxt->mode, &linear);
775 	if (rc == X86EMUL_CONTINUE)
776 		ctxt->_eip = addr.ea;
777 	return rc;
778 }
779 
780 static inline int emulator_recalc_and_set_mode(struct x86_emulate_ctxt *ctxt)
781 {
782 	u64 efer;
783 	struct desc_struct cs;
784 	u16 selector;
785 	u32 base3;
786 
787 	ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
788 
789 	if (!(ctxt->ops->get_cr(ctxt, 0) & X86_CR0_PE)) {
790 		/* Real mode. cpu must not have long mode active */
791 		if (efer & EFER_LMA)
792 			return X86EMUL_UNHANDLEABLE;
793 		ctxt->mode = X86EMUL_MODE_REAL;
794 		return X86EMUL_CONTINUE;
795 	}
796 
797 	if (ctxt->eflags & X86_EFLAGS_VM) {
798 		/* Protected/VM86 mode. cpu must not have long mode active */
799 		if (efer & EFER_LMA)
800 			return X86EMUL_UNHANDLEABLE;
801 		ctxt->mode = X86EMUL_MODE_VM86;
802 		return X86EMUL_CONTINUE;
803 	}
804 
805 	if (!ctxt->ops->get_segment(ctxt, &selector, &cs, &base3, VCPU_SREG_CS))
806 		return X86EMUL_UNHANDLEABLE;
807 
808 	if (efer & EFER_LMA) {
809 		if (cs.l) {
810 			/* Proper long mode */
811 			ctxt->mode = X86EMUL_MODE_PROT64;
812 		} else if (cs.d) {
813 			/* 32 bit compatibility mode*/
814 			ctxt->mode = X86EMUL_MODE_PROT32;
815 		} else {
816 			ctxt->mode = X86EMUL_MODE_PROT16;
817 		}
818 	} else {
819 		/* Legacy 32 bit / 16 bit mode */
820 		ctxt->mode = cs.d ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
821 	}
822 
823 	return X86EMUL_CONTINUE;
824 }
825 
826 static inline int assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst)
827 {
828 	return assign_eip(ctxt, dst);
829 }
830 
831 static int assign_eip_far(struct x86_emulate_ctxt *ctxt, ulong dst)
832 {
833 	int rc = emulator_recalc_and_set_mode(ctxt);
834 
835 	if (rc != X86EMUL_CONTINUE)
836 		return rc;
837 
838 	return assign_eip(ctxt, dst);
839 }
840 
841 static inline int jmp_rel(struct x86_emulate_ctxt *ctxt, int rel)
842 {
843 	return assign_eip_near(ctxt, ctxt->_eip + rel);
844 }
845 
846 static int linear_read_system(struct x86_emulate_ctxt *ctxt, ulong linear,
847 			      void *data, unsigned size)
848 {
849 	return ctxt->ops->read_std(ctxt, linear, data, size, &ctxt->exception, true);
850 }
851 
852 static int linear_write_system(struct x86_emulate_ctxt *ctxt,
853 			       ulong linear, void *data,
854 			       unsigned int size)
855 {
856 	return ctxt->ops->write_std(ctxt, linear, data, size, &ctxt->exception, true);
857 }
858 
859 static int segmented_read_std(struct x86_emulate_ctxt *ctxt,
860 			      struct segmented_address addr,
861 			      void *data,
862 			      unsigned size)
863 {
864 	int rc;
865 	ulong linear;
866 
867 	rc = linearize(ctxt, addr, size, false, &linear);
868 	if (rc != X86EMUL_CONTINUE)
869 		return rc;
870 	return ctxt->ops->read_std(ctxt, linear, data, size, &ctxt->exception, false);
871 }
872 
873 static int segmented_write_std(struct x86_emulate_ctxt *ctxt,
874 			       struct segmented_address addr,
875 			       void *data,
876 			       unsigned int size)
877 {
878 	int rc;
879 	ulong linear;
880 
881 	rc = linearize(ctxt, addr, size, true, &linear);
882 	if (rc != X86EMUL_CONTINUE)
883 		return rc;
884 	return ctxt->ops->write_std(ctxt, linear, data, size, &ctxt->exception, false);
885 }
886 
887 /*
888  * Prefetch the remaining bytes of the instruction without crossing page
889  * boundary if they are not in fetch_cache yet.
890  */
891 static int __do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt, int op_size)
892 {
893 	int rc;
894 	unsigned size, max_size;
895 	unsigned long linear;
896 	int cur_size = ctxt->fetch.end - ctxt->fetch.data;
897 	struct segmented_address addr = { .seg = VCPU_SREG_CS,
898 					   .ea = ctxt->eip + cur_size };
899 
900 	/*
901 	 * We do not know exactly how many bytes will be needed, and
902 	 * __linearize is expensive, so fetch as much as possible.  We
903 	 * just have to avoid going beyond the 15 byte limit, the end
904 	 * of the segment, or the end of the page.
905 	 *
906 	 * __linearize is called with size 0 so that it does not do any
907 	 * boundary check itself.  Instead, we use max_size to check
908 	 * against op_size.
909 	 */
910 	rc = __linearize(ctxt, addr, &max_size, 0, false, true, ctxt->mode,
911 			 &linear);
912 	if (unlikely(rc != X86EMUL_CONTINUE))
913 		return rc;
914 
915 	size = min_t(unsigned, 15UL ^ cur_size, max_size);
916 	size = min_t(unsigned, size, PAGE_SIZE - offset_in_page(linear));
917 
918 	/*
919 	 * One instruction can only straddle two pages,
920 	 * and one has been loaded at the beginning of
921 	 * x86_decode_insn.  So, if not enough bytes
922 	 * still, we must have hit the 15-byte boundary.
923 	 */
924 	if (unlikely(size < op_size))
925 		return emulate_gp(ctxt, 0);
926 
927 	rc = ctxt->ops->fetch(ctxt, linear, ctxt->fetch.end,
928 			      size, &ctxt->exception);
929 	if (unlikely(rc != X86EMUL_CONTINUE))
930 		return rc;
931 	ctxt->fetch.end += size;
932 	return X86EMUL_CONTINUE;
933 }
934 
935 static __always_inline int do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt,
936 					       unsigned size)
937 {
938 	unsigned done_size = ctxt->fetch.end - ctxt->fetch.ptr;
939 
940 	if (unlikely(done_size < size))
941 		return __do_insn_fetch_bytes(ctxt, size - done_size);
942 	else
943 		return X86EMUL_CONTINUE;
944 }
945 
946 /* Fetch next part of the instruction being emulated. */
947 #define insn_fetch(_type, _ctxt)					\
948 ({	_type _x;							\
949 									\
950 	rc = do_insn_fetch_bytes(_ctxt, sizeof(_type));			\
951 	if (rc != X86EMUL_CONTINUE)					\
952 		goto done;						\
953 	ctxt->_eip += sizeof(_type);					\
954 	memcpy(&_x, ctxt->fetch.ptr, sizeof(_type));			\
955 	ctxt->fetch.ptr += sizeof(_type);				\
956 	_x;								\
957 })
958 
959 #define insn_fetch_arr(_arr, _size, _ctxt)				\
960 ({									\
961 	rc = do_insn_fetch_bytes(_ctxt, _size);				\
962 	if (rc != X86EMUL_CONTINUE)					\
963 		goto done;						\
964 	ctxt->_eip += (_size);						\
965 	memcpy(_arr, ctxt->fetch.ptr, _size);				\
966 	ctxt->fetch.ptr += (_size);					\
967 })
968 
969 /*
970  * Given the 'reg' portion of a ModRM byte, and a register block, return a
971  * pointer into the block that addresses the relevant register.
972  * @highbyte_regs specifies whether to decode AH,CH,DH,BH.
973  */
974 static void *decode_register(struct x86_emulate_ctxt *ctxt, u8 modrm_reg,
975 			     int byteop)
976 {
977 	void *p;
978 	int highbyte_regs = (ctxt->rex_prefix == 0) && byteop;
979 
980 	if (highbyte_regs && modrm_reg >= 4 && modrm_reg < 8)
981 		p = (unsigned char *)reg_rmw(ctxt, modrm_reg & 3) + 1;
982 	else
983 		p = reg_rmw(ctxt, modrm_reg);
984 	return p;
985 }
986 
987 static int read_descriptor(struct x86_emulate_ctxt *ctxt,
988 			   struct segmented_address addr,
989 			   u16 *size, unsigned long *address, int op_bytes)
990 {
991 	int rc;
992 
993 	if (op_bytes == 2)
994 		op_bytes = 3;
995 	*address = 0;
996 	rc = segmented_read_std(ctxt, addr, size, 2);
997 	if (rc != X86EMUL_CONTINUE)
998 		return rc;
999 	addr.ea += 2;
1000 	rc = segmented_read_std(ctxt, addr, address, op_bytes);
1001 	return rc;
1002 }
1003 
1004 FASTOP2(add);
1005 FASTOP2(or);
1006 FASTOP2(adc);
1007 FASTOP2(sbb);
1008 FASTOP2(and);
1009 FASTOP2(sub);
1010 FASTOP2(xor);
1011 FASTOP2(cmp);
1012 FASTOP2(test);
1013 
1014 FASTOP1SRC2(mul, mul_ex);
1015 FASTOP1SRC2(imul, imul_ex);
1016 FASTOP1SRC2EX(div, div_ex);
1017 FASTOP1SRC2EX(idiv, idiv_ex);
1018 
1019 FASTOP3WCL(shld);
1020 FASTOP3WCL(shrd);
1021 
1022 FASTOP2W(imul);
1023 
1024 FASTOP1(not);
1025 FASTOP1(neg);
1026 FASTOP1(inc);
1027 FASTOP1(dec);
1028 
1029 FASTOP2CL(rol);
1030 FASTOP2CL(ror);
1031 FASTOP2CL(rcl);
1032 FASTOP2CL(rcr);
1033 FASTOP2CL(shl);
1034 FASTOP2CL(shr);
1035 FASTOP2CL(sar);
1036 
1037 FASTOP2W(bsf);
1038 FASTOP2W(bsr);
1039 FASTOP2W(bt);
1040 FASTOP2W(bts);
1041 FASTOP2W(btr);
1042 FASTOP2W(btc);
1043 
1044 FASTOP2(xadd);
1045 
1046 FASTOP2R(cmp, cmp_r);
1047 
1048 static int em_bsf_c(struct x86_emulate_ctxt *ctxt)
1049 {
1050 	/* If src is zero, do not writeback, but update flags */
1051 	if (ctxt->src.val == 0)
1052 		ctxt->dst.type = OP_NONE;
1053 	return fastop(ctxt, em_bsf);
1054 }
1055 
1056 static int em_bsr_c(struct x86_emulate_ctxt *ctxt)
1057 {
1058 	/* If src is zero, do not writeback, but update flags */
1059 	if (ctxt->src.val == 0)
1060 		ctxt->dst.type = OP_NONE;
1061 	return fastop(ctxt, em_bsr);
1062 }
1063 
1064 static __always_inline u8 test_cc(unsigned int condition, unsigned long flags)
1065 {
1066 	u8 rc;
1067 	void (*fop)(void) = (void *)em_setcc + FASTOP_SIZE * (condition & 0xf);
1068 
1069 	flags = (flags & EFLAGS_MASK) | X86_EFLAGS_IF;
1070 	asm("push %[flags]; popf; " CALL_NOSPEC
1071 	    : "=a"(rc) : [thunk_target]"r"(fop), [flags]"r"(flags));
1072 	return rc;
1073 }
1074 
1075 static void fetch_register_operand(struct operand *op)
1076 {
1077 	switch (op->bytes) {
1078 	case 1:
1079 		op->val = *(u8 *)op->addr.reg;
1080 		break;
1081 	case 2:
1082 		op->val = *(u16 *)op->addr.reg;
1083 		break;
1084 	case 4:
1085 		op->val = *(u32 *)op->addr.reg;
1086 		break;
1087 	case 8:
1088 		op->val = *(u64 *)op->addr.reg;
1089 		break;
1090 	}
1091 }
1092 
1093 static int em_fninit(struct x86_emulate_ctxt *ctxt)
1094 {
1095 	if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
1096 		return emulate_nm(ctxt);
1097 
1098 	kvm_fpu_get();
1099 	asm volatile("fninit");
1100 	kvm_fpu_put();
1101 	return X86EMUL_CONTINUE;
1102 }
1103 
1104 static int em_fnstcw(struct x86_emulate_ctxt *ctxt)
1105 {
1106 	u16 fcw;
1107 
1108 	if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
1109 		return emulate_nm(ctxt);
1110 
1111 	kvm_fpu_get();
1112 	asm volatile("fnstcw %0": "+m"(fcw));
1113 	kvm_fpu_put();
1114 
1115 	ctxt->dst.val = fcw;
1116 
1117 	return X86EMUL_CONTINUE;
1118 }
1119 
1120 static int em_fnstsw(struct x86_emulate_ctxt *ctxt)
1121 {
1122 	u16 fsw;
1123 
1124 	if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
1125 		return emulate_nm(ctxt);
1126 
1127 	kvm_fpu_get();
1128 	asm volatile("fnstsw %0": "+m"(fsw));
1129 	kvm_fpu_put();
1130 
1131 	ctxt->dst.val = fsw;
1132 
1133 	return X86EMUL_CONTINUE;
1134 }
1135 
1136 static void decode_register_operand(struct x86_emulate_ctxt *ctxt,
1137 				    struct operand *op)
1138 {
1139 	unsigned int reg;
1140 
1141 	if (ctxt->d & ModRM)
1142 		reg = ctxt->modrm_reg;
1143 	else
1144 		reg = (ctxt->b & 7) | ((ctxt->rex_prefix & 1) << 3);
1145 
1146 	if (ctxt->d & Sse) {
1147 		op->type = OP_XMM;
1148 		op->bytes = 16;
1149 		op->addr.xmm = reg;
1150 		kvm_read_sse_reg(reg, &op->vec_val);
1151 		return;
1152 	}
1153 	if (ctxt->d & Mmx) {
1154 		reg &= 7;
1155 		op->type = OP_MM;
1156 		op->bytes = 8;
1157 		op->addr.mm = reg;
1158 		return;
1159 	}
1160 
1161 	op->type = OP_REG;
1162 	op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
1163 	op->addr.reg = decode_register(ctxt, reg, ctxt->d & ByteOp);
1164 
1165 	fetch_register_operand(op);
1166 	op->orig_val = op->val;
1167 }
1168 
1169 static void adjust_modrm_seg(struct x86_emulate_ctxt *ctxt, int base_reg)
1170 {
1171 	if (base_reg == VCPU_REGS_RSP || base_reg == VCPU_REGS_RBP)
1172 		ctxt->modrm_seg = VCPU_SREG_SS;
1173 }
1174 
1175 static int decode_modrm(struct x86_emulate_ctxt *ctxt,
1176 			struct operand *op)
1177 {
1178 	u8 sib;
1179 	int index_reg, base_reg, scale;
1180 	int rc = X86EMUL_CONTINUE;
1181 	ulong modrm_ea = 0;
1182 
1183 	ctxt->modrm_reg = ((ctxt->rex_prefix << 1) & 8); /* REX.R */
1184 	index_reg = (ctxt->rex_prefix << 2) & 8; /* REX.X */
1185 	base_reg = (ctxt->rex_prefix << 3) & 8; /* REX.B */
1186 
1187 	ctxt->modrm_mod = (ctxt->modrm & 0xc0) >> 6;
1188 	ctxt->modrm_reg |= (ctxt->modrm & 0x38) >> 3;
1189 	ctxt->modrm_rm = base_reg | (ctxt->modrm & 0x07);
1190 	ctxt->modrm_seg = VCPU_SREG_DS;
1191 
1192 	if (ctxt->modrm_mod == 3 || (ctxt->d & NoMod)) {
1193 		op->type = OP_REG;
1194 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
1195 		op->addr.reg = decode_register(ctxt, ctxt->modrm_rm,
1196 				ctxt->d & ByteOp);
1197 		if (ctxt->d & Sse) {
1198 			op->type = OP_XMM;
1199 			op->bytes = 16;
1200 			op->addr.xmm = ctxt->modrm_rm;
1201 			kvm_read_sse_reg(ctxt->modrm_rm, &op->vec_val);
1202 			return rc;
1203 		}
1204 		if (ctxt->d & Mmx) {
1205 			op->type = OP_MM;
1206 			op->bytes = 8;
1207 			op->addr.mm = ctxt->modrm_rm & 7;
1208 			return rc;
1209 		}
1210 		fetch_register_operand(op);
1211 		return rc;
1212 	}
1213 
1214 	op->type = OP_MEM;
1215 
1216 	if (ctxt->ad_bytes == 2) {
1217 		unsigned bx = reg_read(ctxt, VCPU_REGS_RBX);
1218 		unsigned bp = reg_read(ctxt, VCPU_REGS_RBP);
1219 		unsigned si = reg_read(ctxt, VCPU_REGS_RSI);
1220 		unsigned di = reg_read(ctxt, VCPU_REGS_RDI);
1221 
1222 		/* 16-bit ModR/M decode. */
1223 		switch (ctxt->modrm_mod) {
1224 		case 0:
1225 			if (ctxt->modrm_rm == 6)
1226 				modrm_ea += insn_fetch(u16, ctxt);
1227 			break;
1228 		case 1:
1229 			modrm_ea += insn_fetch(s8, ctxt);
1230 			break;
1231 		case 2:
1232 			modrm_ea += insn_fetch(u16, ctxt);
1233 			break;
1234 		}
1235 		switch (ctxt->modrm_rm) {
1236 		case 0:
1237 			modrm_ea += bx + si;
1238 			break;
1239 		case 1:
1240 			modrm_ea += bx + di;
1241 			break;
1242 		case 2:
1243 			modrm_ea += bp + si;
1244 			break;
1245 		case 3:
1246 			modrm_ea += bp + di;
1247 			break;
1248 		case 4:
1249 			modrm_ea += si;
1250 			break;
1251 		case 5:
1252 			modrm_ea += di;
1253 			break;
1254 		case 6:
1255 			if (ctxt->modrm_mod != 0)
1256 				modrm_ea += bp;
1257 			break;
1258 		case 7:
1259 			modrm_ea += bx;
1260 			break;
1261 		}
1262 		if (ctxt->modrm_rm == 2 || ctxt->modrm_rm == 3 ||
1263 		    (ctxt->modrm_rm == 6 && ctxt->modrm_mod != 0))
1264 			ctxt->modrm_seg = VCPU_SREG_SS;
1265 		modrm_ea = (u16)modrm_ea;
1266 	} else {
1267 		/* 32/64-bit ModR/M decode. */
1268 		if ((ctxt->modrm_rm & 7) == 4) {
1269 			sib = insn_fetch(u8, ctxt);
1270 			index_reg |= (sib >> 3) & 7;
1271 			base_reg |= sib & 7;
1272 			scale = sib >> 6;
1273 
1274 			if ((base_reg & 7) == 5 && ctxt->modrm_mod == 0)
1275 				modrm_ea += insn_fetch(s32, ctxt);
1276 			else {
1277 				modrm_ea += reg_read(ctxt, base_reg);
1278 				adjust_modrm_seg(ctxt, base_reg);
1279 				/* Increment ESP on POP [ESP] */
1280 				if ((ctxt->d & IncSP) &&
1281 				    base_reg == VCPU_REGS_RSP)
1282 					modrm_ea += ctxt->op_bytes;
1283 			}
1284 			if (index_reg != 4)
1285 				modrm_ea += reg_read(ctxt, index_reg) << scale;
1286 		} else if ((ctxt->modrm_rm & 7) == 5 && ctxt->modrm_mod == 0) {
1287 			modrm_ea += insn_fetch(s32, ctxt);
1288 			if (ctxt->mode == X86EMUL_MODE_PROT64)
1289 				ctxt->rip_relative = 1;
1290 		} else {
1291 			base_reg = ctxt->modrm_rm;
1292 			modrm_ea += reg_read(ctxt, base_reg);
1293 			adjust_modrm_seg(ctxt, base_reg);
1294 		}
1295 		switch (ctxt->modrm_mod) {
1296 		case 1:
1297 			modrm_ea += insn_fetch(s8, ctxt);
1298 			break;
1299 		case 2:
1300 			modrm_ea += insn_fetch(s32, ctxt);
1301 			break;
1302 		}
1303 	}
1304 	op->addr.mem.ea = modrm_ea;
1305 	if (ctxt->ad_bytes != 8)
1306 		ctxt->memop.addr.mem.ea = (u32)ctxt->memop.addr.mem.ea;
1307 
1308 done:
1309 	return rc;
1310 }
1311 
1312 static int decode_abs(struct x86_emulate_ctxt *ctxt,
1313 		      struct operand *op)
1314 {
1315 	int rc = X86EMUL_CONTINUE;
1316 
1317 	op->type = OP_MEM;
1318 	switch (ctxt->ad_bytes) {
1319 	case 2:
1320 		op->addr.mem.ea = insn_fetch(u16, ctxt);
1321 		break;
1322 	case 4:
1323 		op->addr.mem.ea = insn_fetch(u32, ctxt);
1324 		break;
1325 	case 8:
1326 		op->addr.mem.ea = insn_fetch(u64, ctxt);
1327 		break;
1328 	}
1329 done:
1330 	return rc;
1331 }
1332 
1333 static void fetch_bit_operand(struct x86_emulate_ctxt *ctxt)
1334 {
1335 	long sv = 0, mask;
1336 
1337 	if (ctxt->dst.type == OP_MEM && ctxt->src.type == OP_REG) {
1338 		mask = ~((long)ctxt->dst.bytes * 8 - 1);
1339 
1340 		if (ctxt->src.bytes == 2)
1341 			sv = (s16)ctxt->src.val & (s16)mask;
1342 		else if (ctxt->src.bytes == 4)
1343 			sv = (s32)ctxt->src.val & (s32)mask;
1344 		else
1345 			sv = (s64)ctxt->src.val & (s64)mask;
1346 
1347 		ctxt->dst.addr.mem.ea = address_mask(ctxt,
1348 					   ctxt->dst.addr.mem.ea + (sv >> 3));
1349 	}
1350 
1351 	/* only subword offset */
1352 	ctxt->src.val &= (ctxt->dst.bytes << 3) - 1;
1353 }
1354 
1355 static int read_emulated(struct x86_emulate_ctxt *ctxt,
1356 			 unsigned long addr, void *dest, unsigned size)
1357 {
1358 	int rc;
1359 	struct read_cache *mc = &ctxt->mem_read;
1360 
1361 	if (mc->pos < mc->end)
1362 		goto read_cached;
1363 
1364 	if (KVM_EMULATOR_BUG_ON((mc->end + size) >= sizeof(mc->data), ctxt))
1365 		return X86EMUL_UNHANDLEABLE;
1366 
1367 	rc = ctxt->ops->read_emulated(ctxt, addr, mc->data + mc->end, size,
1368 				      &ctxt->exception);
1369 	if (rc != X86EMUL_CONTINUE)
1370 		return rc;
1371 
1372 	mc->end += size;
1373 
1374 read_cached:
1375 	memcpy(dest, mc->data + mc->pos, size);
1376 	mc->pos += size;
1377 	return X86EMUL_CONTINUE;
1378 }
1379 
1380 static int segmented_read(struct x86_emulate_ctxt *ctxt,
1381 			  struct segmented_address addr,
1382 			  void *data,
1383 			  unsigned size)
1384 {
1385 	int rc;
1386 	ulong linear;
1387 
1388 	rc = linearize(ctxt, addr, size, false, &linear);
1389 	if (rc != X86EMUL_CONTINUE)
1390 		return rc;
1391 	return read_emulated(ctxt, linear, data, size);
1392 }
1393 
1394 static int segmented_write(struct x86_emulate_ctxt *ctxt,
1395 			   struct segmented_address addr,
1396 			   const void *data,
1397 			   unsigned size)
1398 {
1399 	int rc;
1400 	ulong linear;
1401 
1402 	rc = linearize(ctxt, addr, size, true, &linear);
1403 	if (rc != X86EMUL_CONTINUE)
1404 		return rc;
1405 	return ctxt->ops->write_emulated(ctxt, linear, data, size,
1406 					 &ctxt->exception);
1407 }
1408 
1409 static int segmented_cmpxchg(struct x86_emulate_ctxt *ctxt,
1410 			     struct segmented_address addr,
1411 			     const void *orig_data, const void *data,
1412 			     unsigned size)
1413 {
1414 	int rc;
1415 	ulong linear;
1416 
1417 	rc = linearize(ctxt, addr, size, true, &linear);
1418 	if (rc != X86EMUL_CONTINUE)
1419 		return rc;
1420 	return ctxt->ops->cmpxchg_emulated(ctxt, linear, orig_data, data,
1421 					   size, &ctxt->exception);
1422 }
1423 
1424 static int pio_in_emulated(struct x86_emulate_ctxt *ctxt,
1425 			   unsigned int size, unsigned short port,
1426 			   void *dest)
1427 {
1428 	struct read_cache *rc = &ctxt->io_read;
1429 
1430 	if (rc->pos == rc->end) { /* refill pio read ahead */
1431 		unsigned int in_page, n;
1432 		unsigned int count = ctxt->rep_prefix ?
1433 			address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) : 1;
1434 		in_page = (ctxt->eflags & X86_EFLAGS_DF) ?
1435 			offset_in_page(reg_read(ctxt, VCPU_REGS_RDI)) :
1436 			PAGE_SIZE - offset_in_page(reg_read(ctxt, VCPU_REGS_RDI));
1437 		n = min3(in_page, (unsigned int)sizeof(rc->data) / size, count);
1438 		if (n == 0)
1439 			n = 1;
1440 		rc->pos = rc->end = 0;
1441 		if (!ctxt->ops->pio_in_emulated(ctxt, size, port, rc->data, n))
1442 			return 0;
1443 		rc->end = n * size;
1444 	}
1445 
1446 	if (ctxt->rep_prefix && (ctxt->d & String) &&
1447 	    !(ctxt->eflags & X86_EFLAGS_DF)) {
1448 		ctxt->dst.data = rc->data + rc->pos;
1449 		ctxt->dst.type = OP_MEM_STR;
1450 		ctxt->dst.count = (rc->end - rc->pos) / size;
1451 		rc->pos = rc->end;
1452 	} else {
1453 		memcpy(dest, rc->data + rc->pos, size);
1454 		rc->pos += size;
1455 	}
1456 	return 1;
1457 }
1458 
1459 static int read_interrupt_descriptor(struct x86_emulate_ctxt *ctxt,
1460 				     u16 index, struct desc_struct *desc)
1461 {
1462 	struct desc_ptr dt;
1463 	ulong addr;
1464 
1465 	ctxt->ops->get_idt(ctxt, &dt);
1466 
1467 	if (dt.size < index * 8 + 7)
1468 		return emulate_gp(ctxt, index << 3 | 0x2);
1469 
1470 	addr = dt.address + index * 8;
1471 	return linear_read_system(ctxt, addr, desc, sizeof(*desc));
1472 }
1473 
1474 static void get_descriptor_table_ptr(struct x86_emulate_ctxt *ctxt,
1475 				     u16 selector, struct desc_ptr *dt)
1476 {
1477 	const struct x86_emulate_ops *ops = ctxt->ops;
1478 	u32 base3 = 0;
1479 
1480 	if (selector & 1 << 2) {
1481 		struct desc_struct desc;
1482 		u16 sel;
1483 
1484 		memset(dt, 0, sizeof(*dt));
1485 		if (!ops->get_segment(ctxt, &sel, &desc, &base3,
1486 				      VCPU_SREG_LDTR))
1487 			return;
1488 
1489 		dt->size = desc_limit_scaled(&desc); /* what if limit > 65535? */
1490 		dt->address = get_desc_base(&desc) | ((u64)base3 << 32);
1491 	} else
1492 		ops->get_gdt(ctxt, dt);
1493 }
1494 
1495 static int get_descriptor_ptr(struct x86_emulate_ctxt *ctxt,
1496 			      u16 selector, ulong *desc_addr_p)
1497 {
1498 	struct desc_ptr dt;
1499 	u16 index = selector >> 3;
1500 	ulong addr;
1501 
1502 	get_descriptor_table_ptr(ctxt, selector, &dt);
1503 
1504 	if (dt.size < index * 8 + 7)
1505 		return emulate_gp(ctxt, selector & 0xfffc);
1506 
1507 	addr = dt.address + index * 8;
1508 
1509 #ifdef CONFIG_X86_64
1510 	if (addr >> 32 != 0) {
1511 		u64 efer = 0;
1512 
1513 		ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
1514 		if (!(efer & EFER_LMA))
1515 			addr &= (u32)-1;
1516 	}
1517 #endif
1518 
1519 	*desc_addr_p = addr;
1520 	return X86EMUL_CONTINUE;
1521 }
1522 
1523 /* allowed just for 8 bytes segments */
1524 static int read_segment_descriptor(struct x86_emulate_ctxt *ctxt,
1525 				   u16 selector, struct desc_struct *desc,
1526 				   ulong *desc_addr_p)
1527 {
1528 	int rc;
1529 
1530 	rc = get_descriptor_ptr(ctxt, selector, desc_addr_p);
1531 	if (rc != X86EMUL_CONTINUE)
1532 		return rc;
1533 
1534 	return linear_read_system(ctxt, *desc_addr_p, desc, sizeof(*desc));
1535 }
1536 
1537 /* allowed just for 8 bytes segments */
1538 static int write_segment_descriptor(struct x86_emulate_ctxt *ctxt,
1539 				    u16 selector, struct desc_struct *desc)
1540 {
1541 	int rc;
1542 	ulong addr;
1543 
1544 	rc = get_descriptor_ptr(ctxt, selector, &addr);
1545 	if (rc != X86EMUL_CONTINUE)
1546 		return rc;
1547 
1548 	return linear_write_system(ctxt, addr, desc, sizeof(*desc));
1549 }
1550 
1551 static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
1552 				     u16 selector, int seg, u8 cpl,
1553 				     enum x86_transfer_type transfer,
1554 				     struct desc_struct *desc)
1555 {
1556 	struct desc_struct seg_desc, old_desc;
1557 	u8 dpl, rpl;
1558 	unsigned err_vec = GP_VECTOR;
1559 	u32 err_code = 0;
1560 	bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
1561 	ulong desc_addr;
1562 	int ret;
1563 	u16 dummy;
1564 	u32 base3 = 0;
1565 
1566 	memset(&seg_desc, 0, sizeof(seg_desc));
1567 
1568 	if (ctxt->mode == X86EMUL_MODE_REAL) {
1569 		/* set real mode segment descriptor (keep limit etc. for
1570 		 * unreal mode) */
1571 		ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);
1572 		set_desc_base(&seg_desc, selector << 4);
1573 		goto load;
1574 	} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {
1575 		/* VM86 needs a clean new segment descriptor */
1576 		set_desc_base(&seg_desc, selector << 4);
1577 		set_desc_limit(&seg_desc, 0xffff);
1578 		seg_desc.type = 3;
1579 		seg_desc.p = 1;
1580 		seg_desc.s = 1;
1581 		seg_desc.dpl = 3;
1582 		goto load;
1583 	}
1584 
1585 	rpl = selector & 3;
1586 
1587 	/* TR should be in GDT only */
1588 	if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
1589 		goto exception;
1590 
1591 	/* NULL selector is not valid for TR, CS and (except for long mode) SS */
1592 	if (null_selector) {
1593 		if (seg == VCPU_SREG_CS || seg == VCPU_SREG_TR)
1594 			goto exception;
1595 
1596 		if (seg == VCPU_SREG_SS) {
1597 			if (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl)
1598 				goto exception;
1599 
1600 			/*
1601 			 * ctxt->ops->set_segment expects the CPL to be in
1602 			 * SS.DPL, so fake an expand-up 32-bit data segment.
1603 			 */
1604 			seg_desc.type = 3;
1605 			seg_desc.p = 1;
1606 			seg_desc.s = 1;
1607 			seg_desc.dpl = cpl;
1608 			seg_desc.d = 1;
1609 			seg_desc.g = 1;
1610 		}
1611 
1612 		/* Skip all following checks */
1613 		goto load;
1614 	}
1615 
1616 	ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);
1617 	if (ret != X86EMUL_CONTINUE)
1618 		return ret;
1619 
1620 	err_code = selector & 0xfffc;
1621 	err_vec = (transfer == X86_TRANSFER_TASK_SWITCH) ? TS_VECTOR :
1622 							   GP_VECTOR;
1623 
1624 	/* can't load system descriptor into segment selector */
1625 	if (seg <= VCPU_SREG_GS && !seg_desc.s) {
1626 		if (transfer == X86_TRANSFER_CALL_JMP)
1627 			return X86EMUL_UNHANDLEABLE;
1628 		goto exception;
1629 	}
1630 
1631 	dpl = seg_desc.dpl;
1632 
1633 	switch (seg) {
1634 	case VCPU_SREG_SS:
1635 		/*
1636 		 * segment is not a writable data segment or segment
1637 		 * selector's RPL != CPL or DPL != CPL
1638 		 */
1639 		if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
1640 			goto exception;
1641 		break;
1642 	case VCPU_SREG_CS:
1643 		/*
1644 		 * KVM uses "none" when loading CS as part of emulating Real
1645 		 * Mode exceptions and IRET (handled above).  In all other
1646 		 * cases, loading CS without a control transfer is a KVM bug.
1647 		 */
1648 		if (WARN_ON_ONCE(transfer == X86_TRANSFER_NONE))
1649 			goto exception;
1650 
1651 		if (!(seg_desc.type & 8))
1652 			goto exception;
1653 
1654 		if (transfer == X86_TRANSFER_RET) {
1655 			/* RET can never return to an inner privilege level. */
1656 			if (rpl < cpl)
1657 				goto exception;
1658 			/* Outer-privilege level return is not implemented */
1659 			if (rpl > cpl)
1660 				return X86EMUL_UNHANDLEABLE;
1661 		}
1662 		if (transfer == X86_TRANSFER_RET || transfer == X86_TRANSFER_TASK_SWITCH) {
1663 			if (seg_desc.type & 4) {
1664 				/* conforming */
1665 				if (dpl > rpl)
1666 					goto exception;
1667 			} else {
1668 				/* nonconforming */
1669 				if (dpl != rpl)
1670 					goto exception;
1671 			}
1672 		} else { /* X86_TRANSFER_CALL_JMP */
1673 			if (seg_desc.type & 4) {
1674 				/* conforming */
1675 				if (dpl > cpl)
1676 					goto exception;
1677 			} else {
1678 				/* nonconforming */
1679 				if (rpl > cpl || dpl != cpl)
1680 					goto exception;
1681 			}
1682 		}
1683 		/* in long-mode d/b must be clear if l is set */
1684 		if (seg_desc.d && seg_desc.l) {
1685 			u64 efer = 0;
1686 
1687 			ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
1688 			if (efer & EFER_LMA)
1689 				goto exception;
1690 		}
1691 
1692 		/* CS(RPL) <- CPL */
1693 		selector = (selector & 0xfffc) | cpl;
1694 		break;
1695 	case VCPU_SREG_TR:
1696 		if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
1697 			goto exception;
1698 		break;
1699 	case VCPU_SREG_LDTR:
1700 		if (seg_desc.s || seg_desc.type != 2)
1701 			goto exception;
1702 		break;
1703 	default: /*  DS, ES, FS, or GS */
1704 		/*
1705 		 * segment is not a data or readable code segment or
1706 		 * ((segment is a data or nonconforming code segment)
1707 		 * and ((RPL > DPL) or (CPL > DPL)))
1708 		 */
1709 		if ((seg_desc.type & 0xa) == 0x8 ||
1710 		    (((seg_desc.type & 0xc) != 0xc) &&
1711 		     (rpl > dpl || cpl > dpl)))
1712 			goto exception;
1713 		break;
1714 	}
1715 
1716 	if (!seg_desc.p) {
1717 		err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
1718 		goto exception;
1719 	}
1720 
1721 	if (seg_desc.s) {
1722 		/* mark segment as accessed */
1723 		if (!(seg_desc.type & 1)) {
1724 			seg_desc.type |= 1;
1725 			ret = write_segment_descriptor(ctxt, selector,
1726 						       &seg_desc);
1727 			if (ret != X86EMUL_CONTINUE)
1728 				return ret;
1729 		}
1730 	} else if (ctxt->mode == X86EMUL_MODE_PROT64) {
1731 		ret = linear_read_system(ctxt, desc_addr+8, &base3, sizeof(base3));
1732 		if (ret != X86EMUL_CONTINUE)
1733 			return ret;
1734 		if (emul_is_noncanonical_address(get_desc_base(&seg_desc) |
1735 						 ((u64)base3 << 32), ctxt))
1736 			return emulate_gp(ctxt, err_code);
1737 	}
1738 
1739 	if (seg == VCPU_SREG_TR) {
1740 		old_desc = seg_desc;
1741 		seg_desc.type |= 2; /* busy */
1742 		ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,
1743 						  sizeof(seg_desc), &ctxt->exception);
1744 		if (ret != X86EMUL_CONTINUE)
1745 			return ret;
1746 	}
1747 load:
1748 	ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);
1749 	if (desc)
1750 		*desc = seg_desc;
1751 	return X86EMUL_CONTINUE;
1752 exception:
1753 	return emulate_exception(ctxt, err_vec, err_code, true);
1754 }
1755 
1756 static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
1757 				   u16 selector, int seg)
1758 {
1759 	u8 cpl = ctxt->ops->cpl(ctxt);
1760 
1761 	/*
1762 	 * None of MOV, POP and LSS can load a NULL selector in CPL=3, but
1763 	 * they can load it at CPL<3 (Intel's manual says only LSS can,
1764 	 * but it's wrong).
1765 	 *
1766 	 * However, the Intel manual says that putting IST=1/DPL=3 in
1767 	 * an interrupt gate will result in SS=3 (the AMD manual instead
1768 	 * says it doesn't), so allow SS=3 in __load_segment_descriptor
1769 	 * and only forbid it here.
1770 	 */
1771 	if (seg == VCPU_SREG_SS && selector == 3 &&
1772 	    ctxt->mode == X86EMUL_MODE_PROT64)
1773 		return emulate_exception(ctxt, GP_VECTOR, 0, true);
1774 
1775 	return __load_segment_descriptor(ctxt, selector, seg, cpl,
1776 					 X86_TRANSFER_NONE, NULL);
1777 }
1778 
1779 static void write_register_operand(struct operand *op)
1780 {
1781 	return assign_register(op->addr.reg, op->val, op->bytes);
1782 }
1783 
1784 static int writeback(struct x86_emulate_ctxt *ctxt, struct operand *op)
1785 {
1786 	switch (op->type) {
1787 	case OP_REG:
1788 		write_register_operand(op);
1789 		break;
1790 	case OP_MEM:
1791 		if (ctxt->lock_prefix)
1792 			return segmented_cmpxchg(ctxt,
1793 						 op->addr.mem,
1794 						 &op->orig_val,
1795 						 &op->val,
1796 						 op->bytes);
1797 		else
1798 			return segmented_write(ctxt,
1799 					       op->addr.mem,
1800 					       &op->val,
1801 					       op->bytes);
1802 		break;
1803 	case OP_MEM_STR:
1804 		return segmented_write(ctxt,
1805 				       op->addr.mem,
1806 				       op->data,
1807 				       op->bytes * op->count);
1808 		break;
1809 	case OP_XMM:
1810 		kvm_write_sse_reg(op->addr.xmm, &op->vec_val);
1811 		break;
1812 	case OP_MM:
1813 		kvm_write_mmx_reg(op->addr.mm, &op->mm_val);
1814 		break;
1815 	case OP_NONE:
1816 		/* no writeback */
1817 		break;
1818 	default:
1819 		break;
1820 	}
1821 	return X86EMUL_CONTINUE;
1822 }
1823 
1824 static int push(struct x86_emulate_ctxt *ctxt, void *data, int bytes)
1825 {
1826 	struct segmented_address addr;
1827 
1828 	rsp_increment(ctxt, -bytes);
1829 	addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt);
1830 	addr.seg = VCPU_SREG_SS;
1831 
1832 	return segmented_write(ctxt, addr, data, bytes);
1833 }
1834 
1835 static int em_push(struct x86_emulate_ctxt *ctxt)
1836 {
1837 	/* Disable writeback. */
1838 	ctxt->dst.type = OP_NONE;
1839 	return push(ctxt, &ctxt->src.val, ctxt->op_bytes);
1840 }
1841 
1842 static int emulate_pop(struct x86_emulate_ctxt *ctxt,
1843 		       void *dest, int len)
1844 {
1845 	int rc;
1846 	struct segmented_address addr;
1847 
1848 	addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt);
1849 	addr.seg = VCPU_SREG_SS;
1850 	rc = segmented_read(ctxt, addr, dest, len);
1851 	if (rc != X86EMUL_CONTINUE)
1852 		return rc;
1853 
1854 	rsp_increment(ctxt, len);
1855 	return rc;
1856 }
1857 
1858 static int em_pop(struct x86_emulate_ctxt *ctxt)
1859 {
1860 	return emulate_pop(ctxt, &ctxt->dst.val, ctxt->op_bytes);
1861 }
1862 
1863 static int emulate_popf(struct x86_emulate_ctxt *ctxt,
1864 			void *dest, int len)
1865 {
1866 	int rc;
1867 	unsigned long val, change_mask;
1868 	int iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> X86_EFLAGS_IOPL_BIT;
1869 	int cpl = ctxt->ops->cpl(ctxt);
1870 
1871 	rc = emulate_pop(ctxt, &val, len);
1872 	if (rc != X86EMUL_CONTINUE)
1873 		return rc;
1874 
1875 	change_mask = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
1876 		      X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF |
1877 		      X86_EFLAGS_TF | X86_EFLAGS_DF | X86_EFLAGS_NT |
1878 		      X86_EFLAGS_AC | X86_EFLAGS_ID;
1879 
1880 	switch(ctxt->mode) {
1881 	case X86EMUL_MODE_PROT64:
1882 	case X86EMUL_MODE_PROT32:
1883 	case X86EMUL_MODE_PROT16:
1884 		if (cpl == 0)
1885 			change_mask |= X86_EFLAGS_IOPL;
1886 		if (cpl <= iopl)
1887 			change_mask |= X86_EFLAGS_IF;
1888 		break;
1889 	case X86EMUL_MODE_VM86:
1890 		if (iopl < 3)
1891 			return emulate_gp(ctxt, 0);
1892 		change_mask |= X86_EFLAGS_IF;
1893 		break;
1894 	default: /* real mode */
1895 		change_mask |= (X86_EFLAGS_IOPL | X86_EFLAGS_IF);
1896 		break;
1897 	}
1898 
1899 	*(unsigned long *)dest =
1900 		(ctxt->eflags & ~change_mask) | (val & change_mask);
1901 
1902 	return rc;
1903 }
1904 
1905 static int em_popf(struct x86_emulate_ctxt *ctxt)
1906 {
1907 	ctxt->dst.type = OP_REG;
1908 	ctxt->dst.addr.reg = &ctxt->eflags;
1909 	ctxt->dst.bytes = ctxt->op_bytes;
1910 	return emulate_popf(ctxt, &ctxt->dst.val, ctxt->op_bytes);
1911 }
1912 
1913 static int em_enter(struct x86_emulate_ctxt *ctxt)
1914 {
1915 	int rc;
1916 	unsigned frame_size = ctxt->src.val;
1917 	unsigned nesting_level = ctxt->src2.val & 31;
1918 	ulong rbp;
1919 
1920 	if (nesting_level)
1921 		return X86EMUL_UNHANDLEABLE;
1922 
1923 	rbp = reg_read(ctxt, VCPU_REGS_RBP);
1924 	rc = push(ctxt, &rbp, stack_size(ctxt));
1925 	if (rc != X86EMUL_CONTINUE)
1926 		return rc;
1927 	assign_masked(reg_rmw(ctxt, VCPU_REGS_RBP), reg_read(ctxt, VCPU_REGS_RSP),
1928 		      stack_mask(ctxt));
1929 	assign_masked(reg_rmw(ctxt, VCPU_REGS_RSP),
1930 		      reg_read(ctxt, VCPU_REGS_RSP) - frame_size,
1931 		      stack_mask(ctxt));
1932 	return X86EMUL_CONTINUE;
1933 }
1934 
1935 static int em_leave(struct x86_emulate_ctxt *ctxt)
1936 {
1937 	assign_masked(reg_rmw(ctxt, VCPU_REGS_RSP), reg_read(ctxt, VCPU_REGS_RBP),
1938 		      stack_mask(ctxt));
1939 	return emulate_pop(ctxt, reg_rmw(ctxt, VCPU_REGS_RBP), ctxt->op_bytes);
1940 }
1941 
1942 static int em_push_sreg(struct x86_emulate_ctxt *ctxt)
1943 {
1944 	int seg = ctxt->src2.val;
1945 
1946 	ctxt->src.val = get_segment_selector(ctxt, seg);
1947 	if (ctxt->op_bytes == 4) {
1948 		rsp_increment(ctxt, -2);
1949 		ctxt->op_bytes = 2;
1950 	}
1951 
1952 	return em_push(ctxt);
1953 }
1954 
1955 static int em_pop_sreg(struct x86_emulate_ctxt *ctxt)
1956 {
1957 	int seg = ctxt->src2.val;
1958 	unsigned long selector;
1959 	int rc;
1960 
1961 	rc = emulate_pop(ctxt, &selector, 2);
1962 	if (rc != X86EMUL_CONTINUE)
1963 		return rc;
1964 
1965 	if (seg == VCPU_SREG_SS)
1966 		ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS;
1967 	if (ctxt->op_bytes > 2)
1968 		rsp_increment(ctxt, ctxt->op_bytes - 2);
1969 
1970 	rc = load_segment_descriptor(ctxt, (u16)selector, seg);
1971 	return rc;
1972 }
1973 
1974 static int em_pusha(struct x86_emulate_ctxt *ctxt)
1975 {
1976 	unsigned long old_esp = reg_read(ctxt, VCPU_REGS_RSP);
1977 	int rc = X86EMUL_CONTINUE;
1978 	int reg = VCPU_REGS_RAX;
1979 
1980 	while (reg <= VCPU_REGS_RDI) {
1981 		(reg == VCPU_REGS_RSP) ?
1982 		(ctxt->src.val = old_esp) : (ctxt->src.val = reg_read(ctxt, reg));
1983 
1984 		rc = em_push(ctxt);
1985 		if (rc != X86EMUL_CONTINUE)
1986 			return rc;
1987 
1988 		++reg;
1989 	}
1990 
1991 	return rc;
1992 }
1993 
1994 static int em_pushf(struct x86_emulate_ctxt *ctxt)
1995 {
1996 	ctxt->src.val = (unsigned long)ctxt->eflags & ~X86_EFLAGS_VM;
1997 	return em_push(ctxt);
1998 }
1999 
2000 static int em_popa(struct x86_emulate_ctxt *ctxt)
2001 {
2002 	int rc = X86EMUL_CONTINUE;
2003 	int reg = VCPU_REGS_RDI;
2004 	u32 val;
2005 
2006 	while (reg >= VCPU_REGS_RAX) {
2007 		if (reg == VCPU_REGS_RSP) {
2008 			rsp_increment(ctxt, ctxt->op_bytes);
2009 			--reg;
2010 		}
2011 
2012 		rc = emulate_pop(ctxt, &val, ctxt->op_bytes);
2013 		if (rc != X86EMUL_CONTINUE)
2014 			break;
2015 		assign_register(reg_rmw(ctxt, reg), val, ctxt->op_bytes);
2016 		--reg;
2017 	}
2018 	return rc;
2019 }
2020 
2021 static int __emulate_int_real(struct x86_emulate_ctxt *ctxt, int irq)
2022 {
2023 	const struct x86_emulate_ops *ops = ctxt->ops;
2024 	int rc;
2025 	struct desc_ptr dt;
2026 	gva_t cs_addr;
2027 	gva_t eip_addr;
2028 	u16 cs, eip;
2029 
2030 	/* TODO: Add limit checks */
2031 	ctxt->src.val = ctxt->eflags;
2032 	rc = em_push(ctxt);
2033 	if (rc != X86EMUL_CONTINUE)
2034 		return rc;
2035 
2036 	ctxt->eflags &= ~(X86_EFLAGS_IF | X86_EFLAGS_TF | X86_EFLAGS_AC);
2037 
2038 	ctxt->src.val = get_segment_selector(ctxt, VCPU_SREG_CS);
2039 	rc = em_push(ctxt);
2040 	if (rc != X86EMUL_CONTINUE)
2041 		return rc;
2042 
2043 	ctxt->src.val = ctxt->_eip;
2044 	rc = em_push(ctxt);
2045 	if (rc != X86EMUL_CONTINUE)
2046 		return rc;
2047 
2048 	ops->get_idt(ctxt, &dt);
2049 
2050 	eip_addr = dt.address + (irq << 2);
2051 	cs_addr = dt.address + (irq << 2) + 2;
2052 
2053 	rc = linear_read_system(ctxt, cs_addr, &cs, 2);
2054 	if (rc != X86EMUL_CONTINUE)
2055 		return rc;
2056 
2057 	rc = linear_read_system(ctxt, eip_addr, &eip, 2);
2058 	if (rc != X86EMUL_CONTINUE)
2059 		return rc;
2060 
2061 	rc = load_segment_descriptor(ctxt, cs, VCPU_SREG_CS);
2062 	if (rc != X86EMUL_CONTINUE)
2063 		return rc;
2064 
2065 	ctxt->_eip = eip;
2066 
2067 	return rc;
2068 }
2069 
2070 int emulate_int_real(struct x86_emulate_ctxt *ctxt, int irq)
2071 {
2072 	int rc;
2073 
2074 	invalidate_registers(ctxt);
2075 	rc = __emulate_int_real(ctxt, irq);
2076 	if (rc == X86EMUL_CONTINUE)
2077 		writeback_registers(ctxt);
2078 	return rc;
2079 }
2080 
2081 static int emulate_int(struct x86_emulate_ctxt *ctxt, int irq)
2082 {
2083 	switch(ctxt->mode) {
2084 	case X86EMUL_MODE_REAL:
2085 		return __emulate_int_real(ctxt, irq);
2086 	case X86EMUL_MODE_VM86:
2087 	case X86EMUL_MODE_PROT16:
2088 	case X86EMUL_MODE_PROT32:
2089 	case X86EMUL_MODE_PROT64:
2090 	default:
2091 		/* Protected mode interrupts unimplemented yet */
2092 		return X86EMUL_UNHANDLEABLE;
2093 	}
2094 }
2095 
2096 static int emulate_iret_real(struct x86_emulate_ctxt *ctxt)
2097 {
2098 	int rc = X86EMUL_CONTINUE;
2099 	unsigned long temp_eip = 0;
2100 	unsigned long temp_eflags = 0;
2101 	unsigned long cs = 0;
2102 	unsigned long mask = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
2103 			     X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_TF |
2104 			     X86_EFLAGS_IF | X86_EFLAGS_DF | X86_EFLAGS_OF |
2105 			     X86_EFLAGS_IOPL | X86_EFLAGS_NT | X86_EFLAGS_RF |
2106 			     X86_EFLAGS_AC | X86_EFLAGS_ID |
2107 			     X86_EFLAGS_FIXED;
2108 	unsigned long vm86_mask = X86_EFLAGS_VM | X86_EFLAGS_VIF |
2109 				  X86_EFLAGS_VIP;
2110 
2111 	/* TODO: Add stack limit check */
2112 
2113 	rc = emulate_pop(ctxt, &temp_eip, ctxt->op_bytes);
2114 
2115 	if (rc != X86EMUL_CONTINUE)
2116 		return rc;
2117 
2118 	if (temp_eip & ~0xffff)
2119 		return emulate_gp(ctxt, 0);
2120 
2121 	rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
2122 
2123 	if (rc != X86EMUL_CONTINUE)
2124 		return rc;
2125 
2126 	rc = emulate_pop(ctxt, &temp_eflags, ctxt->op_bytes);
2127 
2128 	if (rc != X86EMUL_CONTINUE)
2129 		return rc;
2130 
2131 	rc = load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS);
2132 
2133 	if (rc != X86EMUL_CONTINUE)
2134 		return rc;
2135 
2136 	ctxt->_eip = temp_eip;
2137 
2138 	if (ctxt->op_bytes == 4)
2139 		ctxt->eflags = ((temp_eflags & mask) | (ctxt->eflags & vm86_mask));
2140 	else if (ctxt->op_bytes == 2) {
2141 		ctxt->eflags &= ~0xffff;
2142 		ctxt->eflags |= temp_eflags;
2143 	}
2144 
2145 	ctxt->eflags &= ~EFLG_RESERVED_ZEROS_MASK; /* Clear reserved zeros */
2146 	ctxt->eflags |= X86_EFLAGS_FIXED;
2147 	ctxt->ops->set_nmi_mask(ctxt, false);
2148 
2149 	return rc;
2150 }
2151 
2152 static int em_iret(struct x86_emulate_ctxt *ctxt)
2153 {
2154 	switch(ctxt->mode) {
2155 	case X86EMUL_MODE_REAL:
2156 		return emulate_iret_real(ctxt);
2157 	case X86EMUL_MODE_VM86:
2158 	case X86EMUL_MODE_PROT16:
2159 	case X86EMUL_MODE_PROT32:
2160 	case X86EMUL_MODE_PROT64:
2161 	default:
2162 		/* iret from protected mode unimplemented yet */
2163 		return X86EMUL_UNHANDLEABLE;
2164 	}
2165 }
2166 
2167 static int em_jmp_far(struct x86_emulate_ctxt *ctxt)
2168 {
2169 	int rc;
2170 	unsigned short sel;
2171 	struct desc_struct new_desc;
2172 	u8 cpl = ctxt->ops->cpl(ctxt);
2173 
2174 	memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
2175 
2176 	rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,
2177 				       X86_TRANSFER_CALL_JMP,
2178 				       &new_desc);
2179 	if (rc != X86EMUL_CONTINUE)
2180 		return rc;
2181 
2182 	rc = assign_eip_far(ctxt, ctxt->src.val);
2183 	/* Error handling is not implemented. */
2184 	if (rc != X86EMUL_CONTINUE)
2185 		return X86EMUL_UNHANDLEABLE;
2186 
2187 	return rc;
2188 }
2189 
2190 static int em_jmp_abs(struct x86_emulate_ctxt *ctxt)
2191 {
2192 	return assign_eip_near(ctxt, ctxt->src.val);
2193 }
2194 
2195 static int em_call_near_abs(struct x86_emulate_ctxt *ctxt)
2196 {
2197 	int rc;
2198 	long int old_eip;
2199 
2200 	old_eip = ctxt->_eip;
2201 	rc = assign_eip_near(ctxt, ctxt->src.val);
2202 	if (rc != X86EMUL_CONTINUE)
2203 		return rc;
2204 	ctxt->src.val = old_eip;
2205 	rc = em_push(ctxt);
2206 	return rc;
2207 }
2208 
2209 static int em_cmpxchg8b(struct x86_emulate_ctxt *ctxt)
2210 {
2211 	u64 old = ctxt->dst.orig_val64;
2212 
2213 	if (ctxt->dst.bytes == 16)
2214 		return X86EMUL_UNHANDLEABLE;
2215 
2216 	if (((u32) (old >> 0) != (u32) reg_read(ctxt, VCPU_REGS_RAX)) ||
2217 	    ((u32) (old >> 32) != (u32) reg_read(ctxt, VCPU_REGS_RDX))) {
2218 		*reg_write(ctxt, VCPU_REGS_RAX) = (u32) (old >> 0);
2219 		*reg_write(ctxt, VCPU_REGS_RDX) = (u32) (old >> 32);
2220 		ctxt->eflags &= ~X86_EFLAGS_ZF;
2221 	} else {
2222 		ctxt->dst.val64 = ((u64)reg_read(ctxt, VCPU_REGS_RCX) << 32) |
2223 			(u32) reg_read(ctxt, VCPU_REGS_RBX);
2224 
2225 		ctxt->eflags |= X86_EFLAGS_ZF;
2226 	}
2227 	return X86EMUL_CONTINUE;
2228 }
2229 
2230 static int em_ret(struct x86_emulate_ctxt *ctxt)
2231 {
2232 	int rc;
2233 	unsigned long eip;
2234 
2235 	rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
2236 	if (rc != X86EMUL_CONTINUE)
2237 		return rc;
2238 
2239 	return assign_eip_near(ctxt, eip);
2240 }
2241 
2242 static int em_ret_far(struct x86_emulate_ctxt *ctxt)
2243 {
2244 	int rc;
2245 	unsigned long eip, cs;
2246 	int cpl = ctxt->ops->cpl(ctxt);
2247 	struct desc_struct new_desc;
2248 
2249 	rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
2250 	if (rc != X86EMUL_CONTINUE)
2251 		return rc;
2252 	rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
2253 	if (rc != X86EMUL_CONTINUE)
2254 		return rc;
2255 	rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, cpl,
2256 				       X86_TRANSFER_RET,
2257 				       &new_desc);
2258 	if (rc != X86EMUL_CONTINUE)
2259 		return rc;
2260 	rc = assign_eip_far(ctxt, eip);
2261 	/* Error handling is not implemented. */
2262 	if (rc != X86EMUL_CONTINUE)
2263 		return X86EMUL_UNHANDLEABLE;
2264 
2265 	return rc;
2266 }
2267 
2268 static int em_ret_far_imm(struct x86_emulate_ctxt *ctxt)
2269 {
2270         int rc;
2271 
2272         rc = em_ret_far(ctxt);
2273         if (rc != X86EMUL_CONTINUE)
2274                 return rc;
2275         rsp_increment(ctxt, ctxt->src.val);
2276         return X86EMUL_CONTINUE;
2277 }
2278 
2279 static int em_cmpxchg(struct x86_emulate_ctxt *ctxt)
2280 {
2281 	/* Save real source value, then compare EAX against destination. */
2282 	ctxt->dst.orig_val = ctxt->dst.val;
2283 	ctxt->dst.val = reg_read(ctxt, VCPU_REGS_RAX);
2284 	ctxt->src.orig_val = ctxt->src.val;
2285 	ctxt->src.val = ctxt->dst.orig_val;
2286 	fastop(ctxt, em_cmp);
2287 
2288 	if (ctxt->eflags & X86_EFLAGS_ZF) {
2289 		/* Success: write back to memory; no update of EAX */
2290 		ctxt->src.type = OP_NONE;
2291 		ctxt->dst.val = ctxt->src.orig_val;
2292 	} else {
2293 		/* Failure: write the value we saw to EAX. */
2294 		ctxt->src.type = OP_REG;
2295 		ctxt->src.addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
2296 		ctxt->src.val = ctxt->dst.orig_val;
2297 		/* Create write-cycle to dest by writing the same value */
2298 		ctxt->dst.val = ctxt->dst.orig_val;
2299 	}
2300 	return X86EMUL_CONTINUE;
2301 }
2302 
2303 static int em_lseg(struct x86_emulate_ctxt *ctxt)
2304 {
2305 	int seg = ctxt->src2.val;
2306 	unsigned short sel;
2307 	int rc;
2308 
2309 	memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
2310 
2311 	rc = load_segment_descriptor(ctxt, sel, seg);
2312 	if (rc != X86EMUL_CONTINUE)
2313 		return rc;
2314 
2315 	ctxt->dst.val = ctxt->src.val;
2316 	return rc;
2317 }
2318 
2319 static int em_rsm(struct x86_emulate_ctxt *ctxt)
2320 {
2321 	if (!ctxt->ops->is_smm(ctxt))
2322 		return emulate_ud(ctxt);
2323 
2324 	if (ctxt->ops->leave_smm(ctxt))
2325 		ctxt->ops->triple_fault(ctxt);
2326 
2327 	return emulator_recalc_and_set_mode(ctxt);
2328 }
2329 
2330 static void
2331 setup_syscalls_segments(struct desc_struct *cs, struct desc_struct *ss)
2332 {
2333 	cs->l = 0;		/* will be adjusted later */
2334 	set_desc_base(cs, 0);	/* flat segment */
2335 	cs->g = 1;		/* 4kb granularity */
2336 	set_desc_limit(cs, 0xfffff);	/* 4GB limit */
2337 	cs->type = 0x0b;	/* Read, Execute, Accessed */
2338 	cs->s = 1;
2339 	cs->dpl = 0;		/* will be adjusted later */
2340 	cs->p = 1;
2341 	cs->d = 1;
2342 	cs->avl = 0;
2343 
2344 	set_desc_base(ss, 0);	/* flat segment */
2345 	set_desc_limit(ss, 0xfffff);	/* 4GB limit */
2346 	ss->g = 1;		/* 4kb granularity */
2347 	ss->s = 1;
2348 	ss->type = 0x03;	/* Read/Write, Accessed */
2349 	ss->d = 1;		/* 32bit stack segment */
2350 	ss->dpl = 0;
2351 	ss->p = 1;
2352 	ss->l = 0;
2353 	ss->avl = 0;
2354 }
2355 
2356 static bool vendor_intel(struct x86_emulate_ctxt *ctxt)
2357 {
2358 	u32 eax, ebx, ecx, edx;
2359 
2360 	eax = ecx = 0;
2361 	ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx, true);
2362 	return is_guest_vendor_intel(ebx, ecx, edx);
2363 }
2364 
2365 static bool em_syscall_is_enabled(struct x86_emulate_ctxt *ctxt)
2366 {
2367 	const struct x86_emulate_ops *ops = ctxt->ops;
2368 	u32 eax, ebx, ecx, edx;
2369 
2370 	/*
2371 	 * syscall should always be enabled in longmode - so only become
2372 	 * vendor specific (cpuid) if other modes are active...
2373 	 */
2374 	if (ctxt->mode == X86EMUL_MODE_PROT64)
2375 		return true;
2376 
2377 	eax = 0x00000000;
2378 	ecx = 0x00000000;
2379 	ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx, true);
2380 	/*
2381 	 * remark: Intel CPUs only support "syscall" in 64bit longmode. Also a
2382 	 * 64bit guest with a 32bit compat-app running will #UD !! While this
2383 	 * behaviour can be fixed (by emulating) into AMD response - CPUs of
2384 	 * AMD can't behave like Intel.
2385 	 */
2386 	if (is_guest_vendor_intel(ebx, ecx, edx))
2387 		return false;
2388 
2389 	if (is_guest_vendor_amd(ebx, ecx, edx) ||
2390 	    is_guest_vendor_hygon(ebx, ecx, edx))
2391 		return true;
2392 
2393 	/*
2394 	 * default: (not Intel, not AMD, not Hygon), apply Intel's
2395 	 * stricter rules...
2396 	 */
2397 	return false;
2398 }
2399 
2400 static int em_syscall(struct x86_emulate_ctxt *ctxt)
2401 {
2402 	const struct x86_emulate_ops *ops = ctxt->ops;
2403 	struct desc_struct cs, ss;
2404 	u64 msr_data;
2405 	u16 cs_sel, ss_sel;
2406 	u64 efer = 0;
2407 
2408 	/* syscall is not available in real mode */
2409 	if (ctxt->mode == X86EMUL_MODE_REAL ||
2410 	    ctxt->mode == X86EMUL_MODE_VM86)
2411 		return emulate_ud(ctxt);
2412 
2413 	if (!(em_syscall_is_enabled(ctxt)))
2414 		return emulate_ud(ctxt);
2415 
2416 	ops->get_msr(ctxt, MSR_EFER, &efer);
2417 	if (!(efer & EFER_SCE))
2418 		return emulate_ud(ctxt);
2419 
2420 	setup_syscalls_segments(&cs, &ss);
2421 	ops->get_msr(ctxt, MSR_STAR, &msr_data);
2422 	msr_data >>= 32;
2423 	cs_sel = (u16)(msr_data & 0xfffc);
2424 	ss_sel = (u16)(msr_data + 8);
2425 
2426 	if (efer & EFER_LMA) {
2427 		cs.d = 0;
2428 		cs.l = 1;
2429 	}
2430 	ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
2431 	ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
2432 
2433 	*reg_write(ctxt, VCPU_REGS_RCX) = ctxt->_eip;
2434 	if (efer & EFER_LMA) {
2435 #ifdef CONFIG_X86_64
2436 		*reg_write(ctxt, VCPU_REGS_R11) = ctxt->eflags;
2437 
2438 		ops->get_msr(ctxt,
2439 			     ctxt->mode == X86EMUL_MODE_PROT64 ?
2440 			     MSR_LSTAR : MSR_CSTAR, &msr_data);
2441 		ctxt->_eip = msr_data;
2442 
2443 		ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data);
2444 		ctxt->eflags &= ~msr_data;
2445 		ctxt->eflags |= X86_EFLAGS_FIXED;
2446 #endif
2447 	} else {
2448 		/* legacy mode */
2449 		ops->get_msr(ctxt, MSR_STAR, &msr_data);
2450 		ctxt->_eip = (u32)msr_data;
2451 
2452 		ctxt->eflags &= ~(X86_EFLAGS_VM | X86_EFLAGS_IF);
2453 	}
2454 
2455 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
2456 	return X86EMUL_CONTINUE;
2457 }
2458 
2459 static int em_sysenter(struct x86_emulate_ctxt *ctxt)
2460 {
2461 	const struct x86_emulate_ops *ops = ctxt->ops;
2462 	struct desc_struct cs, ss;
2463 	u64 msr_data;
2464 	u16 cs_sel, ss_sel;
2465 	u64 efer = 0;
2466 
2467 	ops->get_msr(ctxt, MSR_EFER, &efer);
2468 	/* inject #GP if in real mode */
2469 	if (ctxt->mode == X86EMUL_MODE_REAL)
2470 		return emulate_gp(ctxt, 0);
2471 
2472 	/*
2473 	 * Not recognized on AMD in compat mode (but is recognized in legacy
2474 	 * mode).
2475 	 */
2476 	if ((ctxt->mode != X86EMUL_MODE_PROT64) && (efer & EFER_LMA)
2477 	    && !vendor_intel(ctxt))
2478 		return emulate_ud(ctxt);
2479 
2480 	/* sysenter/sysexit have not been tested in 64bit mode. */
2481 	if (ctxt->mode == X86EMUL_MODE_PROT64)
2482 		return X86EMUL_UNHANDLEABLE;
2483 
2484 	ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
2485 	if ((msr_data & 0xfffc) == 0x0)
2486 		return emulate_gp(ctxt, 0);
2487 
2488 	setup_syscalls_segments(&cs, &ss);
2489 	ctxt->eflags &= ~(X86_EFLAGS_VM | X86_EFLAGS_IF);
2490 	cs_sel = (u16)msr_data & ~SEGMENT_RPL_MASK;
2491 	ss_sel = cs_sel + 8;
2492 	if (efer & EFER_LMA) {
2493 		cs.d = 0;
2494 		cs.l = 1;
2495 	}
2496 
2497 	ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
2498 	ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
2499 
2500 	ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data);
2501 	ctxt->_eip = (efer & EFER_LMA) ? msr_data : (u32)msr_data;
2502 
2503 	ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data);
2504 	*reg_write(ctxt, VCPU_REGS_RSP) = (efer & EFER_LMA) ? msr_data :
2505 							      (u32)msr_data;
2506 	if (efer & EFER_LMA)
2507 		ctxt->mode = X86EMUL_MODE_PROT64;
2508 
2509 	return X86EMUL_CONTINUE;
2510 }
2511 
2512 static int em_sysexit(struct x86_emulate_ctxt *ctxt)
2513 {
2514 	const struct x86_emulate_ops *ops = ctxt->ops;
2515 	struct desc_struct cs, ss;
2516 	u64 msr_data, rcx, rdx;
2517 	int usermode;
2518 	u16 cs_sel = 0, ss_sel = 0;
2519 
2520 	/* inject #GP if in real mode or Virtual 8086 mode */
2521 	if (ctxt->mode == X86EMUL_MODE_REAL ||
2522 	    ctxt->mode == X86EMUL_MODE_VM86)
2523 		return emulate_gp(ctxt, 0);
2524 
2525 	setup_syscalls_segments(&cs, &ss);
2526 
2527 	if ((ctxt->rex_prefix & 0x8) != 0x0)
2528 		usermode = X86EMUL_MODE_PROT64;
2529 	else
2530 		usermode = X86EMUL_MODE_PROT32;
2531 
2532 	rcx = reg_read(ctxt, VCPU_REGS_RCX);
2533 	rdx = reg_read(ctxt, VCPU_REGS_RDX);
2534 
2535 	cs.dpl = 3;
2536 	ss.dpl = 3;
2537 	ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
2538 	switch (usermode) {
2539 	case X86EMUL_MODE_PROT32:
2540 		cs_sel = (u16)(msr_data + 16);
2541 		if ((msr_data & 0xfffc) == 0x0)
2542 			return emulate_gp(ctxt, 0);
2543 		ss_sel = (u16)(msr_data + 24);
2544 		rcx = (u32)rcx;
2545 		rdx = (u32)rdx;
2546 		break;
2547 	case X86EMUL_MODE_PROT64:
2548 		cs_sel = (u16)(msr_data + 32);
2549 		if (msr_data == 0x0)
2550 			return emulate_gp(ctxt, 0);
2551 		ss_sel = cs_sel + 8;
2552 		cs.d = 0;
2553 		cs.l = 1;
2554 		if (emul_is_noncanonical_address(rcx, ctxt) ||
2555 		    emul_is_noncanonical_address(rdx, ctxt))
2556 			return emulate_gp(ctxt, 0);
2557 		break;
2558 	}
2559 	cs_sel |= SEGMENT_RPL_MASK;
2560 	ss_sel |= SEGMENT_RPL_MASK;
2561 
2562 	ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
2563 	ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
2564 
2565 	ctxt->_eip = rdx;
2566 	ctxt->mode = usermode;
2567 	*reg_write(ctxt, VCPU_REGS_RSP) = rcx;
2568 
2569 	return X86EMUL_CONTINUE;
2570 }
2571 
2572 static bool emulator_bad_iopl(struct x86_emulate_ctxt *ctxt)
2573 {
2574 	int iopl;
2575 	if (ctxt->mode == X86EMUL_MODE_REAL)
2576 		return false;
2577 	if (ctxt->mode == X86EMUL_MODE_VM86)
2578 		return true;
2579 	iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> X86_EFLAGS_IOPL_BIT;
2580 	return ctxt->ops->cpl(ctxt) > iopl;
2581 }
2582 
2583 #define VMWARE_PORT_VMPORT	(0x5658)
2584 #define VMWARE_PORT_VMRPC	(0x5659)
2585 
2586 static bool emulator_io_port_access_allowed(struct x86_emulate_ctxt *ctxt,
2587 					    u16 port, u16 len)
2588 {
2589 	const struct x86_emulate_ops *ops = ctxt->ops;
2590 	struct desc_struct tr_seg;
2591 	u32 base3;
2592 	int r;
2593 	u16 tr, io_bitmap_ptr, perm, bit_idx = port & 0x7;
2594 	unsigned mask = (1 << len) - 1;
2595 	unsigned long base;
2596 
2597 	/*
2598 	 * VMware allows access to these ports even if denied
2599 	 * by TSS I/O permission bitmap. Mimic behavior.
2600 	 */
2601 	if (enable_vmware_backdoor &&
2602 	    ((port == VMWARE_PORT_VMPORT) || (port == VMWARE_PORT_VMRPC)))
2603 		return true;
2604 
2605 	ops->get_segment(ctxt, &tr, &tr_seg, &base3, VCPU_SREG_TR);
2606 	if (!tr_seg.p)
2607 		return false;
2608 	if (desc_limit_scaled(&tr_seg) < 103)
2609 		return false;
2610 	base = get_desc_base(&tr_seg);
2611 #ifdef CONFIG_X86_64
2612 	base |= ((u64)base3) << 32;
2613 #endif
2614 	r = ops->read_std(ctxt, base + 102, &io_bitmap_ptr, 2, NULL, true);
2615 	if (r != X86EMUL_CONTINUE)
2616 		return false;
2617 	if (io_bitmap_ptr + port/8 > desc_limit_scaled(&tr_seg))
2618 		return false;
2619 	r = ops->read_std(ctxt, base + io_bitmap_ptr + port/8, &perm, 2, NULL, true);
2620 	if (r != X86EMUL_CONTINUE)
2621 		return false;
2622 	if ((perm >> bit_idx) & mask)
2623 		return false;
2624 	return true;
2625 }
2626 
2627 static bool emulator_io_permitted(struct x86_emulate_ctxt *ctxt,
2628 				  u16 port, u16 len)
2629 {
2630 	if (ctxt->perm_ok)
2631 		return true;
2632 
2633 	if (emulator_bad_iopl(ctxt))
2634 		if (!emulator_io_port_access_allowed(ctxt, port, len))
2635 			return false;
2636 
2637 	ctxt->perm_ok = true;
2638 
2639 	return true;
2640 }
2641 
2642 static void string_registers_quirk(struct x86_emulate_ctxt *ctxt)
2643 {
2644 	/*
2645 	 * Intel CPUs mask the counter and pointers in quite strange
2646 	 * manner when ECX is zero due to REP-string optimizations.
2647 	 */
2648 #ifdef CONFIG_X86_64
2649 	if (ctxt->ad_bytes != 4 || !vendor_intel(ctxt))
2650 		return;
2651 
2652 	*reg_write(ctxt, VCPU_REGS_RCX) = 0;
2653 
2654 	switch (ctxt->b) {
2655 	case 0xa4:	/* movsb */
2656 	case 0xa5:	/* movsd/w */
2657 		*reg_rmw(ctxt, VCPU_REGS_RSI) &= (u32)-1;
2658 		fallthrough;
2659 	case 0xaa:	/* stosb */
2660 	case 0xab:	/* stosd/w */
2661 		*reg_rmw(ctxt, VCPU_REGS_RDI) &= (u32)-1;
2662 	}
2663 #endif
2664 }
2665 
2666 static void save_state_to_tss16(struct x86_emulate_ctxt *ctxt,
2667 				struct tss_segment_16 *tss)
2668 {
2669 	tss->ip = ctxt->_eip;
2670 	tss->flag = ctxt->eflags;
2671 	tss->ax = reg_read(ctxt, VCPU_REGS_RAX);
2672 	tss->cx = reg_read(ctxt, VCPU_REGS_RCX);
2673 	tss->dx = reg_read(ctxt, VCPU_REGS_RDX);
2674 	tss->bx = reg_read(ctxt, VCPU_REGS_RBX);
2675 	tss->sp = reg_read(ctxt, VCPU_REGS_RSP);
2676 	tss->bp = reg_read(ctxt, VCPU_REGS_RBP);
2677 	tss->si = reg_read(ctxt, VCPU_REGS_RSI);
2678 	tss->di = reg_read(ctxt, VCPU_REGS_RDI);
2679 
2680 	tss->es = get_segment_selector(ctxt, VCPU_SREG_ES);
2681 	tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS);
2682 	tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS);
2683 	tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS);
2684 	tss->ldt = get_segment_selector(ctxt, VCPU_SREG_LDTR);
2685 }
2686 
2687 static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt,
2688 				 struct tss_segment_16 *tss)
2689 {
2690 	int ret;
2691 	u8 cpl;
2692 
2693 	ctxt->_eip = tss->ip;
2694 	ctxt->eflags = tss->flag | 2;
2695 	*reg_write(ctxt, VCPU_REGS_RAX) = tss->ax;
2696 	*reg_write(ctxt, VCPU_REGS_RCX) = tss->cx;
2697 	*reg_write(ctxt, VCPU_REGS_RDX) = tss->dx;
2698 	*reg_write(ctxt, VCPU_REGS_RBX) = tss->bx;
2699 	*reg_write(ctxt, VCPU_REGS_RSP) = tss->sp;
2700 	*reg_write(ctxt, VCPU_REGS_RBP) = tss->bp;
2701 	*reg_write(ctxt, VCPU_REGS_RSI) = tss->si;
2702 	*reg_write(ctxt, VCPU_REGS_RDI) = tss->di;
2703 
2704 	/*
2705 	 * SDM says that segment selectors are loaded before segment
2706 	 * descriptors
2707 	 */
2708 	set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR);
2709 	set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
2710 	set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
2711 	set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
2712 	set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
2713 
2714 	cpl = tss->cs & 3;
2715 
2716 	/*
2717 	 * Now load segment descriptors. If fault happens at this stage
2718 	 * it is handled in a context of new task
2719 	 */
2720 	ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl,
2721 					X86_TRANSFER_TASK_SWITCH, NULL);
2722 	if (ret != X86EMUL_CONTINUE)
2723 		return ret;
2724 	ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
2725 					X86_TRANSFER_TASK_SWITCH, NULL);
2726 	if (ret != X86EMUL_CONTINUE)
2727 		return ret;
2728 	ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
2729 					X86_TRANSFER_TASK_SWITCH, NULL);
2730 	if (ret != X86EMUL_CONTINUE)
2731 		return ret;
2732 	ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
2733 					X86_TRANSFER_TASK_SWITCH, NULL);
2734 	if (ret != X86EMUL_CONTINUE)
2735 		return ret;
2736 	ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
2737 					X86_TRANSFER_TASK_SWITCH, NULL);
2738 	if (ret != X86EMUL_CONTINUE)
2739 		return ret;
2740 
2741 	return X86EMUL_CONTINUE;
2742 }
2743 
2744 static int task_switch_16(struct x86_emulate_ctxt *ctxt, u16 old_tss_sel,
2745 			  ulong old_tss_base, struct desc_struct *new_desc)
2746 {
2747 	struct tss_segment_16 tss_seg;
2748 	int ret;
2749 	u32 new_tss_base = get_desc_base(new_desc);
2750 
2751 	ret = linear_read_system(ctxt, old_tss_base, &tss_seg, sizeof(tss_seg));
2752 	if (ret != X86EMUL_CONTINUE)
2753 		return ret;
2754 
2755 	save_state_to_tss16(ctxt, &tss_seg);
2756 
2757 	ret = linear_write_system(ctxt, old_tss_base, &tss_seg, sizeof(tss_seg));
2758 	if (ret != X86EMUL_CONTINUE)
2759 		return ret;
2760 
2761 	ret = linear_read_system(ctxt, new_tss_base, &tss_seg, sizeof(tss_seg));
2762 	if (ret != X86EMUL_CONTINUE)
2763 		return ret;
2764 
2765 	if (old_tss_sel != 0xffff) {
2766 		tss_seg.prev_task_link = old_tss_sel;
2767 
2768 		ret = linear_write_system(ctxt, new_tss_base,
2769 					  &tss_seg.prev_task_link,
2770 					  sizeof(tss_seg.prev_task_link));
2771 		if (ret != X86EMUL_CONTINUE)
2772 			return ret;
2773 	}
2774 
2775 	return load_state_from_tss16(ctxt, &tss_seg);
2776 }
2777 
2778 static void save_state_to_tss32(struct x86_emulate_ctxt *ctxt,
2779 				struct tss_segment_32 *tss)
2780 {
2781 	/* CR3 and ldt selector are not saved intentionally */
2782 	tss->eip = ctxt->_eip;
2783 	tss->eflags = ctxt->eflags;
2784 	tss->eax = reg_read(ctxt, VCPU_REGS_RAX);
2785 	tss->ecx = reg_read(ctxt, VCPU_REGS_RCX);
2786 	tss->edx = reg_read(ctxt, VCPU_REGS_RDX);
2787 	tss->ebx = reg_read(ctxt, VCPU_REGS_RBX);
2788 	tss->esp = reg_read(ctxt, VCPU_REGS_RSP);
2789 	tss->ebp = reg_read(ctxt, VCPU_REGS_RBP);
2790 	tss->esi = reg_read(ctxt, VCPU_REGS_RSI);
2791 	tss->edi = reg_read(ctxt, VCPU_REGS_RDI);
2792 
2793 	tss->es = get_segment_selector(ctxt, VCPU_SREG_ES);
2794 	tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS);
2795 	tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS);
2796 	tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS);
2797 	tss->fs = get_segment_selector(ctxt, VCPU_SREG_FS);
2798 	tss->gs = get_segment_selector(ctxt, VCPU_SREG_GS);
2799 }
2800 
2801 static int load_state_from_tss32(struct x86_emulate_ctxt *ctxt,
2802 				 struct tss_segment_32 *tss)
2803 {
2804 	int ret;
2805 	u8 cpl;
2806 
2807 	if (ctxt->ops->set_cr(ctxt, 3, tss->cr3))
2808 		return emulate_gp(ctxt, 0);
2809 	ctxt->_eip = tss->eip;
2810 	ctxt->eflags = tss->eflags | 2;
2811 
2812 	/* General purpose registers */
2813 	*reg_write(ctxt, VCPU_REGS_RAX) = tss->eax;
2814 	*reg_write(ctxt, VCPU_REGS_RCX) = tss->ecx;
2815 	*reg_write(ctxt, VCPU_REGS_RDX) = tss->edx;
2816 	*reg_write(ctxt, VCPU_REGS_RBX) = tss->ebx;
2817 	*reg_write(ctxt, VCPU_REGS_RSP) = tss->esp;
2818 	*reg_write(ctxt, VCPU_REGS_RBP) = tss->ebp;
2819 	*reg_write(ctxt, VCPU_REGS_RSI) = tss->esi;
2820 	*reg_write(ctxt, VCPU_REGS_RDI) = tss->edi;
2821 
2822 	/*
2823 	 * SDM says that segment selectors are loaded before segment
2824 	 * descriptors.  This is important because CPL checks will
2825 	 * use CS.RPL.
2826 	 */
2827 	set_segment_selector(ctxt, tss->ldt_selector, VCPU_SREG_LDTR);
2828 	set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
2829 	set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
2830 	set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
2831 	set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
2832 	set_segment_selector(ctxt, tss->fs, VCPU_SREG_FS);
2833 	set_segment_selector(ctxt, tss->gs, VCPU_SREG_GS);
2834 
2835 	/*
2836 	 * If we're switching between Protected Mode and VM86, we need to make
2837 	 * sure to update the mode before loading the segment descriptors so
2838 	 * that the selectors are interpreted correctly.
2839 	 */
2840 	if (ctxt->eflags & X86_EFLAGS_VM) {
2841 		ctxt->mode = X86EMUL_MODE_VM86;
2842 		cpl = 3;
2843 	} else {
2844 		ctxt->mode = X86EMUL_MODE_PROT32;
2845 		cpl = tss->cs & 3;
2846 	}
2847 
2848 	/*
2849 	 * Now load segment descriptors. If fault happens at this stage
2850 	 * it is handled in a context of new task
2851 	 */
2852 	ret = __load_segment_descriptor(ctxt, tss->ldt_selector, VCPU_SREG_LDTR,
2853 					cpl, X86_TRANSFER_TASK_SWITCH, NULL);
2854 	if (ret != X86EMUL_CONTINUE)
2855 		return ret;
2856 	ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
2857 					X86_TRANSFER_TASK_SWITCH, NULL);
2858 	if (ret != X86EMUL_CONTINUE)
2859 		return ret;
2860 	ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
2861 					X86_TRANSFER_TASK_SWITCH, NULL);
2862 	if (ret != X86EMUL_CONTINUE)
2863 		return ret;
2864 	ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
2865 					X86_TRANSFER_TASK_SWITCH, NULL);
2866 	if (ret != X86EMUL_CONTINUE)
2867 		return ret;
2868 	ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
2869 					X86_TRANSFER_TASK_SWITCH, NULL);
2870 	if (ret != X86EMUL_CONTINUE)
2871 		return ret;
2872 	ret = __load_segment_descriptor(ctxt, tss->fs, VCPU_SREG_FS, cpl,
2873 					X86_TRANSFER_TASK_SWITCH, NULL);
2874 	if (ret != X86EMUL_CONTINUE)
2875 		return ret;
2876 	ret = __load_segment_descriptor(ctxt, tss->gs, VCPU_SREG_GS, cpl,
2877 					X86_TRANSFER_TASK_SWITCH, NULL);
2878 
2879 	return ret;
2880 }
2881 
2882 static int task_switch_32(struct x86_emulate_ctxt *ctxt, u16 old_tss_sel,
2883 			  ulong old_tss_base, struct desc_struct *new_desc)
2884 {
2885 	struct tss_segment_32 tss_seg;
2886 	int ret;
2887 	u32 new_tss_base = get_desc_base(new_desc);
2888 	u32 eip_offset = offsetof(struct tss_segment_32, eip);
2889 	u32 ldt_sel_offset = offsetof(struct tss_segment_32, ldt_selector);
2890 
2891 	ret = linear_read_system(ctxt, old_tss_base, &tss_seg, sizeof(tss_seg));
2892 	if (ret != X86EMUL_CONTINUE)
2893 		return ret;
2894 
2895 	save_state_to_tss32(ctxt, &tss_seg);
2896 
2897 	/* Only GP registers and segment selectors are saved */
2898 	ret = linear_write_system(ctxt, old_tss_base + eip_offset, &tss_seg.eip,
2899 				  ldt_sel_offset - eip_offset);
2900 	if (ret != X86EMUL_CONTINUE)
2901 		return ret;
2902 
2903 	ret = linear_read_system(ctxt, new_tss_base, &tss_seg, sizeof(tss_seg));
2904 	if (ret != X86EMUL_CONTINUE)
2905 		return ret;
2906 
2907 	if (old_tss_sel != 0xffff) {
2908 		tss_seg.prev_task_link = old_tss_sel;
2909 
2910 		ret = linear_write_system(ctxt, new_tss_base,
2911 					  &tss_seg.prev_task_link,
2912 					  sizeof(tss_seg.prev_task_link));
2913 		if (ret != X86EMUL_CONTINUE)
2914 			return ret;
2915 	}
2916 
2917 	return load_state_from_tss32(ctxt, &tss_seg);
2918 }
2919 
2920 static int emulator_do_task_switch(struct x86_emulate_ctxt *ctxt,
2921 				   u16 tss_selector, int idt_index, int reason,
2922 				   bool has_error_code, u32 error_code)
2923 {
2924 	const struct x86_emulate_ops *ops = ctxt->ops;
2925 	struct desc_struct curr_tss_desc, next_tss_desc;
2926 	int ret;
2927 	u16 old_tss_sel = get_segment_selector(ctxt, VCPU_SREG_TR);
2928 	ulong old_tss_base =
2929 		ops->get_cached_segment_base(ctxt, VCPU_SREG_TR);
2930 	u32 desc_limit;
2931 	ulong desc_addr, dr7;
2932 
2933 	/* FIXME: old_tss_base == ~0 ? */
2934 
2935 	ret = read_segment_descriptor(ctxt, tss_selector, &next_tss_desc, &desc_addr);
2936 	if (ret != X86EMUL_CONTINUE)
2937 		return ret;
2938 	ret = read_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc, &desc_addr);
2939 	if (ret != X86EMUL_CONTINUE)
2940 		return ret;
2941 
2942 	/* FIXME: check that next_tss_desc is tss */
2943 
2944 	/*
2945 	 * Check privileges. The three cases are task switch caused by...
2946 	 *
2947 	 * 1. jmp/call/int to task gate: Check against DPL of the task gate
2948 	 * 2. Exception/IRQ/iret: No check is performed
2949 	 * 3. jmp/call to TSS/task-gate: No check is performed since the
2950 	 *    hardware checks it before exiting.
2951 	 */
2952 	if (reason == TASK_SWITCH_GATE) {
2953 		if (idt_index != -1) {
2954 			/* Software interrupts */
2955 			struct desc_struct task_gate_desc;
2956 			int dpl;
2957 
2958 			ret = read_interrupt_descriptor(ctxt, idt_index,
2959 							&task_gate_desc);
2960 			if (ret != X86EMUL_CONTINUE)
2961 				return ret;
2962 
2963 			dpl = task_gate_desc.dpl;
2964 			if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl)
2965 				return emulate_gp(ctxt, (idt_index << 3) | 0x2);
2966 		}
2967 	}
2968 
2969 	desc_limit = desc_limit_scaled(&next_tss_desc);
2970 	if (!next_tss_desc.p ||
2971 	    ((desc_limit < 0x67 && (next_tss_desc.type & 8)) ||
2972 	     desc_limit < 0x2b)) {
2973 		return emulate_ts(ctxt, tss_selector & 0xfffc);
2974 	}
2975 
2976 	if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
2977 		curr_tss_desc.type &= ~(1 << 1); /* clear busy flag */
2978 		write_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc);
2979 	}
2980 
2981 	if (reason == TASK_SWITCH_IRET)
2982 		ctxt->eflags = ctxt->eflags & ~X86_EFLAGS_NT;
2983 
2984 	/* set back link to prev task only if NT bit is set in eflags
2985 	   note that old_tss_sel is not used after this point */
2986 	if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE)
2987 		old_tss_sel = 0xffff;
2988 
2989 	if (next_tss_desc.type & 8)
2990 		ret = task_switch_32(ctxt, old_tss_sel, old_tss_base, &next_tss_desc);
2991 	else
2992 		ret = task_switch_16(ctxt, old_tss_sel,
2993 				     old_tss_base, &next_tss_desc);
2994 	if (ret != X86EMUL_CONTINUE)
2995 		return ret;
2996 
2997 	if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE)
2998 		ctxt->eflags = ctxt->eflags | X86_EFLAGS_NT;
2999 
3000 	if (reason != TASK_SWITCH_IRET) {
3001 		next_tss_desc.type |= (1 << 1); /* set busy flag */
3002 		write_segment_descriptor(ctxt, tss_selector, &next_tss_desc);
3003 	}
3004 
3005 	ops->set_cr(ctxt, 0,  ops->get_cr(ctxt, 0) | X86_CR0_TS);
3006 	ops->set_segment(ctxt, tss_selector, &next_tss_desc, 0, VCPU_SREG_TR);
3007 
3008 	if (has_error_code) {
3009 		ctxt->op_bytes = ctxt->ad_bytes = (next_tss_desc.type & 8) ? 4 : 2;
3010 		ctxt->lock_prefix = 0;
3011 		ctxt->src.val = (unsigned long) error_code;
3012 		ret = em_push(ctxt);
3013 	}
3014 
3015 	ops->get_dr(ctxt, 7, &dr7);
3016 	ops->set_dr(ctxt, 7, dr7 & ~(DR_LOCAL_ENABLE_MASK | DR_LOCAL_SLOWDOWN));
3017 
3018 	return ret;
3019 }
3020 
3021 int emulator_task_switch(struct x86_emulate_ctxt *ctxt,
3022 			 u16 tss_selector, int idt_index, int reason,
3023 			 bool has_error_code, u32 error_code)
3024 {
3025 	int rc;
3026 
3027 	invalidate_registers(ctxt);
3028 	ctxt->_eip = ctxt->eip;
3029 	ctxt->dst.type = OP_NONE;
3030 
3031 	rc = emulator_do_task_switch(ctxt, tss_selector, idt_index, reason,
3032 				     has_error_code, error_code);
3033 
3034 	if (rc == X86EMUL_CONTINUE) {
3035 		ctxt->eip = ctxt->_eip;
3036 		writeback_registers(ctxt);
3037 	}
3038 
3039 	return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK;
3040 }
3041 
3042 static void string_addr_inc(struct x86_emulate_ctxt *ctxt, int reg,
3043 		struct operand *op)
3044 {
3045 	int df = (ctxt->eflags & X86_EFLAGS_DF) ? -op->count : op->count;
3046 
3047 	register_address_increment(ctxt, reg, df * op->bytes);
3048 	op->addr.mem.ea = register_address(ctxt, reg);
3049 }
3050 
3051 static int em_das(struct x86_emulate_ctxt *ctxt)
3052 {
3053 	u8 al, old_al;
3054 	bool af, cf, old_cf;
3055 
3056 	cf = ctxt->eflags & X86_EFLAGS_CF;
3057 	al = ctxt->dst.val;
3058 
3059 	old_al = al;
3060 	old_cf = cf;
3061 	cf = false;
3062 	af = ctxt->eflags & X86_EFLAGS_AF;
3063 	if ((al & 0x0f) > 9 || af) {
3064 		al -= 6;
3065 		cf = old_cf | (al >= 250);
3066 		af = true;
3067 	} else {
3068 		af = false;
3069 	}
3070 	if (old_al > 0x99 || old_cf) {
3071 		al -= 0x60;
3072 		cf = true;
3073 	}
3074 
3075 	ctxt->dst.val = al;
3076 	/* Set PF, ZF, SF */
3077 	ctxt->src.type = OP_IMM;
3078 	ctxt->src.val = 0;
3079 	ctxt->src.bytes = 1;
3080 	fastop(ctxt, em_or);
3081 	ctxt->eflags &= ~(X86_EFLAGS_AF | X86_EFLAGS_CF);
3082 	if (cf)
3083 		ctxt->eflags |= X86_EFLAGS_CF;
3084 	if (af)
3085 		ctxt->eflags |= X86_EFLAGS_AF;
3086 	return X86EMUL_CONTINUE;
3087 }
3088 
3089 static int em_aam(struct x86_emulate_ctxt *ctxt)
3090 {
3091 	u8 al, ah;
3092 
3093 	if (ctxt->src.val == 0)
3094 		return emulate_de(ctxt);
3095 
3096 	al = ctxt->dst.val & 0xff;
3097 	ah = al / ctxt->src.val;
3098 	al %= ctxt->src.val;
3099 
3100 	ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al | (ah << 8);
3101 
3102 	/* Set PF, ZF, SF */
3103 	ctxt->src.type = OP_IMM;
3104 	ctxt->src.val = 0;
3105 	ctxt->src.bytes = 1;
3106 	fastop(ctxt, em_or);
3107 
3108 	return X86EMUL_CONTINUE;
3109 }
3110 
3111 static int em_aad(struct x86_emulate_ctxt *ctxt)
3112 {
3113 	u8 al = ctxt->dst.val & 0xff;
3114 	u8 ah = (ctxt->dst.val >> 8) & 0xff;
3115 
3116 	al = (al + (ah * ctxt->src.val)) & 0xff;
3117 
3118 	ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al;
3119 
3120 	/* Set PF, ZF, SF */
3121 	ctxt->src.type = OP_IMM;
3122 	ctxt->src.val = 0;
3123 	ctxt->src.bytes = 1;
3124 	fastop(ctxt, em_or);
3125 
3126 	return X86EMUL_CONTINUE;
3127 }
3128 
3129 static int em_call(struct x86_emulate_ctxt *ctxt)
3130 {
3131 	int rc;
3132 	long rel = ctxt->src.val;
3133 
3134 	ctxt->src.val = (unsigned long)ctxt->_eip;
3135 	rc = jmp_rel(ctxt, rel);
3136 	if (rc != X86EMUL_CONTINUE)
3137 		return rc;
3138 	return em_push(ctxt);
3139 }
3140 
3141 static int em_call_far(struct x86_emulate_ctxt *ctxt)
3142 {
3143 	u16 sel, old_cs;
3144 	ulong old_eip;
3145 	int rc;
3146 	struct desc_struct old_desc, new_desc;
3147 	const struct x86_emulate_ops *ops = ctxt->ops;
3148 	int cpl = ctxt->ops->cpl(ctxt);
3149 	enum x86emul_mode prev_mode = ctxt->mode;
3150 
3151 	old_eip = ctxt->_eip;
3152 	ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS);
3153 
3154 	memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
3155 	rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,
3156 				       X86_TRANSFER_CALL_JMP, &new_desc);
3157 	if (rc != X86EMUL_CONTINUE)
3158 		return rc;
3159 
3160 	rc = assign_eip_far(ctxt, ctxt->src.val);
3161 	if (rc != X86EMUL_CONTINUE)
3162 		goto fail;
3163 
3164 	ctxt->src.val = old_cs;
3165 	rc = em_push(ctxt);
3166 	if (rc != X86EMUL_CONTINUE)
3167 		goto fail;
3168 
3169 	ctxt->src.val = old_eip;
3170 	rc = em_push(ctxt);
3171 	/* If we failed, we tainted the memory, but the very least we should
3172 	   restore cs */
3173 	if (rc != X86EMUL_CONTINUE) {
3174 		pr_warn_once("faulting far call emulation tainted memory\n");
3175 		goto fail;
3176 	}
3177 	return rc;
3178 fail:
3179 	ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
3180 	ctxt->mode = prev_mode;
3181 	return rc;
3182 
3183 }
3184 
3185 static int em_ret_near_imm(struct x86_emulate_ctxt *ctxt)
3186 {
3187 	int rc;
3188 	unsigned long eip;
3189 
3190 	rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
3191 	if (rc != X86EMUL_CONTINUE)
3192 		return rc;
3193 	rc = assign_eip_near(ctxt, eip);
3194 	if (rc != X86EMUL_CONTINUE)
3195 		return rc;
3196 	rsp_increment(ctxt, ctxt->src.val);
3197 	return X86EMUL_CONTINUE;
3198 }
3199 
3200 static int em_xchg(struct x86_emulate_ctxt *ctxt)
3201 {
3202 	/* Write back the register source. */
3203 	ctxt->src.val = ctxt->dst.val;
3204 	write_register_operand(&ctxt->src);
3205 
3206 	/* Write back the memory destination with implicit LOCK prefix. */
3207 	ctxt->dst.val = ctxt->src.orig_val;
3208 	ctxt->lock_prefix = 1;
3209 	return X86EMUL_CONTINUE;
3210 }
3211 
3212 static int em_imul_3op(struct x86_emulate_ctxt *ctxt)
3213 {
3214 	ctxt->dst.val = ctxt->src2.val;
3215 	return fastop(ctxt, em_imul);
3216 }
3217 
3218 static int em_cwd(struct x86_emulate_ctxt *ctxt)
3219 {
3220 	ctxt->dst.type = OP_REG;
3221 	ctxt->dst.bytes = ctxt->src.bytes;
3222 	ctxt->dst.addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
3223 	ctxt->dst.val = ~((ctxt->src.val >> (ctxt->src.bytes * 8 - 1)) - 1);
3224 
3225 	return X86EMUL_CONTINUE;
3226 }
3227 
3228 static int em_rdpid(struct x86_emulate_ctxt *ctxt)
3229 {
3230 	u64 tsc_aux = 0;
3231 
3232 	if (!ctxt->ops->guest_has_rdpid(ctxt))
3233 		return emulate_ud(ctxt);
3234 
3235 	ctxt->ops->get_msr(ctxt, MSR_TSC_AUX, &tsc_aux);
3236 	ctxt->dst.val = tsc_aux;
3237 	return X86EMUL_CONTINUE;
3238 }
3239 
3240 static int em_rdtsc(struct x86_emulate_ctxt *ctxt)
3241 {
3242 	u64 tsc = 0;
3243 
3244 	ctxt->ops->get_msr(ctxt, MSR_IA32_TSC, &tsc);
3245 	*reg_write(ctxt, VCPU_REGS_RAX) = (u32)tsc;
3246 	*reg_write(ctxt, VCPU_REGS_RDX) = tsc >> 32;
3247 	return X86EMUL_CONTINUE;
3248 }
3249 
3250 static int em_rdpmc(struct x86_emulate_ctxt *ctxt)
3251 {
3252 	u64 pmc;
3253 
3254 	if (ctxt->ops->read_pmc(ctxt, reg_read(ctxt, VCPU_REGS_RCX), &pmc))
3255 		return emulate_gp(ctxt, 0);
3256 	*reg_write(ctxt, VCPU_REGS_RAX) = (u32)pmc;
3257 	*reg_write(ctxt, VCPU_REGS_RDX) = pmc >> 32;
3258 	return X86EMUL_CONTINUE;
3259 }
3260 
3261 static int em_mov(struct x86_emulate_ctxt *ctxt)
3262 {
3263 	memcpy(ctxt->dst.valptr, ctxt->src.valptr, sizeof(ctxt->src.valptr));
3264 	return X86EMUL_CONTINUE;
3265 }
3266 
3267 static int em_movbe(struct x86_emulate_ctxt *ctxt)
3268 {
3269 	u16 tmp;
3270 
3271 	if (!ctxt->ops->guest_has_movbe(ctxt))
3272 		return emulate_ud(ctxt);
3273 
3274 	switch (ctxt->op_bytes) {
3275 	case 2:
3276 		/*
3277 		 * From MOVBE definition: "...When the operand size is 16 bits,
3278 		 * the upper word of the destination register remains unchanged
3279 		 * ..."
3280 		 *
3281 		 * Both casting ->valptr and ->val to u16 breaks strict aliasing
3282 		 * rules so we have to do the operation almost per hand.
3283 		 */
3284 		tmp = (u16)ctxt->src.val;
3285 		ctxt->dst.val &= ~0xffffUL;
3286 		ctxt->dst.val |= (unsigned long)swab16(tmp);
3287 		break;
3288 	case 4:
3289 		ctxt->dst.val = swab32((u32)ctxt->src.val);
3290 		break;
3291 	case 8:
3292 		ctxt->dst.val = swab64(ctxt->src.val);
3293 		break;
3294 	default:
3295 		BUG();
3296 	}
3297 	return X86EMUL_CONTINUE;
3298 }
3299 
3300 static int em_cr_write(struct x86_emulate_ctxt *ctxt)
3301 {
3302 	int cr_num = ctxt->modrm_reg;
3303 	int r;
3304 
3305 	if (ctxt->ops->set_cr(ctxt, cr_num, ctxt->src.val))
3306 		return emulate_gp(ctxt, 0);
3307 
3308 	/* Disable writeback. */
3309 	ctxt->dst.type = OP_NONE;
3310 
3311 	if (cr_num == 0) {
3312 		/*
3313 		 * CR0 write might have updated CR0.PE and/or CR0.PG
3314 		 * which can affect the cpu's execution mode.
3315 		 */
3316 		r = emulator_recalc_and_set_mode(ctxt);
3317 		if (r != X86EMUL_CONTINUE)
3318 			return r;
3319 	}
3320 
3321 	return X86EMUL_CONTINUE;
3322 }
3323 
3324 static int em_dr_write(struct x86_emulate_ctxt *ctxt)
3325 {
3326 	unsigned long val;
3327 
3328 	if (ctxt->mode == X86EMUL_MODE_PROT64)
3329 		val = ctxt->src.val & ~0ULL;
3330 	else
3331 		val = ctxt->src.val & ~0U;
3332 
3333 	/* #UD condition is already handled. */
3334 	if (ctxt->ops->set_dr(ctxt, ctxt->modrm_reg, val) < 0)
3335 		return emulate_gp(ctxt, 0);
3336 
3337 	/* Disable writeback. */
3338 	ctxt->dst.type = OP_NONE;
3339 	return X86EMUL_CONTINUE;
3340 }
3341 
3342 static int em_wrmsr(struct x86_emulate_ctxt *ctxt)
3343 {
3344 	u64 msr_index = reg_read(ctxt, VCPU_REGS_RCX);
3345 	u64 msr_data;
3346 	int r;
3347 
3348 	msr_data = (u32)reg_read(ctxt, VCPU_REGS_RAX)
3349 		| ((u64)reg_read(ctxt, VCPU_REGS_RDX) << 32);
3350 	r = ctxt->ops->set_msr_with_filter(ctxt, msr_index, msr_data);
3351 
3352 	if (r == X86EMUL_PROPAGATE_FAULT)
3353 		return emulate_gp(ctxt, 0);
3354 
3355 	return r;
3356 }
3357 
3358 static int em_rdmsr(struct x86_emulate_ctxt *ctxt)
3359 {
3360 	u64 msr_index = reg_read(ctxt, VCPU_REGS_RCX);
3361 	u64 msr_data;
3362 	int r;
3363 
3364 	r = ctxt->ops->get_msr_with_filter(ctxt, msr_index, &msr_data);
3365 
3366 	if (r == X86EMUL_PROPAGATE_FAULT)
3367 		return emulate_gp(ctxt, 0);
3368 
3369 	if (r == X86EMUL_CONTINUE) {
3370 		*reg_write(ctxt, VCPU_REGS_RAX) = (u32)msr_data;
3371 		*reg_write(ctxt, VCPU_REGS_RDX) = msr_data >> 32;
3372 	}
3373 	return r;
3374 }
3375 
3376 static int em_store_sreg(struct x86_emulate_ctxt *ctxt, int segment)
3377 {
3378 	if (segment > VCPU_SREG_GS &&
3379 	    (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_UMIP) &&
3380 	    ctxt->ops->cpl(ctxt) > 0)
3381 		return emulate_gp(ctxt, 0);
3382 
3383 	ctxt->dst.val = get_segment_selector(ctxt, segment);
3384 	if (ctxt->dst.bytes == 4 && ctxt->dst.type == OP_MEM)
3385 		ctxt->dst.bytes = 2;
3386 	return X86EMUL_CONTINUE;
3387 }
3388 
3389 static int em_mov_rm_sreg(struct x86_emulate_ctxt *ctxt)
3390 {
3391 	if (ctxt->modrm_reg > VCPU_SREG_GS)
3392 		return emulate_ud(ctxt);
3393 
3394 	return em_store_sreg(ctxt, ctxt->modrm_reg);
3395 }
3396 
3397 static int em_mov_sreg_rm(struct x86_emulate_ctxt *ctxt)
3398 {
3399 	u16 sel = ctxt->src.val;
3400 
3401 	if (ctxt->modrm_reg == VCPU_SREG_CS || ctxt->modrm_reg > VCPU_SREG_GS)
3402 		return emulate_ud(ctxt);
3403 
3404 	if (ctxt->modrm_reg == VCPU_SREG_SS)
3405 		ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS;
3406 
3407 	/* Disable writeback. */
3408 	ctxt->dst.type = OP_NONE;
3409 	return load_segment_descriptor(ctxt, sel, ctxt->modrm_reg);
3410 }
3411 
3412 static int em_sldt(struct x86_emulate_ctxt *ctxt)
3413 {
3414 	return em_store_sreg(ctxt, VCPU_SREG_LDTR);
3415 }
3416 
3417 static int em_lldt(struct x86_emulate_ctxt *ctxt)
3418 {
3419 	u16 sel = ctxt->src.val;
3420 
3421 	/* Disable writeback. */
3422 	ctxt->dst.type = OP_NONE;
3423 	return load_segment_descriptor(ctxt, sel, VCPU_SREG_LDTR);
3424 }
3425 
3426 static int em_str(struct x86_emulate_ctxt *ctxt)
3427 {
3428 	return em_store_sreg(ctxt, VCPU_SREG_TR);
3429 }
3430 
3431 static int em_ltr(struct x86_emulate_ctxt *ctxt)
3432 {
3433 	u16 sel = ctxt->src.val;
3434 
3435 	/* Disable writeback. */
3436 	ctxt->dst.type = OP_NONE;
3437 	return load_segment_descriptor(ctxt, sel, VCPU_SREG_TR);
3438 }
3439 
3440 static int em_invlpg(struct x86_emulate_ctxt *ctxt)
3441 {
3442 	int rc;
3443 	ulong linear;
3444 
3445 	rc = linearize(ctxt, ctxt->src.addr.mem, 1, false, &linear);
3446 	if (rc == X86EMUL_CONTINUE)
3447 		ctxt->ops->invlpg(ctxt, linear);
3448 	/* Disable writeback. */
3449 	ctxt->dst.type = OP_NONE;
3450 	return X86EMUL_CONTINUE;
3451 }
3452 
3453 static int em_clts(struct x86_emulate_ctxt *ctxt)
3454 {
3455 	ulong cr0;
3456 
3457 	cr0 = ctxt->ops->get_cr(ctxt, 0);
3458 	cr0 &= ~X86_CR0_TS;
3459 	ctxt->ops->set_cr(ctxt, 0, cr0);
3460 	return X86EMUL_CONTINUE;
3461 }
3462 
3463 static int em_hypercall(struct x86_emulate_ctxt *ctxt)
3464 {
3465 	int rc = ctxt->ops->fix_hypercall(ctxt);
3466 
3467 	if (rc != X86EMUL_CONTINUE)
3468 		return rc;
3469 
3470 	/* Let the processor re-execute the fixed hypercall */
3471 	ctxt->_eip = ctxt->eip;
3472 	/* Disable writeback. */
3473 	ctxt->dst.type = OP_NONE;
3474 	return X86EMUL_CONTINUE;
3475 }
3476 
3477 static int emulate_store_desc_ptr(struct x86_emulate_ctxt *ctxt,
3478 				  void (*get)(struct x86_emulate_ctxt *ctxt,
3479 					      struct desc_ptr *ptr))
3480 {
3481 	struct desc_ptr desc_ptr;
3482 
3483 	if ((ctxt->ops->get_cr(ctxt, 4) & X86_CR4_UMIP) &&
3484 	    ctxt->ops->cpl(ctxt) > 0)
3485 		return emulate_gp(ctxt, 0);
3486 
3487 	if (ctxt->mode == X86EMUL_MODE_PROT64)
3488 		ctxt->op_bytes = 8;
3489 	get(ctxt, &desc_ptr);
3490 	if (ctxt->op_bytes == 2) {
3491 		ctxt->op_bytes = 4;
3492 		desc_ptr.address &= 0x00ffffff;
3493 	}
3494 	/* Disable writeback. */
3495 	ctxt->dst.type = OP_NONE;
3496 	return segmented_write_std(ctxt, ctxt->dst.addr.mem,
3497 				   &desc_ptr, 2 + ctxt->op_bytes);
3498 }
3499 
3500 static int em_sgdt(struct x86_emulate_ctxt *ctxt)
3501 {
3502 	return emulate_store_desc_ptr(ctxt, ctxt->ops->get_gdt);
3503 }
3504 
3505 static int em_sidt(struct x86_emulate_ctxt *ctxt)
3506 {
3507 	return emulate_store_desc_ptr(ctxt, ctxt->ops->get_idt);
3508 }
3509 
3510 static int em_lgdt_lidt(struct x86_emulate_ctxt *ctxt, bool lgdt)
3511 {
3512 	struct desc_ptr desc_ptr;
3513 	int rc;
3514 
3515 	if (ctxt->mode == X86EMUL_MODE_PROT64)
3516 		ctxt->op_bytes = 8;
3517 	rc = read_descriptor(ctxt, ctxt->src.addr.mem,
3518 			     &desc_ptr.size, &desc_ptr.address,
3519 			     ctxt->op_bytes);
3520 	if (rc != X86EMUL_CONTINUE)
3521 		return rc;
3522 	if (ctxt->mode == X86EMUL_MODE_PROT64 &&
3523 	    emul_is_noncanonical_address(desc_ptr.address, ctxt))
3524 		return emulate_gp(ctxt, 0);
3525 	if (lgdt)
3526 		ctxt->ops->set_gdt(ctxt, &desc_ptr);
3527 	else
3528 		ctxt->ops->set_idt(ctxt, &desc_ptr);
3529 	/* Disable writeback. */
3530 	ctxt->dst.type = OP_NONE;
3531 	return X86EMUL_CONTINUE;
3532 }
3533 
3534 static int em_lgdt(struct x86_emulate_ctxt *ctxt)
3535 {
3536 	return em_lgdt_lidt(ctxt, true);
3537 }
3538 
3539 static int em_lidt(struct x86_emulate_ctxt *ctxt)
3540 {
3541 	return em_lgdt_lidt(ctxt, false);
3542 }
3543 
3544 static int em_smsw(struct x86_emulate_ctxt *ctxt)
3545 {
3546 	if ((ctxt->ops->get_cr(ctxt, 4) & X86_CR4_UMIP) &&
3547 	    ctxt->ops->cpl(ctxt) > 0)
3548 		return emulate_gp(ctxt, 0);
3549 
3550 	if (ctxt->dst.type == OP_MEM)
3551 		ctxt->dst.bytes = 2;
3552 	ctxt->dst.val = ctxt->ops->get_cr(ctxt, 0);
3553 	return X86EMUL_CONTINUE;
3554 }
3555 
3556 static int em_lmsw(struct x86_emulate_ctxt *ctxt)
3557 {
3558 	ctxt->ops->set_cr(ctxt, 0, (ctxt->ops->get_cr(ctxt, 0) & ~0x0eul)
3559 			  | (ctxt->src.val & 0x0f));
3560 	ctxt->dst.type = OP_NONE;
3561 	return X86EMUL_CONTINUE;
3562 }
3563 
3564 static int em_loop(struct x86_emulate_ctxt *ctxt)
3565 {
3566 	int rc = X86EMUL_CONTINUE;
3567 
3568 	register_address_increment(ctxt, VCPU_REGS_RCX, -1);
3569 	if ((address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) != 0) &&
3570 	    (ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags)))
3571 		rc = jmp_rel(ctxt, ctxt->src.val);
3572 
3573 	return rc;
3574 }
3575 
3576 static int em_jcxz(struct x86_emulate_ctxt *ctxt)
3577 {
3578 	int rc = X86EMUL_CONTINUE;
3579 
3580 	if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)
3581 		rc = jmp_rel(ctxt, ctxt->src.val);
3582 
3583 	return rc;
3584 }
3585 
3586 static int em_in(struct x86_emulate_ctxt *ctxt)
3587 {
3588 	if (!pio_in_emulated(ctxt, ctxt->dst.bytes, ctxt->src.val,
3589 			     &ctxt->dst.val))
3590 		return X86EMUL_IO_NEEDED;
3591 
3592 	return X86EMUL_CONTINUE;
3593 }
3594 
3595 static int em_out(struct x86_emulate_ctxt *ctxt)
3596 {
3597 	ctxt->ops->pio_out_emulated(ctxt, ctxt->src.bytes, ctxt->dst.val,
3598 				    &ctxt->src.val, 1);
3599 	/* Disable writeback. */
3600 	ctxt->dst.type = OP_NONE;
3601 	return X86EMUL_CONTINUE;
3602 }
3603 
3604 static int em_cli(struct x86_emulate_ctxt *ctxt)
3605 {
3606 	if (emulator_bad_iopl(ctxt))
3607 		return emulate_gp(ctxt, 0);
3608 
3609 	ctxt->eflags &= ~X86_EFLAGS_IF;
3610 	return X86EMUL_CONTINUE;
3611 }
3612 
3613 static int em_sti(struct x86_emulate_ctxt *ctxt)
3614 {
3615 	if (emulator_bad_iopl(ctxt))
3616 		return emulate_gp(ctxt, 0);
3617 
3618 	ctxt->interruptibility = KVM_X86_SHADOW_INT_STI;
3619 	ctxt->eflags |= X86_EFLAGS_IF;
3620 	return X86EMUL_CONTINUE;
3621 }
3622 
3623 static int em_cpuid(struct x86_emulate_ctxt *ctxt)
3624 {
3625 	u32 eax, ebx, ecx, edx;
3626 	u64 msr = 0;
3627 
3628 	ctxt->ops->get_msr(ctxt, MSR_MISC_FEATURES_ENABLES, &msr);
3629 	if (msr & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3630 	    ctxt->ops->cpl(ctxt)) {
3631 		return emulate_gp(ctxt, 0);
3632 	}
3633 
3634 	eax = reg_read(ctxt, VCPU_REGS_RAX);
3635 	ecx = reg_read(ctxt, VCPU_REGS_RCX);
3636 	ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx, false);
3637 	*reg_write(ctxt, VCPU_REGS_RAX) = eax;
3638 	*reg_write(ctxt, VCPU_REGS_RBX) = ebx;
3639 	*reg_write(ctxt, VCPU_REGS_RCX) = ecx;
3640 	*reg_write(ctxt, VCPU_REGS_RDX) = edx;
3641 	return X86EMUL_CONTINUE;
3642 }
3643 
3644 static int em_sahf(struct x86_emulate_ctxt *ctxt)
3645 {
3646 	u32 flags;
3647 
3648 	flags = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
3649 		X86_EFLAGS_SF;
3650 	flags &= *reg_rmw(ctxt, VCPU_REGS_RAX) >> 8;
3651 
3652 	ctxt->eflags &= ~0xffUL;
3653 	ctxt->eflags |= flags | X86_EFLAGS_FIXED;
3654 	return X86EMUL_CONTINUE;
3655 }
3656 
3657 static int em_lahf(struct x86_emulate_ctxt *ctxt)
3658 {
3659 	*reg_rmw(ctxt, VCPU_REGS_RAX) &= ~0xff00UL;
3660 	*reg_rmw(ctxt, VCPU_REGS_RAX) |= (ctxt->eflags & 0xff) << 8;
3661 	return X86EMUL_CONTINUE;
3662 }
3663 
3664 static int em_bswap(struct x86_emulate_ctxt *ctxt)
3665 {
3666 	switch (ctxt->op_bytes) {
3667 #ifdef CONFIG_X86_64
3668 	case 8:
3669 		asm("bswap %0" : "+r"(ctxt->dst.val));
3670 		break;
3671 #endif
3672 	default:
3673 		asm("bswap %0" : "+r"(*(u32 *)&ctxt->dst.val));
3674 		break;
3675 	}
3676 	return X86EMUL_CONTINUE;
3677 }
3678 
3679 static int em_clflush(struct x86_emulate_ctxt *ctxt)
3680 {
3681 	/* emulating clflush regardless of cpuid */
3682 	return X86EMUL_CONTINUE;
3683 }
3684 
3685 static int em_clflushopt(struct x86_emulate_ctxt *ctxt)
3686 {
3687 	/* emulating clflushopt regardless of cpuid */
3688 	return X86EMUL_CONTINUE;
3689 }
3690 
3691 static int em_movsxd(struct x86_emulate_ctxt *ctxt)
3692 {
3693 	ctxt->dst.val = (s32) ctxt->src.val;
3694 	return X86EMUL_CONTINUE;
3695 }
3696 
3697 static int check_fxsr(struct x86_emulate_ctxt *ctxt)
3698 {
3699 	if (!ctxt->ops->guest_has_fxsr(ctxt))
3700 		return emulate_ud(ctxt);
3701 
3702 	if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
3703 		return emulate_nm(ctxt);
3704 
3705 	/*
3706 	 * Don't emulate a case that should never be hit, instead of working
3707 	 * around a lack of fxsave64/fxrstor64 on old compilers.
3708 	 */
3709 	if (ctxt->mode >= X86EMUL_MODE_PROT64)
3710 		return X86EMUL_UNHANDLEABLE;
3711 
3712 	return X86EMUL_CONTINUE;
3713 }
3714 
3715 /*
3716  * Hardware doesn't save and restore XMM 0-7 without CR4.OSFXSR, but does save
3717  * and restore MXCSR.
3718  */
3719 static size_t __fxstate_size(int nregs)
3720 {
3721 	return offsetof(struct fxregs_state, xmm_space[0]) + nregs * 16;
3722 }
3723 
3724 static inline size_t fxstate_size(struct x86_emulate_ctxt *ctxt)
3725 {
3726 	bool cr4_osfxsr;
3727 	if (ctxt->mode == X86EMUL_MODE_PROT64)
3728 		return __fxstate_size(16);
3729 
3730 	cr4_osfxsr = ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR;
3731 	return __fxstate_size(cr4_osfxsr ? 8 : 0);
3732 }
3733 
3734 /*
3735  * FXSAVE and FXRSTOR have 4 different formats depending on execution mode,
3736  *  1) 16 bit mode
3737  *  2) 32 bit mode
3738  *     - like (1), but FIP and FDP (foo) are only 16 bit.  At least Intel CPUs
3739  *       preserve whole 32 bit values, though, so (1) and (2) are the same wrt.
3740  *       save and restore
3741  *  3) 64-bit mode with REX.W prefix
3742  *     - like (2), but XMM 8-15 are being saved and restored
3743  *  4) 64-bit mode without REX.W prefix
3744  *     - like (3), but FIP and FDP are 64 bit
3745  *
3746  * Emulation uses (3) for (1) and (2) and preserves XMM 8-15 to reach the
3747  * desired result.  (4) is not emulated.
3748  *
3749  * Note: Guest and host CPUID.(EAX=07H,ECX=0H):EBX[bit 13] (deprecate FPU CS
3750  * and FPU DS) should match.
3751  */
3752 static int em_fxsave(struct x86_emulate_ctxt *ctxt)
3753 {
3754 	struct fxregs_state fx_state;
3755 	int rc;
3756 
3757 	rc = check_fxsr(ctxt);
3758 	if (rc != X86EMUL_CONTINUE)
3759 		return rc;
3760 
3761 	kvm_fpu_get();
3762 
3763 	rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state));
3764 
3765 	kvm_fpu_put();
3766 
3767 	if (rc != X86EMUL_CONTINUE)
3768 		return rc;
3769 
3770 	return segmented_write_std(ctxt, ctxt->memop.addr.mem, &fx_state,
3771 		                   fxstate_size(ctxt));
3772 }
3773 
3774 /*
3775  * FXRSTOR might restore XMM registers not provided by the guest. Fill
3776  * in the host registers (via FXSAVE) instead, so they won't be modified.
3777  * (preemption has to stay disabled until FXRSTOR).
3778  *
3779  * Use noinline to keep the stack for other functions called by callers small.
3780  */
3781 static noinline int fxregs_fixup(struct fxregs_state *fx_state,
3782 				 const size_t used_size)
3783 {
3784 	struct fxregs_state fx_tmp;
3785 	int rc;
3786 
3787 	rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_tmp));
3788 	memcpy((void *)fx_state + used_size, (void *)&fx_tmp + used_size,
3789 	       __fxstate_size(16) - used_size);
3790 
3791 	return rc;
3792 }
3793 
3794 static int em_fxrstor(struct x86_emulate_ctxt *ctxt)
3795 {
3796 	struct fxregs_state fx_state;
3797 	int rc;
3798 	size_t size;
3799 
3800 	rc = check_fxsr(ctxt);
3801 	if (rc != X86EMUL_CONTINUE)
3802 		return rc;
3803 
3804 	size = fxstate_size(ctxt);
3805 	rc = segmented_read_std(ctxt, ctxt->memop.addr.mem, &fx_state, size);
3806 	if (rc != X86EMUL_CONTINUE)
3807 		return rc;
3808 
3809 	kvm_fpu_get();
3810 
3811 	if (size < __fxstate_size(16)) {
3812 		rc = fxregs_fixup(&fx_state, size);
3813 		if (rc != X86EMUL_CONTINUE)
3814 			goto out;
3815 	}
3816 
3817 	if (fx_state.mxcsr >> 16) {
3818 		rc = emulate_gp(ctxt, 0);
3819 		goto out;
3820 	}
3821 
3822 	if (rc == X86EMUL_CONTINUE)
3823 		rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state));
3824 
3825 out:
3826 	kvm_fpu_put();
3827 
3828 	return rc;
3829 }
3830 
3831 static int em_xsetbv(struct x86_emulate_ctxt *ctxt)
3832 {
3833 	u32 eax, ecx, edx;
3834 
3835 	if (!(ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSXSAVE))
3836 		return emulate_ud(ctxt);
3837 
3838 	eax = reg_read(ctxt, VCPU_REGS_RAX);
3839 	edx = reg_read(ctxt, VCPU_REGS_RDX);
3840 	ecx = reg_read(ctxt, VCPU_REGS_RCX);
3841 
3842 	if (ctxt->ops->set_xcr(ctxt, ecx, ((u64)edx << 32) | eax))
3843 		return emulate_gp(ctxt, 0);
3844 
3845 	return X86EMUL_CONTINUE;
3846 }
3847 
3848 static bool valid_cr(int nr)
3849 {
3850 	switch (nr) {
3851 	case 0:
3852 	case 2 ... 4:
3853 	case 8:
3854 		return true;
3855 	default:
3856 		return false;
3857 	}
3858 }
3859 
3860 static int check_cr_access(struct x86_emulate_ctxt *ctxt)
3861 {
3862 	if (!valid_cr(ctxt->modrm_reg))
3863 		return emulate_ud(ctxt);
3864 
3865 	return X86EMUL_CONTINUE;
3866 }
3867 
3868 static int check_dr7_gd(struct x86_emulate_ctxt *ctxt)
3869 {
3870 	unsigned long dr7;
3871 
3872 	ctxt->ops->get_dr(ctxt, 7, &dr7);
3873 
3874 	return dr7 & DR7_GD;
3875 }
3876 
3877 static int check_dr_read(struct x86_emulate_ctxt *ctxt)
3878 {
3879 	int dr = ctxt->modrm_reg;
3880 	u64 cr4;
3881 
3882 	if (dr > 7)
3883 		return emulate_ud(ctxt);
3884 
3885 	cr4 = ctxt->ops->get_cr(ctxt, 4);
3886 	if ((cr4 & X86_CR4_DE) && (dr == 4 || dr == 5))
3887 		return emulate_ud(ctxt);
3888 
3889 	if (check_dr7_gd(ctxt)) {
3890 		ulong dr6;
3891 
3892 		ctxt->ops->get_dr(ctxt, 6, &dr6);
3893 		dr6 &= ~DR_TRAP_BITS;
3894 		dr6 |= DR6_BD | DR6_ACTIVE_LOW;
3895 		ctxt->ops->set_dr(ctxt, 6, dr6);
3896 		return emulate_db(ctxt);
3897 	}
3898 
3899 	return X86EMUL_CONTINUE;
3900 }
3901 
3902 static int check_dr_write(struct x86_emulate_ctxt *ctxt)
3903 {
3904 	u64 new_val = ctxt->src.val64;
3905 	int dr = ctxt->modrm_reg;
3906 
3907 	if ((dr == 6 || dr == 7) && (new_val & 0xffffffff00000000ULL))
3908 		return emulate_gp(ctxt, 0);
3909 
3910 	return check_dr_read(ctxt);
3911 }
3912 
3913 static int check_svme(struct x86_emulate_ctxt *ctxt)
3914 {
3915 	u64 efer = 0;
3916 
3917 	ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
3918 
3919 	if (!(efer & EFER_SVME))
3920 		return emulate_ud(ctxt);
3921 
3922 	return X86EMUL_CONTINUE;
3923 }
3924 
3925 static int check_svme_pa(struct x86_emulate_ctxt *ctxt)
3926 {
3927 	u64 rax = reg_read(ctxt, VCPU_REGS_RAX);
3928 
3929 	/* Valid physical address? */
3930 	if (rax & 0xffff000000000000ULL)
3931 		return emulate_gp(ctxt, 0);
3932 
3933 	return check_svme(ctxt);
3934 }
3935 
3936 static int check_rdtsc(struct x86_emulate_ctxt *ctxt)
3937 {
3938 	u64 cr4 = ctxt->ops->get_cr(ctxt, 4);
3939 
3940 	if (cr4 & X86_CR4_TSD && ctxt->ops->cpl(ctxt))
3941 		return emulate_gp(ctxt, 0);
3942 
3943 	return X86EMUL_CONTINUE;
3944 }
3945 
3946 static int check_rdpmc(struct x86_emulate_ctxt *ctxt)
3947 {
3948 	u64 cr4 = ctxt->ops->get_cr(ctxt, 4);
3949 	u64 rcx = reg_read(ctxt, VCPU_REGS_RCX);
3950 
3951 	/*
3952 	 * VMware allows access to these Pseduo-PMCs even when read via RDPMC
3953 	 * in Ring3 when CR4.PCE=0.
3954 	 */
3955 	if (enable_vmware_backdoor && is_vmware_backdoor_pmc(rcx))
3956 		return X86EMUL_CONTINUE;
3957 
3958 	/*
3959 	 * If CR4.PCE is set, the SDM requires CPL=0 or CR0.PE=0.  The CR0.PE
3960 	 * check however is unnecessary because CPL is always 0 outside
3961 	 * protected mode.
3962 	 */
3963 	if ((!(cr4 & X86_CR4_PCE) && ctxt->ops->cpl(ctxt)) ||
3964 	    ctxt->ops->check_pmc(ctxt, rcx))
3965 		return emulate_gp(ctxt, 0);
3966 
3967 	return X86EMUL_CONTINUE;
3968 }
3969 
3970 static int check_perm_in(struct x86_emulate_ctxt *ctxt)
3971 {
3972 	ctxt->dst.bytes = min(ctxt->dst.bytes, 4u);
3973 	if (!emulator_io_permitted(ctxt, ctxt->src.val, ctxt->dst.bytes))
3974 		return emulate_gp(ctxt, 0);
3975 
3976 	return X86EMUL_CONTINUE;
3977 }
3978 
3979 static int check_perm_out(struct x86_emulate_ctxt *ctxt)
3980 {
3981 	ctxt->src.bytes = min(ctxt->src.bytes, 4u);
3982 	if (!emulator_io_permitted(ctxt, ctxt->dst.val, ctxt->src.bytes))
3983 		return emulate_gp(ctxt, 0);
3984 
3985 	return X86EMUL_CONTINUE;
3986 }
3987 
3988 #define D(_y) { .flags = (_y) }
3989 #define DI(_y, _i) { .flags = (_y)|Intercept, .intercept = x86_intercept_##_i }
3990 #define DIP(_y, _i, _p) { .flags = (_y)|Intercept|CheckPerm, \
3991 		      .intercept = x86_intercept_##_i, .check_perm = (_p) }
3992 #define N    D(NotImpl)
3993 #define EXT(_f, _e) { .flags = ((_f) | RMExt), .u.group = (_e) }
3994 #define G(_f, _g) { .flags = ((_f) | Group | ModRM), .u.group = (_g) }
3995 #define GD(_f, _g) { .flags = ((_f) | GroupDual | ModRM), .u.gdual = (_g) }
3996 #define ID(_f, _i) { .flags = ((_f) | InstrDual | ModRM), .u.idual = (_i) }
3997 #define MD(_f, _m) { .flags = ((_f) | ModeDual), .u.mdual = (_m) }
3998 #define E(_f, _e) { .flags = ((_f) | Escape | ModRM), .u.esc = (_e) }
3999 #define I(_f, _e) { .flags = (_f), .u.execute = (_e) }
4000 #define F(_f, _e) { .flags = (_f) | Fastop, .u.fastop = (_e) }
4001 #define II(_f, _e, _i) \
4002 	{ .flags = (_f)|Intercept, .u.execute = (_e), .intercept = x86_intercept_##_i }
4003 #define IIP(_f, _e, _i, _p) \
4004 	{ .flags = (_f)|Intercept|CheckPerm, .u.execute = (_e), \
4005 	  .intercept = x86_intercept_##_i, .check_perm = (_p) }
4006 #define GP(_f, _g) { .flags = ((_f) | Prefix), .u.gprefix = (_g) }
4007 
4008 #define D2bv(_f)      D((_f) | ByteOp), D(_f)
4009 #define D2bvIP(_f, _i, _p) DIP((_f) | ByteOp, _i, _p), DIP(_f, _i, _p)
4010 #define I2bv(_f, _e)  I((_f) | ByteOp, _e), I(_f, _e)
4011 #define F2bv(_f, _e)  F((_f) | ByteOp, _e), F(_f, _e)
4012 #define I2bvIP(_f, _e, _i, _p) \
4013 	IIP((_f) | ByteOp, _e, _i, _p), IIP(_f, _e, _i, _p)
4014 
4015 #define F6ALU(_f, _e) F2bv((_f) | DstMem | SrcReg | ModRM, _e),		\
4016 		F2bv(((_f) | DstReg | SrcMem | ModRM) & ~Lock, _e),	\
4017 		F2bv(((_f) & ~Lock) | DstAcc | SrcImm, _e)
4018 
4019 static const struct opcode group7_rm0[] = {
4020 	N,
4021 	I(SrcNone | Priv | EmulateOnUD,	em_hypercall),
4022 	N, N, N, N, N, N,
4023 };
4024 
4025 static const struct opcode group7_rm1[] = {
4026 	DI(SrcNone | Priv, monitor),
4027 	DI(SrcNone | Priv, mwait),
4028 	N, N, N, N, N, N,
4029 };
4030 
4031 static const struct opcode group7_rm2[] = {
4032 	N,
4033 	II(ImplicitOps | Priv,			em_xsetbv,	xsetbv),
4034 	N, N, N, N, N, N,
4035 };
4036 
4037 static const struct opcode group7_rm3[] = {
4038 	DIP(SrcNone | Prot | Priv,		vmrun,		check_svme_pa),
4039 	II(SrcNone  | Prot | EmulateOnUD,	em_hypercall,	vmmcall),
4040 	DIP(SrcNone | Prot | Priv,		vmload,		check_svme_pa),
4041 	DIP(SrcNone | Prot | Priv,		vmsave,		check_svme_pa),
4042 	DIP(SrcNone | Prot | Priv,		stgi,		check_svme),
4043 	DIP(SrcNone | Prot | Priv,		clgi,		check_svme),
4044 	DIP(SrcNone | Prot | Priv,		skinit,		check_svme),
4045 	DIP(SrcNone | Prot | Priv,		invlpga,	check_svme),
4046 };
4047 
4048 static const struct opcode group7_rm7[] = {
4049 	N,
4050 	DIP(SrcNone, rdtscp, check_rdtsc),
4051 	N, N, N, N, N, N,
4052 };
4053 
4054 static const struct opcode group1[] = {
4055 	F(Lock, em_add),
4056 	F(Lock | PageTable, em_or),
4057 	F(Lock, em_adc),
4058 	F(Lock, em_sbb),
4059 	F(Lock | PageTable, em_and),
4060 	F(Lock, em_sub),
4061 	F(Lock, em_xor),
4062 	F(NoWrite, em_cmp),
4063 };
4064 
4065 static const struct opcode group1A[] = {
4066 	I(DstMem | SrcNone | Mov | Stack | IncSP | TwoMemOp, em_pop), N, N, N, N, N, N, N,
4067 };
4068 
4069 static const struct opcode group2[] = {
4070 	F(DstMem | ModRM, em_rol),
4071 	F(DstMem | ModRM, em_ror),
4072 	F(DstMem | ModRM, em_rcl),
4073 	F(DstMem | ModRM, em_rcr),
4074 	F(DstMem | ModRM, em_shl),
4075 	F(DstMem | ModRM, em_shr),
4076 	F(DstMem | ModRM, em_shl),
4077 	F(DstMem | ModRM, em_sar),
4078 };
4079 
4080 static const struct opcode group3[] = {
4081 	F(DstMem | SrcImm | NoWrite, em_test),
4082 	F(DstMem | SrcImm | NoWrite, em_test),
4083 	F(DstMem | SrcNone | Lock, em_not),
4084 	F(DstMem | SrcNone | Lock, em_neg),
4085 	F(DstXacc | Src2Mem, em_mul_ex),
4086 	F(DstXacc | Src2Mem, em_imul_ex),
4087 	F(DstXacc | Src2Mem, em_div_ex),
4088 	F(DstXacc | Src2Mem, em_idiv_ex),
4089 };
4090 
4091 static const struct opcode group4[] = {
4092 	F(ByteOp | DstMem | SrcNone | Lock, em_inc),
4093 	F(ByteOp | DstMem | SrcNone | Lock, em_dec),
4094 	N, N, N, N, N, N,
4095 };
4096 
4097 static const struct opcode group5[] = {
4098 	F(DstMem | SrcNone | Lock,		em_inc),
4099 	F(DstMem | SrcNone | Lock,		em_dec),
4100 	I(SrcMem | NearBranch | IsBranch,       em_call_near_abs),
4101 	I(SrcMemFAddr | ImplicitOps | IsBranch, em_call_far),
4102 	I(SrcMem | NearBranch | IsBranch,       em_jmp_abs),
4103 	I(SrcMemFAddr | ImplicitOps | IsBranch, em_jmp_far),
4104 	I(SrcMem | Stack | TwoMemOp,		em_push), D(Undefined),
4105 };
4106 
4107 static const struct opcode group6[] = {
4108 	II(Prot | DstMem,	   em_sldt, sldt),
4109 	II(Prot | DstMem,	   em_str, str),
4110 	II(Prot | Priv | SrcMem16, em_lldt, lldt),
4111 	II(Prot | Priv | SrcMem16, em_ltr, ltr),
4112 	N, N, N, N,
4113 };
4114 
4115 static const struct group_dual group7 = { {
4116 	II(Mov | DstMem,			em_sgdt, sgdt),
4117 	II(Mov | DstMem,			em_sidt, sidt),
4118 	II(SrcMem | Priv,			em_lgdt, lgdt),
4119 	II(SrcMem | Priv,			em_lidt, lidt),
4120 	II(SrcNone | DstMem | Mov,		em_smsw, smsw), N,
4121 	II(SrcMem16 | Mov | Priv,		em_lmsw, lmsw),
4122 	II(SrcMem | ByteOp | Priv | NoAccess,	em_invlpg, invlpg),
4123 }, {
4124 	EXT(0, group7_rm0),
4125 	EXT(0, group7_rm1),
4126 	EXT(0, group7_rm2),
4127 	EXT(0, group7_rm3),
4128 	II(SrcNone | DstMem | Mov,		em_smsw, smsw), N,
4129 	II(SrcMem16 | Mov | Priv,		em_lmsw, lmsw),
4130 	EXT(0, group7_rm7),
4131 } };
4132 
4133 static const struct opcode group8[] = {
4134 	N, N, N, N,
4135 	F(DstMem | SrcImmByte | NoWrite,		em_bt),
4136 	F(DstMem | SrcImmByte | Lock | PageTable,	em_bts),
4137 	F(DstMem | SrcImmByte | Lock,			em_btr),
4138 	F(DstMem | SrcImmByte | Lock | PageTable,	em_btc),
4139 };
4140 
4141 /*
4142  * The "memory" destination is actually always a register, since we come
4143  * from the register case of group9.
4144  */
4145 static const struct gprefix pfx_0f_c7_7 = {
4146 	N, N, N, II(DstMem | ModRM | Op3264 | EmulateOnUD, em_rdpid, rdpid),
4147 };
4148 
4149 
4150 static const struct group_dual group9 = { {
4151 	N, I(DstMem64 | Lock | PageTable, em_cmpxchg8b), N, N, N, N, N, N,
4152 }, {
4153 	N, N, N, N, N, N, N,
4154 	GP(0, &pfx_0f_c7_7),
4155 } };
4156 
4157 static const struct opcode group11[] = {
4158 	I(DstMem | SrcImm | Mov | PageTable, em_mov),
4159 	X7(D(Undefined)),
4160 };
4161 
4162 static const struct gprefix pfx_0f_ae_7 = {
4163 	I(SrcMem | ByteOp, em_clflush), I(SrcMem | ByteOp, em_clflushopt), N, N,
4164 };
4165 
4166 static const struct group_dual group15 = { {
4167 	I(ModRM | Aligned16, em_fxsave),
4168 	I(ModRM | Aligned16, em_fxrstor),
4169 	N, N, N, N, N, GP(0, &pfx_0f_ae_7),
4170 }, {
4171 	N, N, N, N, N, N, N, N,
4172 } };
4173 
4174 static const struct gprefix pfx_0f_6f_0f_7f = {
4175 	I(Mmx, em_mov), I(Sse | Aligned, em_mov), N, I(Sse | Unaligned, em_mov),
4176 };
4177 
4178 static const struct instr_dual instr_dual_0f_2b = {
4179 	I(0, em_mov), N
4180 };
4181 
4182 static const struct gprefix pfx_0f_2b = {
4183 	ID(0, &instr_dual_0f_2b), ID(0, &instr_dual_0f_2b), N, N,
4184 };
4185 
4186 static const struct gprefix pfx_0f_10_0f_11 = {
4187 	I(Unaligned, em_mov), I(Unaligned, em_mov), N, N,
4188 };
4189 
4190 static const struct gprefix pfx_0f_28_0f_29 = {
4191 	I(Aligned, em_mov), I(Aligned, em_mov), N, N,
4192 };
4193 
4194 static const struct gprefix pfx_0f_e7 = {
4195 	N, I(Sse, em_mov), N, N,
4196 };
4197 
4198 static const struct escape escape_d9 = { {
4199 	N, N, N, N, N, N, N, I(DstMem16 | Mov, em_fnstcw),
4200 }, {
4201 	/* 0xC0 - 0xC7 */
4202 	N, N, N, N, N, N, N, N,
4203 	/* 0xC8 - 0xCF */
4204 	N, N, N, N, N, N, N, N,
4205 	/* 0xD0 - 0xC7 */
4206 	N, N, N, N, N, N, N, N,
4207 	/* 0xD8 - 0xDF */
4208 	N, N, N, N, N, N, N, N,
4209 	/* 0xE0 - 0xE7 */
4210 	N, N, N, N, N, N, N, N,
4211 	/* 0xE8 - 0xEF */
4212 	N, N, N, N, N, N, N, N,
4213 	/* 0xF0 - 0xF7 */
4214 	N, N, N, N, N, N, N, N,
4215 	/* 0xF8 - 0xFF */
4216 	N, N, N, N, N, N, N, N,
4217 } };
4218 
4219 static const struct escape escape_db = { {
4220 	N, N, N, N, N, N, N, N,
4221 }, {
4222 	/* 0xC0 - 0xC7 */
4223 	N, N, N, N, N, N, N, N,
4224 	/* 0xC8 - 0xCF */
4225 	N, N, N, N, N, N, N, N,
4226 	/* 0xD0 - 0xC7 */
4227 	N, N, N, N, N, N, N, N,
4228 	/* 0xD8 - 0xDF */
4229 	N, N, N, N, N, N, N, N,
4230 	/* 0xE0 - 0xE7 */
4231 	N, N, N, I(ImplicitOps, em_fninit), N, N, N, N,
4232 	/* 0xE8 - 0xEF */
4233 	N, N, N, N, N, N, N, N,
4234 	/* 0xF0 - 0xF7 */
4235 	N, N, N, N, N, N, N, N,
4236 	/* 0xF8 - 0xFF */
4237 	N, N, N, N, N, N, N, N,
4238 } };
4239 
4240 static const struct escape escape_dd = { {
4241 	N, N, N, N, N, N, N, I(DstMem16 | Mov, em_fnstsw),
4242 }, {
4243 	/* 0xC0 - 0xC7 */
4244 	N, N, N, N, N, N, N, N,
4245 	/* 0xC8 - 0xCF */
4246 	N, N, N, N, N, N, N, N,
4247 	/* 0xD0 - 0xC7 */
4248 	N, N, N, N, N, N, N, N,
4249 	/* 0xD8 - 0xDF */
4250 	N, N, N, N, N, N, N, N,
4251 	/* 0xE0 - 0xE7 */
4252 	N, N, N, N, N, N, N, N,
4253 	/* 0xE8 - 0xEF */
4254 	N, N, N, N, N, N, N, N,
4255 	/* 0xF0 - 0xF7 */
4256 	N, N, N, N, N, N, N, N,
4257 	/* 0xF8 - 0xFF */
4258 	N, N, N, N, N, N, N, N,
4259 } };
4260 
4261 static const struct instr_dual instr_dual_0f_c3 = {
4262 	I(DstMem | SrcReg | ModRM | No16 | Mov, em_mov), N
4263 };
4264 
4265 static const struct mode_dual mode_dual_63 = {
4266 	N, I(DstReg | SrcMem32 | ModRM | Mov, em_movsxd)
4267 };
4268 
4269 static const struct instr_dual instr_dual_8d = {
4270 	D(DstReg | SrcMem | ModRM | NoAccess), N
4271 };
4272 
4273 static const struct opcode opcode_table[256] = {
4274 	/* 0x00 - 0x07 */
4275 	F6ALU(Lock, em_add),
4276 	I(ImplicitOps | Stack | No64 | Src2ES, em_push_sreg),
4277 	I(ImplicitOps | Stack | No64 | Src2ES, em_pop_sreg),
4278 	/* 0x08 - 0x0F */
4279 	F6ALU(Lock | PageTable, em_or),
4280 	I(ImplicitOps | Stack | No64 | Src2CS, em_push_sreg),
4281 	N,
4282 	/* 0x10 - 0x17 */
4283 	F6ALU(Lock, em_adc),
4284 	I(ImplicitOps | Stack | No64 | Src2SS, em_push_sreg),
4285 	I(ImplicitOps | Stack | No64 | Src2SS, em_pop_sreg),
4286 	/* 0x18 - 0x1F */
4287 	F6ALU(Lock, em_sbb),
4288 	I(ImplicitOps | Stack | No64 | Src2DS, em_push_sreg),
4289 	I(ImplicitOps | Stack | No64 | Src2DS, em_pop_sreg),
4290 	/* 0x20 - 0x27 */
4291 	F6ALU(Lock | PageTable, em_and), N, N,
4292 	/* 0x28 - 0x2F */
4293 	F6ALU(Lock, em_sub), N, I(ByteOp | DstAcc | No64, em_das),
4294 	/* 0x30 - 0x37 */
4295 	F6ALU(Lock, em_xor), N, N,
4296 	/* 0x38 - 0x3F */
4297 	F6ALU(NoWrite, em_cmp), N, N,
4298 	/* 0x40 - 0x4F */
4299 	X8(F(DstReg, em_inc)), X8(F(DstReg, em_dec)),
4300 	/* 0x50 - 0x57 */
4301 	X8(I(SrcReg | Stack, em_push)),
4302 	/* 0x58 - 0x5F */
4303 	X8(I(DstReg | Stack, em_pop)),
4304 	/* 0x60 - 0x67 */
4305 	I(ImplicitOps | Stack | No64, em_pusha),
4306 	I(ImplicitOps | Stack | No64, em_popa),
4307 	N, MD(ModRM, &mode_dual_63),
4308 	N, N, N, N,
4309 	/* 0x68 - 0x6F */
4310 	I(SrcImm | Mov | Stack, em_push),
4311 	I(DstReg | SrcMem | ModRM | Src2Imm, em_imul_3op),
4312 	I(SrcImmByte | Mov | Stack, em_push),
4313 	I(DstReg | SrcMem | ModRM | Src2ImmByte, em_imul_3op),
4314 	I2bvIP(DstDI | SrcDX | Mov | String | Unaligned, em_in, ins, check_perm_in), /* insb, insw/insd */
4315 	I2bvIP(SrcSI | DstDX | String, em_out, outs, check_perm_out), /* outsb, outsw/outsd */
4316 	/* 0x70 - 0x7F */
4317 	X16(D(SrcImmByte | NearBranch | IsBranch)),
4318 	/* 0x80 - 0x87 */
4319 	G(ByteOp | DstMem | SrcImm, group1),
4320 	G(DstMem | SrcImm, group1),
4321 	G(ByteOp | DstMem | SrcImm | No64, group1),
4322 	G(DstMem | SrcImmByte, group1),
4323 	F2bv(DstMem | SrcReg | ModRM | NoWrite, em_test),
4324 	I2bv(DstMem | SrcReg | ModRM | Lock | PageTable, em_xchg),
4325 	/* 0x88 - 0x8F */
4326 	I2bv(DstMem | SrcReg | ModRM | Mov | PageTable, em_mov),
4327 	I2bv(DstReg | SrcMem | ModRM | Mov, em_mov),
4328 	I(DstMem | SrcNone | ModRM | Mov | PageTable, em_mov_rm_sreg),
4329 	ID(0, &instr_dual_8d),
4330 	I(ImplicitOps | SrcMem16 | ModRM, em_mov_sreg_rm),
4331 	G(0, group1A),
4332 	/* 0x90 - 0x97 */
4333 	DI(SrcAcc | DstReg, pause), X7(D(SrcAcc | DstReg)),
4334 	/* 0x98 - 0x9F */
4335 	D(DstAcc | SrcNone), I(ImplicitOps | SrcAcc, em_cwd),
4336 	I(SrcImmFAddr | No64 | IsBranch, em_call_far), N,
4337 	II(ImplicitOps | Stack, em_pushf, pushf),
4338 	II(ImplicitOps | Stack, em_popf, popf),
4339 	I(ImplicitOps, em_sahf), I(ImplicitOps, em_lahf),
4340 	/* 0xA0 - 0xA7 */
4341 	I2bv(DstAcc | SrcMem | Mov | MemAbs, em_mov),
4342 	I2bv(DstMem | SrcAcc | Mov | MemAbs | PageTable, em_mov),
4343 	I2bv(SrcSI | DstDI | Mov | String | TwoMemOp, em_mov),
4344 	F2bv(SrcSI | DstDI | String | NoWrite | TwoMemOp, em_cmp_r),
4345 	/* 0xA8 - 0xAF */
4346 	F2bv(DstAcc | SrcImm | NoWrite, em_test),
4347 	I2bv(SrcAcc | DstDI | Mov | String, em_mov),
4348 	I2bv(SrcSI | DstAcc | Mov | String, em_mov),
4349 	F2bv(SrcAcc | DstDI | String | NoWrite, em_cmp_r),
4350 	/* 0xB0 - 0xB7 */
4351 	X8(I(ByteOp | DstReg | SrcImm | Mov, em_mov)),
4352 	/* 0xB8 - 0xBF */
4353 	X8(I(DstReg | SrcImm64 | Mov, em_mov)),
4354 	/* 0xC0 - 0xC7 */
4355 	G(ByteOp | Src2ImmByte, group2), G(Src2ImmByte, group2),
4356 	I(ImplicitOps | NearBranch | SrcImmU16 | IsBranch, em_ret_near_imm),
4357 	I(ImplicitOps | NearBranch | IsBranch, em_ret),
4358 	I(DstReg | SrcMemFAddr | ModRM | No64 | Src2ES, em_lseg),
4359 	I(DstReg | SrcMemFAddr | ModRM | No64 | Src2DS, em_lseg),
4360 	G(ByteOp, group11), G(0, group11),
4361 	/* 0xC8 - 0xCF */
4362 	I(Stack | SrcImmU16 | Src2ImmByte | IsBranch, em_enter),
4363 	I(Stack | IsBranch, em_leave),
4364 	I(ImplicitOps | SrcImmU16 | IsBranch, em_ret_far_imm),
4365 	I(ImplicitOps | IsBranch, em_ret_far),
4366 	D(ImplicitOps | IsBranch), DI(SrcImmByte | IsBranch, intn),
4367 	D(ImplicitOps | No64 | IsBranch),
4368 	II(ImplicitOps | IsBranch, em_iret, iret),
4369 	/* 0xD0 - 0xD7 */
4370 	G(Src2One | ByteOp, group2), G(Src2One, group2),
4371 	G(Src2CL | ByteOp, group2), G(Src2CL, group2),
4372 	I(DstAcc | SrcImmUByte | No64, em_aam),
4373 	I(DstAcc | SrcImmUByte | No64, em_aad),
4374 	F(DstAcc | ByteOp | No64, em_salc),
4375 	I(DstAcc | SrcXLat | ByteOp, em_mov),
4376 	/* 0xD8 - 0xDF */
4377 	N, E(0, &escape_d9), N, E(0, &escape_db), N, E(0, &escape_dd), N, N,
4378 	/* 0xE0 - 0xE7 */
4379 	X3(I(SrcImmByte | NearBranch | IsBranch, em_loop)),
4380 	I(SrcImmByte | NearBranch | IsBranch, em_jcxz),
4381 	I2bvIP(SrcImmUByte | DstAcc, em_in,  in,  check_perm_in),
4382 	I2bvIP(SrcAcc | DstImmUByte, em_out, out, check_perm_out),
4383 	/* 0xE8 - 0xEF */
4384 	I(SrcImm | NearBranch | IsBranch, em_call),
4385 	D(SrcImm | ImplicitOps | NearBranch | IsBranch),
4386 	I(SrcImmFAddr | No64 | IsBranch, em_jmp_far),
4387 	D(SrcImmByte | ImplicitOps | NearBranch | IsBranch),
4388 	I2bvIP(SrcDX | DstAcc, em_in,  in,  check_perm_in),
4389 	I2bvIP(SrcAcc | DstDX, em_out, out, check_perm_out),
4390 	/* 0xF0 - 0xF7 */
4391 	N, DI(ImplicitOps, icebp), N, N,
4392 	DI(ImplicitOps | Priv, hlt), D(ImplicitOps),
4393 	G(ByteOp, group3), G(0, group3),
4394 	/* 0xF8 - 0xFF */
4395 	D(ImplicitOps), D(ImplicitOps),
4396 	I(ImplicitOps, em_cli), I(ImplicitOps, em_sti),
4397 	D(ImplicitOps), D(ImplicitOps), G(0, group4), G(0, group5),
4398 };
4399 
4400 static const struct opcode twobyte_table[256] = {
4401 	/* 0x00 - 0x0F */
4402 	G(0, group6), GD(0, &group7), N, N,
4403 	N, I(ImplicitOps | EmulateOnUD | IsBranch, em_syscall),
4404 	II(ImplicitOps | Priv, em_clts, clts), N,
4405 	DI(ImplicitOps | Priv, invd), DI(ImplicitOps | Priv, wbinvd), N, N,
4406 	N, D(ImplicitOps | ModRM | SrcMem | NoAccess), N, N,
4407 	/* 0x10 - 0x1F */
4408 	GP(ModRM | DstReg | SrcMem | Mov | Sse, &pfx_0f_10_0f_11),
4409 	GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_10_0f_11),
4410 	N, N, N, N, N, N,
4411 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* 4 * prefetch + 4 * reserved NOP */
4412 	D(ImplicitOps | ModRM | SrcMem | NoAccess), N, N,
4413 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* 8 * reserved NOP */
4414 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* 8 * reserved NOP */
4415 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* 8 * reserved NOP */
4416 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* NOP + 7 * reserved NOP */
4417 	/* 0x20 - 0x2F */
4418 	DIP(ModRM | DstMem | Priv | Op3264 | NoMod, cr_read, check_cr_access),
4419 	DIP(ModRM | DstMem | Priv | Op3264 | NoMod, dr_read, check_dr_read),
4420 	IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_cr_write, cr_write,
4421 						check_cr_access),
4422 	IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_dr_write, dr_write,
4423 						check_dr_write),
4424 	N, N, N, N,
4425 	GP(ModRM | DstReg | SrcMem | Mov | Sse, &pfx_0f_28_0f_29),
4426 	GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_28_0f_29),
4427 	N, GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_2b),
4428 	N, N, N, N,
4429 	/* 0x30 - 0x3F */
4430 	II(ImplicitOps | Priv, em_wrmsr, wrmsr),
4431 	IIP(ImplicitOps, em_rdtsc, rdtsc, check_rdtsc),
4432 	II(ImplicitOps | Priv, em_rdmsr, rdmsr),
4433 	IIP(ImplicitOps, em_rdpmc, rdpmc, check_rdpmc),
4434 	I(ImplicitOps | EmulateOnUD | IsBranch, em_sysenter),
4435 	I(ImplicitOps | Priv | EmulateOnUD | IsBranch, em_sysexit),
4436 	N, N,
4437 	N, N, N, N, N, N, N, N,
4438 	/* 0x40 - 0x4F */
4439 	X16(D(DstReg | SrcMem | ModRM)),
4440 	/* 0x50 - 0x5F */
4441 	N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N,
4442 	/* 0x60 - 0x6F */
4443 	N, N, N, N,
4444 	N, N, N, N,
4445 	N, N, N, N,
4446 	N, N, N, GP(SrcMem | DstReg | ModRM | Mov, &pfx_0f_6f_0f_7f),
4447 	/* 0x70 - 0x7F */
4448 	N, N, N, N,
4449 	N, N, N, N,
4450 	N, N, N, N,
4451 	N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_6f_0f_7f),
4452 	/* 0x80 - 0x8F */
4453 	X16(D(SrcImm | NearBranch | IsBranch)),
4454 	/* 0x90 - 0x9F */
4455 	X16(D(ByteOp | DstMem | SrcNone | ModRM| Mov)),
4456 	/* 0xA0 - 0xA7 */
4457 	I(Stack | Src2FS, em_push_sreg), I(Stack | Src2FS, em_pop_sreg),
4458 	II(ImplicitOps, em_cpuid, cpuid),
4459 	F(DstMem | SrcReg | ModRM | BitOp | NoWrite, em_bt),
4460 	F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shld),
4461 	F(DstMem | SrcReg | Src2CL | ModRM, em_shld), N, N,
4462 	/* 0xA8 - 0xAF */
4463 	I(Stack | Src2GS, em_push_sreg), I(Stack | Src2GS, em_pop_sreg),
4464 	II(EmulateOnUD | ImplicitOps, em_rsm, rsm),
4465 	F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_bts),
4466 	F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shrd),
4467 	F(DstMem | SrcReg | Src2CL | ModRM, em_shrd),
4468 	GD(0, &group15), F(DstReg | SrcMem | ModRM, em_imul),
4469 	/* 0xB0 - 0xB7 */
4470 	I2bv(DstMem | SrcReg | ModRM | Lock | PageTable | SrcWrite, em_cmpxchg),
4471 	I(DstReg | SrcMemFAddr | ModRM | Src2SS, em_lseg),
4472 	F(DstMem | SrcReg | ModRM | BitOp | Lock, em_btr),
4473 	I(DstReg | SrcMemFAddr | ModRM | Src2FS, em_lseg),
4474 	I(DstReg | SrcMemFAddr | ModRM | Src2GS, em_lseg),
4475 	D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov),
4476 	/* 0xB8 - 0xBF */
4477 	N, N,
4478 	G(BitOp, group8),
4479 	F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_btc),
4480 	I(DstReg | SrcMem | ModRM, em_bsf_c),
4481 	I(DstReg | SrcMem | ModRM, em_bsr_c),
4482 	D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov),
4483 	/* 0xC0 - 0xC7 */
4484 	F2bv(DstMem | SrcReg | ModRM | SrcWrite | Lock, em_xadd),
4485 	N, ID(0, &instr_dual_0f_c3),
4486 	N, N, N, GD(0, &group9),
4487 	/* 0xC8 - 0xCF */
4488 	X8(I(DstReg, em_bswap)),
4489 	/* 0xD0 - 0xDF */
4490 	N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N,
4491 	/* 0xE0 - 0xEF */
4492 	N, N, N, N, N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_e7),
4493 	N, N, N, N, N, N, N, N,
4494 	/* 0xF0 - 0xFF */
4495 	N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N
4496 };
4497 
4498 static const struct instr_dual instr_dual_0f_38_f0 = {
4499 	I(DstReg | SrcMem | Mov, em_movbe), N
4500 };
4501 
4502 static const struct instr_dual instr_dual_0f_38_f1 = {
4503 	I(DstMem | SrcReg | Mov, em_movbe), N
4504 };
4505 
4506 static const struct gprefix three_byte_0f_38_f0 = {
4507 	ID(0, &instr_dual_0f_38_f0), N, N, N
4508 };
4509 
4510 static const struct gprefix three_byte_0f_38_f1 = {
4511 	ID(0, &instr_dual_0f_38_f1), N, N, N
4512 };
4513 
4514 /*
4515  * Insns below are selected by the prefix which indexed by the third opcode
4516  * byte.
4517  */
4518 static const struct opcode opcode_map_0f_38[256] = {
4519 	/* 0x00 - 0x7f */
4520 	X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N),
4521 	/* 0x80 - 0xef */
4522 	X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N),
4523 	/* 0xf0 - 0xf1 */
4524 	GP(EmulateOnUD | ModRM, &three_byte_0f_38_f0),
4525 	GP(EmulateOnUD | ModRM, &three_byte_0f_38_f1),
4526 	/* 0xf2 - 0xff */
4527 	N, N, X4(N), X8(N)
4528 };
4529 
4530 #undef D
4531 #undef N
4532 #undef G
4533 #undef GD
4534 #undef I
4535 #undef GP
4536 #undef EXT
4537 #undef MD
4538 #undef ID
4539 
4540 #undef D2bv
4541 #undef D2bvIP
4542 #undef I2bv
4543 #undef I2bvIP
4544 #undef I6ALU
4545 
4546 static unsigned imm_size(struct x86_emulate_ctxt *ctxt)
4547 {
4548 	unsigned size;
4549 
4550 	size = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4551 	if (size == 8)
4552 		size = 4;
4553 	return size;
4554 }
4555 
4556 static int decode_imm(struct x86_emulate_ctxt *ctxt, struct operand *op,
4557 		      unsigned size, bool sign_extension)
4558 {
4559 	int rc = X86EMUL_CONTINUE;
4560 
4561 	op->type = OP_IMM;
4562 	op->bytes = size;
4563 	op->addr.mem.ea = ctxt->_eip;
4564 	/* NB. Immediates are sign-extended as necessary. */
4565 	switch (op->bytes) {
4566 	case 1:
4567 		op->val = insn_fetch(s8, ctxt);
4568 		break;
4569 	case 2:
4570 		op->val = insn_fetch(s16, ctxt);
4571 		break;
4572 	case 4:
4573 		op->val = insn_fetch(s32, ctxt);
4574 		break;
4575 	case 8:
4576 		op->val = insn_fetch(s64, ctxt);
4577 		break;
4578 	}
4579 	if (!sign_extension) {
4580 		switch (op->bytes) {
4581 		case 1:
4582 			op->val &= 0xff;
4583 			break;
4584 		case 2:
4585 			op->val &= 0xffff;
4586 			break;
4587 		case 4:
4588 			op->val &= 0xffffffff;
4589 			break;
4590 		}
4591 	}
4592 done:
4593 	return rc;
4594 }
4595 
4596 static int decode_operand(struct x86_emulate_ctxt *ctxt, struct operand *op,
4597 			  unsigned d)
4598 {
4599 	int rc = X86EMUL_CONTINUE;
4600 
4601 	switch (d) {
4602 	case OpReg:
4603 		decode_register_operand(ctxt, op);
4604 		break;
4605 	case OpImmUByte:
4606 		rc = decode_imm(ctxt, op, 1, false);
4607 		break;
4608 	case OpMem:
4609 		ctxt->memop.bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4610 	mem_common:
4611 		*op = ctxt->memop;
4612 		ctxt->memopp = op;
4613 		if (ctxt->d & BitOp)
4614 			fetch_bit_operand(ctxt);
4615 		op->orig_val = op->val;
4616 		break;
4617 	case OpMem64:
4618 		ctxt->memop.bytes = (ctxt->op_bytes == 8) ? 16 : 8;
4619 		goto mem_common;
4620 	case OpAcc:
4621 		op->type = OP_REG;
4622 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4623 		op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
4624 		fetch_register_operand(op);
4625 		op->orig_val = op->val;
4626 		break;
4627 	case OpAccLo:
4628 		op->type = OP_REG;
4629 		op->bytes = (ctxt->d & ByteOp) ? 2 : ctxt->op_bytes;
4630 		op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
4631 		fetch_register_operand(op);
4632 		op->orig_val = op->val;
4633 		break;
4634 	case OpAccHi:
4635 		if (ctxt->d & ByteOp) {
4636 			op->type = OP_NONE;
4637 			break;
4638 		}
4639 		op->type = OP_REG;
4640 		op->bytes = ctxt->op_bytes;
4641 		op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
4642 		fetch_register_operand(op);
4643 		op->orig_val = op->val;
4644 		break;
4645 	case OpDI:
4646 		op->type = OP_MEM;
4647 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4648 		op->addr.mem.ea =
4649 			register_address(ctxt, VCPU_REGS_RDI);
4650 		op->addr.mem.seg = VCPU_SREG_ES;
4651 		op->val = 0;
4652 		op->count = 1;
4653 		break;
4654 	case OpDX:
4655 		op->type = OP_REG;
4656 		op->bytes = 2;
4657 		op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
4658 		fetch_register_operand(op);
4659 		break;
4660 	case OpCL:
4661 		op->type = OP_IMM;
4662 		op->bytes = 1;
4663 		op->val = reg_read(ctxt, VCPU_REGS_RCX) & 0xff;
4664 		break;
4665 	case OpImmByte:
4666 		rc = decode_imm(ctxt, op, 1, true);
4667 		break;
4668 	case OpOne:
4669 		op->type = OP_IMM;
4670 		op->bytes = 1;
4671 		op->val = 1;
4672 		break;
4673 	case OpImm:
4674 		rc = decode_imm(ctxt, op, imm_size(ctxt), true);
4675 		break;
4676 	case OpImm64:
4677 		rc = decode_imm(ctxt, op, ctxt->op_bytes, true);
4678 		break;
4679 	case OpMem8:
4680 		ctxt->memop.bytes = 1;
4681 		if (ctxt->memop.type == OP_REG) {
4682 			ctxt->memop.addr.reg = decode_register(ctxt,
4683 					ctxt->modrm_rm, true);
4684 			fetch_register_operand(&ctxt->memop);
4685 		}
4686 		goto mem_common;
4687 	case OpMem16:
4688 		ctxt->memop.bytes = 2;
4689 		goto mem_common;
4690 	case OpMem32:
4691 		ctxt->memop.bytes = 4;
4692 		goto mem_common;
4693 	case OpImmU16:
4694 		rc = decode_imm(ctxt, op, 2, false);
4695 		break;
4696 	case OpImmU:
4697 		rc = decode_imm(ctxt, op, imm_size(ctxt), false);
4698 		break;
4699 	case OpSI:
4700 		op->type = OP_MEM;
4701 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4702 		op->addr.mem.ea =
4703 			register_address(ctxt, VCPU_REGS_RSI);
4704 		op->addr.mem.seg = ctxt->seg_override;
4705 		op->val = 0;
4706 		op->count = 1;
4707 		break;
4708 	case OpXLat:
4709 		op->type = OP_MEM;
4710 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4711 		op->addr.mem.ea =
4712 			address_mask(ctxt,
4713 				reg_read(ctxt, VCPU_REGS_RBX) +
4714 				(reg_read(ctxt, VCPU_REGS_RAX) & 0xff));
4715 		op->addr.mem.seg = ctxt->seg_override;
4716 		op->val = 0;
4717 		break;
4718 	case OpImmFAddr:
4719 		op->type = OP_IMM;
4720 		op->addr.mem.ea = ctxt->_eip;
4721 		op->bytes = ctxt->op_bytes + 2;
4722 		insn_fetch_arr(op->valptr, op->bytes, ctxt);
4723 		break;
4724 	case OpMemFAddr:
4725 		ctxt->memop.bytes = ctxt->op_bytes + 2;
4726 		goto mem_common;
4727 	case OpES:
4728 		op->type = OP_IMM;
4729 		op->val = VCPU_SREG_ES;
4730 		break;
4731 	case OpCS:
4732 		op->type = OP_IMM;
4733 		op->val = VCPU_SREG_CS;
4734 		break;
4735 	case OpSS:
4736 		op->type = OP_IMM;
4737 		op->val = VCPU_SREG_SS;
4738 		break;
4739 	case OpDS:
4740 		op->type = OP_IMM;
4741 		op->val = VCPU_SREG_DS;
4742 		break;
4743 	case OpFS:
4744 		op->type = OP_IMM;
4745 		op->val = VCPU_SREG_FS;
4746 		break;
4747 	case OpGS:
4748 		op->type = OP_IMM;
4749 		op->val = VCPU_SREG_GS;
4750 		break;
4751 	case OpImplicit:
4752 		/* Special instructions do their own operand decoding. */
4753 	default:
4754 		op->type = OP_NONE; /* Disable writeback. */
4755 		break;
4756 	}
4757 
4758 done:
4759 	return rc;
4760 }
4761 
4762 int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len, int emulation_type)
4763 {
4764 	int rc = X86EMUL_CONTINUE;
4765 	int mode = ctxt->mode;
4766 	int def_op_bytes, def_ad_bytes, goffset, simd_prefix;
4767 	bool op_prefix = false;
4768 	bool has_seg_override = false;
4769 	struct opcode opcode;
4770 	u16 dummy;
4771 	struct desc_struct desc;
4772 
4773 	ctxt->memop.type = OP_NONE;
4774 	ctxt->memopp = NULL;
4775 	ctxt->_eip = ctxt->eip;
4776 	ctxt->fetch.ptr = ctxt->fetch.data;
4777 	ctxt->fetch.end = ctxt->fetch.data + insn_len;
4778 	ctxt->opcode_len = 1;
4779 	ctxt->intercept = x86_intercept_none;
4780 	if (insn_len > 0)
4781 		memcpy(ctxt->fetch.data, insn, insn_len);
4782 	else {
4783 		rc = __do_insn_fetch_bytes(ctxt, 1);
4784 		if (rc != X86EMUL_CONTINUE)
4785 			goto done;
4786 	}
4787 
4788 	switch (mode) {
4789 	case X86EMUL_MODE_REAL:
4790 	case X86EMUL_MODE_VM86:
4791 		def_op_bytes = def_ad_bytes = 2;
4792 		ctxt->ops->get_segment(ctxt, &dummy, &desc, NULL, VCPU_SREG_CS);
4793 		if (desc.d)
4794 			def_op_bytes = def_ad_bytes = 4;
4795 		break;
4796 	case X86EMUL_MODE_PROT16:
4797 		def_op_bytes = def_ad_bytes = 2;
4798 		break;
4799 	case X86EMUL_MODE_PROT32:
4800 		def_op_bytes = def_ad_bytes = 4;
4801 		break;
4802 #ifdef CONFIG_X86_64
4803 	case X86EMUL_MODE_PROT64:
4804 		def_op_bytes = 4;
4805 		def_ad_bytes = 8;
4806 		break;
4807 #endif
4808 	default:
4809 		return EMULATION_FAILED;
4810 	}
4811 
4812 	ctxt->op_bytes = def_op_bytes;
4813 	ctxt->ad_bytes = def_ad_bytes;
4814 
4815 	/* Legacy prefixes. */
4816 	for (;;) {
4817 		switch (ctxt->b = insn_fetch(u8, ctxt)) {
4818 		case 0x66:	/* operand-size override */
4819 			op_prefix = true;
4820 			/* switch between 2/4 bytes */
4821 			ctxt->op_bytes = def_op_bytes ^ 6;
4822 			break;
4823 		case 0x67:	/* address-size override */
4824 			if (mode == X86EMUL_MODE_PROT64)
4825 				/* switch between 4/8 bytes */
4826 				ctxt->ad_bytes = def_ad_bytes ^ 12;
4827 			else
4828 				/* switch between 2/4 bytes */
4829 				ctxt->ad_bytes = def_ad_bytes ^ 6;
4830 			break;
4831 		case 0x26:	/* ES override */
4832 			has_seg_override = true;
4833 			ctxt->seg_override = VCPU_SREG_ES;
4834 			break;
4835 		case 0x2e:	/* CS override */
4836 			has_seg_override = true;
4837 			ctxt->seg_override = VCPU_SREG_CS;
4838 			break;
4839 		case 0x36:	/* SS override */
4840 			has_seg_override = true;
4841 			ctxt->seg_override = VCPU_SREG_SS;
4842 			break;
4843 		case 0x3e:	/* DS override */
4844 			has_seg_override = true;
4845 			ctxt->seg_override = VCPU_SREG_DS;
4846 			break;
4847 		case 0x64:	/* FS override */
4848 			has_seg_override = true;
4849 			ctxt->seg_override = VCPU_SREG_FS;
4850 			break;
4851 		case 0x65:	/* GS override */
4852 			has_seg_override = true;
4853 			ctxt->seg_override = VCPU_SREG_GS;
4854 			break;
4855 		case 0x40 ... 0x4f: /* REX */
4856 			if (mode != X86EMUL_MODE_PROT64)
4857 				goto done_prefixes;
4858 			ctxt->rex_prefix = ctxt->b;
4859 			continue;
4860 		case 0xf0:	/* LOCK */
4861 			ctxt->lock_prefix = 1;
4862 			break;
4863 		case 0xf2:	/* REPNE/REPNZ */
4864 		case 0xf3:	/* REP/REPE/REPZ */
4865 			ctxt->rep_prefix = ctxt->b;
4866 			break;
4867 		default:
4868 			goto done_prefixes;
4869 		}
4870 
4871 		/* Any legacy prefix after a REX prefix nullifies its effect. */
4872 
4873 		ctxt->rex_prefix = 0;
4874 	}
4875 
4876 done_prefixes:
4877 
4878 	/* REX prefix. */
4879 	if (ctxt->rex_prefix & 8)
4880 		ctxt->op_bytes = 8;	/* REX.W */
4881 
4882 	/* Opcode byte(s). */
4883 	opcode = opcode_table[ctxt->b];
4884 	/* Two-byte opcode? */
4885 	if (ctxt->b == 0x0f) {
4886 		ctxt->opcode_len = 2;
4887 		ctxt->b = insn_fetch(u8, ctxt);
4888 		opcode = twobyte_table[ctxt->b];
4889 
4890 		/* 0F_38 opcode map */
4891 		if (ctxt->b == 0x38) {
4892 			ctxt->opcode_len = 3;
4893 			ctxt->b = insn_fetch(u8, ctxt);
4894 			opcode = opcode_map_0f_38[ctxt->b];
4895 		}
4896 	}
4897 	ctxt->d = opcode.flags;
4898 
4899 	if (ctxt->d & ModRM)
4900 		ctxt->modrm = insn_fetch(u8, ctxt);
4901 
4902 	/* vex-prefix instructions are not implemented */
4903 	if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) &&
4904 	    (mode == X86EMUL_MODE_PROT64 || (ctxt->modrm & 0xc0) == 0xc0)) {
4905 		ctxt->d = NotImpl;
4906 	}
4907 
4908 	while (ctxt->d & GroupMask) {
4909 		switch (ctxt->d & GroupMask) {
4910 		case Group:
4911 			goffset = (ctxt->modrm >> 3) & 7;
4912 			opcode = opcode.u.group[goffset];
4913 			break;
4914 		case GroupDual:
4915 			goffset = (ctxt->modrm >> 3) & 7;
4916 			if ((ctxt->modrm >> 6) == 3)
4917 				opcode = opcode.u.gdual->mod3[goffset];
4918 			else
4919 				opcode = opcode.u.gdual->mod012[goffset];
4920 			break;
4921 		case RMExt:
4922 			goffset = ctxt->modrm & 7;
4923 			opcode = opcode.u.group[goffset];
4924 			break;
4925 		case Prefix:
4926 			if (ctxt->rep_prefix && op_prefix)
4927 				return EMULATION_FAILED;
4928 			simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix;
4929 			switch (simd_prefix) {
4930 			case 0x00: opcode = opcode.u.gprefix->pfx_no; break;
4931 			case 0x66: opcode = opcode.u.gprefix->pfx_66; break;
4932 			case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break;
4933 			case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break;
4934 			}
4935 			break;
4936 		case Escape:
4937 			if (ctxt->modrm > 0xbf) {
4938 				size_t size = ARRAY_SIZE(opcode.u.esc->high);
4939 				u32 index = array_index_nospec(
4940 					ctxt->modrm - 0xc0, size);
4941 
4942 				opcode = opcode.u.esc->high[index];
4943 			} else {
4944 				opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7];
4945 			}
4946 			break;
4947 		case InstrDual:
4948 			if ((ctxt->modrm >> 6) == 3)
4949 				opcode = opcode.u.idual->mod3;
4950 			else
4951 				opcode = opcode.u.idual->mod012;
4952 			break;
4953 		case ModeDual:
4954 			if (ctxt->mode == X86EMUL_MODE_PROT64)
4955 				opcode = opcode.u.mdual->mode64;
4956 			else
4957 				opcode = opcode.u.mdual->mode32;
4958 			break;
4959 		default:
4960 			return EMULATION_FAILED;
4961 		}
4962 
4963 		ctxt->d &= ~(u64)GroupMask;
4964 		ctxt->d |= opcode.flags;
4965 	}
4966 
4967 	ctxt->is_branch = opcode.flags & IsBranch;
4968 
4969 	/* Unrecognised? */
4970 	if (ctxt->d == 0)
4971 		return EMULATION_FAILED;
4972 
4973 	ctxt->execute = opcode.u.execute;
4974 
4975 	if (unlikely(emulation_type & EMULTYPE_TRAP_UD) &&
4976 	    likely(!(ctxt->d & EmulateOnUD)))
4977 		return EMULATION_FAILED;
4978 
4979 	if (unlikely(ctxt->d &
4980 	    (NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm|NearBranch|
4981 	     No16))) {
4982 		/*
4983 		 * These are copied unconditionally here, and checked unconditionally
4984 		 * in x86_emulate_insn.
4985 		 */
4986 		ctxt->check_perm = opcode.check_perm;
4987 		ctxt->intercept = opcode.intercept;
4988 
4989 		if (ctxt->d & NotImpl)
4990 			return EMULATION_FAILED;
4991 
4992 		if (mode == X86EMUL_MODE_PROT64) {
4993 			if (ctxt->op_bytes == 4 && (ctxt->d & Stack))
4994 				ctxt->op_bytes = 8;
4995 			else if (ctxt->d & NearBranch)
4996 				ctxt->op_bytes = 8;
4997 		}
4998 
4999 		if (ctxt->d & Op3264) {
5000 			if (mode == X86EMUL_MODE_PROT64)
5001 				ctxt->op_bytes = 8;
5002 			else
5003 				ctxt->op_bytes = 4;
5004 		}
5005 
5006 		if ((ctxt->d & No16) && ctxt->op_bytes == 2)
5007 			ctxt->op_bytes = 4;
5008 
5009 		if (ctxt->d & Sse)
5010 			ctxt->op_bytes = 16;
5011 		else if (ctxt->d & Mmx)
5012 			ctxt->op_bytes = 8;
5013 	}
5014 
5015 	/* ModRM and SIB bytes. */
5016 	if (ctxt->d & ModRM) {
5017 		rc = decode_modrm(ctxt, &ctxt->memop);
5018 		if (!has_seg_override) {
5019 			has_seg_override = true;
5020 			ctxt->seg_override = ctxt->modrm_seg;
5021 		}
5022 	} else if (ctxt->d & MemAbs)
5023 		rc = decode_abs(ctxt, &ctxt->memop);
5024 	if (rc != X86EMUL_CONTINUE)
5025 		goto done;
5026 
5027 	if (!has_seg_override)
5028 		ctxt->seg_override = VCPU_SREG_DS;
5029 
5030 	ctxt->memop.addr.mem.seg = ctxt->seg_override;
5031 
5032 	/*
5033 	 * Decode and fetch the source operand: register, memory
5034 	 * or immediate.
5035 	 */
5036 	rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask);
5037 	if (rc != X86EMUL_CONTINUE)
5038 		goto done;
5039 
5040 	/*
5041 	 * Decode and fetch the second source operand: register, memory
5042 	 * or immediate.
5043 	 */
5044 	rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask);
5045 	if (rc != X86EMUL_CONTINUE)
5046 		goto done;
5047 
5048 	/* Decode and fetch the destination operand: register or memory. */
5049 	rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask);
5050 
5051 	if (ctxt->rip_relative && likely(ctxt->memopp))
5052 		ctxt->memopp->addr.mem.ea = address_mask(ctxt,
5053 					ctxt->memopp->addr.mem.ea + ctxt->_eip);
5054 
5055 done:
5056 	if (rc == X86EMUL_PROPAGATE_FAULT)
5057 		ctxt->have_exception = true;
5058 	return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK;
5059 }
5060 
5061 bool x86_page_table_writing_insn(struct x86_emulate_ctxt *ctxt)
5062 {
5063 	return ctxt->d & PageTable;
5064 }
5065 
5066 static bool string_insn_completed(struct x86_emulate_ctxt *ctxt)
5067 {
5068 	/* The second termination condition only applies for REPE
5069 	 * and REPNE. Test if the repeat string operation prefix is
5070 	 * REPE/REPZ or REPNE/REPNZ and if it's the case it tests the
5071 	 * corresponding termination condition according to:
5072 	 * 	- if REPE/REPZ and ZF = 0 then done
5073 	 * 	- if REPNE/REPNZ and ZF = 1 then done
5074 	 */
5075 	if (((ctxt->b == 0xa6) || (ctxt->b == 0xa7) ||
5076 	     (ctxt->b == 0xae) || (ctxt->b == 0xaf))
5077 	    && (((ctxt->rep_prefix == REPE_PREFIX) &&
5078 		 ((ctxt->eflags & X86_EFLAGS_ZF) == 0))
5079 		|| ((ctxt->rep_prefix == REPNE_PREFIX) &&
5080 		    ((ctxt->eflags & X86_EFLAGS_ZF) == X86_EFLAGS_ZF))))
5081 		return true;
5082 
5083 	return false;
5084 }
5085 
5086 static int flush_pending_x87_faults(struct x86_emulate_ctxt *ctxt)
5087 {
5088 	int rc;
5089 
5090 	kvm_fpu_get();
5091 	rc = asm_safe("fwait");
5092 	kvm_fpu_put();
5093 
5094 	if (unlikely(rc != X86EMUL_CONTINUE))
5095 		return emulate_exception(ctxt, MF_VECTOR, 0, false);
5096 
5097 	return X86EMUL_CONTINUE;
5098 }
5099 
5100 static void fetch_possible_mmx_operand(struct operand *op)
5101 {
5102 	if (op->type == OP_MM)
5103 		kvm_read_mmx_reg(op->addr.mm, &op->mm_val);
5104 }
5105 
5106 static int fastop(struct x86_emulate_ctxt *ctxt, fastop_t fop)
5107 {
5108 	ulong flags = (ctxt->eflags & EFLAGS_MASK) | X86_EFLAGS_IF;
5109 
5110 	if (!(ctxt->d & ByteOp))
5111 		fop += __ffs(ctxt->dst.bytes) * FASTOP_SIZE;
5112 
5113 	asm("push %[flags]; popf; " CALL_NOSPEC " ; pushf; pop %[flags]\n"
5114 	    : "+a"(ctxt->dst.val), "+d"(ctxt->src.val), [flags]"+D"(flags),
5115 	      [thunk_target]"+S"(fop), ASM_CALL_CONSTRAINT
5116 	    : "c"(ctxt->src2.val));
5117 
5118 	ctxt->eflags = (ctxt->eflags & ~EFLAGS_MASK) | (flags & EFLAGS_MASK);
5119 	if (!fop) /* exception is returned in fop variable */
5120 		return emulate_de(ctxt);
5121 	return X86EMUL_CONTINUE;
5122 }
5123 
5124 void init_decode_cache(struct x86_emulate_ctxt *ctxt)
5125 {
5126 	/* Clear fields that are set conditionally but read without a guard. */
5127 	ctxt->rip_relative = false;
5128 	ctxt->rex_prefix = 0;
5129 	ctxt->lock_prefix = 0;
5130 	ctxt->rep_prefix = 0;
5131 	ctxt->regs_valid = 0;
5132 	ctxt->regs_dirty = 0;
5133 
5134 	ctxt->io_read.pos = 0;
5135 	ctxt->io_read.end = 0;
5136 	ctxt->mem_read.end = 0;
5137 }
5138 
5139 int x86_emulate_insn(struct x86_emulate_ctxt *ctxt)
5140 {
5141 	const struct x86_emulate_ops *ops = ctxt->ops;
5142 	int rc = X86EMUL_CONTINUE;
5143 	int saved_dst_type = ctxt->dst.type;
5144 	bool is_guest_mode = ctxt->ops->is_guest_mode(ctxt);
5145 
5146 	ctxt->mem_read.pos = 0;
5147 
5148 	/* LOCK prefix is allowed only with some instructions */
5149 	if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) {
5150 		rc = emulate_ud(ctxt);
5151 		goto done;
5152 	}
5153 
5154 	if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) {
5155 		rc = emulate_ud(ctxt);
5156 		goto done;
5157 	}
5158 
5159 	if (unlikely(ctxt->d &
5160 		     (No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) {
5161 		if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) ||
5162 				(ctxt->d & Undefined)) {
5163 			rc = emulate_ud(ctxt);
5164 			goto done;
5165 		}
5166 
5167 		if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM)))
5168 		    || ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) {
5169 			rc = emulate_ud(ctxt);
5170 			goto done;
5171 		}
5172 
5173 		if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) {
5174 			rc = emulate_nm(ctxt);
5175 			goto done;
5176 		}
5177 
5178 		if (ctxt->d & Mmx) {
5179 			rc = flush_pending_x87_faults(ctxt);
5180 			if (rc != X86EMUL_CONTINUE)
5181 				goto done;
5182 			/*
5183 			 * Now that we know the fpu is exception safe, we can fetch
5184 			 * operands from it.
5185 			 */
5186 			fetch_possible_mmx_operand(&ctxt->src);
5187 			fetch_possible_mmx_operand(&ctxt->src2);
5188 			if (!(ctxt->d & Mov))
5189 				fetch_possible_mmx_operand(&ctxt->dst);
5190 		}
5191 
5192 		if (unlikely(is_guest_mode) && ctxt->intercept) {
5193 			rc = emulator_check_intercept(ctxt, ctxt->intercept,
5194 						      X86_ICPT_PRE_EXCEPT);
5195 			if (rc != X86EMUL_CONTINUE)
5196 				goto done;
5197 		}
5198 
5199 		/* Instruction can only be executed in protected mode */
5200 		if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) {
5201 			rc = emulate_ud(ctxt);
5202 			goto done;
5203 		}
5204 
5205 		/* Privileged instruction can be executed only in CPL=0 */
5206 		if ((ctxt->d & Priv) && ops->cpl(ctxt)) {
5207 			if (ctxt->d & PrivUD)
5208 				rc = emulate_ud(ctxt);
5209 			else
5210 				rc = emulate_gp(ctxt, 0);
5211 			goto done;
5212 		}
5213 
5214 		/* Do instruction specific permission checks */
5215 		if (ctxt->d & CheckPerm) {
5216 			rc = ctxt->check_perm(ctxt);
5217 			if (rc != X86EMUL_CONTINUE)
5218 				goto done;
5219 		}
5220 
5221 		if (unlikely(is_guest_mode) && (ctxt->d & Intercept)) {
5222 			rc = emulator_check_intercept(ctxt, ctxt->intercept,
5223 						      X86_ICPT_POST_EXCEPT);
5224 			if (rc != X86EMUL_CONTINUE)
5225 				goto done;
5226 		}
5227 
5228 		if (ctxt->rep_prefix && (ctxt->d & String)) {
5229 			/* All REP prefixes have the same first termination condition */
5230 			if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) {
5231 				string_registers_quirk(ctxt);
5232 				ctxt->eip = ctxt->_eip;
5233 				ctxt->eflags &= ~X86_EFLAGS_RF;
5234 				goto done;
5235 			}
5236 		}
5237 	}
5238 
5239 	if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) {
5240 		rc = segmented_read(ctxt, ctxt->src.addr.mem,
5241 				    ctxt->src.valptr, ctxt->src.bytes);
5242 		if (rc != X86EMUL_CONTINUE)
5243 			goto done;
5244 		ctxt->src.orig_val64 = ctxt->src.val64;
5245 	}
5246 
5247 	if (ctxt->src2.type == OP_MEM) {
5248 		rc = segmented_read(ctxt, ctxt->src2.addr.mem,
5249 				    &ctxt->src2.val, ctxt->src2.bytes);
5250 		if (rc != X86EMUL_CONTINUE)
5251 			goto done;
5252 	}
5253 
5254 	if ((ctxt->d & DstMask) == ImplicitOps)
5255 		goto special_insn;
5256 
5257 
5258 	if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) {
5259 		/* optimisation - avoid slow emulated read if Mov */
5260 		rc = segmented_read(ctxt, ctxt->dst.addr.mem,
5261 				   &ctxt->dst.val, ctxt->dst.bytes);
5262 		if (rc != X86EMUL_CONTINUE) {
5263 			if (!(ctxt->d & NoWrite) &&
5264 			    rc == X86EMUL_PROPAGATE_FAULT &&
5265 			    ctxt->exception.vector == PF_VECTOR)
5266 				ctxt->exception.error_code |= PFERR_WRITE_MASK;
5267 			goto done;
5268 		}
5269 	}
5270 	/* Copy full 64-bit value for CMPXCHG8B.  */
5271 	ctxt->dst.orig_val64 = ctxt->dst.val64;
5272 
5273 special_insn:
5274 
5275 	if (unlikely(is_guest_mode) && (ctxt->d & Intercept)) {
5276 		rc = emulator_check_intercept(ctxt, ctxt->intercept,
5277 					      X86_ICPT_POST_MEMACCESS);
5278 		if (rc != X86EMUL_CONTINUE)
5279 			goto done;
5280 	}
5281 
5282 	if (ctxt->rep_prefix && (ctxt->d & String))
5283 		ctxt->eflags |= X86_EFLAGS_RF;
5284 	else
5285 		ctxt->eflags &= ~X86_EFLAGS_RF;
5286 
5287 	if (ctxt->execute) {
5288 		if (ctxt->d & Fastop)
5289 			rc = fastop(ctxt, ctxt->fop);
5290 		else
5291 			rc = ctxt->execute(ctxt);
5292 		if (rc != X86EMUL_CONTINUE)
5293 			goto done;
5294 		goto writeback;
5295 	}
5296 
5297 	if (ctxt->opcode_len == 2)
5298 		goto twobyte_insn;
5299 	else if (ctxt->opcode_len == 3)
5300 		goto threebyte_insn;
5301 
5302 	switch (ctxt->b) {
5303 	case 0x70 ... 0x7f: /* jcc (short) */
5304 		if (test_cc(ctxt->b, ctxt->eflags))
5305 			rc = jmp_rel(ctxt, ctxt->src.val);
5306 		break;
5307 	case 0x8d: /* lea r16/r32, m */
5308 		ctxt->dst.val = ctxt->src.addr.mem.ea;
5309 		break;
5310 	case 0x90 ... 0x97: /* nop / xchg reg, rax */
5311 		if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX))
5312 			ctxt->dst.type = OP_NONE;
5313 		else
5314 			rc = em_xchg(ctxt);
5315 		break;
5316 	case 0x98: /* cbw/cwde/cdqe */
5317 		switch (ctxt->op_bytes) {
5318 		case 2: ctxt->dst.val = (s8)ctxt->dst.val; break;
5319 		case 4: ctxt->dst.val = (s16)ctxt->dst.val; break;
5320 		case 8: ctxt->dst.val = (s32)ctxt->dst.val; break;
5321 		}
5322 		break;
5323 	case 0xcc:		/* int3 */
5324 		rc = emulate_int(ctxt, 3);
5325 		break;
5326 	case 0xcd:		/* int n */
5327 		rc = emulate_int(ctxt, ctxt->src.val);
5328 		break;
5329 	case 0xce:		/* into */
5330 		if (ctxt->eflags & X86_EFLAGS_OF)
5331 			rc = emulate_int(ctxt, 4);
5332 		break;
5333 	case 0xe9: /* jmp rel */
5334 	case 0xeb: /* jmp rel short */
5335 		rc = jmp_rel(ctxt, ctxt->src.val);
5336 		ctxt->dst.type = OP_NONE; /* Disable writeback. */
5337 		break;
5338 	case 0xf4:              /* hlt */
5339 		ctxt->ops->halt(ctxt);
5340 		break;
5341 	case 0xf5:	/* cmc */
5342 		/* complement carry flag from eflags reg */
5343 		ctxt->eflags ^= X86_EFLAGS_CF;
5344 		break;
5345 	case 0xf8: /* clc */
5346 		ctxt->eflags &= ~X86_EFLAGS_CF;
5347 		break;
5348 	case 0xf9: /* stc */
5349 		ctxt->eflags |= X86_EFLAGS_CF;
5350 		break;
5351 	case 0xfc: /* cld */
5352 		ctxt->eflags &= ~X86_EFLAGS_DF;
5353 		break;
5354 	case 0xfd: /* std */
5355 		ctxt->eflags |= X86_EFLAGS_DF;
5356 		break;
5357 	default:
5358 		goto cannot_emulate;
5359 	}
5360 
5361 	if (rc != X86EMUL_CONTINUE)
5362 		goto done;
5363 
5364 writeback:
5365 	if (ctxt->d & SrcWrite) {
5366 		BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR);
5367 		rc = writeback(ctxt, &ctxt->src);
5368 		if (rc != X86EMUL_CONTINUE)
5369 			goto done;
5370 	}
5371 	if (!(ctxt->d & NoWrite)) {
5372 		rc = writeback(ctxt, &ctxt->dst);
5373 		if (rc != X86EMUL_CONTINUE)
5374 			goto done;
5375 	}
5376 
5377 	/*
5378 	 * restore dst type in case the decoding will be reused
5379 	 * (happens for string instruction )
5380 	 */
5381 	ctxt->dst.type = saved_dst_type;
5382 
5383 	if ((ctxt->d & SrcMask) == SrcSI)
5384 		string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src);
5385 
5386 	if ((ctxt->d & DstMask) == DstDI)
5387 		string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst);
5388 
5389 	if (ctxt->rep_prefix && (ctxt->d & String)) {
5390 		unsigned int count;
5391 		struct read_cache *r = &ctxt->io_read;
5392 		if ((ctxt->d & SrcMask) == SrcSI)
5393 			count = ctxt->src.count;
5394 		else
5395 			count = ctxt->dst.count;
5396 		register_address_increment(ctxt, VCPU_REGS_RCX, -count);
5397 
5398 		if (!string_insn_completed(ctxt)) {
5399 			/*
5400 			 * Re-enter guest when pio read ahead buffer is empty
5401 			 * or, if it is not used, after each 1024 iteration.
5402 			 */
5403 			if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) &&
5404 			    (r->end == 0 || r->end != r->pos)) {
5405 				/*
5406 				 * Reset read cache. Usually happens before
5407 				 * decode, but since instruction is restarted
5408 				 * we have to do it here.
5409 				 */
5410 				ctxt->mem_read.end = 0;
5411 				writeback_registers(ctxt);
5412 				return EMULATION_RESTART;
5413 			}
5414 			goto done; /* skip rip writeback */
5415 		}
5416 		ctxt->eflags &= ~X86_EFLAGS_RF;
5417 	}
5418 
5419 	ctxt->eip = ctxt->_eip;
5420 	if (ctxt->mode != X86EMUL_MODE_PROT64)
5421 		ctxt->eip = (u32)ctxt->_eip;
5422 
5423 done:
5424 	if (rc == X86EMUL_PROPAGATE_FAULT) {
5425 		if (KVM_EMULATOR_BUG_ON(ctxt->exception.vector > 0x1f, ctxt))
5426 			return EMULATION_FAILED;
5427 		ctxt->have_exception = true;
5428 	}
5429 	if (rc == X86EMUL_INTERCEPTED)
5430 		return EMULATION_INTERCEPTED;
5431 
5432 	if (rc == X86EMUL_CONTINUE)
5433 		writeback_registers(ctxt);
5434 
5435 	return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK;
5436 
5437 twobyte_insn:
5438 	switch (ctxt->b) {
5439 	case 0x09:		/* wbinvd */
5440 		(ctxt->ops->wbinvd)(ctxt);
5441 		break;
5442 	case 0x08:		/* invd */
5443 	case 0x0d:		/* GrpP (prefetch) */
5444 	case 0x18:		/* Grp16 (prefetch/nop) */
5445 	case 0x1f:		/* nop */
5446 		break;
5447 	case 0x20: /* mov cr, reg */
5448 		ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg);
5449 		break;
5450 	case 0x21: /* mov from dr to reg */
5451 		ops->get_dr(ctxt, ctxt->modrm_reg, &ctxt->dst.val);
5452 		break;
5453 	case 0x40 ... 0x4f:	/* cmov */
5454 		if (test_cc(ctxt->b, ctxt->eflags))
5455 			ctxt->dst.val = ctxt->src.val;
5456 		else if (ctxt->op_bytes != 4)
5457 			ctxt->dst.type = OP_NONE; /* no writeback */
5458 		break;
5459 	case 0x80 ... 0x8f: /* jnz rel, etc*/
5460 		if (test_cc(ctxt->b, ctxt->eflags))
5461 			rc = jmp_rel(ctxt, ctxt->src.val);
5462 		break;
5463 	case 0x90 ... 0x9f:     /* setcc r/m8 */
5464 		ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags);
5465 		break;
5466 	case 0xb6 ... 0xb7:	/* movzx */
5467 		ctxt->dst.bytes = ctxt->op_bytes;
5468 		ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val
5469 						       : (u16) ctxt->src.val;
5470 		break;
5471 	case 0xbe ... 0xbf:	/* movsx */
5472 		ctxt->dst.bytes = ctxt->op_bytes;
5473 		ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val :
5474 							(s16) ctxt->src.val;
5475 		break;
5476 	default:
5477 		goto cannot_emulate;
5478 	}
5479 
5480 threebyte_insn:
5481 
5482 	if (rc != X86EMUL_CONTINUE)
5483 		goto done;
5484 
5485 	goto writeback;
5486 
5487 cannot_emulate:
5488 	return EMULATION_FAILED;
5489 }
5490 
5491 void emulator_invalidate_register_cache(struct x86_emulate_ctxt *ctxt)
5492 {
5493 	invalidate_registers(ctxt);
5494 }
5495 
5496 void emulator_writeback_register_cache(struct x86_emulate_ctxt *ctxt)
5497 {
5498 	writeback_registers(ctxt);
5499 }
5500 
5501 bool emulator_can_use_gpa(struct x86_emulate_ctxt *ctxt)
5502 {
5503 	if (ctxt->rep_prefix && (ctxt->d & String))
5504 		return false;
5505 
5506 	if (ctxt->d & TwoMemOp)
5507 		return false;
5508 
5509 	return true;
5510 }
5511