summaryrefslogtreecommitdiff
path: root/usr.sbin/vmd/mmio.c
blob: c5a189d5b85b55f5b5890b434d5a68c35089fd7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
/*	$OpenBSD: mmio.c,v 1.3 2024/02/10 12:31:16 dv Exp $	*/

/*
 * Copyright (c) 2022 Dave Voutila <dv@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <errno.h>
#include <string.h>

#include <sys/types.h>
#include <machine/specialreg.h>

#include "vmd.h"
#include "mmio.h"

#define MMIO_DEBUG 0

extern char* __progname;

struct x86_decode_state {
	uint8_t	s_bytes[15];
	size_t	s_len;
	size_t	s_idx;
};

enum decode_result {
	DECODE_ERROR = 0,	/* Something went wrong. */
	DECODE_DONE,		/* Decode success and no more work needed. */
	DECODE_MORE,		/* Decode success and more work required. */
};

static const char *str_cpu_mode(int);
static const char *str_decode_res(enum decode_result);
static const char *str_opcode(struct x86_opcode *);
static const char *str_operand_enc(struct x86_opcode *);
static const char *str_reg(int);
static const char *str_sreg(int);
static int detect_cpu_mode(struct vcpu_reg_state *);

static enum decode_result decode_prefix(struct x86_decode_state *,
    struct x86_insn *);
static enum decode_result decode_opcode(struct x86_decode_state *,
    struct x86_insn *);
static enum decode_result decode_modrm(struct x86_decode_state *,
    struct x86_insn *);
static int get_modrm_reg(struct x86_insn *);
static int get_modrm_addr(struct x86_insn *, struct vcpu_reg_state *vrs);
static enum decode_result decode_disp(struct x86_decode_state *,
    struct x86_insn *);
static enum decode_result decode_sib(struct x86_decode_state *,
    struct x86_insn *);
static enum decode_result decode_imm(struct x86_decode_state *,
    struct x86_insn *);

static enum decode_result peek_byte(struct x86_decode_state *, uint8_t *);
static enum decode_result next_byte(struct x86_decode_state *, uint8_t *);
static enum decode_result next_value(struct x86_decode_state *, size_t,
    uint64_t *);
static int is_valid_state(struct x86_decode_state *, const char *);

static int emulate_mov(struct x86_insn *, struct vm_exit *);
static int emulate_movzx(struct x86_insn *, struct vm_exit *);

/* Lookup table for 1-byte opcodes, in opcode alphabetical order. */
const enum x86_opcode_type x86_1byte_opcode_tbl[255] = {
	/* MOV */
	[0x88] = OP_MOV,
	[0x89] = OP_MOV,
	[0x8A] = OP_MOV,
	[0x8B] = OP_MOV,
	[0x8C] = OP_MOV,
	[0xA0] = OP_MOV,
	[0xA1] = OP_MOV,
	[0xA2] = OP_MOV,
	[0xA3] = OP_MOV,

	/* MOVS */
	[0xA4] = OP_UNSUPPORTED,
	[0xA5] = OP_UNSUPPORTED,

	[ESCAPE] = OP_TWO_BYTE,
};

/* Lookup table for 1-byte operand encodings, in opcode alphabetical order. */
const enum x86_operand_enc x86_1byte_operand_enc_tbl[255] = {
	/* MOV */
	[0x88] = OP_ENC_MR,
	[0x89] = OP_ENC_MR,
	[0x8A] = OP_ENC_RM,
	[0x8B] = OP_ENC_RM,
	[0x8C] = OP_ENC_MR,
	[0xA0] = OP_ENC_FD,
	[0xA1] = OP_ENC_FD,
	[0xA2] = OP_ENC_TD,
	[0xA3] = OP_ENC_TD,

	/* MOVS */
	[0xA4] = OP_ENC_ZO,
	[0xA5] = OP_ENC_ZO,
};

const enum x86_opcode_type x86_2byte_opcode_tbl[255] = {
	/* MOVZX */
	[0xB6] = OP_MOVZX,
	[0xB7] = OP_MOVZX,
};

const enum x86_operand_enc x86_2byte_operand_enc_table[255] = {
	/* MOVZX */
	[0xB6] = OP_ENC_RM,
	[0xB7] = OP_ENC_RM,
};

