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