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