/*
 * peek_byte
 *
 * Fetch the next byte fron the instruction bytes without advancing the
 * position in the stream.
 *
 * Return values:
 *  DECODE_DONE: byte was found and is the last in the stream
 *  DECODE_MORE: byte was found and there are more remaining to be read
 *  DECODE_ERROR: state is invalid and not byte was found, *byte left unchanged
 */
static enum decode_result
peek_byte(struct x86_decode_state *state, uint8_t *byte)
{
	enum decode_result res;

	if (state == NULL)
		return (DECODE_ERROR);

	if (state->s_idx == state->s_len)
		return (DECODE_ERROR);

	if (state->s_idx + 1 == state->s_len)
		res = DECODE_DONE;
	else
		res = DECODE_MORE;

	if (byte != NULL)
		*byte = state->s_bytes[state->s_idx];
	return (res);
}

/*
 * next_byte
 *
 * Fetch the next byte fron the instruction bytes, advancing the position in the
 * stream and mutating decode state.
 *
 * Return values:
 *  DECODE_DONE: byte was found and is the last in the stream
 *  DECODE_MORE: byte was found and there are more remaining to be read
 *  DECODE_ERROR: state is invalid and not byte was found, *byte left unchanged
 */
static enum decode_result
next_byte(struct x86_decode_state *state, uint8_t *byte)
{
	uint8_t next;

	/* Cheat and see if we're going to fail. */
	if (peek_byte(state, &next) == DECODE_ERROR)
		return (DECODE_ERROR);

	if (byte != NULL)
		*byte = next;
	state->s_idx++;

	return (state->s_idx < state->s_len ? DECODE_MORE : DECODE_DONE);
}

/*
 * Fetch the next `n' bytes as a single uint64_t value.
 */
static enum decode_result
next_value(struct x86_decode_state *state, size_t n, uint64_t *value)
{
	uint8_t bytes[8];
	size_t i;
	enum decode_result res;

	if (value == NULL)
		return (DECODE_ERROR);

	if (n == 0 || n > sizeof(bytes))
		return (DECODE_ERROR);

	memset(bytes, 0, sizeof(bytes));
	for (i = 0; i < n; i++)
		if ((res = next_byte(state, &bytes[i])) == DECODE_ERROR)
			return (DECODE_ERROR);

	*value = *((uint64_t*)bytes);

	return (res);
}

/*
 * is_valid_state
 *
 * Validate the decode state looks viable.
 *
 * Returns:
 *  1: if state is valid
 *  0: if an invariant is detected
 */
static int
is_valid_state(struct x86_decode_state *state, const char *fn_name)
{
	const char *s = (fn_name != NULL) ? fn_name : __func__;

	if (state == NULL) {
		log_warnx("%s: null state", s);
		return (0);
	}
	if (state->s_len > sizeof(state->s_bytes)) {
		log_warnx("%s: invalid length", s);
		return (0);
	}
	if (state->s_idx + 1 > state->s_len) {
		log_warnx("%s: invalid index", s);
		return (0);
	}

	return (1);
}

#ifdef MMIO_DEBUG
static void
dump_regs(struct vcpu_reg_state *vrs)
{
	size_t i;
	struct vcpu_segment_info *vsi;

	for (i = 0; i < VCPU_REGS_NGPRS; i++)
		log_info("%s: %s 0x%llx", __progname, str_reg(i),
		    vrs->vrs_gprs[i]);

	for (i = 0; i < VCPU_REGS_NSREGS; i++) {
		vsi = &vrs->vrs_sregs[i];
		log_info("%s: %s { sel: 0x%04x, lim: 0x%08x, ar: 0x%08x, "
		    "base: 0x%llx }", __progname, str_sreg(i),
		    vsi->vsi_sel, vsi->vsi_limit, vsi->vsi_ar, vsi->vsi_base);
	}
}

static void
dump_insn(struct x86_insn *insn)
{
	log_info("instruction { %s, enc=%s, len=%d, mod=0x%02x, ("
	    "reg=%s, addr=0x%lx) sib=0x%02x }",
	    str_opcode(&insn->insn_opcode),
	    str_operand_enc(&insn->insn_opcode), insn->insn_bytes_len,
	    insn->insn_modrm, str_reg(insn->insn_reg),
	    insn->insn_gva, insn->insn_sib);
}
#endif /* MMIO_DEBUG */

