xref: /linux/arch/x86/kvm/emulate.c (revision 55d0969c451159cff86949b38c39171cab962069)
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 				       enum x86emul_mode mode, ulong *linear,
691 				       unsigned int flags)
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 = ctxt->ops->get_untagged_addr(ctxt, la, flags);
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)) || !(desc.type & 2)) &&
721 		    (flags & X86EMUL_F_WRITE))
722 			goto bad;
723 		/* unreadable code segment */
724 		if (!(flags & X86EMUL_F_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, ctxt->mode, linear,
761 			   write ? X86EMUL_F_WRITE : 0);
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, ctxt->mode, &linear,
775 			 X86EMUL_F_FETCH);
776 	if (rc == X86EMUL_CONTINUE)
777 		ctxt->_eip = addr.ea;
778 	return rc;
779 }
780 
781 static inline int emulator_recalc_and_set_mode(struct x86_emulate_ctxt *ctxt)
782 {
783 	u64 efer;
784 	struct desc_struct cs;
785 	u16 selector;
786 	u32 base3;
787 
788 	ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
789 
790 	if (!(ctxt->ops->get_cr(ctxt, 0) & X86_CR0_PE)) {
791 		/* Real mode. cpu must not have long mode active */
792 		if (efer & EFER_LMA)
793 			return X86EMUL_UNHANDLEABLE;
794 		ctxt->mode = X86EMUL_MODE_REAL;
795 		return X86EMUL_CONTINUE;
796 	}
797 
798 	if (ctxt->eflags & X86_EFLAGS_VM) {
799 		/* Protected/VM86 mode. cpu must not have long mode active */
800 		if (efer & EFER_LMA)
801 			return X86EMUL_UNHANDLEABLE;
802 		ctxt->mode = X86EMUL_MODE_VM86;
803 		return X86EMUL_CONTINUE;
804 	}
805 
806 	if (!ctxt->ops->get_segment(ctxt, &selector, &cs, &base3, VCPU_SREG_CS))
807 		return X86EMUL_UNHANDLEABLE;
808 
809 	if (efer & EFER_LMA) {
810 		if (cs.l) {
811 			/* Proper long mode */
812 			ctxt->mode = X86EMUL_MODE_PROT64;
813 		} else if (cs.d) {
814 			/* 32 bit compatibility mode*/
815 			ctxt->mode = X86EMUL_MODE_PROT32;
816 		} else {
817 			ctxt->mode = X86EMUL_MODE_PROT16;
818 		}
819 	} else {
820 		/* Legacy 32 bit / 16 bit mode */
821 		ctxt->mode = cs.d ? X86EMUL_MODE_PROT32 : X86EMUL_MODE_PROT16;
822 	}
823 
824 	return X86EMUL_CONTINUE;
825 }
826 
827 static inline int assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst)
828 {
829 	return assign_eip(ctxt, dst);
830 }
831 
832 static int assign_eip_far(struct x86_emulate_ctxt *ctxt, ulong dst)
833 {
834 	int rc = emulator_recalc_and_set_mode(ctxt);
835 
836 	if (rc != X86EMUL_CONTINUE)
837 		return rc;
838 
839 	return assign_eip(ctxt, dst);
840 }
841 
842 static inline int jmp_rel(struct x86_emulate_ctxt *ctxt, int rel)
843 {
844 	return assign_eip_near(ctxt, ctxt->_eip + rel);
845 }
846 
847 static int linear_read_system(struct x86_emulate_ctxt *ctxt, ulong linear,
848 			      void *data, unsigned size)
849 {
850 	return ctxt->ops->read_std(ctxt, linear, data, size, &ctxt->exception, true);
851 }
852 
853 static int linear_write_system(struct x86_emulate_ctxt *ctxt,
854 			       ulong linear, void *data,
855 			       unsigned int size)
856 {
857 	return ctxt->ops->write_std(ctxt, linear, data, size, &ctxt->exception, true);
858 }
859 
860 static int segmented_read_std(struct x86_emulate_ctxt *ctxt,
861 			      struct segmented_address addr,
862 			      void *data,
863 			      unsigned size)
864 {
865 	int rc;
866 	ulong linear;
867 
868 	rc = linearize(ctxt, addr, size, false, &linear);
869 	if (rc != X86EMUL_CONTINUE)
870 		return rc;
871 	return ctxt->ops->read_std(ctxt, linear, data, size, &ctxt->exception, false);
872 }
873 
874 static int segmented_write_std(struct x86_emulate_ctxt *ctxt,
875 			       struct segmented_address addr,
876 			       void *data,
877 			       unsigned int size)
878 {
879 	int rc;
880 	ulong linear;
881 
882 	rc = linearize(ctxt, addr, size, true, &linear);
883 	if (rc != X86EMUL_CONTINUE)
884 		return rc;
885 	return ctxt->ops->write_std(ctxt, linear, data, size, &ctxt->exception, false);
886 }
887 
888 /*
889  * Prefetch the remaining bytes of the instruction without crossing page
890  * boundary if they are not in fetch_cache yet.
891  */
892 static int __do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt, int op_size)
893 {
894 	int rc;
895 	unsigned size, max_size;
896 	unsigned long linear;
897 	int cur_size = ctxt->fetch.end - ctxt->fetch.data;
898 	struct segmented_address addr = { .seg = VCPU_SREG_CS,
899 					   .ea = ctxt->eip + cur_size };
900 
901 	/*
902 	 * We do not know exactly how many bytes will be needed, and
903 	 * __linearize is expensive, so fetch as much as possible.  We
904 	 * just have to avoid going beyond the 15 byte limit, the end
905 	 * of the segment, or the end of the page.
906 	 *
907 	 * __linearize is called with size 0 so that it does not do any
908 	 * boundary check itself.  Instead, we use max_size to check
909 	 * against op_size.
910 	 */
911 	rc = __linearize(ctxt, addr, &max_size, 0, ctxt->mode, &linear,
912 			 X86EMUL_F_FETCH);
913 	if (unlikely(rc != X86EMUL_CONTINUE))
914 		return rc;
915 
916 	size = min_t(unsigned, 15UL ^ cur_size, max_size);
917 	size = min_t(unsigned, size, PAGE_SIZE - offset_in_page(linear));
918 
919 	/*
920 	 * One instruction can only straddle two pages,
921 	 * and one has been loaded at the beginning of
922 	 * x86_decode_insn.  So, if not enough bytes
923 	 * still, we must have hit the 15-byte boundary.
924 	 */
925 	if (unlikely(size < op_size))
926 		return emulate_gp(ctxt, 0);
927 
928 	rc = ctxt->ops->fetch(ctxt, linear, ctxt->fetch.end,
929 			      size, &ctxt->exception);
930 	if (unlikely(rc != X86EMUL_CONTINUE))
931 		return rc;
932 	ctxt->fetch.end += size;
933 	return X86EMUL_CONTINUE;
934 }
935 
936 static __always_inline int do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt,
937 					       unsigned size)
938 {
939 	unsigned done_size = ctxt->fetch.end - ctxt->fetch.ptr;
940 
941 	if (unlikely(done_size < size))
942 		return __do_insn_fetch_bytes(ctxt, size - done_size);
943 	else
944 		return X86EMUL_CONTINUE;
945 }
946 
947 /* Fetch next part of the instruction being emulated. */
948 #define insn_fetch(_type, _ctxt)					\
949 ({	_type _x;							\
950 									\
951 	rc = do_insn_fetch_bytes(_ctxt, sizeof(_type));			\
952 	if (rc != X86EMUL_CONTINUE)					\
953 		goto done;						\
954 	ctxt->_eip += sizeof(_type);					\
955 	memcpy(&_x, ctxt->fetch.ptr, sizeof(_type));			\
956 	ctxt->fetch.ptr += sizeof(_type);				\
957 	_x;								\
958 })
959 
960 #define insn_fetch_arr(_arr, _size, _ctxt)				\
961 ({									\
962 	rc = do_insn_fetch_bytes(_ctxt, _size);				\
963 	if (rc != X86EMUL_CONTINUE)					\
964 		goto done;						\
965 	ctxt->_eip += (_size);						\
966 	memcpy(_arr, ctxt->fetch.ptr, _size);				\
967 	ctxt->fetch.ptr += (_size);					\
968 })
969 
970 /*
971  * Given the 'reg' portion of a ModRM byte, and a register block, return a
972  * pointer into the block that addresses the relevant register.
973  * @highbyte_regs specifies whether to decode AH,CH,DH,BH.
974  */
975 static void *decode_register(struct x86_emulate_ctxt *ctxt, u8 modrm_reg,
976 			     int byteop)
977 {
978 	void *p;
979 	int highbyte_regs = (ctxt->rex_prefix == 0) && byteop;
980 
981 	if (highbyte_regs && modrm_reg >= 4 && modrm_reg < 8)
982 		p = (unsigned char *)reg_rmw(ctxt, modrm_reg & 3) + 1;
983 	else
984 		p = reg_rmw(ctxt, modrm_reg);
985 	return p;
986 }
987 
988 static int read_descriptor(struct x86_emulate_ctxt *ctxt,
989 			   struct segmented_address addr,
990 			   u16 *size, unsigned long *address, int op_bytes)
991 {
992 	int rc;
993 
994 	if (op_bytes == 2)
995 		op_bytes = 3;
996 	*address = 0;
997 	rc = segmented_read_std(ctxt, addr, size, 2);
998 	if (rc != X86EMUL_CONTINUE)
999 		return rc;
1000 	addr.ea += 2;
1001 	rc = segmented_read_std(ctxt, addr, address, op_bytes);
1002 	return rc;
1003 }
1004 
1005 FASTOP2(add);
1006 FASTOP2(or);
1007 FASTOP2(adc);
1008 FASTOP2(sbb);
1009 FASTOP2(and);
1010 FASTOP2(sub);
1011 FASTOP2(xor);
1012 FASTOP2(cmp);
1013 FASTOP2(test);
1014 
1015 FASTOP1SRC2(mul, mul_ex);
1016 FASTOP1SRC2(imul, imul_ex);
1017 FASTOP1SRC2EX(div, div_ex);
1018 FASTOP1SRC2EX(idiv, idiv_ex);
1019 
1020 FASTOP3WCL(shld);
1021 FASTOP3WCL(shrd);
1022 
1023 FASTOP2W(imul);
1024 
1025 FASTOP1(not);
1026 FASTOP1(neg);
1027 FASTOP1(inc);
1028 FASTOP1(dec);
1029 
1030 FASTOP2CL(rol);
1031 FASTOP2CL(ror);
1032 FASTOP2CL(rcl);
1033 FASTOP2CL(rcr);
1034 FASTOP2CL(shl);
1035 FASTOP2CL(shr);
1036 FASTOP2CL(sar);
1037 
1038 FASTOP2W(bsf);
1039 FASTOP2W(bsr);
1040 FASTOP2W(bt);
1041 FASTOP2W(bts);
1042 FASTOP2W(btr);
1043 FASTOP2W(btc);
1044 
1045 FASTOP2(xadd);
1046 
1047 FASTOP2R(cmp, cmp_r);
1048 
1049 static int em_bsf_c(struct x86_emulate_ctxt *ctxt)
1050 {
1051 	/* If src is zero, do not writeback, but update flags */
1052 	if (ctxt->src.val == 0)
1053 		ctxt->dst.type = OP_NONE;
1054 	return fastop(ctxt, em_bsf);
1055 }
1056 
1057 static int em_bsr_c(struct x86_emulate_ctxt *ctxt)
1058 {
1059 	/* If src is zero, do not writeback, but update flags */
1060 	if (ctxt->src.val == 0)
1061 		ctxt->dst.type = OP_NONE;
1062 	return fastop(ctxt, em_bsr);
1063 }
1064 
1065 static __always_inline u8 test_cc(unsigned int condition, unsigned long flags)
1066 {
1067 	u8 rc;
1068 	void (*fop)(void) = (void *)em_setcc + FASTOP_SIZE * (condition & 0xf);
1069 
1070 	flags = (flags & EFLAGS_MASK) | X86_EFLAGS_IF;
1071 	asm("push %[flags]; popf; " CALL_NOSPEC
1072 	    : "=a"(rc), ASM_CALL_CONSTRAINT : [thunk_target]"r"(fop), [flags]"r"(flags));
1073 	return rc;
1074 }
1075 
1076 static void fetch_register_operand(struct operand *op)
1077 {
1078 	switch (op->bytes) {
1079 	case 1:
1080 		op->val = *(u8 *)op->addr.reg;
1081 		break;
1082 	case 2:
1083 		op->val = *(u16 *)op->addr.reg;
1084 		break;
1085 	case 4:
1086 		op->val = *(u32 *)op->addr.reg;
1087 		break;
1088 	case 8:
1089 		op->val = *(u64 *)op->addr.reg;
1090 		break;
1091 	}
1092 }
1093 
1094 static int em_fninit(struct x86_emulate_ctxt *ctxt)
1095 {
1096 	if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
1097 		return emulate_nm(ctxt);
1098 
1099 	kvm_fpu_get();
1100 	asm volatile("fninit");
1101 	kvm_fpu_put();
1102 	return X86EMUL_CONTINUE;
1103 }
1104 
1105 static int em_fnstcw(struct x86_emulate_ctxt *ctxt)
1106 {
1107 	u16 fcw;
1108 
1109 	if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
1110 		return emulate_nm(ctxt);
1111 
1112 	kvm_fpu_get();
1113 	asm volatile("fnstcw %0": "+m"(fcw));
1114 	kvm_fpu_put();
1115 
1116 	ctxt->dst.val = fcw;
1117 
1118 	return X86EMUL_CONTINUE;
1119 }
1120 
1121 static int em_fnstsw(struct x86_emulate_ctxt *ctxt)
1122 {
1123 	u16 fsw;
1124 
1125 	if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
1126 		return emulate_nm(ctxt);
1127 
1128 	kvm_fpu_get();
1129 	asm volatile("fnstsw %0": "+m"(fsw));
1130 	kvm_fpu_put();
1131 
1132 	ctxt->dst.val = fsw;
1133 
1134 	return X86EMUL_CONTINUE;
1135 }
1136 
1137 static void decode_register_operand(struct x86_emulate_ctxt *ctxt,
1138 				    struct operand *op)
1139 {
1140 	unsigned int reg;
1141 
1142 	if (ctxt->d & ModRM)
1143 		reg = ctxt->modrm_reg;
1144 	else
1145 		reg = (ctxt->b & 7) | ((ctxt->rex_prefix & 1) << 3);
1146 
1147 	if (ctxt->d & Sse) {
1148 		op->type = OP_XMM;
1149 		op->bytes = 16;
1150 		op->addr.xmm = reg;
1151 		kvm_read_sse_reg(reg, &op->vec_val);
1152 		return;
1153 	}
1154 	if (ctxt->d & Mmx) {
1155 		reg &= 7;
1156 		op->type = OP_MM;
1157 		op->bytes = 8;
1158 		op->addr.mm = reg;
1159 		return;
1160 	}
1161 
1162 	op->type = OP_REG;
1163 	op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
1164 	op->addr.reg = decode_register(ctxt, reg, ctxt->d & ByteOp);
1165 
1166 	fetch_register_operand(op);
1167 	op->orig_val = op->val;
1168 }
1169 
1170 static void adjust_modrm_seg(struct x86_emulate_ctxt *ctxt, int base_reg)
1171 {
1172 	if (base_reg == VCPU_REGS_RSP || base_reg == VCPU_REGS_RBP)
1173 		ctxt->modrm_seg = VCPU_SREG_SS;
1174 }
1175 
1176 static int decode_modrm(struct x86_emulate_ctxt *ctxt,
1177 			struct operand *op)
1178 {
1179 	u8 sib;
1180 	int index_reg, base_reg, scale;
1181 	int rc = X86EMUL_CONTINUE;
1182 	ulong modrm_ea = 0;
1183 
1184 	ctxt->modrm_reg = ((ctxt->rex_prefix << 1) & 8); /* REX.R */
1185 	index_reg = (ctxt->rex_prefix << 2) & 8; /* REX.X */
1186 	base_reg = (ctxt->rex_prefix << 3) & 8; /* REX.B */
1187 
1188 	ctxt->modrm_mod = (ctxt->modrm & 0xc0) >> 6;
1189 	ctxt->modrm_reg |= (ctxt->modrm & 0x38) >> 3;
1190 	ctxt->modrm_rm = base_reg | (ctxt->modrm & 0x07);
1191 	ctxt->modrm_seg = VCPU_SREG_DS;
1192 
1193 	if (ctxt->modrm_mod == 3 || (ctxt->d & NoMod)) {
1194 		op->type = OP_REG;
1195 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
1196 		op->addr.reg = decode_register(ctxt, ctxt->modrm_rm,
1197 				ctxt->d & ByteOp);
1198 		if (ctxt->d & Sse) {
1199 			op->type = OP_XMM;
1200 			op->bytes = 16;
1201 			op->addr.xmm = ctxt->modrm_rm;
1202 			kvm_read_sse_reg(ctxt->modrm_rm, &op->vec_val);
1203 			return rc;
1204 		}
1205 		if (ctxt->d & Mmx) {
1206 			op->type = OP_MM;
1207 			op->bytes = 8;
1208 			op->addr.mm = ctxt->modrm_rm & 7;
1209 			return rc;
1210 		}
1211 		fetch_register_operand(op);
1212 		return rc;
1213 	}
1214 
1215 	op->type = OP_MEM;
1216 
1217 	if (ctxt->ad_bytes == 2) {
1218 		unsigned bx = reg_read(ctxt, VCPU_REGS_RBX);
1219 		unsigned bp = reg_read(ctxt, VCPU_REGS_RBP);
1220 		unsigned si = reg_read(ctxt, VCPU_REGS_RSI);
1221 		unsigned di = reg_read(ctxt, VCPU_REGS_RDI);
1222 
1223 		/* 16-bit ModR/M decode. */
1224 		switch (ctxt->modrm_mod) {
1225 		case 0:
1226 			if (ctxt->modrm_rm == 6)
1227 				modrm_ea += insn_fetch(u16, ctxt);
1228 			break;
1229 		case 1:
1230 			modrm_ea += insn_fetch(s8, ctxt);
1231 			break;
1232 		case 2:
1233 			modrm_ea += insn_fetch(u16, ctxt);
1234 			break;
1235 		}
1236 		switch (ctxt->modrm_rm) {
1237 		case 0:
1238 			modrm_ea += bx + si;
1239 			break;
1240 		case 1:
1241 			modrm_ea += bx + di;
1242 			break;
1243 		case 2:
1244 			modrm_ea += bp + si;
1245 			break;
1246 		case 3:
1247 			modrm_ea += bp + di;
1248 			break;
1249 		case 4:
1250 			modrm_ea += si;
1251 			break;
1252 		case 5:
1253 			modrm_ea += di;
1254 			break;
1255 		case 6:
1256 			if (ctxt->modrm_mod != 0)
1257 				modrm_ea += bp;
1258 			break;
1259 		case 7:
1260 			modrm_ea += bx;
1261 			break;
1262 		}
1263 		if (ctxt->modrm_rm == 2 || ctxt->modrm_rm == 3 ||
1264 		    (ctxt->modrm_rm == 6 && ctxt->modrm_mod != 0))
1265 			ctxt->modrm_seg = VCPU_SREG_SS;
1266 		modrm_ea = (u16)modrm_ea;
1267 	} else {
1268 		/* 32/64-bit ModR/M decode. */
1269 		if ((ctxt->modrm_rm & 7) == 4) {
1270 			sib = insn_fetch(u8, ctxt);
1271 			index_reg |= (sib >> 3) & 7;
1272 			base_reg |= sib & 7;
1273 			scale = sib >> 6;
1274 
1275 			if ((base_reg & 7) == 5 && ctxt->modrm_mod == 0)
1276 				modrm_ea += insn_fetch(s32, ctxt);
1277 			else {
1278 				modrm_ea += reg_read(ctxt, base_reg);
1279 				adjust_modrm_seg(ctxt, base_reg);
1280 				/* Increment ESP on POP [ESP] */
1281 				if ((ctxt->d & IncSP) &&
1282 				    base_reg == VCPU_REGS_RSP)
1283 					modrm_ea += ctxt->op_bytes;
1284 			}
1285 			if (index_reg != 4)
1286 				modrm_ea += reg_read(ctxt, index_reg) << scale;
1287 		} else if ((ctxt->modrm_rm & 7) == 5 && ctxt->modrm_mod == 0) {
1288 			modrm_ea += insn_fetch(s32, ctxt);
1289 			if (ctxt->mode == X86EMUL_MODE_PROT64)
1290 				ctxt->rip_relative = 1;
1291 		} else {
1292 			base_reg = ctxt->modrm_rm;
1293 			modrm_ea += reg_read(ctxt, base_reg);
1294 			adjust_modrm_seg(ctxt, base_reg);
1295 		}
1296 		switch (ctxt->modrm_mod) {
1297 		case 1:
1298 			modrm_ea += insn_fetch(s8, ctxt);
1299 			break;
1300 		case 2:
1301 			modrm_ea += insn_fetch(s32, ctxt);
1302 			break;
1303 		}
1304 	}
1305 	op->addr.mem.ea = modrm_ea;
1306 	if (ctxt->ad_bytes != 8)
1307 		ctxt->memop.addr.mem.ea = (u32)ctxt->memop.addr.mem.ea;
1308 
1309 done:
1310 	return rc;
1311 }
1312 
1313 static int decode_abs(struct x86_emulate_ctxt *ctxt,
1314 		      struct operand *op)
1315 {
1316 	int rc = X86EMUL_CONTINUE;
1317 
1318 	op->type = OP_MEM;
1319 	switch (ctxt->ad_bytes) {
1320 	case 2:
1321 		op->addr.mem.ea = insn_fetch(u16, ctxt);
1322 		break;
1323 	case 4:
1324 		op->addr.mem.ea = insn_fetch(u32, ctxt);
1325 		break;
1326 	case 8:
1327 		op->addr.mem.ea = insn_fetch(u64, ctxt);
1328 		break;
1329 	}
1330 done:
1331 	return rc;
1332 }
1333 
1334 static void fetch_bit_operand(struct x86_emulate_ctxt *ctxt)
1335 {
1336 	long sv = 0, mask;
1337 
1338 	if (ctxt->dst.type == OP_MEM && ctxt->src.type == OP_REG) {
1339 		mask = ~((long)ctxt->dst.bytes * 8 - 1);
1340 
1341 		if (ctxt->src.bytes == 2)
1342 			sv = (s16)ctxt->src.val & (s16)mask;
1343 		else if (ctxt->src.bytes == 4)
1344 			sv = (s32)ctxt->src.val & (s32)mask;
1345 		else
1346 			sv = (s64)ctxt->src.val & (s64)mask;
1347 
1348 		ctxt->dst.addr.mem.ea = address_mask(ctxt,
1349 					   ctxt->dst.addr.mem.ea + (sv >> 3));
1350 	}
1351 
1352 	/* only subword offset */
1353 	ctxt->src.val &= (ctxt->dst.bytes << 3) - 1;
1354 }
1355 
1356 static int read_emulated(struct x86_emulate_ctxt *ctxt,
1357 			 unsigned long addr, void *dest, unsigned size)
1358 {
1359 	int rc;
1360 	struct read_cache *mc = &ctxt->mem_read;
1361 
1362 	if (mc->pos < mc->end)
1363 		goto read_cached;
1364 
1365 	if (KVM_EMULATOR_BUG_ON((mc->end + size) >= sizeof(mc->data), ctxt))
1366 		return X86EMUL_UNHANDLEABLE;
1367 
1368 	rc = ctxt->ops->read_emulated(ctxt, addr, mc->data + mc->end, size,
1369 				      &ctxt->exception);
1370 	if (rc != X86EMUL_CONTINUE)
1371 		return rc;
1372 
1373 	mc->end += size;
1374 
1375 read_cached:
1376 	memcpy(dest, mc->data + mc->pos, size);
1377 	mc->pos += size;
1378 	return X86EMUL_CONTINUE;
1379 }
1380 
1381 static int segmented_read(struct x86_emulate_ctxt *ctxt,
1382 			  struct segmented_address addr,
1383 			  void *data,
1384 			  unsigned size)
1385 {
1386 	int rc;
1387 	ulong linear;
1388 
1389 	rc = linearize(ctxt, addr, size, false, &linear);
1390 	if (rc != X86EMUL_CONTINUE)
1391 		return rc;
1392 	return read_emulated(ctxt, linear, data, size);
1393 }
1394 
1395 static int segmented_write(struct x86_emulate_ctxt *ctxt,
1396 			   struct segmented_address addr,
1397 			   const void *data,
1398 			   unsigned size)
1399 {
1400 	int rc;
1401 	ulong linear;
1402 
1403 	rc = linearize(ctxt, addr, size, true, &linear);
1404 	if (rc != X86EMUL_CONTINUE)
1405 		return rc;
1406 	return ctxt->ops->write_emulated(ctxt, linear, data, size,
1407 					 &ctxt->exception);
1408 }
1409 
1410 static int segmented_cmpxchg(struct x86_emulate_ctxt *ctxt,
1411 			     struct segmented_address addr,
1412 			     const void *orig_data, const void *data,
1413 			     unsigned size)
1414 {
1415 	int rc;
1416 	ulong linear;
1417 
1418 	rc = linearize(ctxt, addr, size, true, &linear);
1419 	if (rc != X86EMUL_CONTINUE)
1420 		return rc;
1421 	return ctxt->ops->cmpxchg_emulated(ctxt, linear, orig_data, data,
1422 					   size, &ctxt->exception);
1423 }
1424 
1425 static int pio_in_emulated(struct x86_emulate_ctxt *ctxt,
1426 			   unsigned int size, unsigned short port,
1427 			   void *dest)
1428 {
1429 	struct read_cache *rc = &ctxt->io_read;
1430 
1431 	if (rc->pos == rc->end) { /* refill pio read ahead */
1432 		unsigned int in_page, n;
1433 		unsigned int count = ctxt->rep_prefix ?
1434 			address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) : 1;
1435 		in_page = (ctxt->eflags & X86_EFLAGS_DF) ?
1436 			offset_in_page(reg_read(ctxt, VCPU_REGS_RDI)) :
1437 			PAGE_SIZE - offset_in_page(reg_read(ctxt, VCPU_REGS_RDI));
1438 		n = min3(in_page, (unsigned int)sizeof(rc->data) / size, count);
1439 		if (n == 0)
1440 			n = 1;
1441 		rc->pos = rc->end = 0;
1442 		if (!ctxt->ops->pio_in_emulated(ctxt, size, port, rc->data, n))
1443 			return 0;
1444 		rc->end = n * size;
1445 	}
1446 
1447 	if (ctxt->rep_prefix && (ctxt->d & String) &&
1448 	    !(ctxt->eflags & X86_EFLAGS_DF)) {
1449 		ctxt->dst.data = rc->data + rc->pos;
1450 		ctxt->dst.type = OP_MEM_STR;
1451 		ctxt->dst.count = (rc->end - rc->pos) / size;
1452 		rc->pos = rc->end;
1453 	} else {
1454 		memcpy(dest, rc->data + rc->pos, size);
1455 		rc->pos += size;
1456 	}
1457 	return 1;
1458 }
1459 
1460 static int read_interrupt_descriptor(struct x86_emulate_ctxt *ctxt,
1461 				     u16 index, struct desc_struct *desc)
1462 {
1463 	struct desc_ptr dt;
1464 	ulong addr;
1465 
1466 	ctxt->ops->get_idt(ctxt, &dt);
1467 
1468 	if (dt.size < index * 8 + 7)
1469 		return emulate_gp(ctxt, index << 3 | 0x2);
1470 
1471 	addr = dt.address + index * 8;
1472 	return linear_read_system(ctxt, addr, desc, sizeof(*desc));
1473 }
1474 
1475 static void get_descriptor_table_ptr(struct x86_emulate_ctxt *ctxt,
1476 				     u16 selector, struct desc_ptr *dt)
1477 {
1478 	const struct x86_emulate_ops *ops = ctxt->ops;
1479 	u32 base3 = 0;
1480 
1481 	if (selector & 1 << 2) {
1482 		struct desc_struct desc;
1483 		u16 sel;
1484 
1485 		memset(dt, 0, sizeof(*dt));
1486 		if (!ops->get_segment(ctxt, &sel, &desc, &base3,
1487 				      VCPU_SREG_LDTR))
1488 			return;
1489 
1490 		dt->size = desc_limit_scaled(&desc); /* what if limit > 65535? */
1491 		dt->address = get_desc_base(&desc) | ((u64)base3 << 32);
1492 	} else
1493 		ops->get_gdt(ctxt, dt);
1494 }
1495 
1496 static int get_descriptor_ptr(struct x86_emulate_ctxt *ctxt,
1497 			      u16 selector, ulong *desc_addr_p)
1498 {
1499 	struct desc_ptr dt;
1500 	u16 index = selector >> 3;
1501 	ulong addr;
1502 
1503 	get_descriptor_table_ptr(ctxt, selector, &dt);
1504 
1505 	if (dt.size < index * 8 + 7)
1506 		return emulate_gp(ctxt, selector & 0xfffc);
1507 
1508 	addr = dt.address + index * 8;
1509 
1510 #ifdef CONFIG_X86_64
1511 	if (addr >> 32 != 0) {
1512 		u64 efer = 0;
1513 
1514 		ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
1515 		if (!(efer & EFER_LMA))
1516 			addr &= (u32)-1;
1517 	}
1518 #endif
1519 
1520 	*desc_addr_p = addr;
1521 	return X86EMUL_CONTINUE;
1522 }
1523 
1524 /* allowed just for 8 bytes segments */
1525 static int read_segment_descriptor(struct x86_emulate_ctxt *ctxt,
1526 				   u16 selector, struct desc_struct *desc,
1527 				   ulong *desc_addr_p)
1528 {
1529 	int rc;
1530 
1531 	rc = get_descriptor_ptr(ctxt, selector, desc_addr_p);
1532 	if (rc != X86EMUL_CONTINUE)
1533 		return rc;
1534 
1535 	return linear_read_system(ctxt, *desc_addr_p, desc, sizeof(*desc));
1536 }
1537 
1538 /* allowed just for 8 bytes segments */
1539 static int write_segment_descriptor(struct x86_emulate_ctxt *ctxt,
1540 				    u16 selector, struct desc_struct *desc)
1541 {
1542 	int rc;
1543 	ulong addr;
1544 
1545 	rc = get_descriptor_ptr(ctxt, selector, &addr);
1546 	if (rc != X86EMUL_CONTINUE)
1547 		return rc;
1548 
1549 	return linear_write_system(ctxt, addr, desc, sizeof(*desc));
1550 }
1551 
1552 static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
1553 				     u16 selector, int seg, u8 cpl,
1554 				     enum x86_transfer_type transfer,
1555 				     struct desc_struct *desc)
1556 {
1557 	struct desc_struct seg_desc, old_desc;
1558 	u8 dpl, rpl;
1559 	unsigned err_vec = GP_VECTOR;
1560 	u32 err_code = 0;
1561 	bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */
1562 	ulong desc_addr;
1563 	int ret;
1564 	u16 dummy;
1565 	u32 base3 = 0;
1566 
1567 	memset(&seg_desc, 0, sizeof(seg_desc));
1568 
1569 	if (ctxt->mode == X86EMUL_MODE_REAL) {
1570 		/* set real mode segment descriptor (keep limit etc. for
1571 		 * unreal mode) */
1572 		ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg);
1573 		set_desc_base(&seg_desc, selector << 4);
1574 		goto load;
1575 	} else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) {
1576 		/* VM86 needs a clean new segment descriptor */
1577 		set_desc_base(&seg_desc, selector << 4);
1578 		set_desc_limit(&seg_desc, 0xffff);
1579 		seg_desc.type = 3;
1580 		seg_desc.p = 1;
1581 		seg_desc.s = 1;
1582 		seg_desc.dpl = 3;
1583 		goto load;
1584 	}
1585 
1586 	rpl = selector & 3;
1587 
1588 	/* TR should be in GDT only */
1589 	if (seg == VCPU_SREG_TR && (selector & (1 << 2)))
1590 		goto exception;
1591 
1592 	/* NULL selector is not valid for TR, CS and (except for long mode) SS */
1593 	if (null_selector) {
1594 		if (seg == VCPU_SREG_CS || seg == VCPU_SREG_TR)
1595 			goto exception;
1596 
1597 		if (seg == VCPU_SREG_SS) {
1598 			if (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl)
1599 				goto exception;
1600 
1601 			/*
1602 			 * ctxt->ops->set_segment expects the CPL to be in
1603 			 * SS.DPL, so fake an expand-up 32-bit data segment.
1604 			 */
1605 			seg_desc.type = 3;
1606 			seg_desc.p = 1;
1607 			seg_desc.s = 1;
1608 			seg_desc.dpl = cpl;
1609 			seg_desc.d = 1;
1610 			seg_desc.g = 1;
1611 		}
1612 
1613 		/* Skip all following checks */
1614 		goto load;
1615 	}
1616 
1617 	ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr);
1618 	if (ret != X86EMUL_CONTINUE)
1619 		return ret;
1620 
1621 	err_code = selector & 0xfffc;
1622 	err_vec = (transfer == X86_TRANSFER_TASK_SWITCH) ? TS_VECTOR :
1623 							   GP_VECTOR;
1624 
1625 	/* can't load system descriptor into segment selector */
1626 	if (seg <= VCPU_SREG_GS && !seg_desc.s) {
1627 		if (transfer == X86_TRANSFER_CALL_JMP)
1628 			return X86EMUL_UNHANDLEABLE;
1629 		goto exception;
1630 	}
1631 
1632 	dpl = seg_desc.dpl;
1633 
1634 	switch (seg) {
1635 	case VCPU_SREG_SS:
1636 		/*
1637 		 * segment is not a writable data segment or segment
1638 		 * selector's RPL != CPL or DPL != CPL
1639 		 */
1640 		if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl)
1641 			goto exception;
1642 		break;
1643 	case VCPU_SREG_CS:
1644 		/*
1645 		 * KVM uses "none" when loading CS as part of emulating Real
1646 		 * Mode exceptions and IRET (handled above).  In all other
1647 		 * cases, loading CS without a control transfer is a KVM bug.
1648 		 */
1649 		if (WARN_ON_ONCE(transfer == X86_TRANSFER_NONE))
1650 			goto exception;
1651 
1652 		if (!(seg_desc.type & 8))
1653 			goto exception;
1654 
1655 		if (transfer == X86_TRANSFER_RET) {
1656 			/* RET can never return to an inner privilege level. */
1657 			if (rpl < cpl)
1658 				goto exception;
1659 			/* Outer-privilege level return is not implemented */
1660 			if (rpl > cpl)
1661 				return X86EMUL_UNHANDLEABLE;
1662 		}
1663 		if (transfer == X86_TRANSFER_RET || transfer == X86_TRANSFER_TASK_SWITCH) {
1664 			if (seg_desc.type & 4) {
1665 				/* conforming */
1666 				if (dpl > rpl)
1667 					goto exception;
1668 			} else {
1669 				/* nonconforming */
1670 				if (dpl != rpl)
1671 					goto exception;
1672 			}
1673 		} else { /* X86_TRANSFER_CALL_JMP */
1674 			if (seg_desc.type & 4) {
1675 				/* conforming */
1676 				if (dpl > cpl)
1677 					goto exception;
1678 			} else {
1679 				/* nonconforming */
1680 				if (rpl > cpl || dpl != cpl)
1681 					goto exception;
1682 			}
1683 		}
1684 		/* in long-mode d/b must be clear if l is set */
1685 		if (seg_desc.d && seg_desc.l) {
1686 			u64 efer = 0;
1687 
1688 			ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
1689 			if (efer & EFER_LMA)
1690 				goto exception;
1691 		}
1692 
1693 		/* CS(RPL) <- CPL */
1694 		selector = (selector & 0xfffc) | cpl;
1695 		break;
1696 	case VCPU_SREG_TR:
1697 		if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9))
1698 			goto exception;
1699 		break;
1700 	case VCPU_SREG_LDTR:
1701 		if (seg_desc.s || seg_desc.type != 2)
1702 			goto exception;
1703 		break;
1704 	default: /*  DS, ES, FS, or GS */
1705 		/*
1706 		 * segment is not a data or readable code segment or
1707 		 * ((segment is a data or nonconforming code segment)
1708 		 * and ((RPL > DPL) or (CPL > DPL)))
1709 		 */
1710 		if ((seg_desc.type & 0xa) == 0x8 ||
1711 		    (((seg_desc.type & 0xc) != 0xc) &&
1712 		     (rpl > dpl || cpl > dpl)))
1713 			goto exception;
1714 		break;
1715 	}
1716 
1717 	if (!seg_desc.p) {
1718 		err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR;
1719 		goto exception;
1720 	}
1721 
1722 	if (seg_desc.s) {
1723 		/* mark segment as accessed */
1724 		if (!(seg_desc.type & 1)) {
1725 			seg_desc.type |= 1;
1726 			ret = write_segment_descriptor(ctxt, selector,
1727 						       &seg_desc);
1728 			if (ret != X86EMUL_CONTINUE)
1729 				return ret;
1730 		}
1731 	} else if (ctxt->mode == X86EMUL_MODE_PROT64) {
1732 		ret = linear_read_system(ctxt, desc_addr+8, &base3, sizeof(base3));
1733 		if (ret != X86EMUL_CONTINUE)
1734 			return ret;
1735 		if (emul_is_noncanonical_address(get_desc_base(&seg_desc) |
1736 						 ((u64)base3 << 32), ctxt))
1737 			return emulate_gp(ctxt, err_code);
1738 	}
1739 
1740 	if (seg == VCPU_SREG_TR) {
1741 		old_desc = seg_desc;
1742 		seg_desc.type |= 2; /* busy */
1743 		ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc,
1744 						  sizeof(seg_desc), &ctxt->exception);
1745 		if (ret != X86EMUL_CONTINUE)
1746 			return ret;
1747 	}
1748 load:
1749 	ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg);
1750 	if (desc)
1751 		*desc = seg_desc;
1752 	return X86EMUL_CONTINUE;
1753 exception:
1754 	return emulate_exception(ctxt, err_vec, err_code, true);
1755 }
1756 
1757 static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt,
1758 				   u16 selector, int seg)
1759 {
1760 	u8 cpl = ctxt->ops->cpl(ctxt);
1761 
1762 	/*
1763 	 * None of MOV, POP and LSS can load a NULL selector in CPL=3, but
1764 	 * they can load it at CPL<3 (Intel's manual says only LSS can,
1765 	 * but it's wrong).
1766 	 *
1767 	 * However, the Intel manual says that putting IST=1/DPL=3 in
1768 	 * an interrupt gate will result in SS=3 (the AMD manual instead
1769 	 * says it doesn't), so allow SS=3 in __load_segment_descriptor
1770 	 * and only forbid it here.
1771 	 */
1772 	if (seg == VCPU_SREG_SS && selector == 3 &&
1773 	    ctxt->mode == X86EMUL_MODE_PROT64)
1774 		return emulate_exception(ctxt, GP_VECTOR, 0, true);
1775 
1776 	return __load_segment_descriptor(ctxt, selector, seg, cpl,
1777 					 X86_TRANSFER_NONE, NULL);
1778 }
1779 
1780 static void write_register_operand(struct operand *op)
1781 {
1782 	return assign_register(op->addr.reg, op->val, op->bytes);
1783 }
1784 
1785 static int writeback(struct x86_emulate_ctxt *ctxt, struct operand *op)
1786 {
1787 	switch (op->type) {
1788 	case OP_REG:
1789 		write_register_operand(op);
1790 		break;
1791 	case OP_MEM:
1792 		if (ctxt->lock_prefix)
1793 			return segmented_cmpxchg(ctxt,
1794 						 op->addr.mem,
1795 						 &op->orig_val,
1796 						 &op->val,
1797 						 op->bytes);
1798 		else
1799 			return segmented_write(ctxt,
1800 					       op->addr.mem,
1801 					       &op->val,
1802 					       op->bytes);
1803 	case OP_MEM_STR:
1804 		return segmented_write(ctxt,
1805 				       op->addr.mem,
1806 				       op->data,
1807 				       op->bytes * op->count);
1808 	case OP_XMM:
1809 		kvm_write_sse_reg(op->addr.xmm, &op->vec_val);
1810 		break;
1811 	case OP_MM:
1812 		kvm_write_mmx_reg(op->addr.mm, &op->mm_val);
1813 		break;
1814 	case OP_NONE:
1815 		/* no writeback */
1816 		break;
1817 	default:
1818 		break;
1819 	}
1820 	return X86EMUL_CONTINUE;
1821 }
1822 
1823 static int emulate_push(struct x86_emulate_ctxt *ctxt, const void *data, int len)
1824 {
1825 	struct segmented_address addr;
1826 
1827 	rsp_increment(ctxt, -len);
1828 	addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt);
1829 	addr.seg = VCPU_SREG_SS;
1830 
1831 	return segmented_write(ctxt, addr, data, len);
1832 }
1833 
1834 static int em_push(struct x86_emulate_ctxt *ctxt)
1835 {
1836 	/* Disable writeback. */
1837 	ctxt->dst.type = OP_NONE;
1838 	return emulate_push(ctxt, &ctxt->src.val, ctxt->op_bytes);
1839 }
1840 
1841 static int emulate_pop(struct x86_emulate_ctxt *ctxt,
1842 		       void *dest, int len)
1843 {
1844 	int rc;
1845 	struct segmented_address addr;
1846 
1847 	addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt);
1848 	addr.seg = VCPU_SREG_SS;
1849 	rc = segmented_read(ctxt, addr, dest, len);
1850 	if (rc != X86EMUL_CONTINUE)
1851 		return rc;
1852 
1853 	rsp_increment(ctxt, len);
1854 	return rc;
1855 }
1856 
1857 static int em_pop(struct x86_emulate_ctxt *ctxt)
1858 {
1859 	return emulate_pop(ctxt, &ctxt->dst.val, ctxt->op_bytes);
1860 }
1861 
1862 static int emulate_popf(struct x86_emulate_ctxt *ctxt,
1863 			void *dest, int len)
1864 {
1865 	int rc;
1866 	unsigned long val = 0;
1867 	unsigned long 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 = emulate_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 = 0;
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 = 0;
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 = 0;
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 = 0;
2246 	unsigned long cs = 0;
2247 	int cpl = ctxt->ops->cpl(ctxt);
2248 	struct desc_struct new_desc;
2249 
2250 	rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
2251 	if (rc != X86EMUL_CONTINUE)
2252 		return rc;
2253 	rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
2254 	if (rc != X86EMUL_CONTINUE)
2255 		return rc;
2256 	rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, cpl,
2257 				       X86_TRANSFER_RET,
2258 				       &new_desc);
2259 	if (rc != X86EMUL_CONTINUE)
2260 		return rc;
2261 	rc = assign_eip_far(ctxt, eip);
2262 	/* Error handling is not implemented. */
2263 	if (rc != X86EMUL_CONTINUE)
2264 		return X86EMUL_UNHANDLEABLE;
2265 
2266 	return rc;
2267 }
2268 
2269 static int em_ret_far_imm(struct x86_emulate_ctxt *ctxt)
2270 {
2271         int rc;
2272 
2273         rc = em_ret_far(ctxt);
2274         if (rc != X86EMUL_CONTINUE)
2275                 return rc;
2276         rsp_increment(ctxt, ctxt->src.val);
2277         return X86EMUL_CONTINUE;
2278 }
2279 
2280 static int em_cmpxchg(struct x86_emulate_ctxt *ctxt)
2281 {
2282 	/* Save real source value, then compare EAX against destination. */
2283 	ctxt->dst.orig_val = ctxt->dst.val;
2284 	ctxt->dst.val = reg_read(ctxt, VCPU_REGS_RAX);
2285 	ctxt->src.orig_val = ctxt->src.val;
2286 	ctxt->src.val = ctxt->dst.orig_val;
2287 	fastop(ctxt, em_cmp);
2288 
2289 	if (ctxt->eflags & X86_EFLAGS_ZF) {
2290 		/* Success: write back to memory; no update of EAX */
2291 		ctxt->src.type = OP_NONE;
2292 		ctxt->dst.val = ctxt->src.orig_val;
2293 	} else {
2294 		/* Failure: write the value we saw to EAX. */
2295 		ctxt->src.type = OP_REG;
2296 		ctxt->src.addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
2297 		ctxt->src.val = ctxt->dst.orig_val;
2298 		/* Create write-cycle to dest by writing the same value */
2299 		ctxt->dst.val = ctxt->dst.orig_val;
2300 	}
2301 	return X86EMUL_CONTINUE;
2302 }
2303 
2304 static int em_lseg(struct x86_emulate_ctxt *ctxt)
2305 {
2306 	int seg = ctxt->src2.val;
2307 	unsigned short sel;
2308 	int rc;
2309 
2310 	memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
2311 
2312 	rc = load_segment_descriptor(ctxt, sel, seg);
2313 	if (rc != X86EMUL_CONTINUE)
2314 		return rc;
2315 
2316 	ctxt->dst.val = ctxt->src.val;
2317 	return rc;
2318 }
2319 
2320 static int em_rsm(struct x86_emulate_ctxt *ctxt)
2321 {
2322 	if (!ctxt->ops->is_smm(ctxt))
2323 		return emulate_ud(ctxt);
2324 
2325 	if (ctxt->ops->leave_smm(ctxt))
2326 		ctxt->ops->triple_fault(ctxt);
2327 
2328 	return emulator_recalc_and_set_mode(ctxt);
2329 }
2330 
2331 static void
2332 setup_syscalls_segments(struct desc_struct *cs, struct desc_struct *ss)
2333 {
2334 	cs->l = 0;		/* will be adjusted later */
2335 	set_desc_base(cs, 0);	/* flat segment */
2336 	cs->g = 1;		/* 4kb granularity */
2337 	set_desc_limit(cs, 0xfffff);	/* 4GB limit */
2338 	cs->type = 0x0b;	/* Read, Execute, Accessed */
2339 	cs->s = 1;
2340 	cs->dpl = 0;		/* will be adjusted later */
2341 	cs->p = 1;
2342 	cs->d = 1;
2343 	cs->avl = 0;
2344 
2345 	set_desc_base(ss, 0);	/* flat segment */
2346 	set_desc_limit(ss, 0xfffff);	/* 4GB limit */
2347 	ss->g = 1;		/* 4kb granularity */
2348 	ss->s = 1;
2349 	ss->type = 0x03;	/* Read/Write, Accessed */
2350 	ss->d = 1;		/* 32bit stack segment */
2351 	ss->dpl = 0;
2352 	ss->p = 1;
2353 	ss->l = 0;
2354 	ss->avl = 0;
2355 }
2356 
2357 static int em_syscall(struct x86_emulate_ctxt *ctxt)
2358 {
2359 	const struct x86_emulate_ops *ops = ctxt->ops;
2360 	struct desc_struct cs, ss;
2361 	u64 msr_data;
2362 	u16 cs_sel, ss_sel;
2363 	u64 efer = 0;
2364 
2365 	/* syscall is not available in real mode */
2366 	if (ctxt->mode == X86EMUL_MODE_REAL ||
2367 	    ctxt->mode == X86EMUL_MODE_VM86)
2368 		return emulate_ud(ctxt);
2369 
2370 	/*
2371 	 * Intel compatible CPUs only support SYSCALL in 64-bit mode, whereas
2372 	 * AMD allows SYSCALL in any flavor of protected mode.  Note, it's
2373 	 * infeasible to emulate Intel behavior when running on AMD hardware,
2374 	 * as SYSCALL won't fault in the "wrong" mode, i.e. there is no #UD
2375 	 * for KVM to trap-and-emulate, unlike emulating AMD on Intel.
2376 	 */
2377 	if (ctxt->mode != X86EMUL_MODE_PROT64 &&
2378 	    ctxt->ops->guest_cpuid_is_intel_compatible(ctxt))
2379 		return emulate_ud(ctxt);
2380 
2381 	ops->get_msr(ctxt, MSR_EFER, &efer);
2382 	if (!(efer & EFER_SCE))
2383 		return emulate_ud(ctxt);
2384 
2385 	setup_syscalls_segments(&cs, &ss);
2386 	ops->get_msr(ctxt, MSR_STAR, &msr_data);
2387 	msr_data >>= 32;
2388 	cs_sel = (u16)(msr_data & 0xfffc);
2389 	ss_sel = (u16)(msr_data + 8);
2390 
2391 	if (efer & EFER_LMA) {
2392 		cs.d = 0;
2393 		cs.l = 1;
2394 	}
2395 	ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
2396 	ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
2397 
2398 	*reg_write(ctxt, VCPU_REGS_RCX) = ctxt->_eip;
2399 	if (efer & EFER_LMA) {
2400 #ifdef CONFIG_X86_64
2401 		*reg_write(ctxt, VCPU_REGS_R11) = ctxt->eflags;
2402 
2403 		ops->get_msr(ctxt,
2404 			     ctxt->mode == X86EMUL_MODE_PROT64 ?
2405 			     MSR_LSTAR : MSR_CSTAR, &msr_data);
2406 		ctxt->_eip = msr_data;
2407 
2408 		ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data);
2409 		ctxt->eflags &= ~msr_data;
2410 		ctxt->eflags |= X86_EFLAGS_FIXED;
2411 #endif
2412 	} else {
2413 		/* legacy mode */
2414 		ops->get_msr(ctxt, MSR_STAR, &msr_data);
2415 		ctxt->_eip = (u32)msr_data;
2416 
2417 		ctxt->eflags &= ~(X86_EFLAGS_VM | X86_EFLAGS_IF);
2418 	}
2419 
2420 	ctxt->tf = (ctxt->eflags & X86_EFLAGS_TF) != 0;
2421 	return X86EMUL_CONTINUE;
2422 }
2423 
2424 static int em_sysenter(struct x86_emulate_ctxt *ctxt)
2425 {
2426 	const struct x86_emulate_ops *ops = ctxt->ops;
2427 	struct desc_struct cs, ss;
2428 	u64 msr_data;
2429 	u16 cs_sel, ss_sel;
2430 	u64 efer = 0;
2431 
2432 	ops->get_msr(ctxt, MSR_EFER, &efer);
2433 	/* inject #GP if in real mode */
2434 	if (ctxt->mode == X86EMUL_MODE_REAL)
2435 		return emulate_gp(ctxt, 0);
2436 
2437 	/*
2438 	 * Intel's architecture allows SYSENTER in compatibility mode, but AMD
2439 	 * does not.  Note, AMD does allow SYSENTER in legacy protected mode.
2440 	 */
2441 	if ((ctxt->mode != X86EMUL_MODE_PROT64) && (efer & EFER_LMA) &&
2442 	    !ctxt->ops->guest_cpuid_is_intel_compatible(ctxt))
2443 		return emulate_ud(ctxt);
2444 
2445 	/* sysenter/sysexit have not been tested in 64bit mode. */
2446 	if (ctxt->mode == X86EMUL_MODE_PROT64)
2447 		return X86EMUL_UNHANDLEABLE;
2448 
2449 	ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
2450 	if ((msr_data & 0xfffc) == 0x0)
2451 		return emulate_gp(ctxt, 0);
2452 
2453 	setup_syscalls_segments(&cs, &ss);
2454 	ctxt->eflags &= ~(X86_EFLAGS_VM | X86_EFLAGS_IF);
2455 	cs_sel = (u16)msr_data & ~SEGMENT_RPL_MASK;
2456 	ss_sel = cs_sel + 8;
2457 	if (efer & EFER_LMA) {
2458 		cs.d = 0;
2459 		cs.l = 1;
2460 	}
2461 
2462 	ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
2463 	ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
2464 
2465 	ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data);
2466 	ctxt->_eip = (efer & EFER_LMA) ? msr_data : (u32)msr_data;
2467 
2468 	ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data);
2469 	*reg_write(ctxt, VCPU_REGS_RSP) = (efer & EFER_LMA) ? msr_data :
2470 							      (u32)msr_data;
2471 	if (efer & EFER_LMA)
2472 		ctxt->mode = X86EMUL_MODE_PROT64;
2473 
2474 	return X86EMUL_CONTINUE;
2475 }
2476 
2477 static int em_sysexit(struct x86_emulate_ctxt *ctxt)
2478 {
2479 	const struct x86_emulate_ops *ops = ctxt->ops;
2480 	struct desc_struct cs, ss;
2481 	u64 msr_data, rcx, rdx;
2482 	int usermode;
2483 	u16 cs_sel = 0, ss_sel = 0;
2484 
2485 	/* inject #GP if in real mode or Virtual 8086 mode */
2486 	if (ctxt->mode == X86EMUL_MODE_REAL ||
2487 	    ctxt->mode == X86EMUL_MODE_VM86)
2488 		return emulate_gp(ctxt, 0);
2489 
2490 	setup_syscalls_segments(&cs, &ss);
2491 
2492 	if ((ctxt->rex_prefix & 0x8) != 0x0)
2493 		usermode = X86EMUL_MODE_PROT64;
2494 	else
2495 		usermode = X86EMUL_MODE_PROT32;
2496 
2497 	rcx = reg_read(ctxt, VCPU_REGS_RCX);
2498 	rdx = reg_read(ctxt, VCPU_REGS_RDX);
2499 
2500 	cs.dpl = 3;
2501 	ss.dpl = 3;
2502 	ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
2503 	switch (usermode) {
2504 	case X86EMUL_MODE_PROT32:
2505 		cs_sel = (u16)(msr_data + 16);
2506 		if ((msr_data & 0xfffc) == 0x0)
2507 			return emulate_gp(ctxt, 0);
2508 		ss_sel = (u16)(msr_data + 24);
2509 		rcx = (u32)rcx;
2510 		rdx = (u32)rdx;
2511 		break;
2512 	case X86EMUL_MODE_PROT64:
2513 		cs_sel = (u16)(msr_data + 32);
2514 		if (msr_data == 0x0)
2515 			return emulate_gp(ctxt, 0);
2516 		ss_sel = cs_sel + 8;
2517 		cs.d = 0;
2518 		cs.l = 1;
2519 		if (emul_is_noncanonical_address(rcx, ctxt) ||
2520 		    emul_is_noncanonical_address(rdx, ctxt))
2521 			return emulate_gp(ctxt, 0);
2522 		break;
2523 	}
2524 	cs_sel |= SEGMENT_RPL_MASK;
2525 	ss_sel |= SEGMENT_RPL_MASK;
2526 
2527 	ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
2528 	ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
2529 
2530 	ctxt->_eip = rdx;
2531 	ctxt->mode = usermode;
2532 	*reg_write(ctxt, VCPU_REGS_RSP) = rcx;
2533 
2534 	return X86EMUL_CONTINUE;
2535 }
2536 
2537 static bool emulator_bad_iopl(struct x86_emulate_ctxt *ctxt)
2538 {
2539 	int iopl;
2540 	if (ctxt->mode == X86EMUL_MODE_REAL)
2541 		return false;
2542 	if (ctxt->mode == X86EMUL_MODE_VM86)
2543 		return true;
2544 	iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> X86_EFLAGS_IOPL_BIT;
2545 	return ctxt->ops->cpl(ctxt) > iopl;
2546 }
2547 
2548 #define VMWARE_PORT_VMPORT	(0x5658)
2549 #define VMWARE_PORT_VMRPC	(0x5659)
2550 
2551 static bool emulator_io_port_access_allowed(struct x86_emulate_ctxt *ctxt,
2552 					    u16 port, u16 len)
2553 {
2554 	const struct x86_emulate_ops *ops = ctxt->ops;
2555 	struct desc_struct tr_seg;
2556 	u32 base3;
2557 	int r;
2558 	u16 tr, io_bitmap_ptr, perm, bit_idx = port & 0x7;
2559 	unsigned mask = (1 << len) - 1;
2560 	unsigned long base;
2561 
2562 	/*
2563 	 * VMware allows access to these ports even if denied
2564 	 * by TSS I/O permission bitmap. Mimic behavior.
2565 	 */
2566 	if (enable_vmware_backdoor &&
2567 	    ((port == VMWARE_PORT_VMPORT) || (port == VMWARE_PORT_VMRPC)))
2568 		return true;
2569 
2570 	ops->get_segment(ctxt, &tr, &tr_seg, &base3, VCPU_SREG_TR);
2571 	if (!tr_seg.p)
2572 		return false;
2573 	if (desc_limit_scaled(&tr_seg) < 103)
2574 		return false;
2575 	base = get_desc_base(&tr_seg);
2576 #ifdef CONFIG_X86_64
2577 	base |= ((u64)base3) << 32;
2578 #endif
2579 	r = ops->read_std(ctxt, base + 102, &io_bitmap_ptr, 2, NULL, true);
2580 	if (r != X86EMUL_CONTINUE)
2581 		return false;
2582 	if (io_bitmap_ptr + port/8 > desc_limit_scaled(&tr_seg))
2583 		return false;
2584 	r = ops->read_std(ctxt, base + io_bitmap_ptr + port/8, &perm, 2, NULL, true);
2585 	if (r != X86EMUL_CONTINUE)
2586 		return false;
2587 	if ((perm >> bit_idx) & mask)
2588 		return false;
2589 	return true;
2590 }
2591 
2592 static bool emulator_io_permitted(struct x86_emulate_ctxt *ctxt,
2593 				  u16 port, u16 len)
2594 {
2595 	if (ctxt->perm_ok)
2596 		return true;
2597 
2598 	if (emulator_bad_iopl(ctxt))
2599 		if (!emulator_io_port_access_allowed(ctxt, port, len))
2600 			return false;
2601 
2602 	ctxt->perm_ok = true;
2603 
2604 	return true;
2605 }
2606 
2607 static void string_registers_quirk(struct x86_emulate_ctxt *ctxt)
2608 {
2609 	/*
2610 	 * Intel CPUs mask the counter and pointers in quite strange
2611 	 * manner when ECX is zero due to REP-string optimizations.
2612 	 */
2613 #ifdef CONFIG_X86_64
2614 	u32 eax, ebx, ecx, edx;
2615 
2616 	if (ctxt->ad_bytes != 4)
2617 		return;
2618 
2619 	eax = ecx = 0;
2620 	ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx, true);
2621 	if (!is_guest_vendor_intel(ebx, ecx, edx))
2622 		return;
2623 
2624 	*reg_write(ctxt, VCPU_REGS_RCX) = 0;
2625 
2626 	switch (ctxt->b) {
2627 	case 0xa4:	/* movsb */
2628 	case 0xa5:	/* movsd/w */
2629 		*reg_rmw(ctxt, VCPU_REGS_RSI) &= (u32)-1;
2630 		fallthrough;
2631 	case 0xaa:	/* stosb */
2632 	case 0xab:	/* stosd/w */
2633 		*reg_rmw(ctxt, VCPU_REGS_RDI) &= (u32)-1;
2634 	}
2635 #endif
2636 }
2637 
2638 static void save_state_to_tss16(struct x86_emulate_ctxt *ctxt,
2639 				struct tss_segment_16 *tss)
2640 {
2641 	tss->ip = ctxt->_eip;
2642 	tss->flag = ctxt->eflags;
2643 	tss->ax = reg_read(ctxt, VCPU_REGS_RAX);
2644 	tss->cx = reg_read(ctxt, VCPU_REGS_RCX);
2645 	tss->dx = reg_read(ctxt, VCPU_REGS_RDX);
2646 	tss->bx = reg_read(ctxt, VCPU_REGS_RBX);
2647 	tss->sp = reg_read(ctxt, VCPU_REGS_RSP);
2648 	tss->bp = reg_read(ctxt, VCPU_REGS_RBP);
2649 	tss->si = reg_read(ctxt, VCPU_REGS_RSI);
2650 	tss->di = reg_read(ctxt, VCPU_REGS_RDI);
2651 
2652 	tss->es = get_segment_selector(ctxt, VCPU_SREG_ES);
2653 	tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS);
2654 	tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS);
2655 	tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS);
2656 	tss->ldt = get_segment_selector(ctxt, VCPU_SREG_LDTR);
2657 }
2658 
2659 static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt,
2660 				 struct tss_segment_16 *tss)
2661 {
2662 	int ret;
2663 	u8 cpl;
2664 
2665 	ctxt->_eip = tss->ip;
2666 	ctxt->eflags = tss->flag | 2;
2667 	*reg_write(ctxt, VCPU_REGS_RAX) = tss->ax;
2668 	*reg_write(ctxt, VCPU_REGS_RCX) = tss->cx;
2669 	*reg_write(ctxt, VCPU_REGS_RDX) = tss->dx;
2670 	*reg_write(ctxt, VCPU_REGS_RBX) = tss->bx;
2671 	*reg_write(ctxt, VCPU_REGS_RSP) = tss->sp;
2672 	*reg_write(ctxt, VCPU_REGS_RBP) = tss->bp;
2673 	*reg_write(ctxt, VCPU_REGS_RSI) = tss->si;
2674 	*reg_write(ctxt, VCPU_REGS_RDI) = tss->di;
2675 
2676 	/*
2677 	 * SDM says that segment selectors are loaded before segment
2678 	 * descriptors
2679 	 */
2680 	set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR);
2681 	set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
2682 	set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
2683 	set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
2684 	set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
2685 
2686 	cpl = tss->cs & 3;
2687 
2688 	/*
2689 	 * Now load segment descriptors. If fault happens at this stage
2690 	 * it is handled in a context of new task
2691 	 */
2692 	ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl,
2693 					X86_TRANSFER_TASK_SWITCH, NULL);
2694 	if (ret != X86EMUL_CONTINUE)
2695 		return ret;
2696 	ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
2697 					X86_TRANSFER_TASK_SWITCH, NULL);
2698 	if (ret != X86EMUL_CONTINUE)
2699 		return ret;
2700 	ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
2701 					X86_TRANSFER_TASK_SWITCH, NULL);
2702 	if (ret != X86EMUL_CONTINUE)
2703 		return ret;
2704 	ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
2705 					X86_TRANSFER_TASK_SWITCH, NULL);
2706 	if (ret != X86EMUL_CONTINUE)
2707 		return ret;
2708 	ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
2709 					X86_TRANSFER_TASK_SWITCH, NULL);
2710 	if (ret != X86EMUL_CONTINUE)
2711 		return ret;
2712 
2713 	return X86EMUL_CONTINUE;
2714 }
2715 
2716 static int task_switch_16(struct x86_emulate_ctxt *ctxt, u16 old_tss_sel,
2717 			  ulong old_tss_base, struct desc_struct *new_desc)
2718 {
2719 	struct tss_segment_16 tss_seg;
2720 	int ret;
2721 	u32 new_tss_base = get_desc_base(new_desc);
2722 
2723 	ret = linear_read_system(ctxt, old_tss_base, &tss_seg, sizeof(tss_seg));
2724 	if (ret != X86EMUL_CONTINUE)
2725 		return ret;
2726 
2727 	save_state_to_tss16(ctxt, &tss_seg);
2728 
2729 	ret = linear_write_system(ctxt, old_tss_base, &tss_seg, sizeof(tss_seg));
2730 	if (ret != X86EMUL_CONTINUE)
2731 		return ret;
2732 
2733 	ret = linear_read_system(ctxt, new_tss_base, &tss_seg, sizeof(tss_seg));
2734 	if (ret != X86EMUL_CONTINUE)
2735 		return ret;
2736 
2737 	if (old_tss_sel != 0xffff) {
2738 		tss_seg.prev_task_link = old_tss_sel;
2739 
2740 		ret = linear_write_system(ctxt, new_tss_base,
2741 					  &tss_seg.prev_task_link,
2742 					  sizeof(tss_seg.prev_task_link));
2743 		if (ret != X86EMUL_CONTINUE)
2744 			return ret;
2745 	}
2746 
2747 	return load_state_from_tss16(ctxt, &tss_seg);
2748 }
2749 
2750 static void save_state_to_tss32(struct x86_emulate_ctxt *ctxt,
2751 				struct tss_segment_32 *tss)
2752 {
2753 	/* CR3 and ldt selector are not saved intentionally */
2754 	tss->eip = ctxt->_eip;
2755 	tss->eflags = ctxt->eflags;
2756 	tss->eax = reg_read(ctxt, VCPU_REGS_RAX);
2757 	tss->ecx = reg_read(ctxt, VCPU_REGS_RCX);
2758 	tss->edx = reg_read(ctxt, VCPU_REGS_RDX);
2759 	tss->ebx = reg_read(ctxt, VCPU_REGS_RBX);
2760 	tss->esp = reg_read(ctxt, VCPU_REGS_RSP);
2761 	tss->ebp = reg_read(ctxt, VCPU_REGS_RBP);
2762 	tss->esi = reg_read(ctxt, VCPU_REGS_RSI);
2763 	tss->edi = reg_read(ctxt, VCPU_REGS_RDI);
2764 
2765 	tss->es = get_segment_selector(ctxt, VCPU_SREG_ES);
2766 	tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS);
2767 	tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS);
2768 	tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS);
2769 	tss->fs = get_segment_selector(ctxt, VCPU_SREG_FS);
2770 	tss->gs = get_segment_selector(ctxt, VCPU_SREG_GS);
2771 }
2772 
2773 static int load_state_from_tss32(struct x86_emulate_ctxt *ctxt,
2774 				 struct tss_segment_32 *tss)
2775 {
2776 	int ret;
2777 	u8 cpl;
2778 
2779 	if (ctxt->ops->set_cr(ctxt, 3, tss->cr3))
2780 		return emulate_gp(ctxt, 0);
2781 	ctxt->_eip = tss->eip;
2782 	ctxt->eflags = tss->eflags | 2;
2783 
2784 	/* General purpose registers */
2785 	*reg_write(ctxt, VCPU_REGS_RAX) = tss->eax;
2786 	*reg_write(ctxt, VCPU_REGS_RCX) = tss->ecx;
2787 	*reg_write(ctxt, VCPU_REGS_RDX) = tss->edx;
2788 	*reg_write(ctxt, VCPU_REGS_RBX) = tss->ebx;
2789 	*reg_write(ctxt, VCPU_REGS_RSP) = tss->esp;
2790 	*reg_write(ctxt, VCPU_REGS_RBP) = tss->ebp;
2791 	*reg_write(ctxt, VCPU_REGS_RSI) = tss->esi;
2792 	*reg_write(ctxt, VCPU_REGS_RDI) = tss->edi;
2793 
2794 	/*
2795 	 * SDM says that segment selectors are loaded before segment
2796 	 * descriptors.  This is important because CPL checks will
2797 	 * use CS.RPL.
2798 	 */
2799 	set_segment_selector(ctxt, tss->ldt_selector, VCPU_SREG_LDTR);
2800 	set_segment_selector(ctxt, tss->es, VCPU_SREG_ES);
2801 	set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS);
2802 	set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS);
2803 	set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS);
2804 	set_segment_selector(ctxt, tss->fs, VCPU_SREG_FS);
2805 	set_segment_selector(ctxt, tss->gs, VCPU_SREG_GS);
2806 
2807 	/*
2808 	 * If we're switching between Protected Mode and VM86, we need to make
2809 	 * sure to update the mode before loading the segment descriptors so
2810 	 * that the selectors are interpreted correctly.
2811 	 */
2812 	if (ctxt->eflags & X86_EFLAGS_VM) {
2813 		ctxt->mode = X86EMUL_MODE_VM86;
2814 		cpl = 3;
2815 	} else {
2816 		ctxt->mode = X86EMUL_MODE_PROT32;
2817 		cpl = tss->cs & 3;
2818 	}
2819 
2820 	/*
2821 	 * Now load segment descriptors. If fault happens at this stage
2822 	 * it is handled in a context of new task
2823 	 */
2824 	ret = __load_segment_descriptor(ctxt, tss->ldt_selector, VCPU_SREG_LDTR,
2825 					cpl, X86_TRANSFER_TASK_SWITCH, NULL);
2826 	if (ret != X86EMUL_CONTINUE)
2827 		return ret;
2828 	ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl,
2829 					X86_TRANSFER_TASK_SWITCH, NULL);
2830 	if (ret != X86EMUL_CONTINUE)
2831 		return ret;
2832 	ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl,
2833 					X86_TRANSFER_TASK_SWITCH, NULL);
2834 	if (ret != X86EMUL_CONTINUE)
2835 		return ret;
2836 	ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl,
2837 					X86_TRANSFER_TASK_SWITCH, NULL);
2838 	if (ret != X86EMUL_CONTINUE)
2839 		return ret;
2840 	ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl,
2841 					X86_TRANSFER_TASK_SWITCH, NULL);
2842 	if (ret != X86EMUL_CONTINUE)
2843 		return ret;
2844 	ret = __load_segment_descriptor(ctxt, tss->fs, VCPU_SREG_FS, cpl,
2845 					X86_TRANSFER_TASK_SWITCH, NULL);
2846 	if (ret != X86EMUL_CONTINUE)
2847 		return ret;
2848 	ret = __load_segment_descriptor(ctxt, tss->gs, VCPU_SREG_GS, cpl,
2849 					X86_TRANSFER_TASK_SWITCH, NULL);
2850 
2851 	return ret;
2852 }
2853 
2854 static int task_switch_32(struct x86_emulate_ctxt *ctxt, u16 old_tss_sel,
2855 			  ulong old_tss_base, struct desc_struct *new_desc)
2856 {
2857 	struct tss_segment_32 tss_seg;
2858 	int ret;
2859 	u32 new_tss_base = get_desc_base(new_desc);
2860 	u32 eip_offset = offsetof(struct tss_segment_32, eip);
2861 	u32 ldt_sel_offset = offsetof(struct tss_segment_32, ldt_selector);
2862 
2863 	ret = linear_read_system(ctxt, old_tss_base, &tss_seg, sizeof(tss_seg));
2864 	if (ret != X86EMUL_CONTINUE)
2865 		return ret;
2866 
2867 	save_state_to_tss32(ctxt, &tss_seg);
2868 
2869 	/* Only GP registers and segment selectors are saved */
2870 	ret = linear_write_system(ctxt, old_tss_base + eip_offset, &tss_seg.eip,
2871 				  ldt_sel_offset - eip_offset);
2872 	if (ret != X86EMUL_CONTINUE)
2873 		return ret;
2874 
2875 	ret = linear_read_system(ctxt, new_tss_base, &tss_seg, sizeof(tss_seg));
2876 	if (ret != X86EMUL_CONTINUE)
2877 		return ret;
2878 
2879 	if (old_tss_sel != 0xffff) {
2880 		tss_seg.prev_task_link = old_tss_sel;
2881 
2882 		ret = linear_write_system(ctxt, new_tss_base,
2883 					  &tss_seg.prev_task_link,
2884 					  sizeof(tss_seg.prev_task_link));
2885 		if (ret != X86EMUL_CONTINUE)
2886 			return ret;
2887 	}
2888 
2889 	return load_state_from_tss32(ctxt, &tss_seg);
2890 }
2891 
2892 static int emulator_do_task_switch(struct x86_emulate_ctxt *ctxt,
2893 				   u16 tss_selector, int idt_index, int reason,
2894 				   bool has_error_code, u32 error_code)
2895 {
2896 	const struct x86_emulate_ops *ops = ctxt->ops;
2897 	struct desc_struct curr_tss_desc, next_tss_desc;
2898 	int ret;
2899 	u16 old_tss_sel = get_segment_selector(ctxt, VCPU_SREG_TR);
2900 	ulong old_tss_base =
2901 		ops->get_cached_segment_base(ctxt, VCPU_SREG_TR);
2902 	u32 desc_limit;
2903 	ulong desc_addr, dr7;
2904 
2905 	/* FIXME: old_tss_base == ~0 ? */
2906 
2907 	ret = read_segment_descriptor(ctxt, tss_selector, &next_tss_desc, &desc_addr);
2908 	if (ret != X86EMUL_CONTINUE)
2909 		return ret;
2910 	ret = read_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc, &desc_addr);
2911 	if (ret != X86EMUL_CONTINUE)
2912 		return ret;
2913 
2914 	/* FIXME: check that next_tss_desc is tss */
2915 
2916 	/*
2917 	 * Check privileges. The three cases are task switch caused by...
2918 	 *
2919 	 * 1. jmp/call/int to task gate: Check against DPL of the task gate
2920 	 * 2. Exception/IRQ/iret: No check is performed
2921 	 * 3. jmp/call to TSS/task-gate: No check is performed since the
2922 	 *    hardware checks it before exiting.
2923 	 */
2924 	if (reason == TASK_SWITCH_GATE) {
2925 		if (idt_index != -1) {
2926 			/* Software interrupts */
2927 			struct desc_struct task_gate_desc;
2928 			int dpl;
2929 
2930 			ret = read_interrupt_descriptor(ctxt, idt_index,
2931 							&task_gate_desc);
2932 			if (ret != X86EMUL_CONTINUE)
2933 				return ret;
2934 
2935 			dpl = task_gate_desc.dpl;
2936 			if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl)
2937 				return emulate_gp(ctxt, (idt_index << 3) | 0x2);
2938 		}
2939 	}
2940 
2941 	desc_limit = desc_limit_scaled(&next_tss_desc);
2942 	if (!next_tss_desc.p ||
2943 	    ((desc_limit < 0x67 && (next_tss_desc.type & 8)) ||
2944 	     desc_limit < 0x2b)) {
2945 		return emulate_ts(ctxt, tss_selector & 0xfffc);
2946 	}
2947 
2948 	if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) {
2949 		curr_tss_desc.type &= ~(1 << 1); /* clear busy flag */
2950 		write_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc);
2951 	}
2952 
2953 	if (reason == TASK_SWITCH_IRET)
2954 		ctxt->eflags = ctxt->eflags & ~X86_EFLAGS_NT;
2955 
2956 	/* set back link to prev task only if NT bit is set in eflags
2957 	   note that old_tss_sel is not used after this point */
2958 	if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE)
2959 		old_tss_sel = 0xffff;
2960 
2961 	if (next_tss_desc.type & 8)
2962 		ret = task_switch_32(ctxt, old_tss_sel, old_tss_base, &next_tss_desc);
2963 	else
2964 		ret = task_switch_16(ctxt, old_tss_sel,
2965 				     old_tss_base, &next_tss_desc);
2966 	if (ret != X86EMUL_CONTINUE)
2967 		return ret;
2968 
2969 	if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE)
2970 		ctxt->eflags = ctxt->eflags | X86_EFLAGS_NT;
2971 
2972 	if (reason != TASK_SWITCH_IRET) {
2973 		next_tss_desc.type |= (1 << 1); /* set busy flag */
2974 		write_segment_descriptor(ctxt, tss_selector, &next_tss_desc);
2975 	}
2976 
2977 	ops->set_cr(ctxt, 0,  ops->get_cr(ctxt, 0) | X86_CR0_TS);
2978 	ops->set_segment(ctxt, tss_selector, &next_tss_desc, 0, VCPU_SREG_TR);
2979 
2980 	if (has_error_code) {
2981 		ctxt->op_bytes = ctxt->ad_bytes = (next_tss_desc.type & 8) ? 4 : 2;
2982 		ctxt->lock_prefix = 0;
2983 		ctxt->src.val = (unsigned long) error_code;
2984 		ret = em_push(ctxt);
2985 	}
2986 
2987 	dr7 = ops->get_dr(ctxt, 7);
2988 	ops->set_dr(ctxt, 7, dr7 & ~(DR_LOCAL_ENABLE_MASK | DR_LOCAL_SLOWDOWN));
2989 
2990 	return ret;
2991 }
2992 
2993 int emulator_task_switch(struct x86_emulate_ctxt *ctxt,
2994 			 u16 tss_selector, int idt_index, int reason,
2995 			 bool has_error_code, u32 error_code)
2996 {
2997 	int rc;
2998 
2999 	invalidate_registers(ctxt);
3000 	ctxt->_eip = ctxt->eip;
3001 	ctxt->dst.type = OP_NONE;
3002 
3003 	rc = emulator_do_task_switch(ctxt, tss_selector, idt_index, reason,
3004 				     has_error_code, error_code);
3005 
3006 	if (rc == X86EMUL_CONTINUE) {
3007 		ctxt->eip = ctxt->_eip;
3008 		writeback_registers(ctxt);
3009 	}
3010 
3011 	return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK;
3012 }
3013 
3014 static void string_addr_inc(struct x86_emulate_ctxt *ctxt, int reg,
3015 		struct operand *op)
3016 {
3017 	int df = (ctxt->eflags & X86_EFLAGS_DF) ? -op->count : op->count;
3018 
3019 	register_address_increment(ctxt, reg, df * op->bytes);
3020 	op->addr.mem.ea = register_address(ctxt, reg);
3021 }
3022 
3023 static int em_das(struct x86_emulate_ctxt *ctxt)
3024 {
3025 	u8 al, old_al;
3026 	bool af, cf, old_cf;
3027 
3028 	cf = ctxt->eflags & X86_EFLAGS_CF;
3029 	al = ctxt->dst.val;
3030 
3031 	old_al = al;
3032 	old_cf = cf;
3033 	cf = false;
3034 	af = ctxt->eflags & X86_EFLAGS_AF;
3035 	if ((al & 0x0f) > 9 || af) {
3036 		al -= 6;
3037 		cf = old_cf | (al >= 250);
3038 		af = true;
3039 	} else {
3040 		af = false;
3041 	}
3042 	if (old_al > 0x99 || old_cf) {
3043 		al -= 0x60;
3044 		cf = true;
3045 	}
3046 
3047 	ctxt->dst.val = al;
3048 	/* Set PF, ZF, SF */
3049 	ctxt->src.type = OP_IMM;
3050 	ctxt->src.val = 0;
3051 	ctxt->src.bytes = 1;
3052 	fastop(ctxt, em_or);
3053 	ctxt->eflags &= ~(X86_EFLAGS_AF | X86_EFLAGS_CF);
3054 	if (cf)
3055 		ctxt->eflags |= X86_EFLAGS_CF;
3056 	if (af)
3057 		ctxt->eflags |= X86_EFLAGS_AF;
3058 	return X86EMUL_CONTINUE;
3059 }
3060 
3061 static int em_aam(struct x86_emulate_ctxt *ctxt)
3062 {
3063 	u8 al, ah;
3064 
3065 	if (ctxt->src.val == 0)
3066 		return emulate_de(ctxt);
3067 
3068 	al = ctxt->dst.val & 0xff;
3069 	ah = al / ctxt->src.val;
3070 	al %= ctxt->src.val;
3071 
3072 	ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al | (ah << 8);
3073 
3074 	/* Set PF, ZF, SF */
3075 	ctxt->src.type = OP_IMM;
3076 	ctxt->src.val = 0;
3077 	ctxt->src.bytes = 1;
3078 	fastop(ctxt, em_or);
3079 
3080 	return X86EMUL_CONTINUE;
3081 }
3082 
3083 static int em_aad(struct x86_emulate_ctxt *ctxt)
3084 {
3085 	u8 al = ctxt->dst.val & 0xff;
3086 	u8 ah = (ctxt->dst.val >> 8) & 0xff;
3087 
3088 	al = (al + (ah * ctxt->src.val)) & 0xff;
3089 
3090 	ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al;
3091 
3092 	/* Set PF, ZF, SF */
3093 	ctxt->src.type = OP_IMM;
3094 	ctxt->src.val = 0;
3095 	ctxt->src.bytes = 1;
3096 	fastop(ctxt, em_or);
3097 
3098 	return X86EMUL_CONTINUE;
3099 }
3100 
3101 static int em_call(struct x86_emulate_ctxt *ctxt)
3102 {
3103 	int rc;
3104 	long rel = ctxt->src.val;
3105 
3106 	ctxt->src.val = (unsigned long)ctxt->_eip;
3107 	rc = jmp_rel(ctxt, rel);
3108 	if (rc != X86EMUL_CONTINUE)
3109 		return rc;
3110 	return em_push(ctxt);
3111 }
3112 
3113 static int em_call_far(struct x86_emulate_ctxt *ctxt)
3114 {
3115 	u16 sel, old_cs;
3116 	ulong old_eip;
3117 	int rc;
3118 	struct desc_struct old_desc, new_desc;
3119 	const struct x86_emulate_ops *ops = ctxt->ops;
3120 	int cpl = ctxt->ops->cpl(ctxt);
3121 	enum x86emul_mode prev_mode = ctxt->mode;
3122 
3123 	old_eip = ctxt->_eip;
3124 	ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS);
3125 
3126 	memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
3127 	rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,
3128 				       X86_TRANSFER_CALL_JMP, &new_desc);
3129 	if (rc != X86EMUL_CONTINUE)
3130 		return rc;
3131 
3132 	rc = assign_eip_far(ctxt, ctxt->src.val);
3133 	if (rc != X86EMUL_CONTINUE)
3134 		goto fail;
3135 
3136 	ctxt->src.val = old_cs;
3137 	rc = em_push(ctxt);
3138 	if (rc != X86EMUL_CONTINUE)
3139 		goto fail;
3140 
3141 	ctxt->src.val = old_eip;
3142 	rc = em_push(ctxt);
3143 	/* If we failed, we tainted the memory, but the very least we should
3144 	   restore cs */
3145 	if (rc != X86EMUL_CONTINUE) {
3146 		pr_warn_once("faulting far call emulation tainted memory\n");
3147 		goto fail;
3148 	}
3149 	return rc;
3150 fail:
3151 	ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
3152 	ctxt->mode = prev_mode;
3153 	return rc;
3154 
3155 }
3156 
3157 static int em_ret_near_imm(struct x86_emulate_ctxt *ctxt)
3158 {
3159 	int rc;
3160 	unsigned long eip = 0;
3161 
3162 	rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
3163 	if (rc != X86EMUL_CONTINUE)
3164 		return rc;
3165 	rc = assign_eip_near(ctxt, eip);
3166 	if (rc != X86EMUL_CONTINUE)
3167 		return rc;
3168 	rsp_increment(ctxt, ctxt->src.val);
3169 	return X86EMUL_CONTINUE;
3170 }
3171 
3172 static int em_xchg(struct x86_emulate_ctxt *ctxt)
3173 {
3174 	/* Write back the register source. */
3175 	ctxt->src.val = ctxt->dst.val;
3176 	write_register_operand(&ctxt->src);
3177 
3178 	/* Write back the memory destination with implicit LOCK prefix. */
3179 	ctxt->dst.val = ctxt->src.orig_val;
3180 	ctxt->lock_prefix = 1;
3181 	return X86EMUL_CONTINUE;
3182 }
3183 
3184 static int em_imul_3op(struct x86_emulate_ctxt *ctxt)
3185 {
3186 	ctxt->dst.val = ctxt->src2.val;
3187 	return fastop(ctxt, em_imul);
3188 }
3189 
3190 static int em_cwd(struct x86_emulate_ctxt *ctxt)
3191 {
3192 	ctxt->dst.type = OP_REG;
3193 	ctxt->dst.bytes = ctxt->src.bytes;
3194 	ctxt->dst.addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
3195 	ctxt->dst.val = ~((ctxt->src.val >> (ctxt->src.bytes * 8 - 1)) - 1);
3196 
3197 	return X86EMUL_CONTINUE;
3198 }
3199 
3200 static int em_rdpid(struct x86_emulate_ctxt *ctxt)
3201 {
3202 	u64 tsc_aux = 0;
3203 
3204 	if (!ctxt->ops->guest_has_rdpid(ctxt))
3205 		return emulate_ud(ctxt);
3206 
3207 	ctxt->ops->get_msr(ctxt, MSR_TSC_AUX, &tsc_aux);
3208 	ctxt->dst.val = tsc_aux;
3209 	return X86EMUL_CONTINUE;
3210 }
3211 
3212 static int em_rdtsc(struct x86_emulate_ctxt *ctxt)
3213 {
3214 	u64 tsc = 0;
3215 
3216 	ctxt->ops->get_msr(ctxt, MSR_IA32_TSC, &tsc);
3217 	*reg_write(ctxt, VCPU_REGS_RAX) = (u32)tsc;
3218 	*reg_write(ctxt, VCPU_REGS_RDX) = tsc >> 32;
3219 	return X86EMUL_CONTINUE;
3220 }
3221 
3222 static int em_rdpmc(struct x86_emulate_ctxt *ctxt)
3223 {
3224 	u64 pmc;
3225 
3226 	if (ctxt->ops->read_pmc(ctxt, reg_read(ctxt, VCPU_REGS_RCX), &pmc))
3227 		return emulate_gp(ctxt, 0);
3228 	*reg_write(ctxt, VCPU_REGS_RAX) = (u32)pmc;
3229 	*reg_write(ctxt, VCPU_REGS_RDX) = pmc >> 32;
3230 	return X86EMUL_CONTINUE;
3231 }
3232 
3233 static int em_mov(struct x86_emulate_ctxt *ctxt)
3234 {
3235 	memcpy(ctxt->dst.valptr, ctxt->src.valptr, sizeof(ctxt->src.valptr));
3236 	return X86EMUL_CONTINUE;
3237 }
3238 
3239 static int em_movbe(struct x86_emulate_ctxt *ctxt)
3240 {
3241 	u16 tmp;
3242 
3243 	if (!ctxt->ops->guest_has_movbe(ctxt))
3244 		return emulate_ud(ctxt);
3245 
3246 	switch (ctxt->op_bytes) {
3247 	case 2:
3248 		/*
3249 		 * From MOVBE definition: "...When the operand size is 16 bits,
3250 		 * the upper word of the destination register remains unchanged
3251 		 * ..."
3252 		 *
3253 		 * Both casting ->valptr and ->val to u16 breaks strict aliasing
3254 		 * rules so we have to do the operation almost per hand.
3255 		 */
3256 		tmp = (u16)ctxt->src.val;
3257 		ctxt->dst.val &= ~0xffffUL;
3258 		ctxt->dst.val |= (unsigned long)swab16(tmp);
3259 		break;
3260 	case 4:
3261 		ctxt->dst.val = swab32((u32)ctxt->src.val);
3262 		break;
3263 	case 8:
3264 		ctxt->dst.val = swab64(ctxt->src.val);
3265 		break;
3266 	default:
3267 		BUG();
3268 	}
3269 	return X86EMUL_CONTINUE;
3270 }
3271 
3272 static int em_cr_write(struct x86_emulate_ctxt *ctxt)
3273 {
3274 	int cr_num = ctxt->modrm_reg;
3275 	int r;
3276 
3277 	if (ctxt->ops->set_cr(ctxt, cr_num, ctxt->src.val))
3278 		return emulate_gp(ctxt, 0);
3279 
3280 	/* Disable writeback. */
3281 	ctxt->dst.type = OP_NONE;
3282 
3283 	if (cr_num == 0) {
3284 		/*
3285 		 * CR0 write might have updated CR0.PE and/or CR0.PG
3286 		 * which can affect the cpu's execution mode.
3287 		 */
3288 		r = emulator_recalc_and_set_mode(ctxt);
3289 		if (r != X86EMUL_CONTINUE)
3290 			return r;
3291 	}
3292 
3293 	return X86EMUL_CONTINUE;
3294 }
3295 
3296 static int em_dr_write(struct x86_emulate_ctxt *ctxt)
3297 {
3298 	unsigned long val;
3299 
3300 	if (ctxt->mode == X86EMUL_MODE_PROT64)
3301 		val = ctxt->src.val & ~0ULL;
3302 	else
3303 		val = ctxt->src.val & ~0U;
3304 
3305 	/* #UD condition is already handled. */
3306 	if (ctxt->ops->set_dr(ctxt, ctxt->modrm_reg, val) < 0)
3307 		return emulate_gp(ctxt, 0);
3308 
3309 	/* Disable writeback. */
3310 	ctxt->dst.type = OP_NONE;
3311 	return X86EMUL_CONTINUE;
3312 }
3313 
3314 static int em_wrmsr(struct x86_emulate_ctxt *ctxt)
3315 {
3316 	u64 msr_index = reg_read(ctxt, VCPU_REGS_RCX);
3317 	u64 msr_data;
3318 	int r;
3319 
3320 	msr_data = (u32)reg_read(ctxt, VCPU_REGS_RAX)
3321 		| ((u64)reg_read(ctxt, VCPU_REGS_RDX) << 32);
3322 	r = ctxt->ops->set_msr_with_filter(ctxt, msr_index, msr_data);
3323 
3324 	if (r == X86EMUL_PROPAGATE_FAULT)
3325 		return emulate_gp(ctxt, 0);
3326 
3327 	return r;
3328 }
3329 
3330 static int em_rdmsr(struct x86_emulate_ctxt *ctxt)
3331 {
3332 	u64 msr_index = reg_read(ctxt, VCPU_REGS_RCX);
3333 	u64 msr_data;
3334 	int r;
3335 
3336 	r = ctxt->ops->get_msr_with_filter(ctxt, msr_index, &msr_data);
3337 
3338 	if (r == X86EMUL_PROPAGATE_FAULT)
3339 		return emulate_gp(ctxt, 0);
3340 
3341 	if (r == X86EMUL_CONTINUE) {
3342 		*reg_write(ctxt, VCPU_REGS_RAX) = (u32)msr_data;
3343 		*reg_write(ctxt, VCPU_REGS_RDX) = msr_data >> 32;
3344 	}
3345 	return r;
3346 }
3347 
3348 static int em_store_sreg(struct x86_emulate_ctxt *ctxt, int segment)
3349 {
3350 	if (segment > VCPU_SREG_GS &&
3351 	    (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_UMIP) &&
3352 	    ctxt->ops->cpl(ctxt) > 0)
3353 		return emulate_gp(ctxt, 0);
3354 
3355 	ctxt->dst.val = get_segment_selector(ctxt, segment);
3356 	if (ctxt->dst.bytes == 4 && ctxt->dst.type == OP_MEM)
3357 		ctxt->dst.bytes = 2;
3358 	return X86EMUL_CONTINUE;
3359 }
3360 
3361 static int em_mov_rm_sreg(struct x86_emulate_ctxt *ctxt)
3362 {
3363 	if (ctxt->modrm_reg > VCPU_SREG_GS)
3364 		return emulate_ud(ctxt);
3365 
3366 	return em_store_sreg(ctxt, ctxt->modrm_reg);
3367 }
3368 
3369 static int em_mov_sreg_rm(struct x86_emulate_ctxt *ctxt)
3370 {
3371 	u16 sel = ctxt->src.val;
3372 
3373 	if (ctxt->modrm_reg == VCPU_SREG_CS || ctxt->modrm_reg > VCPU_SREG_GS)
3374 		return emulate_ud(ctxt);
3375 
3376 	if (ctxt->modrm_reg == VCPU_SREG_SS)
3377 		ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS;
3378 
3379 	/* Disable writeback. */
3380 	ctxt->dst.type = OP_NONE;
3381 	return load_segment_descriptor(ctxt, sel, ctxt->modrm_reg);
3382 }
3383 
3384 static int em_sldt(struct x86_emulate_ctxt *ctxt)
3385 {
3386 	return em_store_sreg(ctxt, VCPU_SREG_LDTR);
3387 }
3388 
3389 static int em_lldt(struct x86_emulate_ctxt *ctxt)
3390 {
3391 	u16 sel = ctxt->src.val;
3392 
3393 	/* Disable writeback. */
3394 	ctxt->dst.type = OP_NONE;
3395 	return load_segment_descriptor(ctxt, sel, VCPU_SREG_LDTR);
3396 }
3397 
3398 static int em_str(struct x86_emulate_ctxt *ctxt)
3399 {
3400 	return em_store_sreg(ctxt, VCPU_SREG_TR);
3401 }
3402 
3403 static int em_ltr(struct x86_emulate_ctxt *ctxt)
3404 {
3405 	u16 sel = ctxt->src.val;
3406 
3407 	/* Disable writeback. */
3408 	ctxt->dst.type = OP_NONE;
3409 	return load_segment_descriptor(ctxt, sel, VCPU_SREG_TR);
3410 }
3411 
3412 static int em_invlpg(struct x86_emulate_ctxt *ctxt)
3413 {
3414 	int rc;
3415 	ulong linear;
3416 	unsigned int max_size;
3417 
3418 	rc = __linearize(ctxt, ctxt->src.addr.mem, &max_size, 1, ctxt->mode,
3419 			 &linear, X86EMUL_F_INVLPG);
3420 	if (rc == X86EMUL_CONTINUE)
3421 		ctxt->ops->invlpg(ctxt, linear);
3422 	/* Disable writeback. */
3423 	ctxt->dst.type = OP_NONE;
3424 	return X86EMUL_CONTINUE;
3425 }
3426 
3427 static int em_clts(struct x86_emulate_ctxt *ctxt)
3428 {
3429 	ulong cr0;
3430 
3431 	cr0 = ctxt->ops->get_cr(ctxt, 0);
3432 	cr0 &= ~X86_CR0_TS;
3433 	ctxt->ops->set_cr(ctxt, 0, cr0);
3434 	return X86EMUL_CONTINUE;
3435 }
3436 
3437 static int em_hypercall(struct x86_emulate_ctxt *ctxt)
3438 {
3439 	int rc = ctxt->ops->fix_hypercall(ctxt);
3440 
3441 	if (rc != X86EMUL_CONTINUE)
3442 		return rc;
3443 
3444 	/* Let the processor re-execute the fixed hypercall */
3445 	ctxt->_eip = ctxt->eip;
3446 	/* Disable writeback. */
3447 	ctxt->dst.type = OP_NONE;
3448 	return X86EMUL_CONTINUE;
3449 }
3450 
3451 static int emulate_store_desc_ptr(struct x86_emulate_ctxt *ctxt,
3452 				  void (*get)(struct x86_emulate_ctxt *ctxt,
3453 					      struct desc_ptr *ptr))
3454 {
3455 	struct desc_ptr desc_ptr;
3456 
3457 	if ((ctxt->ops->get_cr(ctxt, 4) & X86_CR4_UMIP) &&
3458 	    ctxt->ops->cpl(ctxt) > 0)
3459 		return emulate_gp(ctxt, 0);
3460 
3461 	if (ctxt->mode == X86EMUL_MODE_PROT64)
3462 		ctxt->op_bytes = 8;
3463 	get(ctxt, &desc_ptr);
3464 	if (ctxt->op_bytes == 2) {
3465 		ctxt->op_bytes = 4;
3466 		desc_ptr.address &= 0x00ffffff;
3467 	}
3468 	/* Disable writeback. */
3469 	ctxt->dst.type = OP_NONE;
3470 	return segmented_write_std(ctxt, ctxt->dst.addr.mem,
3471 				   &desc_ptr, 2 + ctxt->op_bytes);
3472 }
3473 
3474 static int em_sgdt(struct x86_emulate_ctxt *ctxt)
3475 {
3476 	return emulate_store_desc_ptr(ctxt, ctxt->ops->get_gdt);
3477 }
3478 
3479 static int em_sidt(struct x86_emulate_ctxt *ctxt)
3480 {
3481 	return emulate_store_desc_ptr(ctxt, ctxt->ops->get_idt);
3482 }
3483 
3484 static int em_lgdt_lidt(struct x86_emulate_ctxt *ctxt, bool lgdt)
3485 {
3486 	struct desc_ptr desc_ptr;
3487 	int rc;
3488 
3489 	if (ctxt->mode == X86EMUL_MODE_PROT64)
3490 		ctxt->op_bytes = 8;
3491 	rc = read_descriptor(ctxt, ctxt->src.addr.mem,
3492 			     &desc_ptr.size, &desc_ptr.address,
3493 			     ctxt->op_bytes);
3494 	if (rc != X86EMUL_CONTINUE)
3495 		return rc;
3496 	if (ctxt->mode == X86EMUL_MODE_PROT64 &&
3497 	    emul_is_noncanonical_address(desc_ptr.address, ctxt))
3498 		return emulate_gp(ctxt, 0);
3499 	if (lgdt)
3500 		ctxt->ops->set_gdt(ctxt, &desc_ptr);
3501 	else
3502 		ctxt->ops->set_idt(ctxt, &desc_ptr);
3503 	/* Disable writeback. */
3504 	ctxt->dst.type = OP_NONE;
3505 	return X86EMUL_CONTINUE;
3506 }
3507 
3508 static int em_lgdt(struct x86_emulate_ctxt *ctxt)
3509 {
3510 	return em_lgdt_lidt(ctxt, true);
3511 }
3512 
3513 static int em_lidt(struct x86_emulate_ctxt *ctxt)
3514 {
3515 	return em_lgdt_lidt(ctxt, false);
3516 }
3517 
3518 static int em_smsw(struct x86_emulate_ctxt *ctxt)
3519 {
3520 	if ((ctxt->ops->get_cr(ctxt, 4) & X86_CR4_UMIP) &&
3521 	    ctxt->ops->cpl(ctxt) > 0)
3522 		return emulate_gp(ctxt, 0);
3523 
3524 	if (ctxt->dst.type == OP_MEM)
3525 		ctxt->dst.bytes = 2;
3526 	ctxt->dst.val = ctxt->ops->get_cr(ctxt, 0);
3527 	return X86EMUL_CONTINUE;
3528 }
3529 
3530 static int em_lmsw(struct x86_emulate_ctxt *ctxt)
3531 {
3532 	ctxt->ops->set_cr(ctxt, 0, (ctxt->ops->get_cr(ctxt, 0) & ~0x0eul)
3533 			  | (ctxt->src.val & 0x0f));
3534 	ctxt->dst.type = OP_NONE;
3535 	return X86EMUL_CONTINUE;
3536 }
3537 
3538 static int em_loop(struct x86_emulate_ctxt *ctxt)
3539 {
3540 	int rc = X86EMUL_CONTINUE;
3541 
3542 	register_address_increment(ctxt, VCPU_REGS_RCX, -1);
3543 	if ((address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) != 0) &&
3544 	    (ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags)))
3545 		rc = jmp_rel(ctxt, ctxt->src.val);
3546 
3547 	return rc;
3548 }
3549 
3550 static int em_jcxz(struct x86_emulate_ctxt *ctxt)
3551 {
3552 	int rc = X86EMUL_CONTINUE;
3553 
3554 	if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)
3555 		rc = jmp_rel(ctxt, ctxt->src.val);
3556 
3557 	return rc;
3558 }
3559 
3560 static int em_in(struct x86_emulate_ctxt *ctxt)
3561 {
3562 	if (!pio_in_emulated(ctxt, ctxt->dst.bytes, ctxt->src.val,
3563 			     &ctxt->dst.val))
3564 		return X86EMUL_IO_NEEDED;
3565 
3566 	return X86EMUL_CONTINUE;
3567 }
3568 
3569 static int em_out(struct x86_emulate_ctxt *ctxt)
3570 {
3571 	ctxt->ops->pio_out_emulated(ctxt, ctxt->src.bytes, ctxt->dst.val,
3572 				    &ctxt->src.val, 1);
3573 	/* Disable writeback. */
3574 	ctxt->dst.type = OP_NONE;
3575 	return X86EMUL_CONTINUE;
3576 }
3577 
3578 static int em_cli(struct x86_emulate_ctxt *ctxt)
3579 {
3580 	if (emulator_bad_iopl(ctxt))
3581 		return emulate_gp(ctxt, 0);
3582 
3583 	ctxt->eflags &= ~X86_EFLAGS_IF;
3584 	return X86EMUL_CONTINUE;
3585 }
3586 
3587 static int em_sti(struct x86_emulate_ctxt *ctxt)
3588 {
3589 	if (emulator_bad_iopl(ctxt))
3590 		return emulate_gp(ctxt, 0);
3591 
3592 	ctxt->interruptibility = KVM_X86_SHADOW_INT_STI;
3593 	ctxt->eflags |= X86_EFLAGS_IF;
3594 	return X86EMUL_CONTINUE;
3595 }
3596 
3597 static int em_cpuid(struct x86_emulate_ctxt *ctxt)
3598 {
3599 	u32 eax, ebx, ecx, edx;
3600 	u64 msr = 0;
3601 
3602 	ctxt->ops->get_msr(ctxt, MSR_MISC_FEATURES_ENABLES, &msr);
3603 	if (msr & MSR_MISC_FEATURES_ENABLES_CPUID_FAULT &&
3604 	    ctxt->ops->cpl(ctxt)) {
3605 		return emulate_gp(ctxt, 0);
3606 	}
3607 
3608 	eax = reg_read(ctxt, VCPU_REGS_RAX);
3609 	ecx = reg_read(ctxt, VCPU_REGS_RCX);
3610 	ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx, false);
3611 	*reg_write(ctxt, VCPU_REGS_RAX) = eax;
3612 	*reg_write(ctxt, VCPU_REGS_RBX) = ebx;
3613 	*reg_write(ctxt, VCPU_REGS_RCX) = ecx;
3614 	*reg_write(ctxt, VCPU_REGS_RDX) = edx;
3615 	return X86EMUL_CONTINUE;
3616 }
3617 
3618 static int em_sahf(struct x86_emulate_ctxt *ctxt)
3619 {
3620 	u32 flags;
3621 
3622 	flags = X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
3623 		X86_EFLAGS_SF;
3624 	flags &= *reg_rmw(ctxt, VCPU_REGS_RAX) >> 8;
3625 
3626 	ctxt->eflags &= ~0xffUL;
3627 	ctxt->eflags |= flags | X86_EFLAGS_FIXED;
3628 	return X86EMUL_CONTINUE;
3629 }
3630 
3631 static int em_lahf(struct x86_emulate_ctxt *ctxt)
3632 {
3633 	*reg_rmw(ctxt, VCPU_REGS_RAX) &= ~0xff00UL;
3634 	*reg_rmw(ctxt, VCPU_REGS_RAX) |= (ctxt->eflags & 0xff) << 8;
3635 	return X86EMUL_CONTINUE;
3636 }
3637 
3638 static int em_bswap(struct x86_emulate_ctxt *ctxt)
3639 {
3640 	switch (ctxt->op_bytes) {
3641 #ifdef CONFIG_X86_64
3642 	case 8:
3643 		asm("bswap %0" : "+r"(ctxt->dst.val));
3644 		break;
3645 #endif
3646 	default:
3647 		asm("bswap %0" : "+r"(*(u32 *)&ctxt->dst.val));
3648 		break;
3649 	}
3650 	return X86EMUL_CONTINUE;
3651 }
3652 
3653 static int em_clflush(struct x86_emulate_ctxt *ctxt)
3654 {
3655 	/* emulating clflush regardless of cpuid */
3656 	return X86EMUL_CONTINUE;
3657 }
3658 
3659 static int em_clflushopt(struct x86_emulate_ctxt *ctxt)
3660 {
3661 	/* emulating clflushopt regardless of cpuid */
3662 	return X86EMUL_CONTINUE;
3663 }
3664 
3665 static int em_movsxd(struct x86_emulate_ctxt *ctxt)
3666 {
3667 	ctxt->dst.val = (s32) ctxt->src.val;
3668 	return X86EMUL_CONTINUE;
3669 }
3670 
3671 static int check_fxsr(struct x86_emulate_ctxt *ctxt)
3672 {
3673 	if (!ctxt->ops->guest_has_fxsr(ctxt))
3674 		return emulate_ud(ctxt);
3675 
3676 	if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM))
3677 		return emulate_nm(ctxt);
3678 
3679 	/*
3680 	 * Don't emulate a case that should never be hit, instead of working
3681 	 * around a lack of fxsave64/fxrstor64 on old compilers.
3682 	 */
3683 	if (ctxt->mode >= X86EMUL_MODE_PROT64)
3684 		return X86EMUL_UNHANDLEABLE;
3685 
3686 	return X86EMUL_CONTINUE;
3687 }
3688 
3689 /*
3690  * Hardware doesn't save and restore XMM 0-7 without CR4.OSFXSR, but does save
3691  * and restore MXCSR.
3692  */
3693 static size_t __fxstate_size(int nregs)
3694 {
3695 	return offsetof(struct fxregs_state, xmm_space[0]) + nregs * 16;
3696 }
3697 
3698 static inline size_t fxstate_size(struct x86_emulate_ctxt *ctxt)
3699 {
3700 	bool cr4_osfxsr;
3701 	if (ctxt->mode == X86EMUL_MODE_PROT64)
3702 		return __fxstate_size(16);
3703 
3704 	cr4_osfxsr = ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR;
3705 	return __fxstate_size(cr4_osfxsr ? 8 : 0);
3706 }
3707 
3708 /*
3709  * FXSAVE and FXRSTOR have 4 different formats depending on execution mode,
3710  *  1) 16 bit mode
3711  *  2) 32 bit mode
3712  *     - like (1), but FIP and FDP (foo) are only 16 bit.  At least Intel CPUs
3713  *       preserve whole 32 bit values, though, so (1) and (2) are the same wrt.
3714  *       save and restore
3715  *  3) 64-bit mode with REX.W prefix
3716  *     - like (2), but XMM 8-15 are being saved and restored
3717  *  4) 64-bit mode without REX.W prefix
3718  *     - like (3), but FIP and FDP are 64 bit
3719  *
3720  * Emulation uses (3) for (1) and (2) and preserves XMM 8-15 to reach the
3721  * desired result.  (4) is not emulated.
3722  *
3723  * Note: Guest and host CPUID.(EAX=07H,ECX=0H):EBX[bit 13] (deprecate FPU CS
3724  * and FPU DS) should match.
3725  */
3726 static int em_fxsave(struct x86_emulate_ctxt *ctxt)
3727 {
3728 	struct fxregs_state fx_state;
3729 	int rc;
3730 
3731 	rc = check_fxsr(ctxt);
3732 	if (rc != X86EMUL_CONTINUE)
3733 		return rc;
3734 
3735 	kvm_fpu_get();
3736 
3737 	rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state));
3738 
3739 	kvm_fpu_put();
3740 
3741 	if (rc != X86EMUL_CONTINUE)
3742 		return rc;
3743 
3744 	return segmented_write_std(ctxt, ctxt->memop.addr.mem, &fx_state,
3745 		                   fxstate_size(ctxt));
3746 }
3747 
3748 /*
3749  * FXRSTOR might restore XMM registers not provided by the guest. Fill
3750  * in the host registers (via FXSAVE) instead, so they won't be modified.
3751  * (preemption has to stay disabled until FXRSTOR).
3752  *
3753  * Use noinline to keep the stack for other functions called by callers small.
3754  */
3755 static noinline int fxregs_fixup(struct fxregs_state *fx_state,
3756 				 const size_t used_size)
3757 {
3758 	struct fxregs_state fx_tmp;
3759 	int rc;
3760 
3761 	rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_tmp));
3762 	memcpy((void *)fx_state + used_size, (void *)&fx_tmp + used_size,
3763 	       __fxstate_size(16) - used_size);
3764 
3765 	return rc;
3766 }
3767 
3768 static int em_fxrstor(struct x86_emulate_ctxt *ctxt)
3769 {
3770 	struct fxregs_state fx_state;
3771 	int rc;
3772 	size_t size;
3773 
3774 	rc = check_fxsr(ctxt);
3775 	if (rc != X86EMUL_CONTINUE)
3776 		return rc;
3777 
3778 	size = fxstate_size(ctxt);
3779 	rc = segmented_read_std(ctxt, ctxt->memop.addr.mem, &fx_state, size);
3780 	if (rc != X86EMUL_CONTINUE)
3781 		return rc;
3782 
3783 	kvm_fpu_get();
3784 
3785 	if (size < __fxstate_size(16)) {
3786 		rc = fxregs_fixup(&fx_state, size);
3787 		if (rc != X86EMUL_CONTINUE)
3788 			goto out;
3789 	}
3790 
3791 	if (fx_state.mxcsr >> 16) {
3792 		rc = emulate_gp(ctxt, 0);
3793 		goto out;
3794 	}
3795 
3796 	if (rc == X86EMUL_CONTINUE)
3797 		rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state));
3798 
3799 out:
3800 	kvm_fpu_put();
3801 
3802 	return rc;
3803 }
3804 
3805 static int em_xsetbv(struct x86_emulate_ctxt *ctxt)
3806 {
3807 	u32 eax, ecx, edx;
3808 
3809 	if (!(ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSXSAVE))
3810 		return emulate_ud(ctxt);
3811 
3812 	eax = reg_read(ctxt, VCPU_REGS_RAX);
3813 	edx = reg_read(ctxt, VCPU_REGS_RDX);
3814 	ecx = reg_read(ctxt, VCPU_REGS_RCX);
3815 
3816 	if (ctxt->ops->set_xcr(ctxt, ecx, ((u64)edx << 32) | eax))
3817 		return emulate_gp(ctxt, 0);
3818 
3819 	return X86EMUL_CONTINUE;
3820 }
3821 
3822 static bool valid_cr(int nr)
3823 {
3824 	switch (nr) {
3825 	case 0:
3826 	case 2 ... 4:
3827 	case 8:
3828 		return true;
3829 	default:
3830 		return false;
3831 	}
3832 }
3833 
3834 static int check_cr_access(struct x86_emulate_ctxt *ctxt)
3835 {
3836 	if (!valid_cr(ctxt->modrm_reg))
3837 		return emulate_ud(ctxt);
3838 
3839 	return X86EMUL_CONTINUE;
3840 }
3841 
3842 static int check_dr_read(struct x86_emulate_ctxt *ctxt)
3843 {
3844 	int dr = ctxt->modrm_reg;
3845 	u64 cr4;
3846 
3847 	if (dr > 7)
3848 		return emulate_ud(ctxt);
3849 
3850 	cr4 = ctxt->ops->get_cr(ctxt, 4);
3851 	if ((cr4 & X86_CR4_DE) && (dr == 4 || dr == 5))
3852 		return emulate_ud(ctxt);
3853 
3854 	if (ctxt->ops->get_dr(ctxt, 7) & DR7_GD) {
3855 		ulong dr6;
3856 
3857 		dr6 = ctxt->ops->get_dr(ctxt, 6);
3858 		dr6 &= ~DR_TRAP_BITS;
3859 		dr6 |= DR6_BD | DR6_ACTIVE_LOW;
3860 		ctxt->ops->set_dr(ctxt, 6, dr6);
3861 		return emulate_db(ctxt);
3862 	}
3863 
3864 	return X86EMUL_CONTINUE;
3865 }
3866 
3867 static int check_dr_write(struct x86_emulate_ctxt *ctxt)
3868 {
3869 	u64 new_val = ctxt->src.val64;
3870 	int dr = ctxt->modrm_reg;
3871 
3872 	if ((dr == 6 || dr == 7) && (new_val & 0xffffffff00000000ULL))
3873 		return emulate_gp(ctxt, 0);
3874 
3875 	return check_dr_read(ctxt);
3876 }
3877 
3878 static int check_svme(struct x86_emulate_ctxt *ctxt)
3879 {
3880 	u64 efer = 0;
3881 
3882 	ctxt->ops->get_msr(ctxt, MSR_EFER, &efer);
3883 
3884 	if (!(efer & EFER_SVME))
3885 		return emulate_ud(ctxt);
3886 
3887 	return X86EMUL_CONTINUE;
3888 }
3889 
3890 static int check_svme_pa(struct x86_emulate_ctxt *ctxt)
3891 {
3892 	u64 rax = reg_read(ctxt, VCPU_REGS_RAX);
3893 
3894 	/* Valid physical address? */
3895 	if (rax & 0xffff000000000000ULL)
3896 		return emulate_gp(ctxt, 0);
3897 
3898 	return check_svme(ctxt);
3899 }
3900 
3901 static int check_rdtsc(struct x86_emulate_ctxt *ctxt)
3902 {
3903 	u64 cr4 = ctxt->ops->get_cr(ctxt, 4);
3904 
3905 	if (cr4 & X86_CR4_TSD && ctxt->ops->cpl(ctxt))
3906 		return emulate_gp(ctxt, 0);
3907 
3908 	return X86EMUL_CONTINUE;
3909 }
3910 
3911 static int check_rdpmc(struct x86_emulate_ctxt *ctxt)
3912 {
3913 	u64 cr4 = ctxt->ops->get_cr(ctxt, 4);
3914 	u64 rcx = reg_read(ctxt, VCPU_REGS_RCX);
3915 
3916 	/*
3917 	 * VMware allows access to these Pseduo-PMCs even when read via RDPMC
3918 	 * in Ring3 when CR4.PCE=0.
3919 	 */
3920 	if (enable_vmware_backdoor && is_vmware_backdoor_pmc(rcx))
3921 		return X86EMUL_CONTINUE;
3922 
3923 	/*
3924 	 * If CR4.PCE is set, the SDM requires CPL=0 or CR0.PE=0.  The CR0.PE
3925 	 * check however is unnecessary because CPL is always 0 outside
3926 	 * protected mode.
3927 	 */
3928 	if ((!(cr4 & X86_CR4_PCE) && ctxt->ops->cpl(ctxt)) ||
3929 	    ctxt->ops->check_rdpmc_early(ctxt, rcx))
3930 		return emulate_gp(ctxt, 0);
3931 
3932 	return X86EMUL_CONTINUE;
3933 }
3934 
3935 static int check_perm_in(struct x86_emulate_ctxt *ctxt)
3936 {
3937 	ctxt->dst.bytes = min(ctxt->dst.bytes, 4u);
3938 	if (!emulator_io_permitted(ctxt, ctxt->src.val, ctxt->dst.bytes))
3939 		return emulate_gp(ctxt, 0);
3940 
3941 	return X86EMUL_CONTINUE;
3942 }
3943 
3944 static int check_perm_out(struct x86_emulate_ctxt *ctxt)
3945 {
3946 	ctxt->src.bytes = min(ctxt->src.bytes, 4u);
3947 	if (!emulator_io_permitted(ctxt, ctxt->dst.val, ctxt->src.bytes))
3948 		return emulate_gp(ctxt, 0);
3949 
3950 	return X86EMUL_CONTINUE;
3951 }
3952 
3953 #define D(_y) { .flags = (_y) }
3954 #define DI(_y, _i) { .flags = (_y)|Intercept, .intercept = x86_intercept_##_i }
3955 #define DIP(_y, _i, _p) { .flags = (_y)|Intercept|CheckPerm, \
3956 		      .intercept = x86_intercept_##_i, .check_perm = (_p) }
3957 #define N    D(NotImpl)
3958 #define EXT(_f, _e) { .flags = ((_f) | RMExt), .u.group = (_e) }
3959 #define G(_f, _g) { .flags = ((_f) | Group | ModRM), .u.group = (_g) }
3960 #define GD(_f, _g) { .flags = ((_f) | GroupDual | ModRM), .u.gdual = (_g) }
3961 #define ID(_f, _i) { .flags = ((_f) | InstrDual | ModRM), .u.idual = (_i) }
3962 #define MD(_f, _m) { .flags = ((_f) | ModeDual), .u.mdual = (_m) }
3963 #define E(_f, _e) { .flags = ((_f) | Escape | ModRM), .u.esc = (_e) }
3964 #define I(_f, _e) { .flags = (_f), .u.execute = (_e) }
3965 #define F(_f, _e) { .flags = (_f) | Fastop, .u.fastop = (_e) }
3966 #define II(_f, _e, _i) \
3967 	{ .flags = (_f)|Intercept, .u.execute = (_e), .intercept = x86_intercept_##_i }
3968 #define IIP(_f, _e, _i, _p) \
3969 	{ .flags = (_f)|Intercept|CheckPerm, .u.execute = (_e), \
3970 	  .intercept = x86_intercept_##_i, .check_perm = (_p) }
3971 #define GP(_f, _g) { .flags = ((_f) | Prefix), .u.gprefix = (_g) }
3972 
3973 #define D2bv(_f)      D((_f) | ByteOp), D(_f)
3974 #define D2bvIP(_f, _i, _p) DIP((_f) | ByteOp, _i, _p), DIP(_f, _i, _p)
3975 #define I2bv(_f, _e)  I((_f) | ByteOp, _e), I(_f, _e)
3976 #define F2bv(_f, _e)  F((_f) | ByteOp, _e), F(_f, _e)
3977 #define I2bvIP(_f, _e, _i, _p) \
3978 	IIP((_f) | ByteOp, _e, _i, _p), IIP(_f, _e, _i, _p)
3979 
3980 #define F6ALU(_f, _e) F2bv((_f) | DstMem | SrcReg | ModRM, _e),		\
3981 		F2bv(((_f) | DstReg | SrcMem | ModRM) & ~Lock, _e),	\
3982 		F2bv(((_f) & ~Lock) | DstAcc | SrcImm, _e)
3983 
3984 static const struct opcode group7_rm0[] = {
3985 	N,
3986 	I(SrcNone | Priv | EmulateOnUD,	em_hypercall),
3987 	N, N, N, N, N, N,
3988 };
3989 
3990 static const struct opcode group7_rm1[] = {
3991 	DI(SrcNone | Priv, monitor),
3992 	DI(SrcNone | Priv, mwait),
3993 	N, N, N, N, N, N,
3994 };
3995 
3996 static const struct opcode group7_rm2[] = {
3997 	N,
3998 	II(ImplicitOps | Priv,			em_xsetbv,	xsetbv),
3999 	N, N, N, N, N, N,
4000 };
4001 
4002 static const struct opcode group7_rm3[] = {
4003 	DIP(SrcNone | Prot | Priv,		vmrun,		check_svme_pa),
4004 	II(SrcNone  | Prot | EmulateOnUD,	em_hypercall,	vmmcall),
4005 	DIP(SrcNone | Prot | Priv,		vmload,		check_svme_pa),
4006 	DIP(SrcNone | Prot | Priv,		vmsave,		check_svme_pa),
4007 	DIP(SrcNone | Prot | Priv,		stgi,		check_svme),
4008 	DIP(SrcNone | Prot | Priv,		clgi,		check_svme),
4009 	DIP(SrcNone | Prot | Priv,		skinit,		check_svme),
4010 	DIP(SrcNone | Prot | Priv,		invlpga,	check_svme),
4011 };
4012 
4013 static const struct opcode group7_rm7[] = {
4014 	N,
4015 	DIP(SrcNone, rdtscp, check_rdtsc),
4016 	N, N, N, N, N, N,
4017 };
4018 
4019 static const struct opcode group1[] = {
4020 	F(Lock, em_add),
4021 	F(Lock | PageTable, em_or),
4022 	F(Lock, em_adc),
4023 	F(Lock, em_sbb),
4024 	F(Lock | PageTable, em_and),
4025 	F(Lock, em_sub),
4026 	F(Lock, em_xor),
4027 	F(NoWrite, em_cmp),
4028 };
4029 
4030 static const struct opcode group1A[] = {
4031 	I(DstMem | SrcNone | Mov | Stack | IncSP | TwoMemOp, em_pop), N, N, N, N, N, N, N,
4032 };
4033 
4034 static const struct opcode group2[] = {
4035 	F(DstMem | ModRM, em_rol),
4036 	F(DstMem | ModRM, em_ror),
4037 	F(DstMem | ModRM, em_rcl),
4038 	F(DstMem | ModRM, em_rcr),
4039 	F(DstMem | ModRM, em_shl),
4040 	F(DstMem | ModRM, em_shr),
4041 	F(DstMem | ModRM, em_shl),
4042 	F(DstMem | ModRM, em_sar),
4043 };
4044 
4045 static const struct opcode group3[] = {
4046 	F(DstMem | SrcImm | NoWrite, em_test),
4047 	F(DstMem | SrcImm | NoWrite, em_test),
4048 	F(DstMem | SrcNone | Lock, em_not),
4049 	F(DstMem | SrcNone | Lock, em_neg),
4050 	F(DstXacc | Src2Mem, em_mul_ex),
4051 	F(DstXacc | Src2Mem, em_imul_ex),
4052 	F(DstXacc | Src2Mem, em_div_ex),
4053 	F(DstXacc | Src2Mem, em_idiv_ex),
4054 };
4055 
4056 static const struct opcode group4[] = {
4057 	F(ByteOp | DstMem | SrcNone | Lock, em_inc),
4058 	F(ByteOp | DstMem | SrcNone | Lock, em_dec),
4059 	N, N, N, N, N, N,
4060 };
4061 
4062 static const struct opcode group5[] = {
4063 	F(DstMem | SrcNone | Lock,		em_inc),
4064 	F(DstMem | SrcNone | Lock,		em_dec),
4065 	I(SrcMem | NearBranch | IsBranch,       em_call_near_abs),
4066 	I(SrcMemFAddr | ImplicitOps | IsBranch, em_call_far),
4067 	I(SrcMem | NearBranch | IsBranch,       em_jmp_abs),
4068 	I(SrcMemFAddr | ImplicitOps | IsBranch, em_jmp_far),
4069 	I(SrcMem | Stack | TwoMemOp,		em_push), D(Undefined),
4070 };
4071 
4072 static const struct opcode group6[] = {
4073 	II(Prot | DstMem,	   em_sldt, sldt),
4074 	II(Prot | DstMem,	   em_str, str),
4075 	II(Prot | Priv | SrcMem16, em_lldt, lldt),
4076 	II(Prot | Priv | SrcMem16, em_ltr, ltr),
4077 	N, N, N, N,
4078 };
4079 
4080 static const struct group_dual group7 = { {
4081 	II(Mov | DstMem,			em_sgdt, sgdt),
4082 	II(Mov | DstMem,			em_sidt, sidt),
4083 	II(SrcMem | Priv,			em_lgdt, lgdt),
4084 	II(SrcMem | Priv,			em_lidt, lidt),
4085 	II(SrcNone | DstMem | Mov,		em_smsw, smsw), N,
4086 	II(SrcMem16 | Mov | Priv,		em_lmsw, lmsw),
4087 	II(SrcMem | ByteOp | Priv | NoAccess,	em_invlpg, invlpg),
4088 }, {
4089 	EXT(0, group7_rm0),
4090 	EXT(0, group7_rm1),
4091 	EXT(0, group7_rm2),
4092 	EXT(0, group7_rm3),
4093 	II(SrcNone | DstMem | Mov,		em_smsw, smsw), N,
4094 	II(SrcMem16 | Mov | Priv,		em_lmsw, lmsw),
4095 	EXT(0, group7_rm7),
4096 } };
4097 
4098 static const struct opcode group8[] = {
4099 	N, N, N, N,
4100 	F(DstMem | SrcImmByte | NoWrite,		em_bt),
4101 	F(DstMem | SrcImmByte | Lock | PageTable,	em_bts),
4102 	F(DstMem | SrcImmByte | Lock,			em_btr),
4103 	F(DstMem | SrcImmByte | Lock | PageTable,	em_btc),
4104 };
4105 
4106 /*
4107  * The "memory" destination is actually always a register, since we come
4108  * from the register case of group9.
4109  */
4110 static const struct gprefix pfx_0f_c7_7 = {
4111 	N, N, N, II(DstMem | ModRM | Op3264 | EmulateOnUD, em_rdpid, rdpid),
4112 };
4113 
4114 
4115 static const struct group_dual group9 = { {
4116 	N, I(DstMem64 | Lock | PageTable, em_cmpxchg8b), N, N, N, N, N, N,
4117 }, {
4118 	N, N, N, N, N, N, N,
4119 	GP(0, &pfx_0f_c7_7),
4120 } };
4121 
4122 static const struct opcode group11[] = {
4123 	I(DstMem | SrcImm | Mov | PageTable, em_mov),
4124 	X7(D(Undefined)),
4125 };
4126 
4127 static const struct gprefix pfx_0f_ae_7 = {
4128 	I(SrcMem | ByteOp, em_clflush), I(SrcMem | ByteOp, em_clflushopt), N, N,
4129 };
4130 
4131 static const struct group_dual group15 = { {
4132 	I(ModRM | Aligned16, em_fxsave),
4133 	I(ModRM | Aligned16, em_fxrstor),
4134 	N, N, N, N, N, GP(0, &pfx_0f_ae_7),
4135 }, {
4136 	N, N, N, N, N, N, N, N,
4137 } };
4138 
4139 static const struct gprefix pfx_0f_6f_0f_7f = {
4140 	I(Mmx, em_mov), I(Sse | Aligned, em_mov), N, I(Sse | Unaligned, em_mov),
4141 };
4142 
4143 static const struct instr_dual instr_dual_0f_2b = {
4144 	I(0, em_mov), N
4145 };
4146 
4147 static const struct gprefix pfx_0f_2b = {
4148 	ID(0, &instr_dual_0f_2b), ID(0, &instr_dual_0f_2b), N, N,
4149 };
4150 
4151 static const struct gprefix pfx_0f_10_0f_11 = {
4152 	I(Unaligned, em_mov), I(Unaligned, em_mov), N, N,
4153 };
4154 
4155 static const struct gprefix pfx_0f_28_0f_29 = {
4156 	I(Aligned, em_mov), I(Aligned, em_mov), N, N,
4157 };
4158 
4159 static const struct gprefix pfx_0f_e7 = {
4160 	N, I(Sse, em_mov), N, N,
4161 };
4162 
4163 static const struct escape escape_d9 = { {
4164 	N, N, N, N, N, N, N, I(DstMem16 | Mov, em_fnstcw),
4165 }, {
4166 	/* 0xC0 - 0xC7 */
4167 	N, N, N, N, N, N, N, N,
4168 	/* 0xC8 - 0xCF */
4169 	N, N, N, N, N, N, N, N,
4170 	/* 0xD0 - 0xC7 */
4171 	N, N, N, N, N, N, N, N,
4172 	/* 0xD8 - 0xDF */
4173 	N, N, N, N, N, N, N, N,
4174 	/* 0xE0 - 0xE7 */
4175 	N, N, N, N, N, N, N, N,
4176 	/* 0xE8 - 0xEF */
4177 	N, N, N, N, N, N, N, N,
4178 	/* 0xF0 - 0xF7 */
4179 	N, N, N, N, N, N, N, N,
4180 	/* 0xF8 - 0xFF */
4181 	N, N, N, N, N, N, N, N,
4182 } };
4183 
4184 static const struct escape escape_db = { {
4185 	N, N, N, N, N, N, N, N,
4186 }, {
4187 	/* 0xC0 - 0xC7 */
4188 	N, N, N, N, N, N, N, N,
4189 	/* 0xC8 - 0xCF */
4190 	N, N, N, N, N, N, N, N,
4191 	/* 0xD0 - 0xC7 */
4192 	N, N, N, N, N, N, N, N,
4193 	/* 0xD8 - 0xDF */
4194 	N, N, N, N, N, N, N, N,
4195 	/* 0xE0 - 0xE7 */
4196 	N, N, N, I(ImplicitOps, em_fninit), N, N, N, N,
4197 	/* 0xE8 - 0xEF */
4198 	N, N, N, N, N, N, N, N,
4199 	/* 0xF0 - 0xF7 */
4200 	N, N, N, N, N, N, N, N,
4201 	/* 0xF8 - 0xFF */
4202 	N, N, N, N, N, N, N, N,
4203 } };
4204 
4205 static const struct escape escape_dd = { {
4206 	N, N, N, N, N, N, N, I(DstMem16 | Mov, em_fnstsw),
4207 }, {
4208 	/* 0xC0 - 0xC7 */
4209 	N, N, N, N, N, N, N, N,
4210 	/* 0xC8 - 0xCF */
4211 	N, N, N, N, N, N, N, N,
4212 	/* 0xD0 - 0xC7 */
4213 	N, N, N, N, N, N, N, N,
4214 	/* 0xD8 - 0xDF */
4215 	N, N, N, N, N, N, N, N,
4216 	/* 0xE0 - 0xE7 */
4217 	N, N, N, N, N, N, N, N,
4218 	/* 0xE8 - 0xEF */
4219 	N, N, N, N, N, N, N, N,
4220 	/* 0xF0 - 0xF7 */
4221 	N, N, N, N, N, N, N, N,
4222 	/* 0xF8 - 0xFF */
4223 	N, N, N, N, N, N, N, N,
4224 } };
4225 
4226 static const struct instr_dual instr_dual_0f_c3 = {
4227 	I(DstMem | SrcReg | ModRM | No16 | Mov, em_mov), N
4228 };
4229 
4230 static const struct mode_dual mode_dual_63 = {
4231 	N, I(DstReg | SrcMem32 | ModRM | Mov, em_movsxd)
4232 };
4233 
4234 static const struct instr_dual instr_dual_8d = {
4235 	D(DstReg | SrcMem | ModRM | NoAccess), N
4236 };
4237 
4238 static const struct opcode opcode_table[256] = {
4239 	/* 0x00 - 0x07 */
4240 	F6ALU(Lock, em_add),
4241 	I(ImplicitOps | Stack | No64 | Src2ES, em_push_sreg),
4242 	I(ImplicitOps | Stack | No64 | Src2ES, em_pop_sreg),
4243 	/* 0x08 - 0x0F */
4244 	F6ALU(Lock | PageTable, em_or),
4245 	I(ImplicitOps | Stack | No64 | Src2CS, em_push_sreg),
4246 	N,
4247 	/* 0x10 - 0x17 */
4248 	F6ALU(Lock, em_adc),
4249 	I(ImplicitOps | Stack | No64 | Src2SS, em_push_sreg),
4250 	I(ImplicitOps | Stack | No64 | Src2SS, em_pop_sreg),
4251 	/* 0x18 - 0x1F */
4252 	F6ALU(Lock, em_sbb),
4253 	I(ImplicitOps | Stack | No64 | Src2DS, em_push_sreg),
4254 	I(ImplicitOps | Stack | No64 | Src2DS, em_pop_sreg),
4255 	/* 0x20 - 0x27 */
4256 	F6ALU(Lock | PageTable, em_and), N, N,
4257 	/* 0x28 - 0x2F */
4258 	F6ALU(Lock, em_sub), N, I(ByteOp | DstAcc | No64, em_das),
4259 	/* 0x30 - 0x37 */
4260 	F6ALU(Lock, em_xor), N, N,
4261 	/* 0x38 - 0x3F */
4262 	F6ALU(NoWrite, em_cmp), N, N,
4263 	/* 0x40 - 0x4F */
4264 	X8(F(DstReg, em_inc)), X8(F(DstReg, em_dec)),
4265 	/* 0x50 - 0x57 */
4266 	X8(I(SrcReg | Stack, em_push)),
4267 	/* 0x58 - 0x5F */
4268 	X8(I(DstReg | Stack, em_pop)),
4269 	/* 0x60 - 0x67 */
4270 	I(ImplicitOps | Stack | No64, em_pusha),
4271 	I(ImplicitOps | Stack | No64, em_popa),
4272 	N, MD(ModRM, &mode_dual_63),
4273 	N, N, N, N,
4274 	/* 0x68 - 0x6F */
4275 	I(SrcImm | Mov | Stack, em_push),
4276 	I(DstReg | SrcMem | ModRM | Src2Imm, em_imul_3op),
4277 	I(SrcImmByte | Mov | Stack, em_push),
4278 	I(DstReg | SrcMem | ModRM | Src2ImmByte, em_imul_3op),
4279 	I2bvIP(DstDI | SrcDX | Mov | String | Unaligned, em_in, ins, check_perm_in), /* insb, insw/insd */
4280 	I2bvIP(SrcSI | DstDX | String, em_out, outs, check_perm_out), /* outsb, outsw/outsd */
4281 	/* 0x70 - 0x7F */
4282 	X16(D(SrcImmByte | NearBranch | IsBranch)),
4283 	/* 0x80 - 0x87 */
4284 	G(ByteOp | DstMem | SrcImm, group1),
4285 	G(DstMem | SrcImm, group1),
4286 	G(ByteOp | DstMem | SrcImm | No64, group1),
4287 	G(DstMem | SrcImmByte, group1),
4288 	F2bv(DstMem | SrcReg | ModRM | NoWrite, em_test),
4289 	I2bv(DstMem | SrcReg | ModRM | Lock | PageTable, em_xchg),
4290 	/* 0x88 - 0x8F */
4291 	I2bv(DstMem | SrcReg | ModRM | Mov | PageTable, em_mov),
4292 	I2bv(DstReg | SrcMem | ModRM | Mov, em_mov),
4293 	I(DstMem | SrcNone | ModRM | Mov | PageTable, em_mov_rm_sreg),
4294 	ID(0, &instr_dual_8d),
4295 	I(ImplicitOps | SrcMem16 | ModRM, em_mov_sreg_rm),
4296 	G(0, group1A),
4297 	/* 0x90 - 0x97 */
4298 	DI(SrcAcc | DstReg, pause), X7(D(SrcAcc | DstReg)),
4299 	/* 0x98 - 0x9F */
4300 	D(DstAcc | SrcNone), I(ImplicitOps | SrcAcc, em_cwd),
4301 	I(SrcImmFAddr | No64 | IsBranch, em_call_far), N,
4302 	II(ImplicitOps | Stack, em_pushf, pushf),
4303 	II(ImplicitOps | Stack, em_popf, popf),
4304 	I(ImplicitOps, em_sahf), I(ImplicitOps, em_lahf),
4305 	/* 0xA0 - 0xA7 */
4306 	I2bv(DstAcc | SrcMem | Mov | MemAbs, em_mov),
4307 	I2bv(DstMem | SrcAcc | Mov | MemAbs | PageTable, em_mov),
4308 	I2bv(SrcSI | DstDI | Mov | String | TwoMemOp, em_mov),
4309 	F2bv(SrcSI | DstDI | String | NoWrite | TwoMemOp, em_cmp_r),
4310 	/* 0xA8 - 0xAF */
4311 	F2bv(DstAcc | SrcImm | NoWrite, em_test),
4312 	I2bv(SrcAcc | DstDI | Mov | String, em_mov),
4313 	I2bv(SrcSI | DstAcc | Mov | String, em_mov),
4314 	F2bv(SrcAcc | DstDI | String | NoWrite, em_cmp_r),
4315 	/* 0xB0 - 0xB7 */
4316 	X8(I(ByteOp | DstReg | SrcImm | Mov, em_mov)),
4317 	/* 0xB8 - 0xBF */
4318 	X8(I(DstReg | SrcImm64 | Mov, em_mov)),
4319 	/* 0xC0 - 0xC7 */
4320 	G(ByteOp | Src2ImmByte, group2), G(Src2ImmByte, group2),
4321 	I(ImplicitOps | NearBranch | SrcImmU16 | IsBranch, em_ret_near_imm),
4322 	I(ImplicitOps | NearBranch | IsBranch, em_ret),
4323 	I(DstReg | SrcMemFAddr | ModRM | No64 | Src2ES, em_lseg),
4324 	I(DstReg | SrcMemFAddr | ModRM | No64 | Src2DS, em_lseg),
4325 	G(ByteOp, group11), G(0, group11),
4326 	/* 0xC8 - 0xCF */
4327 	I(Stack | SrcImmU16 | Src2ImmByte | IsBranch, em_enter),
4328 	I(Stack | IsBranch, em_leave),
4329 	I(ImplicitOps | SrcImmU16 | IsBranch, em_ret_far_imm),
4330 	I(ImplicitOps | IsBranch, em_ret_far),
4331 	D(ImplicitOps | IsBranch), DI(SrcImmByte | IsBranch, intn),
4332 	D(ImplicitOps | No64 | IsBranch),
4333 	II(ImplicitOps | IsBranch, em_iret, iret),
4334 	/* 0xD0 - 0xD7 */
4335 	G(Src2One | ByteOp, group2), G(Src2One, group2),
4336 	G(Src2CL | ByteOp, group2), G(Src2CL, group2),
4337 	I(DstAcc | SrcImmUByte | No64, em_aam),
4338 	I(DstAcc | SrcImmUByte | No64, em_aad),
4339 	F(DstAcc | ByteOp | No64, em_salc),
4340 	I(DstAcc | SrcXLat | ByteOp, em_mov),
4341 	/* 0xD8 - 0xDF */
4342 	N, E(0, &escape_d9), N, E(0, &escape_db), N, E(0, &escape_dd), N, N,
4343 	/* 0xE0 - 0xE7 */
4344 	X3(I(SrcImmByte | NearBranch | IsBranch, em_loop)),
4345 	I(SrcImmByte | NearBranch | IsBranch, em_jcxz),
4346 	I2bvIP(SrcImmUByte | DstAcc, em_in,  in,  check_perm_in),
4347 	I2bvIP(SrcAcc | DstImmUByte, em_out, out, check_perm_out),
4348 	/* 0xE8 - 0xEF */
4349 	I(SrcImm | NearBranch | IsBranch, em_call),
4350 	D(SrcImm | ImplicitOps | NearBranch | IsBranch),
4351 	I(SrcImmFAddr | No64 | IsBranch, em_jmp_far),
4352 	D(SrcImmByte | ImplicitOps | NearBranch | IsBranch),
4353 	I2bvIP(SrcDX | DstAcc, em_in,  in,  check_perm_in),
4354 	I2bvIP(SrcAcc | DstDX, em_out, out, check_perm_out),
4355 	/* 0xF0 - 0xF7 */
4356 	N, DI(ImplicitOps, icebp), N, N,
4357 	DI(ImplicitOps | Priv, hlt), D(ImplicitOps),
4358 	G(ByteOp, group3), G(0, group3),
4359 	/* 0xF8 - 0xFF */
4360 	D(ImplicitOps), D(ImplicitOps),
4361 	I(ImplicitOps, em_cli), I(ImplicitOps, em_sti),
4362 	D(ImplicitOps), D(ImplicitOps), G(0, group4), G(0, group5),
4363 };
4364 
4365 static const struct opcode twobyte_table[256] = {
4366 	/* 0x00 - 0x0F */
4367 	G(0, group6), GD(0, &group7), N, N,
4368 	N, I(ImplicitOps | EmulateOnUD | IsBranch, em_syscall),
4369 	II(ImplicitOps | Priv, em_clts, clts), N,
4370 	DI(ImplicitOps | Priv, invd), DI(ImplicitOps | Priv, wbinvd), N, N,
4371 	N, D(ImplicitOps | ModRM | SrcMem | NoAccess), N, N,
4372 	/* 0x10 - 0x1F */
4373 	GP(ModRM | DstReg | SrcMem | Mov | Sse, &pfx_0f_10_0f_11),
4374 	GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_10_0f_11),
4375 	N, N, N, N, N, N,
4376 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* 4 * prefetch + 4 * reserved NOP */
4377 	D(ImplicitOps | ModRM | SrcMem | NoAccess), N, N,
4378 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* 8 * reserved NOP */
4379 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* 8 * reserved NOP */
4380 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* 8 * reserved NOP */
4381 	D(ImplicitOps | ModRM | SrcMem | NoAccess), /* NOP + 7 * reserved NOP */
4382 	/* 0x20 - 0x2F */
4383 	DIP(ModRM | DstMem | Priv | Op3264 | NoMod, cr_read, check_cr_access),
4384 	DIP(ModRM | DstMem | Priv | Op3264 | NoMod, dr_read, check_dr_read),
4385 	IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_cr_write, cr_write,
4386 						check_cr_access),
4387 	IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_dr_write, dr_write,
4388 						check_dr_write),
4389 	N, N, N, N,
4390 	GP(ModRM | DstReg | SrcMem | Mov | Sse, &pfx_0f_28_0f_29),
4391 	GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_28_0f_29),
4392 	N, GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_2b),
4393 	N, N, N, N,
4394 	/* 0x30 - 0x3F */
4395 	II(ImplicitOps | Priv, em_wrmsr, wrmsr),
4396 	IIP(ImplicitOps, em_rdtsc, rdtsc, check_rdtsc),
4397 	II(ImplicitOps | Priv, em_rdmsr, rdmsr),
4398 	IIP(ImplicitOps, em_rdpmc, rdpmc, check_rdpmc),
4399 	I(ImplicitOps | EmulateOnUD | IsBranch, em_sysenter),
4400 	I(ImplicitOps | Priv | EmulateOnUD | IsBranch, em_sysexit),
4401 	N, N,
4402 	N, N, N, N, N, N, N, N,
4403 	/* 0x40 - 0x4F */
4404 	X16(D(DstReg | SrcMem | ModRM)),
4405 	/* 0x50 - 0x5F */
4406 	N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N,
4407 	/* 0x60 - 0x6F */
4408 	N, N, N, N,
4409 	N, N, N, N,
4410 	N, N, N, N,
4411 	N, N, N, GP(SrcMem | DstReg | ModRM | Mov, &pfx_0f_6f_0f_7f),
4412 	/* 0x70 - 0x7F */
4413 	N, N, N, N,
4414 	N, N, N, N,
4415 	N, N, N, N,
4416 	N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_6f_0f_7f),
4417 	/* 0x80 - 0x8F */
4418 	X16(D(SrcImm | NearBranch | IsBranch)),
4419 	/* 0x90 - 0x9F */
4420 	X16(D(ByteOp | DstMem | SrcNone | ModRM| Mov)),
4421 	/* 0xA0 - 0xA7 */
4422 	I(Stack | Src2FS, em_push_sreg), I(Stack | Src2FS, em_pop_sreg),
4423 	II(ImplicitOps, em_cpuid, cpuid),
4424 	F(DstMem | SrcReg | ModRM | BitOp | NoWrite, em_bt),
4425 	F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shld),
4426 	F(DstMem | SrcReg | Src2CL | ModRM, em_shld), N, N,
4427 	/* 0xA8 - 0xAF */
4428 	I(Stack | Src2GS, em_push_sreg), I(Stack | Src2GS, em_pop_sreg),
4429 	II(EmulateOnUD | ImplicitOps, em_rsm, rsm),
4430 	F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_bts),
4431 	F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shrd),
4432 	F(DstMem | SrcReg | Src2CL | ModRM, em_shrd),
4433 	GD(0, &group15), F(DstReg | SrcMem | ModRM, em_imul),
4434 	/* 0xB0 - 0xB7 */
4435 	I2bv(DstMem | SrcReg | ModRM | Lock | PageTable | SrcWrite, em_cmpxchg),
4436 	I(DstReg | SrcMemFAddr | ModRM | Src2SS, em_lseg),
4437 	F(DstMem | SrcReg | ModRM | BitOp | Lock, em_btr),
4438 	I(DstReg | SrcMemFAddr | ModRM | Src2FS, em_lseg),
4439 	I(DstReg | SrcMemFAddr | ModRM | Src2GS, em_lseg),
4440 	D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov),
4441 	/* 0xB8 - 0xBF */
4442 	N, N,
4443 	G(BitOp, group8),
4444 	F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_btc),
4445 	I(DstReg | SrcMem | ModRM, em_bsf_c),
4446 	I(DstReg | SrcMem | ModRM, em_bsr_c),
4447 	D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov),
4448 	/* 0xC0 - 0xC7 */
4449 	F2bv(DstMem | SrcReg | ModRM | SrcWrite | Lock, em_xadd),
4450 	N, ID(0, &instr_dual_0f_c3),
4451 	N, N, N, GD(0, &group9),
4452 	/* 0xC8 - 0xCF */
4453 	X8(I(DstReg, em_bswap)),
4454 	/* 0xD0 - 0xDF */
4455 	N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N,
4456 	/* 0xE0 - 0xEF */
4457 	N, N, N, N, N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_e7),
4458 	N, N, N, N, N, N, N, N,
4459 	/* 0xF0 - 0xFF */
4460 	N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N
4461 };
4462 
4463 static const struct instr_dual instr_dual_0f_38_f0 = {
4464 	I(DstReg | SrcMem | Mov, em_movbe), N
4465 };
4466 
4467 static const struct instr_dual instr_dual_0f_38_f1 = {
4468 	I(DstMem | SrcReg | Mov, em_movbe), N
4469 };
4470 
4471 static const struct gprefix three_byte_0f_38_f0 = {
4472 	ID(0, &instr_dual_0f_38_f0), ID(0, &instr_dual_0f_38_f0), N, N
4473 };
4474 
4475 static const struct gprefix three_byte_0f_38_f1 = {
4476 	ID(0, &instr_dual_0f_38_f1), ID(0, &instr_dual_0f_38_f1), N, N
4477 };
4478 
4479 /*
4480  * Insns below are selected by the prefix which indexed by the third opcode
4481  * byte.
4482  */
4483 static const struct opcode opcode_map_0f_38[256] = {
4484 	/* 0x00 - 0x7f */
4485 	X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N),
4486 	/* 0x80 - 0xef */
4487 	X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N),
4488 	/* 0xf0 - 0xf1 */
4489 	GP(EmulateOnUD | ModRM, &three_byte_0f_38_f0),
4490 	GP(EmulateOnUD | ModRM, &three_byte_0f_38_f1),
4491 	/* 0xf2 - 0xff */
4492 	N, N, X4(N), X8(N)
4493 };
4494 
4495 #undef D
4496 #undef N
4497 #undef G
4498 #undef GD
4499 #undef I
4500 #undef GP
4501 #undef EXT
4502 #undef MD
4503 #undef ID
4504 
4505 #undef D2bv
4506 #undef D2bvIP
4507 #undef I2bv
4508 #undef I2bvIP
4509 #undef I6ALU
4510 
4511 static unsigned imm_size(struct x86_emulate_ctxt *ctxt)
4512 {
4513 	unsigned size;
4514 
4515 	size = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4516 	if (size == 8)
4517 		size = 4;
4518 	return size;
4519 }
4520 
4521 static int decode_imm(struct x86_emulate_ctxt *ctxt, struct operand *op,
4522 		      unsigned size, bool sign_extension)
4523 {
4524 	int rc = X86EMUL_CONTINUE;
4525 
4526 	op->type = OP_IMM;
4527 	op->bytes = size;
4528 	op->addr.mem.ea = ctxt->_eip;
4529 	/* NB. Immediates are sign-extended as necessary. */
4530 	switch (op->bytes) {
4531 	case 1:
4532 		op->val = insn_fetch(s8, ctxt);
4533 		break;
4534 	case 2:
4535 		op->val = insn_fetch(s16, ctxt);
4536 		break;
4537 	case 4:
4538 		op->val = insn_fetch(s32, ctxt);
4539 		break;
4540 	case 8:
4541 		op->val = insn_fetch(s64, ctxt);
4542 		break;
4543 	}
4544 	if (!sign_extension) {
4545 		switch (op->bytes) {
4546 		case 1:
4547 			op->val &= 0xff;
4548 			break;
4549 		case 2:
4550 			op->val &= 0xffff;
4551 			break;
4552 		case 4:
4553 			op->val &= 0xffffffff;
4554 			break;
4555 		}
4556 	}
4557 done:
4558 	return rc;
4559 }
4560 
4561 static int decode_operand(struct x86_emulate_ctxt *ctxt, struct operand *op,
4562 			  unsigned d)
4563 {
4564 	int rc = X86EMUL_CONTINUE;
4565 
4566 	switch (d) {
4567 	case OpReg:
4568 		decode_register_operand(ctxt, op);
4569 		break;
4570 	case OpImmUByte:
4571 		rc = decode_imm(ctxt, op, 1, false);
4572 		break;
4573 	case OpMem:
4574 		ctxt->memop.bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4575 	mem_common:
4576 		*op = ctxt->memop;
4577 		ctxt->memopp = op;
4578 		if (ctxt->d & BitOp)
4579 			fetch_bit_operand(ctxt);
4580 		op->orig_val = op->val;
4581 		break;
4582 	case OpMem64:
4583 		ctxt->memop.bytes = (ctxt->op_bytes == 8) ? 16 : 8;
4584 		goto mem_common;
4585 	case OpAcc:
4586 		op->type = OP_REG;
4587 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4588 		op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
4589 		fetch_register_operand(op);
4590 		op->orig_val = op->val;
4591 		break;
4592 	case OpAccLo:
4593 		op->type = OP_REG;
4594 		op->bytes = (ctxt->d & ByteOp) ? 2 : ctxt->op_bytes;
4595 		op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX);
4596 		fetch_register_operand(op);
4597 		op->orig_val = op->val;
4598 		break;
4599 	case OpAccHi:
4600 		if (ctxt->d & ByteOp) {
4601 			op->type = OP_NONE;
4602 			break;
4603 		}
4604 		op->type = OP_REG;
4605 		op->bytes = ctxt->op_bytes;
4606 		op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
4607 		fetch_register_operand(op);
4608 		op->orig_val = op->val;
4609 		break;
4610 	case OpDI:
4611 		op->type = OP_MEM;
4612 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4613 		op->addr.mem.ea =
4614 			register_address(ctxt, VCPU_REGS_RDI);
4615 		op->addr.mem.seg = VCPU_SREG_ES;
4616 		op->val = 0;
4617 		op->count = 1;
4618 		break;
4619 	case OpDX:
4620 		op->type = OP_REG;
4621 		op->bytes = 2;
4622 		op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX);
4623 		fetch_register_operand(op);
4624 		break;
4625 	case OpCL:
4626 		op->type = OP_IMM;
4627 		op->bytes = 1;
4628 		op->val = reg_read(ctxt, VCPU_REGS_RCX) & 0xff;
4629 		break;
4630 	case OpImmByte:
4631 		rc = decode_imm(ctxt, op, 1, true);
4632 		break;
4633 	case OpOne:
4634 		op->type = OP_IMM;
4635 		op->bytes = 1;
4636 		op->val = 1;
4637 		break;
4638 	case OpImm:
4639 		rc = decode_imm(ctxt, op, imm_size(ctxt), true);
4640 		break;
4641 	case OpImm64:
4642 		rc = decode_imm(ctxt, op, ctxt->op_bytes, true);
4643 		break;
4644 	case OpMem8:
4645 		ctxt->memop.bytes = 1;
4646 		if (ctxt->memop.type == OP_REG) {
4647 			ctxt->memop.addr.reg = decode_register(ctxt,
4648 					ctxt->modrm_rm, true);
4649 			fetch_register_operand(&ctxt->memop);
4650 		}
4651 		goto mem_common;
4652 	case OpMem16:
4653 		ctxt->memop.bytes = 2;
4654 		goto mem_common;
4655 	case OpMem32:
4656 		ctxt->memop.bytes = 4;
4657 		goto mem_common;
4658 	case OpImmU16:
4659 		rc = decode_imm(ctxt, op, 2, false);
4660 		break;
4661 	case OpImmU:
4662 		rc = decode_imm(ctxt, op, imm_size(ctxt), false);
4663 		break;
4664 	case OpSI:
4665 		op->type = OP_MEM;
4666 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4667 		op->addr.mem.ea =
4668 			register_address(ctxt, VCPU_REGS_RSI);
4669 		op->addr.mem.seg = ctxt->seg_override;
4670 		op->val = 0;
4671 		op->count = 1;
4672 		break;
4673 	case OpXLat:
4674 		op->type = OP_MEM;
4675 		op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;
4676 		op->addr.mem.ea =
4677 			address_mask(ctxt,
4678 				reg_read(ctxt, VCPU_REGS_RBX) +
4679 				(reg_read(ctxt, VCPU_REGS_RAX) & 0xff));
4680 		op->addr.mem.seg = ctxt->seg_override;
4681 		op->val = 0;
4682 		break;
4683 	case OpImmFAddr:
4684 		op->type = OP_IMM;
4685 		op->addr.mem.ea = ctxt->_eip;
4686 		op->bytes = ctxt->op_bytes + 2;
4687 		insn_fetch_arr(op->valptr, op->bytes, ctxt);
4688 		break;
4689 	case OpMemFAddr:
4690 		ctxt->memop.bytes = ctxt->op_bytes + 2;
4691 		goto mem_common;
4692 	case OpES:
4693 		op->type = OP_IMM;
4694 		op->val = VCPU_SREG_ES;
4695 		break;
4696 	case OpCS:
4697 		op->type = OP_IMM;
4698 		op->val = VCPU_SREG_CS;
4699 		break;
4700 	case OpSS:
4701 		op->type = OP_IMM;
4702 		op->val = VCPU_SREG_SS;
4703 		break;
4704 	case OpDS:
4705 		op->type = OP_IMM;
4706 		op->val = VCPU_SREG_DS;
4707 		break;
4708 	case OpFS:
4709 		op->type = OP_IMM;
4710 		op->val = VCPU_SREG_FS;
4711 		break;
4712 	case OpGS:
4713 		op->type = OP_IMM;
4714 		op->val = VCPU_SREG_GS;
4715 		break;
4716 	case OpImplicit:
4717 		/* Special instructions do their own operand decoding. */
4718 	default:
4719 		op->type = OP_NONE; /* Disable writeback. */
4720 		break;
4721 	}
4722 
4723 done:
4724 	return rc;
4725 }
4726 
4727 int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len, int emulation_type)
4728 {
4729 	int rc = X86EMUL_CONTINUE;
4730 	int mode = ctxt->mode;
4731 	int def_op_bytes, def_ad_bytes, goffset, simd_prefix;
4732 	bool op_prefix = false;
4733 	bool has_seg_override = false;
4734 	struct opcode opcode;
4735 	u16 dummy;
4736 	struct desc_struct desc;
4737 
4738 	ctxt->memop.type = OP_NONE;
4739 	ctxt->memopp = NULL;
4740 	ctxt->_eip = ctxt->eip;
4741 	ctxt->fetch.ptr = ctxt->fetch.data;
4742 	ctxt->fetch.end = ctxt->fetch.data + insn_len;
4743 	ctxt->opcode_len = 1;
4744 	ctxt->intercept = x86_intercept_none;
4745 	if (insn_len > 0)
4746 		memcpy(ctxt->fetch.data, insn, insn_len);
4747 	else {
4748 		rc = __do_insn_fetch_bytes(ctxt, 1);
4749 		if (rc != X86EMUL_CONTINUE)
4750 			goto done;
4751 	}
4752 
4753 	switch (mode) {
4754 	case X86EMUL_MODE_REAL:
4755 	case X86EMUL_MODE_VM86:
4756 		def_op_bytes = def_ad_bytes = 2;
4757 		ctxt->ops->get_segment(ctxt, &dummy, &desc, NULL, VCPU_SREG_CS);
4758 		if (desc.d)
4759 			def_op_bytes = def_ad_bytes = 4;
4760 		break;
4761 	case X86EMUL_MODE_PROT16:
4762 		def_op_bytes = def_ad_bytes = 2;
4763 		break;
4764 	case X86EMUL_MODE_PROT32:
4765 		def_op_bytes = def_ad_bytes = 4;
4766 		break;
4767 #ifdef CONFIG_X86_64
4768 	case X86EMUL_MODE_PROT64:
4769 		def_op_bytes = 4;
4770 		def_ad_bytes = 8;
4771 		break;
4772 #endif
4773 	default:
4774 		return EMULATION_FAILED;
4775 	}
4776 
4777 	ctxt->op_bytes = def_op_bytes;
4778 	ctxt->ad_bytes = def_ad_bytes;
4779 
4780 	/* Legacy prefixes. */
4781 	for (;;) {
4782 		switch (ctxt->b = insn_fetch(u8, ctxt)) {
4783 		case 0x66:	/* operand-size override */
4784 			op_prefix = true;
4785 			/* switch between 2/4 bytes */
4786 			ctxt->op_bytes = def_op_bytes ^ 6;
4787 			break;
4788 		case 0x67:	/* address-size override */
4789 			if (mode == X86EMUL_MODE_PROT64)
4790 				/* switch between 4/8 bytes */
4791 				ctxt->ad_bytes = def_ad_bytes ^ 12;
4792 			else
4793 				/* switch between 2/4 bytes */
4794 				ctxt->ad_bytes = def_ad_bytes ^ 6;
4795 			break;
4796 		case 0x26:	/* ES override */
4797 			has_seg_override = true;
4798 			ctxt->seg_override = VCPU_SREG_ES;
4799 			break;
4800 		case 0x2e:	/* CS override */
4801 			has_seg_override = true;
4802 			ctxt->seg_override = VCPU_SREG_CS;
4803 			break;
4804 		case 0x36:	/* SS override */
4805 			has_seg_override = true;
4806 			ctxt->seg_override = VCPU_SREG_SS;
4807 			break;
4808 		case 0x3e:	/* DS override */
4809 			has_seg_override = true;
4810 			ctxt->seg_override = VCPU_SREG_DS;
4811 			break;
4812 		case 0x64:	/* FS override */
4813 			has_seg_override = true;
4814 			ctxt->seg_override = VCPU_SREG_FS;
4815 			break;
4816 		case 0x65:	/* GS override */
4817 			has_seg_override = true;
4818 			ctxt->seg_override = VCPU_SREG_GS;
4819 			break;
4820 		case 0x40 ... 0x4f: /* REX */
4821 			if (mode != X86EMUL_MODE_PROT64)
4822 				goto done_prefixes;
4823 			ctxt->rex_prefix = ctxt->b;
4824 			continue;
4825 		case 0xf0:	/* LOCK */
4826 			ctxt->lock_prefix = 1;
4827 			break;
4828 		case 0xf2:	/* REPNE/REPNZ */
4829 		case 0xf3:	/* REP/REPE/REPZ */
4830 			ctxt->rep_prefix = ctxt->b;
4831 			break;
4832 		default:
4833 			goto done_prefixes;
4834 		}
4835 
4836 		/* Any legacy prefix after a REX prefix nullifies its effect. */
4837 
4838 		ctxt->rex_prefix = 0;
4839 	}
4840 
4841 done_prefixes:
4842 
4843 	/* REX prefix. */
4844 	if (ctxt->rex_prefix & 8)
4845 		ctxt->op_bytes = 8;	/* REX.W */
4846 
4847 	/* Opcode byte(s). */
4848 	opcode = opcode_table[ctxt->b];
4849 	/* Two-byte opcode? */
4850 	if (ctxt->b == 0x0f) {
4851 		ctxt->opcode_len = 2;
4852 		ctxt->b = insn_fetch(u8, ctxt);
4853 		opcode = twobyte_table[ctxt->b];
4854 
4855 		/* 0F_38 opcode map */
4856 		if (ctxt->b == 0x38) {
4857 			ctxt->opcode_len = 3;
4858 			ctxt->b = insn_fetch(u8, ctxt);
4859 			opcode = opcode_map_0f_38[ctxt->b];
4860 		}
4861 	}
4862 	ctxt->d = opcode.flags;
4863 
4864 	if (ctxt->d & ModRM)
4865 		ctxt->modrm = insn_fetch(u8, ctxt);
4866 
4867 	/* vex-prefix instructions are not implemented */
4868 	if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) &&
4869 	    (mode == X86EMUL_MODE_PROT64 || (ctxt->modrm & 0xc0) == 0xc0)) {
4870 		ctxt->d = NotImpl;
4871 	}
4872 
4873 	while (ctxt->d & GroupMask) {
4874 		switch (ctxt->d & GroupMask) {
4875 		case Group:
4876 			goffset = (ctxt->modrm >> 3) & 7;
4877 			opcode = opcode.u.group[goffset];
4878 			break;
4879 		case GroupDual:
4880 			goffset = (ctxt->modrm >> 3) & 7;
4881 			if ((ctxt->modrm >> 6) == 3)
4882 				opcode = opcode.u.gdual->mod3[goffset];
4883 			else
4884 				opcode = opcode.u.gdual->mod012[goffset];
4885 			break;
4886 		case RMExt:
4887 			goffset = ctxt->modrm & 7;
4888 			opcode = opcode.u.group[goffset];
4889 			break;
4890 		case Prefix:
4891 			if (ctxt->rep_prefix && op_prefix)
4892 				return EMULATION_FAILED;
4893 			simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix;
4894 			switch (simd_prefix) {
4895 			case 0x00: opcode = opcode.u.gprefix->pfx_no; break;
4896 			case 0x66: opcode = opcode.u.gprefix->pfx_66; break;
4897 			case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break;
4898 			case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break;
4899 			}
4900 			break;
4901 		case Escape:
4902 			if (ctxt->modrm > 0xbf) {
4903 				size_t size = ARRAY_SIZE(opcode.u.esc->high);
4904 				u32 index = array_index_nospec(
4905 					ctxt->modrm - 0xc0, size);
4906 
4907 				opcode = opcode.u.esc->high[index];
4908 			} else {
4909 				opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7];
4910 			}
4911 			break;
4912 		case InstrDual:
4913 			if ((ctxt->modrm >> 6) == 3)
4914 				opcode = opcode.u.idual->mod3;
4915 			else
4916 				opcode = opcode.u.idual->mod012;
4917 			break;
4918 		case ModeDual:
4919 			if (ctxt->mode == X86EMUL_MODE_PROT64)
4920 				opcode = opcode.u.mdual->mode64;
4921 			else
4922 				opcode = opcode.u.mdual->mode32;
4923 			break;
4924 		default:
4925 			return EMULATION_FAILED;
4926 		}
4927 
4928 		ctxt->d &= ~(u64)GroupMask;
4929 		ctxt->d |= opcode.flags;
4930 	}
4931 
4932 	ctxt->is_branch = opcode.flags & IsBranch;
4933 
4934 	/* Unrecognised? */
4935 	if (ctxt->d == 0)
4936 		return EMULATION_FAILED;
4937 
4938 	ctxt->execute = opcode.u.execute;
4939 
4940 	if (unlikely(emulation_type & EMULTYPE_TRAP_UD) &&
4941 	    likely(!(ctxt->d & EmulateOnUD)))
4942 		return EMULATION_FAILED;
4943 
4944 	if (unlikely(ctxt->d &
4945 	    (NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm|NearBranch|
4946 	     No16))) {
4947 		/*
4948 		 * These are copied unconditionally here, and checked unconditionally
4949 		 * in x86_emulate_insn.
4950 		 */
4951 		ctxt->check_perm = opcode.check_perm;
4952 		ctxt->intercept = opcode.intercept;
4953 
4954 		if (ctxt->d & NotImpl)
4955 			return EMULATION_FAILED;
4956 
4957 		if (mode == X86EMUL_MODE_PROT64) {
4958 			if (ctxt->op_bytes == 4 && (ctxt->d & Stack))
4959 				ctxt->op_bytes = 8;
4960 			else if (ctxt->d & NearBranch)
4961 				ctxt->op_bytes = 8;
4962 		}
4963 
4964 		if (ctxt->d & Op3264) {
4965 			if (mode == X86EMUL_MODE_PROT64)
4966 				ctxt->op_bytes = 8;
4967 			else
4968 				ctxt->op_bytes = 4;
4969 		}
4970 
4971 		if ((ctxt->d & No16) && ctxt->op_bytes == 2)
4972 			ctxt->op_bytes = 4;
4973 
4974 		if (ctxt->d & Sse)
4975 			ctxt->op_bytes = 16;
4976 		else if (ctxt->d & Mmx)
4977 			ctxt->op_bytes = 8;
4978 	}
4979 
4980 	/* ModRM and SIB bytes. */
4981 	if (ctxt->d & ModRM) {
4982 		rc = decode_modrm(ctxt, &ctxt->memop);
4983 		if (!has_seg_override) {
4984 			has_seg_override = true;
4985 			ctxt->seg_override = ctxt->modrm_seg;
4986 		}
4987 	} else if (ctxt->d & MemAbs)
4988 		rc = decode_abs(ctxt, &ctxt->memop);
4989 	if (rc != X86EMUL_CONTINUE)
4990 		goto done;
4991 
4992 	if (!has_seg_override)
4993 		ctxt->seg_override = VCPU_SREG_DS;
4994 
4995 	ctxt->memop.addr.mem.seg = ctxt->seg_override;
4996 
4997 	/*
4998 	 * Decode and fetch the source operand: register, memory
4999 	 * or immediate.
5000 	 */
5001 	rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask);
5002 	if (rc != X86EMUL_CONTINUE)
5003 		goto done;
5004 
5005 	/*
5006 	 * Decode and fetch the second source operand: register, memory
5007 	 * or immediate.
5008 	 */
5009 	rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask);
5010 	if (rc != X86EMUL_CONTINUE)
5011 		goto done;
5012 
5013 	/* Decode and fetch the destination operand: register or memory. */
5014 	rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask);
5015 
5016 	if (ctxt->rip_relative && likely(ctxt->memopp))
5017 		ctxt->memopp->addr.mem.ea = address_mask(ctxt,
5018 					ctxt->memopp->addr.mem.ea + ctxt->_eip);
5019 
5020 done:
5021 	if (rc == X86EMUL_PROPAGATE_FAULT)
5022 		ctxt->have_exception = true;
5023 	return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK;
5024 }
5025 
5026 bool x86_page_table_writing_insn(struct x86_emulate_ctxt *ctxt)
5027 {
5028 	return ctxt->d & PageTable;
5029 }
5030 
5031 static bool string_insn_completed(struct x86_emulate_ctxt *ctxt)
5032 {
5033 	/* The second termination condition only applies for REPE
5034 	 * and REPNE. Test if the repeat string operation prefix is
5035 	 * REPE/REPZ or REPNE/REPNZ and if it's the case it tests the
5036 	 * corresponding termination condition according to:
5037 	 * 	- if REPE/REPZ and ZF = 0 then done
5038 	 * 	- if REPNE/REPNZ and ZF = 1 then done
5039 	 */
5040 	if (((ctxt->b == 0xa6) || (ctxt->b == 0xa7) ||
5041 	     (ctxt->b == 0xae) || (ctxt->b == 0xaf))
5042 	    && (((ctxt->rep_prefix == REPE_PREFIX) &&
5043 		 ((ctxt->eflags & X86_EFLAGS_ZF) == 0))
5044 		|| ((ctxt->rep_prefix == REPNE_PREFIX) &&
5045 		    ((ctxt->eflags & X86_EFLAGS_ZF) == X86_EFLAGS_ZF))))
5046 		return true;
5047 
5048 	return false;
5049 }
5050 
5051 static int flush_pending_x87_faults(struct x86_emulate_ctxt *ctxt)
5052 {
5053 	int rc;
5054 
5055 	kvm_fpu_get();
5056 	rc = asm_safe("fwait");
5057 	kvm_fpu_put();
5058 
5059 	if (unlikely(rc != X86EMUL_CONTINUE))
5060 		return emulate_exception(ctxt, MF_VECTOR, 0, false);
5061 
5062 	return X86EMUL_CONTINUE;
5063 }
5064 
5065 static void fetch_possible_mmx_operand(struct operand *op)
5066 {
5067 	if (op->type == OP_MM)
5068 		kvm_read_mmx_reg(op->addr.mm, &op->mm_val);
5069 }
5070 
5071 static int fastop(struct x86_emulate_ctxt *ctxt, fastop_t fop)
5072 {
5073 	ulong flags = (ctxt->eflags & EFLAGS_MASK) | X86_EFLAGS_IF;
5074 
5075 	if (!(ctxt->d & ByteOp))
5076 		fop += __ffs(ctxt->dst.bytes) * FASTOP_SIZE;
5077 
5078 	asm("push %[flags]; popf; " CALL_NOSPEC " ; pushf; pop %[flags]\n"
5079 	    : "+a"(ctxt->dst.val), "+d"(ctxt->src.val), [flags]"+D"(flags),
5080 	      [thunk_target]"+S"(fop), ASM_CALL_CONSTRAINT
5081 	    : "c"(ctxt->src2.val));
5082 
5083 	ctxt->eflags = (ctxt->eflags & ~EFLAGS_MASK) | (flags & EFLAGS_MASK);
5084 	if (!fop) /* exception is returned in fop variable */
5085 		return emulate_de(ctxt);
5086 	return X86EMUL_CONTINUE;
5087 }
5088 
5089 void init_decode_cache(struct x86_emulate_ctxt *ctxt)
5090 {
5091 	/* Clear fields that are set conditionally but read without a guard. */
5092 	ctxt->rip_relative = false;
5093 	ctxt->rex_prefix = 0;
5094 	ctxt->lock_prefix = 0;
5095 	ctxt->rep_prefix = 0;
5096 	ctxt->regs_valid = 0;
5097 	ctxt->regs_dirty = 0;
5098 
5099 	ctxt->io_read.pos = 0;
5100 	ctxt->io_read.end = 0;
5101 	ctxt->mem_read.end = 0;
5102 }
5103 
5104 int x86_emulate_insn(struct x86_emulate_ctxt *ctxt)
5105 {
5106 	const struct x86_emulate_ops *ops = ctxt->ops;
5107 	int rc = X86EMUL_CONTINUE;
5108 	int saved_dst_type = ctxt->dst.type;
5109 	bool is_guest_mode = ctxt->ops->is_guest_mode(ctxt);
5110 
5111 	ctxt->mem_read.pos = 0;
5112 
5113 	/* LOCK prefix is allowed only with some instructions */
5114 	if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) {
5115 		rc = emulate_ud(ctxt);
5116 		goto done;
5117 	}
5118 
5119 	if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) {
5120 		rc = emulate_ud(ctxt);
5121 		goto done;
5122 	}
5123 
5124 	if (unlikely(ctxt->d &
5125 		     (No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) {
5126 		if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) ||
5127 				(ctxt->d & Undefined)) {
5128 			rc = emulate_ud(ctxt);
5129 			goto done;
5130 		}
5131 
5132 		if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM)))
5133 		    || ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) {
5134 			rc = emulate_ud(ctxt);
5135 			goto done;
5136 		}
5137 
5138 		if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) {
5139 			rc = emulate_nm(ctxt);
5140 			goto done;
5141 		}
5142 
5143 		if (ctxt->d & Mmx) {
5144 			rc = flush_pending_x87_faults(ctxt);
5145 			if (rc != X86EMUL_CONTINUE)
5146 				goto done;
5147 			/*
5148 			 * Now that we know the fpu is exception safe, we can fetch
5149 			 * operands from it.
5150 			 */
5151 			fetch_possible_mmx_operand(&ctxt->src);
5152 			fetch_possible_mmx_operand(&ctxt->src2);
5153 			if (!(ctxt->d & Mov))
5154 				fetch_possible_mmx_operand(&ctxt->dst);
5155 		}
5156 
5157 		if (unlikely(is_guest_mode) && ctxt->intercept) {
5158 			rc = emulator_check_intercept(ctxt, ctxt->intercept,
5159 						      X86_ICPT_PRE_EXCEPT);
5160 			if (rc != X86EMUL_CONTINUE)
5161 				goto done;
5162 		}
5163 
5164 		/* Instruction can only be executed in protected mode */
5165 		if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) {
5166 			rc = emulate_ud(ctxt);
5167 			goto done;
5168 		}
5169 
5170 		/* Privileged instruction can be executed only in CPL=0 */
5171 		if ((ctxt->d & Priv) && ops->cpl(ctxt)) {
5172 			if (ctxt->d & PrivUD)
5173 				rc = emulate_ud(ctxt);
5174 			else
5175 				rc = emulate_gp(ctxt, 0);
5176 			goto done;
5177 		}
5178 
5179 		/* Do instruction specific permission checks */
5180 		if (ctxt->d & CheckPerm) {
5181 			rc = ctxt->check_perm(ctxt);
5182 			if (rc != X86EMUL_CONTINUE)
5183 				goto done;
5184 		}
5185 
5186 		if (unlikely(is_guest_mode) && (ctxt->d & Intercept)) {
5187 			rc = emulator_check_intercept(ctxt, ctxt->intercept,
5188 						      X86_ICPT_POST_EXCEPT);
5189 			if (rc != X86EMUL_CONTINUE)
5190 				goto done;
5191 		}
5192 
5193 		if (ctxt->rep_prefix && (ctxt->d & String)) {
5194 			/* All REP prefixes have the same first termination condition */
5195 			if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) {
5196 				string_registers_quirk(ctxt);
5197 				ctxt->eip = ctxt->_eip;
5198 				ctxt->eflags &= ~X86_EFLAGS_RF;
5199 				goto done;
5200 			}
5201 		}
5202 	}
5203 
5204 	if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) {
5205 		rc = segmented_read(ctxt, ctxt->src.addr.mem,
5206 				    ctxt->src.valptr, ctxt->src.bytes);
5207 		if (rc != X86EMUL_CONTINUE)
5208 			goto done;
5209 		ctxt->src.orig_val64 = ctxt->src.val64;
5210 	}
5211 
5212 	if (ctxt->src2.type == OP_MEM) {
5213 		rc = segmented_read(ctxt, ctxt->src2.addr.mem,
5214 				    &ctxt->src2.val, ctxt->src2.bytes);
5215 		if (rc != X86EMUL_CONTINUE)
5216 			goto done;
5217 	}
5218 
5219 	if ((ctxt->d & DstMask) == ImplicitOps)
5220 		goto special_insn;
5221 
5222 
5223 	if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) {
5224 		/* optimisation - avoid slow emulated read if Mov */
5225 		rc = segmented_read(ctxt, ctxt->dst.addr.mem,
5226 				   &ctxt->dst.val, ctxt->dst.bytes);
5227 		if (rc != X86EMUL_CONTINUE) {
5228 			if (!(ctxt->d & NoWrite) &&
5229 			    rc == X86EMUL_PROPAGATE_FAULT &&
5230 			    ctxt->exception.vector == PF_VECTOR)
5231 				ctxt->exception.error_code |= PFERR_WRITE_MASK;
5232 			goto done;
5233 		}
5234 	}
5235 	/* Copy full 64-bit value for CMPXCHG8B.  */
5236 	ctxt->dst.orig_val64 = ctxt->dst.val64;
5237 
5238 special_insn:
5239 
5240 	if (unlikely(is_guest_mode) && (ctxt->d & Intercept)) {
5241 		rc = emulator_check_intercept(ctxt, ctxt->intercept,
5242 					      X86_ICPT_POST_MEMACCESS);
5243 		if (rc != X86EMUL_CONTINUE)
5244 			goto done;
5245 	}
5246 
5247 	if (ctxt->rep_prefix && (ctxt->d & String))
5248 		ctxt->eflags |= X86_EFLAGS_RF;
5249 	else
5250 		ctxt->eflags &= ~X86_EFLAGS_RF;
5251 
5252 	if (ctxt->execute) {
5253 		if (ctxt->d & Fastop)
5254 			rc = fastop(ctxt, ctxt->fop);
5255 		else
5256 			rc = ctxt->execute(ctxt);
5257 		if (rc != X86EMUL_CONTINUE)
5258 			goto done;
5259 		goto writeback;
5260 	}
5261 
5262 	if (ctxt->opcode_len == 2)
5263 		goto twobyte_insn;
5264 	else if (ctxt->opcode_len == 3)
5265 		goto threebyte_insn;
5266 
5267 	switch (ctxt->b) {
5268 	case 0x70 ... 0x7f: /* jcc (short) */
5269 		if (test_cc(ctxt->b, ctxt->eflags))
5270 			rc = jmp_rel(ctxt, ctxt->src.val);
5271 		break;
5272 	case 0x8d: /* lea r16/r32, m */
5273 		ctxt->dst.val = ctxt->src.addr.mem.ea;
5274 		break;
5275 	case 0x90 ... 0x97: /* nop / xchg reg, rax */
5276 		if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX))
5277 			ctxt->dst.type = OP_NONE;
5278 		else
5279 			rc = em_xchg(ctxt);
5280 		break;
5281 	case 0x98: /* cbw/cwde/cdqe */
5282 		switch (ctxt->op_bytes) {
5283 		case 2: ctxt->dst.val = (s8)ctxt->dst.val; break;
5284 		case 4: ctxt->dst.val = (s16)ctxt->dst.val; break;
5285 		case 8: ctxt->dst.val = (s32)ctxt->dst.val; break;
5286 		}
5287 		break;
5288 	case 0xcc:		/* int3 */
5289 		rc = emulate_int(ctxt, 3);
5290 		break;
5291 	case 0xcd:		/* int n */
5292 		rc = emulate_int(ctxt, ctxt->src.val);
5293 		break;
5294 	case 0xce:		/* into */
5295 		if (ctxt->eflags & X86_EFLAGS_OF)
5296 			rc = emulate_int(ctxt, 4);
5297 		break;
5298 	case 0xe9: /* jmp rel */
5299 	case 0xeb: /* jmp rel short */
5300 		rc = jmp_rel(ctxt, ctxt->src.val);
5301 		ctxt->dst.type = OP_NONE; /* Disable writeback. */
5302 		break;
5303 	case 0xf4:              /* hlt */
5304 		ctxt->ops->halt(ctxt);
5305 		break;
5306 	case 0xf5:	/* cmc */
5307 		/* complement carry flag from eflags reg */
5308 		ctxt->eflags ^= X86_EFLAGS_CF;
5309 		break;
5310 	case 0xf8: /* clc */
5311 		ctxt->eflags &= ~X86_EFLAGS_CF;
5312 		break;
5313 	case 0xf9: /* stc */
5314 		ctxt->eflags |= X86_EFLAGS_CF;
5315 		break;
5316 	case 0xfc: /* cld */
5317 		ctxt->eflags &= ~X86_EFLAGS_DF;
5318 		break;
5319 	case 0xfd: /* std */
5320 		ctxt->eflags |= X86_EFLAGS_DF;
5321 		break;
5322 	default:
5323 		goto cannot_emulate;
5324 	}
5325 
5326 	if (rc != X86EMUL_CONTINUE)
5327 		goto done;
5328 
5329 writeback:
5330 	if (ctxt->d & SrcWrite) {
5331 		BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR);
5332 		rc = writeback(ctxt, &ctxt->src);
5333 		if (rc != X86EMUL_CONTINUE)
5334 			goto done;
5335 	}
5336 	if (!(ctxt->d & NoWrite)) {
5337 		rc = writeback(ctxt, &ctxt->dst);
5338 		if (rc != X86EMUL_CONTINUE)
5339 			goto done;
5340 	}
5341 
5342 	/*
5343 	 * restore dst type in case the decoding will be reused
5344 	 * (happens for string instruction )
5345 	 */
5346 	ctxt->dst.type = saved_dst_type;
5347 
5348 	if ((ctxt->d & SrcMask) == SrcSI)
5349 		string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src);
5350 
5351 	if ((ctxt->d & DstMask) == DstDI)
5352 		string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst);
5353 
5354 	if (ctxt->rep_prefix && (ctxt->d & String)) {
5355 		unsigned int count;
5356 		struct read_cache *r = &ctxt->io_read;
5357 		if ((ctxt->d & SrcMask) == SrcSI)
5358 			count = ctxt->src.count;
5359 		else
5360 			count = ctxt->dst.count;
5361 		register_address_increment(ctxt, VCPU_REGS_RCX, -count);
5362 
5363 		if (!string_insn_completed(ctxt)) {
5364 			/*
5365 			 * Re-enter guest when pio read ahead buffer is empty
5366 			 * or, if it is not used, after each 1024 iteration.
5367 			 */
5368 			if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) &&
5369 			    (r->end == 0 || r->end != r->pos)) {
5370 				/*
5371 				 * Reset read cache. Usually happens before
5372 				 * decode, but since instruction is restarted
5373 				 * we have to do it here.
5374 				 */
5375 				ctxt->mem_read.end = 0;
5376 				writeback_registers(ctxt);
5377 				return EMULATION_RESTART;
5378 			}
5379 			goto done; /* skip rip writeback */
5380 		}
5381 		ctxt->eflags &= ~X86_EFLAGS_RF;
5382 	}
5383 
5384 	ctxt->eip = ctxt->_eip;
5385 	if (ctxt->mode != X86EMUL_MODE_PROT64)
5386 		ctxt->eip = (u32)ctxt->_eip;
5387 
5388 done:
5389 	if (rc == X86EMUL_PROPAGATE_FAULT) {
5390 		if (KVM_EMULATOR_BUG_ON(ctxt->exception.vector > 0x1f, ctxt))
5391 			return EMULATION_FAILED;
5392 		ctxt->have_exception = true;
5393 	}
5394 	if (rc == X86EMUL_INTERCEPTED)
5395 		return EMULATION_INTERCEPTED;
5396 
5397 	if (rc == X86EMUL_CONTINUE)
5398 		writeback_registers(ctxt);
5399 
5400 	return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK;
5401 
5402 twobyte_insn:
5403 	switch (ctxt->b) {
5404 	case 0x09:		/* wbinvd */
5405 		(ctxt->ops->wbinvd)(ctxt);
5406 		break;
5407 	case 0x08:		/* invd */
5408 	case 0x0d:		/* GrpP (prefetch) */
5409 	case 0x18:		/* Grp16 (prefetch/nop) */
5410 	case 0x1f:		/* nop */
5411 		break;
5412 	case 0x20: /* mov cr, reg */
5413 		ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg);
5414 		break;
5415 	case 0x21: /* mov from dr to reg */
5416 		ctxt->dst.val = ops->get_dr(ctxt, ctxt->modrm_reg);
5417 		break;
5418 	case 0x40 ... 0x4f:	/* cmov */
5419 		if (test_cc(ctxt->b, ctxt->eflags))
5420 			ctxt->dst.val = ctxt->src.val;
5421 		else if (ctxt->op_bytes != 4)
5422 			ctxt->dst.type = OP_NONE; /* no writeback */
5423 		break;
5424 	case 0x80 ... 0x8f: /* jnz rel, etc*/
5425 		if (test_cc(ctxt->b, ctxt->eflags))
5426 			rc = jmp_rel(ctxt, ctxt->src.val);
5427 		break;
5428 	case 0x90 ... 0x9f:     /* setcc r/m8 */
5429 		ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags);
5430 		break;
5431 	case 0xb6 ... 0xb7:	/* movzx */
5432 		ctxt->dst.bytes = ctxt->op_bytes;
5433 		ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val
5434 						       : (u16) ctxt->src.val;
5435 		break;
5436 	case 0xbe ... 0xbf:	/* movsx */
5437 		ctxt->dst.bytes = ctxt->op_bytes;
5438 		ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val :
5439 							(s16) ctxt->src.val;
5440 		break;
5441 	default:
5442 		goto cannot_emulate;
5443 	}
5444 
5445 threebyte_insn:
5446 
5447 	if (rc != X86EMUL_CONTINUE)
5448 		goto done;
5449 
5450 	goto writeback;
5451 
5452 cannot_emulate:
5453 	return EMULATION_FAILED;
5454 }
5455 
5456 void emulator_invalidate_register_cache(struct x86_emulate_ctxt *ctxt)
5457 {
5458 	invalidate_registers(ctxt);
5459 }
5460 
5461 void emulator_writeback_register_cache(struct x86_emulate_ctxt *ctxt)
5462 {
5463 	writeback_registers(ctxt);
5464 }
5465 
5466 bool emulator_can_use_gpa(struct x86_emulate_ctxt *ctxt)
5467 {
5468 	if (ctxt->rep_prefix && (ctxt->d & String))
5469 		return false;
5470 
5471 	if (ctxt->d & TwoMemOp)
5472 		return false;
5473 
5474 	return true;
5475 }
5476