static const char *
str_cpu_mode(int mode)
{
	switch (mode) {
	case VMM_CPU_MODE_REAL: return "REAL";
	case VMM_CPU_MODE_PROT: return "PROT";
	case VMM_CPU_MODE_PROT32: return "PROT32";
	case VMM_CPU_MODE_COMPAT: return "COMPAT";
	case VMM_CPU_MODE_LONG: return "LONG";
	default: return "UKNOWN";
	}
}

__unused static const char *
str_decode_res(enum decode_result res) {
	switch (res) {
	case DECODE_DONE: return "DONE";
	case DECODE_MORE: return "MORE";
	case DECODE_ERROR: return "ERROR";
	default: return "UNKNOWN";
	}
}

static const char *
str_opcode(struct x86_opcode *opcode)
{
	switch (opcode->op_type) {
	case OP_IN: return "IN";
	case OP_INS: return "INS";
	case OP_MOV: return "MOV";
	case OP_MOVZX: return "MOVZX";
	case OP_OUT: return "OUT";
	case OP_OUTS: return "OUTS";
	case OP_UNSUPPORTED: return "UNSUPPORTED";
	default: return "UNKNOWN";
	}
}

static const char *
str_operand_enc(struct x86_opcode *opcode)
{
	switch (opcode->op_encoding) {
	case OP_ENC_I: return "I";
	case OP_ENC_MI: return "MI";
	case OP_ENC_MR: return "MR";
	case OP_ENC_RM: return "RM";
	case OP_ENC_FD: return "FD";
	case OP_ENC_TD: return "TD";
	case OP_ENC_OI: return "OI";
	case OP_ENC_ZO: return "ZO";
	default: return "UNKNOWN";
	}
}

static const char *
str_reg(int reg) {
	switch (reg) {
	case VCPU_REGS_RAX: return "RAX";
	case VCPU_REGS_RCX: return "RCX";
	case VCPU_REGS_RDX: return "RDX";
	case VCPU_REGS_RBX: return "RBX";
	case VCPU_REGS_RSI: return "RSI";
	case VCPU_REGS_RDI: return "RDI";
	case VCPU_REGS_R8:  return " R8";
	case VCPU_REGS_R9:  return " R9";
	case VCPU_REGS_R10: return "R10";
	case VCPU_REGS_R11: return "R11";
	case VCPU_REGS_R12: return "R12";
	case VCPU_REGS_R13: return "R13";
	case VCPU_REGS_R14: return "R14";
	case VCPU_REGS_R15: return "R15";
	case VCPU_REGS_RSP: return "RSP";
	case VCPU_REGS_RBP: return "RBP";
	case VCPU_REGS_RIP: return "RIP";
	case VCPU_REGS_RFLAGS: return "RFLAGS";
	default: return "UNKNOWN";
	}
}

static const char *
str_sreg(int sreg) {
	switch (sreg) {
	case VCPU_REGS_CS: return "CS";
	case VCPU_REGS_DS: return "DS";
	case VCPU_REGS_ES: return "ES";
	case VCPU_REGS_FS: return "FS";
	case VCPU_REGS_GS: return "GS";
	case VCPU_REGS_SS: return "GS";
	case VCPU_REGS_LDTR: return "LDTR";
	case VCPU_REGS_TR: return "TR";
	default: return "UKNOWN";
	}
}

static int
detect_cpu_mode(struct vcpu_reg_state *vrs)
{
	uint64_t cr0, cr4, cs, efer, rflags;

	/* Is protected mode enabled? */
	cr0 = vrs->vrs_crs[VCPU_REGS_CR0];
	if (!(cr0 & CR0_PE))
		return (VMM_CPU_MODE_REAL);

	cr4 = vrs->vrs_crs[VCPU_REGS_CR4];
	cs = vrs->vrs_sregs[VCPU_REGS_CS].vsi_ar;
	efer = vrs->vrs_msrs[VCPU_REGS_EFER];
	rflags = vrs->vrs_gprs[VCPU_REGS_RFLAGS];

	/* Check for Long modes. */
	if ((efer & EFER_LME) && (cr4 & CR4_PAE) && (cr0 & CR0_PG)) {
		if (cs & CS_L) {
			/* Long Modes */
			if (!(cs & CS_D))
				return (VMM_CPU_MODE_LONG);
			log_warnx("%s: invalid cpu mode", __progname);
			return (VMM_CPU_MODE_UNKNOWN);
		} else {
			/* Compatibility Modes */
			if (cs & CS_D) /* XXX Add Compat32 mode */
				return (VMM_CPU_MODE_UNKNOWN);
			return (VMM_CPU_MODE_COMPAT);
		}
	}

	/* Check for 32-bit Protected Mode. */
	if (cs & CS_D)
		return (VMM_CPU_MODE_PROT32);

	/* Check for virtual 8086 mode. */
	if (rflags & EFLAGS_VM) {
		/* XXX add Virtual8086 mode */
		log_warnx("%s: Virtual 8086 mode", __progname);
		return (VMM_CPU_MODE_UNKNOWN);
	}

	/* Can't determine mode. */
	log_warnx("%s: invalid cpu mode", __progname);
	return (VMM_CPU_MODE_UNKNOWN);
}

static enum decode_result
decode_prefix(struct x86_decode_state *state, struct x86_insn *insn)
{
	enum decode_result res = DECODE_ERROR;
	struct x86_prefix *prefix;
	uint8_t byte;

	if (!is_valid_state(state, __func__) || insn == NULL)
		return (-1);

	prefix = &insn->insn_prefix;
	memset(prefix, 0, sizeof(*prefix));

	/*
	 * Decode prefixes. The last of its kind wins. The behavior is undefined
	 * in the Intel SDM (see Vol 2, 2.1.1 Instruction Prefixes.)
	 */
	while ((res = peek_byte(state, &byte)) != DECODE_ERROR) {
		switch (byte) {
		case LEG_1_LOCK:
		case LEG_1_REPNE:
		case LEG_1_REP:
			prefix->pfx_group1 = byte;
			break;
		case LEG_2_CS:
		case LEG_2_SS:
		case LEG_2_DS:
		case LEG_2_ES:
		case LEG_2_FS:
		case LEG_2_GS:
			prefix->pfx_group2 = byte;
			break;
		case LEG_3_OPSZ:
			prefix->pfx_group3 = byte;
			break;
		case LEG_4_ADDRSZ:
			prefix->pfx_group4 = byte;
			break;
		case REX_BASE...REX_BASE + 0x0F:
			if (insn->insn_cpu_mode == VMM_CPU_MODE_LONG)
				prefix->pfx_rex = byte;
			else /* INC encountered */
				return (DECODE_ERROR);
			break;
		case VEX_2_BYTE:
		case VEX_3_BYTE:
			log_warnx("%s: VEX not supported", __func__);
			return (DECODE_ERROR);
		default:
			/* Something other than a valid prefix. */
			return (DECODE_MORE);
		}
		/* Advance our position. */
		next_byte(state, NULL);
	}

	return (res);
}

static enum decode_result
decode_modrm(struct x86_decode_state *state, struct x86_insn *insn)
{
	enum decode_result res;
	uint8_t byte = 0;

	if (!is_valid_state(state, __func__) || insn == NULL)
		return (DECODE_ERROR);

	insn->insn_modrm_valid = 0;

	/* Check the operand encoding to see if we fetch a byte or abort. */
	switch (insn->insn_opcode.op_encoding) {
	case OP_ENC_MR:
	case OP_ENC_RM:
	case OP_ENC_MI:
		res = next_byte(state, &byte);
		if (res == DECODE_ERROR) {
			log_warnx("%s: failed to get modrm byte", __func__);
			break;
		}
		insn->insn_modrm = byte;
		insn->insn_modrm_valid = 1;
		break;

	case OP_ENC_I:
	case OP_ENC_OI:
		log_warnx("%s: instruction does not need memory assist",
		    __func__);
		res = DECODE_ERROR;
		break;

	default:
		/* Peek to see if we're done decode. */
		res = peek_byte(state, NULL);
	}

	return (res);
}

static int
get_modrm_reg(struct x86_insn *insn)
{
	if (insn == NULL)
		return (-1);

	if (insn->insn_modrm_valid) {
		switch (MODRM_REGOP(insn->insn_modrm)) {
		case 0:
			insn->insn_reg = VCPU_REGS_RAX;
			break;
		case 1:
			insn->insn_reg = VCPU_REGS_RCX;
			break;
		case 2:
			insn->insn_reg = VCPU_REGS_RDX;
			break;
		case 3:
			insn->insn_reg = VCPU_REGS_RBX;
			break;
		case 4:
			insn->insn_reg = VCPU_REGS_RSP;
			break;
		case 5:
			insn->insn_reg = VCPU_REGS_RBP;
			break;
		case 6:
			insn->insn_reg = VCPU_REGS_RSI;
			break;
		case 7:
			insn->insn_reg = VCPU_REGS_RDI;
			break;
		}
	}

	/* REX R bit selects extended registers in LONG mode. */
	if (insn->insn_prefix.pfx_rex & REX_R)
		insn->insn_reg += 8;

	return (0);
}

static int
get_modrm_addr(struct x86_insn *insn, struct vcpu_reg_state *vrs)
{
	uint8_t mod, rm;
	vaddr_t addr = 0x0UL;

	if (insn == NULL || vrs == NULL)
		return (-1);

	if (insn->insn_modrm_valid) {
		rm = MODRM_RM(insn->insn_modrm);
		mod = MODRM_MOD(insn->insn_modrm);

		switch (rm) {
		case 0b000:
			addr = vrs->vrs_gprs[VCPU_REGS_RAX];
			break;
		case 0b001:
			addr = vrs->vrs_gprs[VCPU_REGS_RCX];
			break;
		case 0b010:
			addr = vrs->vrs_gprs[VCPU_REGS_RDX];
			break;
		case 0b011:
			addr = vrs->vrs_gprs[VCPU_REGS_RBX];
			break;
		case 0b100:
			if (mod == 0b11)
				addr = vrs->vrs_gprs[VCPU_REGS_RSP];
			break;
		case 0b101:
			if (mod != 0b00)
				addr = vrs->vrs_gprs[VCPU_REGS_RBP];
			break;
		case 0b110:
			addr = vrs->vrs_gprs[VCPU_REGS_RSI];
			break;
		case 0b111:
			addr = vrs->vrs_gprs[VCPU_REGS_RDI];
			break;
		}

		insn->insn_gva = addr;
	}

	return (0);
}

static enum decode_result
decode_disp(struct x86_decode_state *state, struct x86_insn *insn)
{
	enum decode_result res = DECODE_ERROR;
	uint64_t disp = 0;

	if (!is_valid_state(state, __func__) || insn == NULL)
		return (DECODE_ERROR);

	if (!insn->insn_modrm_valid)
		return (DECODE_ERROR);

	switch (MODRM_MOD(insn->insn_modrm)) {
	case 0x00:
		insn->insn_disp_type = DISP_0;
		res = DECODE_MORE;
		break;
	case 0x01:
		insn->insn_disp_type = DISP_1;
		res = next_value(state, 1, &disp);
		if (res == DECODE_ERROR)
			return (res);
		insn->insn_disp = disp;
		break;
	case 0x02:
		if (insn->insn_prefix.pfx_group4 == LEG_4_ADDRSZ) {
			insn->insn_disp_type = DISP_2;
			res = next_value(state, 2, &disp);
		} else {
			insn->insn_disp_type = DISP_4;
			res = next_value(state, 4, &disp);
		}
		if (res == DECODE_ERROR)
			return (res);
		insn->insn_disp = disp;
		break;
	default:
		insn->insn_disp_type = DISP_NONE;
		res = DECODE_MORE;
	}

	return (res);
}

static enum decode_result
decode_opcode(struct x86_decode_state *state, struct x86_insn *insn)
{
	enum decode_result res;
	enum x86_opcode_type type;
	enum x86_operand_enc enc;
	struct x86_opcode *opcode = &insn->insn_opcode;
	uint8_t byte, byte2;

	if (!is_valid_state(state, __func__) || insn == NULL)
		return (-1);

	memset(opcode, 0, sizeof(*opcode));

	res = next_byte(state, &byte);
	if (res == DECODE_ERROR)
		return (res);

	type = x86_1byte_opcode_tbl[byte];
	switch(type) {
	case OP_UNKNOWN:
	case OP_UNSUPPORTED:
		log_warnx("%s: unsupported opcode", __func__);
		return (DECODE_ERROR);

	case OP_TWO_BYTE:
		res = next_byte(state, &byte2);
		if (res == DECODE_ERROR)
			return (res);

		type = x86_2byte_opcode_tbl[byte2];
		if (type == OP_UNKNOWN || type == OP_UNSUPPORTED) {
			log_warnx("%s: unsupported 2-byte opcode", __func__);
			return (DECODE_ERROR);
		}

		opcode->op_bytes[0] = byte;
		opcode->op_bytes[1] = byte2;
		opcode->op_bytes_len = 2;
		enc = x86_2byte_operand_enc_table[byte2];
		break;

	default:
		/* We've potentially got a known 1-byte opcode. */
		opcode->op_bytes[0] = byte;
		opcode->op_bytes_len = 1;
		enc = x86_1byte_operand_enc_tbl[byte];
	}

	if (enc == OP_ENC_UNKNOWN)
		return (DECODE_ERROR);

	opcode->op_type = type;
	opcode->op_encoding = enc;

	return (res);
}

static enum decode_result
decode_sib(struct x86_decode_state *state, struct x86_insn *insn)
{
	enum decode_result res;
	uint8_t byte;

	if (!is_valid_state(state, __func__) || insn == NULL)
		return (-1);

	/* SIB is optional, so assume we will be continuing. */
	res = DECODE_MORE;

	insn->insn_sib_valid = 0;
	if (!insn->insn_modrm_valid)
		return (res);

	/* XXX is SIB valid in all cpu modes? */
	if (MODRM_RM(insn->insn_modrm) == 0b100) {
		res = next_byte(state, &byte);
		if (res != DECODE_ERROR) {
			insn->insn_sib_valid = 1;
			insn->insn_sib = byte;
		}
	}

	return (res);
}

static enum decode_result
decode_imm(struct x86_decode_state *state, struct x86_insn *insn)
{
	enum decode_result res;
	size_t num_bytes;
	uint64_t value;

	if (!is_valid_state(state, __func__) || insn == NULL)
		return (DECODE_ERROR);

	/* Only handle MI encoded instructions. Others shouldn't need assist. */
	if (insn->insn_opcode.op_encoding != OP_ENC_MI)
		return (DECODE_DONE);

	/* Exceptions related to MOV instructions. */
	if (insn->insn_opcode.op_type == OP_MOV) {
		switch (insn->insn_opcode.op_bytes[0]) {
		case 0xC6:
			num_bytes = 1;
			break;
		case 0xC7:
			if (insn->insn_cpu_mode == VMM_CPU_MODE_REAL)
				num_bytes = 2;
			else
				num_bytes = 4;
			break;
		default:
			log_warnx("%s: cannot decode immediate bytes for MOV",
			    __func__);
			return (DECODE_ERROR);
		}
	} else {
		/* Fallback to interpreting based on cpu mode and REX. */
		if (insn->insn_cpu_mode == VMM_CPU_MODE_REAL)
			num_bytes = 2;
		else if (insn->insn_prefix.pfx_rex == REX_NONE)
			num_bytes = 4;
		else
			num_bytes = 8;
	}

	res = next_value(state, num_bytes, &value);
	if (res != DECODE_ERROR) {
		insn->insn_immediate = value;
		insn->insn_immediate_len = num_bytes;
	}

	return (res);
}


/*
 * insn_decode
 *
 * Decode an x86 instruction from the provided instruction bytes.
 *
 * Return values:
 *  0: successful decode
 *  Non-zero: an exception occurred during decode
 */
int
insn_decode(struct vm_exit *exit, struct x86_insn *insn)
{
	enum decode_result res;
	struct vcpu_reg_state *vrs = &exit->vrs;
	struct x86_decode_state state;
	uint8_t *bytes, len;
	int mode;

	if (exit == NULL || insn == NULL) {
		log_warnx("%s: invalid input", __func__);
		return (DECODE_ERROR);
	}

	bytes = exit->vee.vee_insn_bytes;
	len = exit->vee.vee_insn_len;

	/* 0. Initialize state and instruction objects. */
	memset(insn, 0, sizeof(*insn));
	memset(&state, 0, sizeof(state));
	state.s_len = len;
	memcpy(&state.s_bytes, bytes, len);

	/* 1. Detect CPU mode. */
	mode = detect_cpu_mode(vrs);
	if (mode == VMM_CPU_MODE_UNKNOWN) {
		log_warnx("%s: failed to identify cpu mode", __func__);
#ifdef MMIO_DEBUG
		dump_regs(vrs);
#endif
		return (-1);
	}
	insn->insn_cpu_mode = mode;

#ifdef MMIO_DEBUG
	log_info("%s: cpu mode %s detected", __progname, str_cpu_mode(mode));
	printf("%s: got bytes: [ ", __progname);
	for (int i = 0; i < len; i++) {
		printf("%02x ", bytes[i]);
	}
	printf("]\n");
#endif
	/* 2. Decode prefixes. */
	res = decode_prefix(&state, insn);
	if (res == DECODE_ERROR) {
		log_warnx("%s: error decoding prefixes", __func__);
		goto err;
	} else if (res == DECODE_DONE)
		goto done;

#ifdef MMIO_DEBUG
	log_info("%s: prefixes {g1: 0x%02x, g2: 0x%02x, g3: 0x%02x, g4: 0x%02x,"
	    " rex: 0x%02x }", __progname, insn->insn_prefix.pfx_group1,
	    insn->insn_prefix.pfx_group2, insn->insn_prefix.pfx_group3,
	    insn->insn_prefix.pfx_group4, insn->insn_prefix.pfx_rex);
#endif

	/* 3. Pick apart opcode. Here we can start short-circuiting. */
	res = decode_opcode(&state, insn);
	if (res == DECODE_ERROR) {
		log_warnx("%s: error decoding opcode", __func__);
		goto err;
	} else if (res == DECODE_DONE)
		goto done;

#ifdef MMIO_DEBUG
	log_info("%s: found opcode %s (operand encoding %s) (%s)", __progname,
	    str_opcode(&insn->insn_opcode), str_operand_enc(&insn->insn_opcode),
	    str_decode_res(res));
#endif

	/* Process optional ModR/M byte. */
	res = decode_modrm(&state, insn);
	if (res == DECODE_ERROR) {
		log_warnx("%s: error decoding modrm", __func__);
		goto err;
	}
	if (get_modrm_addr(insn, vrs) != 0)
		goto err;
	if (get_modrm_reg(insn) != 0)
		goto err;
	if (res == DECODE_DONE)
		goto done;

#ifdef MMIO_DEBUG
	if (insn->insn_modrm_valid)
		log_info("%s: found ModRM 0x%02x (%s)", __progname,
		    insn->insn_modrm, str_decode_res(res));
#endif

	/* Process optional SIB byte. */
	res = decode_sib(&state, insn);
	if (res == DECODE_ERROR) {
		log_warnx("%s: error decoding sib", __func__);
		goto err;
	} else if (res == DECODE_DONE)
		goto done;

#ifdef MMIO_DEBUG
	if (insn->insn_sib_valid)
		log_info("%s: found SIB 0x%02x (%s)", __progname,
		    insn->insn_sib, str_decode_res(res));
#endif

	/* Process any Displacement bytes. */
	res = decode_disp(&state, insn);
	if (res == DECODE_ERROR) {
		log_warnx("%s: error decoding displacement", __func__);
		goto err;
	} else if (res == DECODE_DONE)
		goto done;

	/* Process any Immediate data bytes. */
	res = decode_imm(&state, insn);
	if (res == DECODE_ERROR) {
		log_warnx("%s: error decoding immediate bytes", __func__);
		goto err;
	}

done:
	insn->insn_bytes_len = state.s_idx;

#ifdef MMIO_DEBUG
	log_info("%s: final instruction length is %u", __func__,
		insn->insn_bytes_len);
	dump_insn(insn);
	log_info("%s: modrm: {mod: %d, regop: %d, rm: %d}", __func__,
	    MODRM_MOD(insn->insn_modrm), MODRM_REGOP(insn->insn_modrm),
	    MODRM_RM(insn->insn_modrm));
	dump_regs(vrs);
#endif /* MMIO_DEBUG */
	return (0);

err:
#ifdef MMIO_DEBUG
	dump_insn(insn);
	log_info("%s: modrm: {mod: %d, regop: %d, rm: %d}", __func__,
	    MODRM_MOD(insn->insn_modrm), MODRM_REGOP(insn->insn_modrm),
	    MODRM_RM(insn->insn_modrm));
	dump_regs(vrs);
#endif /* MMIO_DEBUG */
	return (-1);
}

static int
emulate_mov(struct x86_insn *insn, struct vm_exit *exit)
{
	/* XXX Only supports read to register for now */
	if (insn->insn_opcode.op_encoding != OP_ENC_RM)
		return (-1);

	/* XXX No device emulation yet. Fill with 0xFFs. */
	exit->vrs.vrs_gprs[insn->insn_reg] = 0xFFFFFFFFFFFFFFFF;

	return (0);
}

static int
emulate_movzx(struct x86_insn *insn, struct vm_exit *exit)
{
	uint8_t byte, len, src = 1, dst = 2;
	uint64_t value = 0;

	/* Only RM is valid for MOVZX. */
	if (insn->insn_opcode.op_encoding != OP_ENC_RM) {
		log_warnx("invalid op encoding for MOVZX: %d",
		    insn->insn_opcode.op_encoding);
		return (-1);
	}

	len = insn->insn_opcode.op_bytes_len;
	if (len < 1 || len > sizeof(insn->insn_opcode.op_bytes)) {
		log_warnx("invalid opcode byte length: %d", len);
		return (-1);
	}

	byte = insn->insn_opcode.op_bytes[len - 1];
	switch (byte) {
	case 0xB6:
		src = 1;
		if (insn->insn_cpu_mode == VMM_CPU_MODE_PROT
		    || insn->insn_cpu_mode == VMM_CPU_MODE_REAL)
			dst = 2;
		else if (insn->insn_prefix.pfx_rex == REX_NONE)
			dst = 4;
		else // XXX validate CPU mode
			dst = 8;
		break;
	case 0xB7:
		src = 2;
		if (insn->insn_prefix.pfx_rex == REX_NONE)
			dst = 4;
		else // XXX validate CPU mode
			dst = 8;
		break;
	default:
		log_warnx("invalid byte in MOVZX opcode: %x", byte);
		return (-1);
	}

	if (dst == 4)
		exit->vrs.vrs_gprs[insn->insn_reg] &= 0xFFFFFFFF00000000;
	else
		exit->vrs.vrs_gprs[insn->insn_reg] = 0x0UL;

	/* XXX No device emulation yet. Fill with 0xFFs. */
	switch (src) {
	case 1: value = 0xFF; break;
	case 2: value = 0xFFFF; break;
	case 4: value = 0xFFFFFFFF; break;
	case 8: value = 0xFFFFFFFFFFFFFFFF; break;
	default:
		log_warnx("invalid source size: %d", src);
		return (-1);
	}

	exit->vrs.vrs_gprs[insn->insn_reg] |= value;

	return (0);
}

/*
 * insn_emulate
 *
 * Returns:
 *  0: success
 *  EINVAL: exception occurred
 *  EFAULT: page fault occurred, requires retry
 *  ENOTSUP: an unsupported instruction was provided
 */
int
insn_emulate(struct vm_exit *exit, struct x86_insn *insn)
{
	int res;

	switch (insn->insn_opcode.op_type) {
	case OP_MOV:
		res = emulate_mov(insn, exit);
		break;

	case OP_MOVZX:
		res = emulate_movzx(insn, exit);
		break;

	default:
		log_warnx("%s: emulation not defined for %s", __func__,
		    str_opcode(&insn->insn_opcode));
		res = ENOTSUP;
	}

	if (res == 0)
		exit->vrs.vrs_gprs[VCPU_REGS_RIP] += insn->insn_bytes_len;

	return (res);
}