DragonFlyBSD Kernel Audit
sys/platform/pc64/x86_64/vm_machdep.c
← back
   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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
/*-
 * Copyright (c) 1982, 1986 The Regents of the University of California.
 * Copyright (c) 1989, 1990 William Jolitz
 * Copyright (c) 1994 John Dyson
 * Copyright (c) 2008-2018 The DragonFly Project.
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * the Systems Programming Group of the University of Utah Computer
 * Science Department, and William Jolitz.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	from: @(#)vm_machdep.c	7.3 (Berkeley) 5/13/91
 *	Utah $Hdr: vm_machdep.c 1.16.1.1 89/06/23$
 * $FreeBSD: src/sys/i386/i386/vm_machdep.c,v 1.132.2.9 2003/01/25 19:02:23 dillon Exp $
 */

#include "opt_reset.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <sys/buf.h>
#include <sys/interrupt.h>
#include <sys/vnode.h>
#include <sys/vmmeter.h>
#include <sys/kernel.h>
#include <sys/sysctl.h>
#include <sys/unistd.h>
#include <sys/lwp.h>

#include <machine/clock.h>
#include <machine/cpu.h>
#include <machine/md_var.h>
#include <machine/smp.h>
#include <machine/pcb.h>
#include <machine/pcb_ext.h>
#include <machine/segments.h>
#include <machine/globaldata.h>	/* npxthread */
#include <machine/specialreg.h>

#include <vm/vm.h>
#include <vm/vm_param.h>
#include <sys/lock.h>
#include <vm/vm_kern.h>
#include <vm/vm_page.h>
#include <vm/vm_map.h>
#include <vm/vm_extern.h>

#include <sys/thread2.h>

#include <bus/isa/isa.h>

static void	cpu_reset_real (void);

static int spectre_mitigation = -1;
static int spectre_support = 0;
static int spectre_mode = 0;
SYSCTL_INT(_machdep, OID_AUTO, spectre_mode, CTLFLAG_RD,
	&spectre_mode, 0, "current Spectre enablements");

static int mds_mitigation = -1;
static int mds_support = 0;
static int mds_mode = 0;
SYSCTL_INT(_machdep, OID_AUTO, mds_mode, CTLFLAG_RD,
	&mds_mode, 0, "current MDS enablements");

/*
 * Finish a fork operation, with lwp lp2 nearly set up.
 * Copy and update the pcb, set up the stack so that the child
 * ready to run and return to user mode.
 */
void
cpu_fork(struct lwp *lp1, struct lwp *lp2, int flags)
{
	struct pcb *pcb2;
	struct pmap *pmap2;

	if ((flags & RFPROC) == 0) {
		if ((flags & RFMEM) == 0) {
			/*
			 * Unshare user LDT.  > 1 test is MPSAFE.  While
			 * it can potentially race a 2->1 transition, the
			 * worst that happens is that we do an unnecessary
			 * ldt replacement.
			 */
			struct pcb *pcb1 = lp1->lwp_thread->td_pcb;
			struct pcb_ldt *pcb_ldt = pcb1->pcb_ldt;

			if (pcb_ldt && pcb_ldt->ldt_refcnt > 1) {
				pcb_ldt = user_ldt_alloc(pcb1,pcb_ldt->ldt_len);
				user_ldt_free(pcb1);
				pcb1->pcb_ldt = pcb_ldt;
				set_user_ldt(pcb1);
			}
		}
		return;
	}

	/* Ensure that lp1's pcb is up to date. */
	if (mdcpu->gd_npxthread == lp1->lwp_thread)
		npxsave(lp1->lwp_thread->td_savefpu);

	/*
	 * Copy lp1's PCB.  This really only applies to the
	 * debug registers and FP state, but its faster to just copy the
	 * whole thing.  Because we only save the PCB at switchout time,
	 * the register state may not be current.
	 */
	pcb2 = lp2->lwp_thread->td_pcb;
	*pcb2 = *lp1->lwp_thread->td_pcb;

	/*
	 * Create a new fresh stack for the new process.
	 * Copy the trap frame for the return to user mode as if from a
	 * syscall.  This copies the user mode register values.
	 *
	 * pcb_rsp must allocate an additional call-return pointer below
	 * the trap frame which will be restored by cpu_heavy_restore from
	 * PCB_RIP, and the thread's td_sp pointer must allocate an
	 * additonal two quadwords below the pcb_rsp call-return pointer to
	 * hold the LWKT restore function pointer and rflags.
	 *
	 * The LWKT restore function pointer must be set to cpu_heavy_restore,
	 * which is our standard heavy-weight process switch-in function.
	 * YYY eventually we should shortcut fork_return and fork_trampoline
	 * to use the LWKT restore function directly so we can get rid of
	 * all the extra crap we are setting up.
	 */
	lp2->lwp_md.md_regs = (struct trapframe *)pcb2 - 1;
	bcopy(lp1->lwp_md.md_regs, lp2->lwp_md.md_regs, sizeof(*lp2->lwp_md.md_regs));

	/*
	 * Set registers for trampoline to user mode.  Leave space for the
	 * return address on stack.  These are the kernel mode register values.
	 *
	 * Set the new pmap CR3.  If the new process uses isolated VM spaces,
	 * also set the isolated CR3.
	 */
	pmap2 = vmspace_pmap(lp2->lwp_proc->p_vmspace);
	pcb2->pcb_cr3 = vtophys(pmap2->pm_pml4);
	if ((pcb2->pcb_flags & PCB_ISOMMU) && pmap2->pm_pmlpv_iso) {
		pcb2->pcb_cr3_iso = vtophys(pmap2->pm_pml4_iso);
	} else {
		pcb2->pcb_flags &= ~PCB_ISOMMU;
		pcb2->pcb_cr3_iso = 0;
	}

#if 0
	/*
	 * Per-process spectre mitigation (future)
	 */
	pcb2->pcb_flags &= ~(PCB_IBRS1 | PCB_IBRS2);
	switch (spectre_mitigation) {
	case 1:
		pcb2->pcb_flags |= PCB_IBRS1;
		break;
	case 2:
		pcb2->pcb_flags |= PCB_IBRS2;
		break;
	default:
		break;
	}
#endif

	pcb2->pcb_rbx = (unsigned long)fork_return;	/* fork_trampoline argument */
	pcb2->pcb_rbp = 0;
	pcb2->pcb_rsp = (unsigned long)lp2->lwp_md.md_regs - sizeof(void *);
	pcb2->pcb_r12 = (unsigned long)lp2;		/* fork_trampoline argument */
	pcb2->pcb_r13 = 0;
	pcb2->pcb_r14 = 0;
	pcb2->pcb_r15 = 0;
	pcb2->pcb_rip = (unsigned long)fork_trampoline;
	lp2->lwp_thread->td_sp = (char *)(pcb2->pcb_rsp - sizeof(void *));
	*(u_int64_t *)lp2->lwp_thread->td_sp = PSL_USER;
	lp2->lwp_thread->td_sp -= sizeof(void *);
	*(void **)lp2->lwp_thread->td_sp = (void *)cpu_heavy_restore;

	/*
	 * pcb2->pcb_ldt:	duplicated below, if necessary.
	 * pcb2->pcb_savefpu:	cloned above.
	 * pcb2->pcb_flags:	cloned above
	 * pcb2->pcb_onfault:	cloned above (always NULL here).
	 * pcb2->pcb_onfault_sp:cloned above (dont care)
	 */

	/*
	 * XXX don't copy the i/o pages.  this should probably be fixed.
	 */
	pcb2->pcb_ext = NULL;

        /* Copy the LDT, if necessary. */
        if (pcb2->pcb_ldt != NULL) {
		if (flags & RFMEM) {
			atomic_add_int(&pcb2->pcb_ldt->ldt_refcnt, 1);
		} else {
			pcb2->pcb_ldt = user_ldt_alloc(pcb2,
						       pcb2->pcb_ldt->ldt_len);
		}
        }
	bcopy(&lp1->lwp_thread->td_tls, &lp2->lwp_thread->td_tls,
	      sizeof(lp2->lwp_thread->td_tls));
	/*
	 * Now, cpu_switch() can schedule the new lwp.
	 * pcb_rsp is loaded pointing to the cpu_switch() stack frame
	 * containing the return address when exiting cpu_switch.
	 * This will normally be to fork_trampoline(), which will have
	 * %rbx loaded with the new lwp's pointer.  fork_trampoline()
	 * will set up a stack to call fork_return(lp, frame); to complete
	 * the return to user-mode.
	 */
}

/*
 * Prepare new lwp to return to the address specified in params.
 */
int
cpu_prepare_lwp(struct lwp *lp, struct lwp_params *params)
{
	struct trapframe *regs = lp->lwp_md.md_regs;
	void *bad_return = NULL;
	int error;

	regs->tf_rip = (long)params->lwp_func;
	regs->tf_rsp = (long)params->lwp_stack;
	/* Set up argument for function call */
	regs->tf_rdi = (long)params->lwp_arg;

	/*
	 * Set up fake return address.  As the lwp function may never return,
	 * we simply copy out a NULL pointer and force the lwp to receive
	 * a SIGSEGV if it returns anyways.
	 */
	regs->tf_rsp -= sizeof(void *);
	error = copyout(&bad_return, (void *)regs->tf_rsp, sizeof(bad_return));
	if (error)
		return (error);

	cpu_set_fork_handler(lp,
	    (void (*)(void *, struct trapframe *))generic_lwp_return, lp);
	return (0);
}

/*
 * Intercept the return address from a freshly forked process that has NOT
 * been scheduled yet.
 *
 * This is needed to make kernel threads stay in kernel mode.
 */
void
cpu_set_fork_handler(struct lwp *lp, void (*func)(void *, struct trapframe *),
		     void *arg)
{
	/*
	 * Note that the trap frame follows the args, so the function
	 * is really called like this:  func(arg, frame);
	 */
	lp->lwp_thread->td_pcb->pcb_rbx = (long)func;	/* function */
	lp->lwp_thread->td_pcb->pcb_r12 = (long)arg;	/* first arg */
}

void
cpu_set_thread_handler(thread_t td, void (*rfunc)(void), void *func, void *arg)
{
	td->td_pcb->pcb_rbx = (long)func;
	td->td_pcb->pcb_r12 = (long)arg;
	td->td_switch = cpu_lwkt_switch;
	td->td_sp -= sizeof(void *);
	*(void **)td->td_sp = rfunc;	/* exit function on return */
	td->td_sp -= sizeof(void *);
	*(void **)td->td_sp = cpu_kthread_restore;
}

void
cpu_lwp_exit(void)
{
	struct thread *td = curthread;
	struct pcb *pcb;

	pcb = td->td_pcb;

	/* Some x86 functionality was dropped */
	KKASSERT(pcb->pcb_ext == NULL);

	/*
	 * disable all hardware breakpoints
	 */
        if (pcb->pcb_flags & PCB_DBREGS) {
                reset_dbregs();
                pcb->pcb_flags &= ~PCB_DBREGS;
        }
	td->td_gd->gd_cnt.v_swtch++;

	crit_enter_quick(td);
	if (td->td_flags & TDF_TSLEEPQ)
		tsleep_remove(td);
	lwkt_deschedule_self(td);
	lwkt_remove_tdallq(td);
	cpu_thread_exit();
}

/*
 * Terminate the current thread.  The caller must have already acquired
 * the thread's rwlock and placed it on a reap list or otherwise notified
 * a reaper of its existance.  We set a special assembly switch function which
 * releases td_rwlock after it has cleaned up the MMU state and switched
 * out the stack.
 *
 * Must be caller from a critical section and with the thread descheduled.
 */
void
cpu_thread_exit(void)
{
	npxexit();
	curthread->td_switch = cpu_exit_switch;
	curthread->td_flags |= TDF_EXITING;
	lwkt_switch();
	panic("cpu_thread_exit: lwkt_switch() unexpectedly returned");
}

void
cpu_reset(void)
{
	cpu_reset_real();
}

static void
cpu_reset_real(void)
{
	/*
	 * Attempt to do a CPU reset via the keyboard controller,
	 * do not turn off the GateA20, as any machine that fails
	 * to do the reset here would then end up in no man's land.
	 */

#if !defined(BROKEN_KEYBOARD_RESET)
	outb(IO_KBD + 4, 0xFE);
	DELAY(500000);	/* wait 0.5 sec to see if that did it */
	kprintf("Keyboard reset did not work, attempting CPU shutdown\n");
	DELAY(1000000);	/* wait 1 sec for kprintf to complete */
#endif
#if 0 /* JG */
	/* force a shutdown by unmapping entire address space ! */
	bzero((caddr_t) PTD, PAGE_SIZE);
#endif

	/* "good night, sweet prince .... <THUNK!>" */
	cpu_invltlb();
	/* NOTREACHED */
	while(1);
}

static void
swi_vm(void *arg, void *frame)
{
	if (busdma_swi_pending != 0)
		busdma_swi();
}

static void
swi_vm_setup(void *arg)
{
	register_swi_mp(SWI_VM, swi_vm, NULL, "swi_vm", NULL, 0);
}

SYSINIT(swi_vm_setup, SI_BOOT2_MACHDEP, SI_ORDER_ANY, swi_vm_setup, NULL);

/*
 * NOTE: This routine is also called after a successful microcode
 *	 reload on cpu 0.
 */
void mitigation_vm_setup(void *arg);

/*
 * Check for IBPB and IBRS support
 *
 * This bits also specify desired modes in the spectre_mitigation sysctl.
 */
#define IBRS_SUPPORTED		0x0001
#define STIBP_SUPPORTED		0x0002
#define IBPB_SUPPORTED		0x0004
#define IBRS_AUTO_SUPPORTED	0x0008
#define STIBP_AUTO_SUPPORTED	0x0010
#define IBRS_PREFERRED_REQUEST	0x0020

static
int
spectre_check_support(void)
{
	uint32_t p[4];
	int rv = 0;

	/*
	 * Spectre mitigation hw bits
	 *
	 * IBRS		Indirect Branch Restricted Speculation   (isolation)
	 * STIBP	Single Thread Indirect Branch Prediction (isolation)
	 * IBPB		Branch Prediction Barrier                (barrier)
	 *
	 * IBRS and STIBP must be toggled (enabled on entry to kernel,
	 * disabled on exit, as well as disabled during any MWAIT/HLT).
	 * When *_AUTO bits are available, IBRS and STIBP may be left
	 * turned on and do not have to be toggled on kernel entry/exit.
	 * Be sure to clear before going idle (else hyperthread performance
	 * will drop).
	 *
	 * All this shit has enormous overhead.  IBPB in particular, and
	 * non-auto modes are disabled by default.
	 */
	if (cpu_vendor_id == CPU_VENDOR_INTEL) {
		p[0] = 0;
		p[1] = 0;
		p[2] = 0;
		p[3] = 0;
		cpuid_count(7, 0, p);
		if (p[3] & CPUID_STDEXT3_IBPB)
			rv |= IBRS_SUPPORTED | IBPB_SUPPORTED;
		if (p[3] & CPUID_STDEXT3_STIBP)
			rv |= STIBP_SUPPORTED;

		/*
		 * 0x80000008 p[1] bit 12 indicates IBPB support
		 *
		 * This bit might be set even though STDEXT3_IBPB is not set.
		 */
		p[0] = 0;
		p[1] = 0;
		p[2] = 0;
		p[3] = 0;
		do_cpuid(0x80000008U, p);
		if (p[1] & CPUID_CAPEX_IBPB)
			rv |= IBPB_SUPPORTED;
	} else if (cpu_vendor_id == CPU_VENDOR_AMD) {
		/*
		 * 0x80000008
		 *	p[1] bit 12 indicates IBPB support
		 *	p[1] bit 14 indicates IBRS support
		 *	p[1] bit 15 indicates STIBP support
		 *
		 *	p[1] bit 16 indicates IBRS auto support
		 *	p[1] bit 17 indicates STIBP auto support
		 *	p[1] bit 18 indicates processor prefers using
		 *		IBRS instead of retpoline.
		 */
		p[0] = 0;
		p[1] = 0;
		p[2] = 0;
		p[3] = 0;
		do_cpuid(0x80000008U, p);
		if (p[1] & CPUID_CAPEX_IBPB)
			rv |= IBPB_SUPPORTED;
		if (p[1] & CPUID_CAPEX_IBRS)
			rv |= IBRS_SUPPORTED;
		if (p[1] & CPUID_CAPEX_STIBP)
			rv |= STIBP_SUPPORTED;

		if (p[1] & CPUID_CAPEX_IBRS_ALWAYSON)
			rv |= IBRS_AUTO_SUPPORTED;
		if (p[1] & CPUID_CAPEX_STIBP_ALWAYSON)
			rv |= STIBP_AUTO_SUPPORTED;
		if (p[1] & CPUID_CAPEX_PREFER_IBRS)
			rv |= IBRS_PREFERRED_REQUEST;
	}

	return rv;
}

/*
 * Iterate CPUs and adjust MSR for global operations, since
 * the KMMU* code won't do it if spectre_mitigation is 0 or 2.
 */
#define CHECK(flag)	(spectre_mitigation & spectre_support & (flag))

static
void
spectre_sysctl_changed(void)
{
	globaldata_t save_gd;
	struct trampframe *tr;
	int spec_ctrl;
	int spec_mask;
	int mode;
	int n;

	spec_mask = SPEC_CTRL_IBRS | SPEC_CTRL_STIBP |
		    SPEC_CTRL_DUMMY_ENABLE | SPEC_CTRL_DUMMY_IBPB;

	/*
	 * Fixup state
	 */
	mode = 0;
	save_gd = mycpu;
	for (n = 0; n < ncpus; ++n) {
		lwkt_setcpu_self(globaldata_find(n));
		cpu_ccfence();
		tr = &pscpu->trampoline;

		/*
		 * Make sure we are cleaned out.
		 *
		 * XXX cleanup, reusing globals inside the loop (they get
		 * set to the same thing each loop)
		 *
		 * [0] kernel entry (idle exit)
		 * [1] kernel exit  (idle entry)
		 */
		tr->tr_pcb_spec_ctrl[0] &= ~spec_mask;
		tr->tr_pcb_spec_ctrl[1] &= ~spec_mask;

		/*
		 * Don't try to parse if not available
		 */
		if (spectre_mitigation < 0)
			continue;

		/*
		 * IBRS mode.  Auto overrides toggling.
		 *
		 * Only set the ENABLE flag if we have to toggle something
		 * on entry and exit.
		 */
		spec_ctrl = 0;
		if (CHECK(IBRS_AUTO_SUPPORTED)) {
			spec_ctrl |= SPEC_CTRL_IBRS;
			mode |= IBRS_AUTO_SUPPORTED;
		} else if (CHECK(IBRS_SUPPORTED)) {
			spec_ctrl |= SPEC_CTRL_IBRS | SPEC_CTRL_DUMMY_ENABLE;
			mode |= IBRS_SUPPORTED;
		}
		if (CHECK(STIBP_AUTO_SUPPORTED)) {
			spec_ctrl |= SPEC_CTRL_STIBP;
			mode |= STIBP_AUTO_SUPPORTED;
		} else if (CHECK(STIBP_SUPPORTED)) {
			spec_ctrl |= SPEC_CTRL_STIBP | SPEC_CTRL_DUMMY_ENABLE;
			mode |= STIBP_SUPPORTED;
		}

		/*
		 * IBPB requested and supported.
		 */
		if (CHECK(IBPB_SUPPORTED)) {
			spec_ctrl |= SPEC_CTRL_DUMMY_IBPB;
			mode |= IBPB_SUPPORTED;
		}

		/*
		 * Update the MSR if the cpu supports the modes to ensure
		 * proper disablement if the user disabled the mode.
		 */
		if (spectre_support & (IBRS_SUPPORTED | IBRS_AUTO_SUPPORTED |
				    STIBP_SUPPORTED | STIBP_AUTO_SUPPORTED)) {
			wrmsr(MSR_SPEC_CTRL,
			      spec_ctrl & (SPEC_CTRL_IBRS|SPEC_CTRL_STIBP));
		}

		/*
		 * Update spec_ctrl fields in the trampoline.
		 *
		 * [0] on-kernel-entry (on-idle-exit)
		 * [1] on-kernel-exit  (on-idle-entry)
		 *
		 * When auto mode is supported we leave the bit set, otherwise
		 * we clear the bits.
		 */
		tr->tr_pcb_spec_ctrl[0] |= spec_ctrl;
		if (CHECK(IBRS_AUTO_SUPPORTED) == 0)
			spec_ctrl &= ~SPEC_CTRL_IBRS;
		if (CHECK(STIBP_AUTO_SUPPORTED) == 0)
			spec_ctrl &= ~SPEC_CTRL_STIBP;
		tr->tr_pcb_spec_ctrl[1] |= spec_ctrl;

		/*
		 * Make sure we set this on the first loop.  It will be
		 * the same value on remaining loops.
		 */
		spectre_mode = mode;
	}
	lwkt_setcpu_self(save_gd);
	cpu_ccfence();

	/*
	 * Console message on mitigation mode change
	 */
	kprintf("Spectre: support=(");
	if (spectre_support == 0) {
		kprintf(" none");
	} else {
		if (spectre_support & IBRS_SUPPORTED)
			kprintf(" IBRS");
		if (spectre_support & STIBP_SUPPORTED)
			kprintf(" STIBP");
		if (spectre_support & IBPB_SUPPORTED)
			kprintf(" IBPB");
		if (spectre_support & IBRS_AUTO_SUPPORTED)
			kprintf(" IBRS_AUTO");
		if (spectre_support & STIBP_AUTO_SUPPORTED)
			kprintf(" STIBP_AUTO");
		if (spectre_support & IBRS_PREFERRED_REQUEST)
			kprintf(" IBRS_REQUESTED");
	}
	kprintf(" ) req=%04x operating=(", (uint16_t)spectre_mitigation);
	if (spectre_mode == 0) {
		kprintf(" none");
	} else {
		if (spectre_mode & IBRS_SUPPORTED)
			kprintf(" IBRS");
		if (spectre_mode & STIBP_SUPPORTED)
			kprintf(" STIBP");
		if (spectre_mode & IBPB_SUPPORTED)
			kprintf(" IBPB");
		if (spectre_mode & IBRS_AUTO_SUPPORTED)
			kprintf(" IBRS_AUTO");
		if (spectre_mode & STIBP_AUTO_SUPPORTED)
			kprintf(" STIBP_AUTO");
		if (spectre_mode & IBRS_PREFERRED_REQUEST)
			kprintf(" IBRS_REQUESTED");
	}
	kprintf(" )\n");
}

#undef CHECK

/*
 * User changes sysctl value
 */
static int
sysctl_spectre_mitigation(SYSCTL_HANDLER_ARGS)
{
	char buf[128];
	char *ptr;
	char *iter;
	size_t len;
	int spectre;
	int error = 0;
	int loop = 0;

	/*
	 * Return current operating mode or support.
	 */
	if (oidp->oid_kind & CTLFLAG_WR)
		spectre = spectre_mode;
	else
		spectre = spectre_support;

	spectre &= (IBRS_SUPPORTED | IBRS_AUTO_SUPPORTED |
		    STIBP_SUPPORTED | STIBP_AUTO_SUPPORTED |
		    IBPB_SUPPORTED);
	while (spectre) {
		if (error)
			break;
		if (loop++) {
			error = SYSCTL_OUT(req, " ", 1);
			if (error)
				break;
		}
		if (spectre & IBRS_SUPPORTED) {
			spectre &= ~IBRS_SUPPORTED;
			error = SYSCTL_OUT(req, "IBRS", 4);
		} else
		if (spectre & IBRS_AUTO_SUPPORTED) {
			spectre &= ~IBRS_AUTO_SUPPORTED;
			error = SYSCTL_OUT(req, "IBRS_AUTO", 9);
		} else
		if (spectre & STIBP_SUPPORTED) {
			spectre &= ~STIBP_SUPPORTED;
			error = SYSCTL_OUT(req, "STIBP", 5);
		} else
		if (spectre & STIBP_AUTO_SUPPORTED) {
			spectre &= ~STIBP_AUTO_SUPPORTED;
			error = SYSCTL_OUT(req, "STIBP_AUTO", 10);
		} else
		if (spectre & IBPB_SUPPORTED) {
			spectre &= ~IBPB_SUPPORTED;
			error = SYSCTL_OUT(req, "IBPB", 4);
		}
	}
	if (loop == 0) {
		error = SYSCTL_OUT(req, "NONE", 4);
	}

	if (error || req->newptr == NULL)
		return error;
	if ((oidp->oid_kind & CTLFLAG_WR) == 0)
		return error;

	/*
	 * Change current operating mode
	 */
	len = req->newlen - req->newidx;
	if (len >= sizeof(buf)) {
		error = EINVAL;
		len = 0;
	} else {
		error = SYSCTL_IN(req, buf, len);
	}
	buf[len] = 0;
	iter = &buf[0];
	spectre = 0;

	while (error == 0 && iter) {
		ptr = strsep(&iter, " ,\t\r\n");
		if (*ptr == 0)
			continue;
		if (strcasecmp(ptr, "NONE") == 0)
			spectre |= 0;
		else if (strcasecmp(ptr, "IBRS") == 0)
			spectre |= IBRS_SUPPORTED;
		else if (strcasecmp(ptr, "IBRS_AUTO") == 0)
			spectre |= IBRS_AUTO_SUPPORTED;
		else if (strcasecmp(ptr, "STIBP") == 0)
			spectre |= STIBP_SUPPORTED;
		else if (strcasecmp(ptr, "STIBP_AUTO") == 0)
			spectre |= STIBP_AUTO_SUPPORTED;
		else if (strcasecmp(ptr, "IBPB") == 0)
			spectre |= IBPB_SUPPORTED;
		else
			error = ENOENT;
	}
	if (error == 0) {
		spectre_mitigation = spectre;
		spectre_sysctl_changed();
	}
	return error;
}

SYSCTL_PROC(_machdep, OID_AUTO, spectre_mitigation,
	CTLTYPE_STRING | CTLFLAG_RW,
	0, 0, sysctl_spectre_mitigation, "A", "Spectre exploit mitigation");
SYSCTL_PROC(_machdep, OID_AUTO, spectre_support,
	CTLTYPE_STRING | CTLFLAG_RD,
	0, 0, sysctl_spectre_mitigation, "A", "Spectre supported features");

/*
 * NOTE: Called at SI_BOOT2_MACHDEP and also when the microcode is
 *	 updated.  Microcode updates must be applied to all cpus
 *	 for support to be recognized.
 */
static void
spectre_vm_setup(void *arg)
{
	int inconsistent = 0;
	int supmask;

	/*
	 * Fetch tunable in auto mode
	 */
	if (spectre_mitigation < 0) {
		TUNABLE_INT_FETCH("machdep.spectre_mitigation",
				  &spectre_mitigation);
	}

	if ((supmask = spectre_check_support()) != 0) {
		/*
		 * Must be supported on all cpus before we
		 * can enable it.  Returns silently if it
		 * isn't.
		 *
		 * NOTE! arg != NULL indicates we were called
		 *	 from cpuctl after a successful microcode
		 *	 update.
		 */
		if (arg != NULL) {
			globaldata_t save_gd;
			int n;

			save_gd = mycpu;
			for (n = 0; n < ncpus; ++n) {
				lwkt_setcpu_self(globaldata_find(n));
				cpu_ccfence();
				if (spectre_check_support() !=
				    supmask) {
					inconsistent = 1;
					break;
				}
			}
			lwkt_setcpu_self(save_gd);
			cpu_ccfence();
		}
	}

	/*
	 * Be silent while microcode is being loaded on various CPUs,
	 * until all done.
	 */
	if (inconsistent) {
		spectre_mitigation = -1;
		spectre_support = 0;
		return;
	}

	/*
	 * IBRS support
	 */
	spectre_support = supmask;

	/*
	 * Enable spectre_mitigation, set defaults if -1, adjust
	 * tuned value according to support if not.
	 *
	 * NOTE!  We do not enable IBPB for user->kernel transitions
	 *	  by default, so this code is commented out for now.
	 */
	if (spectre_support) {
		if (spectre_mitigation < 0) {
			spectre_mitigation = 0;

			/*
			 * IBRS toggling not currently recommended as a
			 * default.
			 */
			if (spectre_support & IBRS_AUTO_SUPPORTED)
				spectre_mitigation |= IBRS_AUTO_SUPPORTED;
			else if (spectre_support & IBRS_SUPPORTED)
				spectre_mitigation |= 0;

			/*
			 * STIBP toggling not currently recommended as a
			 * default.
			 */
			if (spectre_support & STIBP_AUTO_SUPPORTED)
				spectre_mitigation |= STIBP_AUTO_SUPPORTED;
			else if (spectre_support & STIBP_SUPPORTED)
				spectre_mitigation |= 0;

			/*
			 * IBPB adds enormous (~2uS) overhead to system
			 * calls etc, we do not enable it by default.
			 */
			if (spectre_support & IBPB_SUPPORTED)
				spectre_mitigation |= 0;
		}
	} else {
		spectre_mitigation = -1;
	}

	/*
	 * Disallow sysctl changes when there is no support (otherwise
	 * the wrmsr will cause a protection fault).
	 */
	if (spectre_mitigation < 0)
		sysctl___machdep_spectre_mitigation.oid_kind &= ~CTLFLAG_WR;
	else
		sysctl___machdep_spectre_mitigation.oid_kind |= CTLFLAG_WR;

	spectre_sysctl_changed();
}

#define MDS_AVX512_4VNNIW_SUPPORTED	0x0001
#define MDS_AVX512_4FMAPS_SUPPORTED	0x0002
#define MDS_MD_CLEAR_SUPPORTED		0x0004
#define MDS_TSX_FORCE_ABORT_SUPPORTED	0x0008
#define MDS_NOT_REQUIRED		0x8000

static
int
mds_check_support(void)
{
	uint64_t msr;
	uint32_t p[4];
	int rv = 0;

	/*
	 * MDS mitigation hw bits
	 *
	 * MD_CLEAR	Use microcode-supported verf insn.  This is the
	 *		only mode we really support.
	 */
	if (cpu_vendor_id == CPU_VENDOR_INTEL) {
		p[0] = 0;
		p[1] = 0;
		p[2] = 0;
		p[3] = 0;
		cpuid_count(7, 0, p);

		/*
		 * Some hypervisors fail to implement
		 * MSR_IA32_ARCH_CAPABILITIES.
		 */
		if (p[3] & CPUID_STDEXT3_ARCH_CAP) {
			msr = 0;
			if (rdmsr_safe(MSR_IA32_ARCH_CAPABILITIES, &msr)) {
				kprintf("Warning: MSR_IA32_ARCH_CAPABILITIES "
					"cannot be accessed\n");
			}
			if (msr & IA32_ARCH_CAP_MDS_NO)
				rv = MDS_NOT_REQUIRED;
		}
		if (p[3] & CPUID_STDEXT3_AVX5124VNNIW)
			rv |= MDS_AVX512_4VNNIW_SUPPORTED;
		if (p[3] & CPUID_STDEXT3_AVX5124FMAPS)
			rv |= MDS_AVX512_4FMAPS_SUPPORTED;
		if (p[3] & CPUID_STDEXT3_MD_CLEAR)
			rv |= MDS_MD_CLEAR_SUPPORTED;
		if (p[3] & CPUID_STDEXT3_TSXFA)
			rv |= MDS_TSX_FORCE_ABORT_SUPPORTED;
	} else {
		rv = MDS_NOT_REQUIRED;
	}

	return rv;
}

/*
 * Iterate CPUs and adjust MSR for global operations, since
 * the KMMU* code won't do it if spectre_mitigation is 0 or 2.
 */
#define CHECK(flag)	(mds_mitigation & mds_support & (flag))

static
void
mds_sysctl_changed(void)
{
	globaldata_t save_gd;
	struct trampframe *tr;
	int spec_ctrl;
	int spec_mask;
	int mode;
	int n;

	spec_mask = SPEC_CTRL_MDS_ENABLE;

	/*
	 * Fixup state
	 */
	mode = 0;
	save_gd = mycpu;
	for (n = 0; n < ncpus; ++n) {
		lwkt_setcpu_self(globaldata_find(n));
		cpu_ccfence();
		tr = &pscpu->trampoline;

		/*
		 * Make sure we are cleaned out.
		 *
		 * XXX cleanup, reusing globals inside the loop (they get
		 * set to the same thing each loop)
		 *
		 * [0] kernel entry (idle exit)
		 * [1] kernel exit  (idle entry)
		 */
		tr->tr_pcb_spec_ctrl[0] &= ~spec_mask;
		tr->tr_pcb_spec_ctrl[1] &= ~spec_mask;

		/*
		 * Don't try to parse if not available
		 */
		if (mds_mitigation < 0)
			continue;

		spec_ctrl = 0;
		if (CHECK(MDS_MD_CLEAR_SUPPORTED)) {
			spec_ctrl |= SPEC_CTRL_MDS_ENABLE;
			mode |= MDS_MD_CLEAR_SUPPORTED;
		}

		/*
		 * Update spec_ctrl fields in the trampoline.
		 *
		 * [0] on-kernel-entry (on-idle-exit)
		 * [1] on-kernel-exit  (on-idle-entry)
		 *
		 * The MDS stuff is only needed on kernel-exit or idle-entry
		 */
		/* tr->tr_pcb_spec_ctrl[0] |= spec_ctrl; */
		tr->tr_pcb_spec_ctrl[1] |= spec_ctrl;

		/*
		 * Make sure we set this on the first loop.  It will be
		 * the same value on remaining loops.
		 */
		mds_mode = mode;
	}
	lwkt_setcpu_self(save_gd);
	cpu_ccfence();

	/*
	 * Console message on mitigation mode change
	 */
	kprintf("MDS: support=(");
	if (mds_support == 0) {
		kprintf(" none");
	} else {
		if (mds_support & MDS_AVX512_4VNNIW_SUPPORTED)
			kprintf(" AVX512_4VNNIW");
		if (mds_support & MDS_AVX512_4FMAPS_SUPPORTED)
			kprintf(" AVX512_4FMAPS");
		if (mds_support & MDS_MD_CLEAR_SUPPORTED)
			kprintf(" MD_CLEAR");
		if (mds_support & MDS_TSX_FORCE_ABORT_SUPPORTED)
			kprintf(" TSX_FORCE_ABORT");
		if (mds_support & MDS_NOT_REQUIRED)
			kprintf(" MDS_NOT_REQUIRED");
	}
	kprintf(" ) req=%04x operating=(", (uint16_t)mds_mitigation);
	if (mds_mode == 0) {
		kprintf(" none");
	} else {
		if (mds_mode & MDS_AVX512_4VNNIW_SUPPORTED)
			kprintf(" AVX512_4VNNIW");
		if (mds_mode & MDS_AVX512_4FMAPS_SUPPORTED)
			kprintf(" AVX512_4FMAPS");
		if (mds_mode & MDS_MD_CLEAR_SUPPORTED)
			kprintf(" MD_CLEAR");
		if (mds_mode & MDS_TSX_FORCE_ABORT_SUPPORTED)
			kprintf(" TSX_FORCE_ABORT");
		if (mds_mode & MDS_NOT_REQUIRED)
			kprintf(" MDS_NOT_REQUIRED");
	}
	kprintf(" )\n");
}

#undef CHECK

/*
 * User changes sysctl value
 */
static int
sysctl_mds_mitigation(SYSCTL_HANDLER_ARGS)
{
	char buf[128];
	char *ptr;
	char *iter;
	size_t len;
	int mds;
	int error = 0;
	int loop = 0;

	/*
	 * Return current operating mode or support.
	 */
	if (oidp->oid_kind & CTLFLAG_WR)
		mds = mds_mode;
	else
		mds = mds_support;

	mds &= MDS_AVX512_4VNNIW_SUPPORTED |
	       MDS_AVX512_4FMAPS_SUPPORTED |
	       MDS_MD_CLEAR_SUPPORTED |
	       MDS_TSX_FORCE_ABORT_SUPPORTED |
	       MDS_NOT_REQUIRED;

	while (mds) {
		if (error)
			break;
		if (loop++) {
			error = SYSCTL_OUT(req, " ", 1);
			if (error)
				break;
		}
		if (mds & MDS_AVX512_4VNNIW_SUPPORTED) {
			mds &= ~MDS_AVX512_4VNNIW_SUPPORTED;
			error = SYSCTL_OUT(req, "AVX512_4VNNIW", 13);
		} else
		if (mds & MDS_AVX512_4FMAPS_SUPPORTED) {
			mds &= ~MDS_AVX512_4FMAPS_SUPPORTED;
			error = SYSCTL_OUT(req, "AVX512_4FMAPS", 13);
		} else
		if (mds & MDS_MD_CLEAR_SUPPORTED) {
			mds &= ~MDS_MD_CLEAR_SUPPORTED;
			error = SYSCTL_OUT(req, "MD_CLEAR", 8);
		} else
		if (mds & MDS_TSX_FORCE_ABORT_SUPPORTED) {
			mds &= ~MDS_TSX_FORCE_ABORT_SUPPORTED;
			error = SYSCTL_OUT(req, "TSX_FORCE_ABORT", 15);
		} else
		if (mds & MDS_NOT_REQUIRED) {
			mds &= ~MDS_NOT_REQUIRED;
			error = SYSCTL_OUT(req, "MDS_NOT_REQUIRED", 16);
		}
	}
	if (loop == 0) {
		error = SYSCTL_OUT(req, "NONE", 4);
	}

	if (error || req->newptr == NULL)
		return error;
	if ((oidp->oid_kind & CTLFLAG_WR) == 0)
		return error;

	/*
	 * Change current operating mode
	 */
	len = req->newlen - req->newidx;
	if (len >= sizeof(buf)) {
		error = EINVAL;
		len = 0;
	} else {
		error = SYSCTL_IN(req, buf, len);
	}
	buf[len] = 0;
	iter = &buf[0];
	mds = 0;

	while (error == 0 && iter) {
		ptr = strsep(&iter, " ,\t\r\n");
		if (*ptr == 0)
			continue;
		if (strcasecmp(ptr, "NONE") == 0)
			mds |= 0;
		else if (strcasecmp(ptr, "AVX512_4VNNIW") == 0)
			mds |= MDS_AVX512_4VNNIW_SUPPORTED;
		else if (strcasecmp(ptr, "AVX512_4FMAPS") == 0)
			mds |= MDS_AVX512_4FMAPS_SUPPORTED;
		else if (strcasecmp(ptr, "MD_CLEAR") == 0)
			mds |= MDS_MD_CLEAR_SUPPORTED;
		else if (strcasecmp(ptr, "TSX_FORCE_ABORT") == 0)
			mds |= MDS_TSX_FORCE_ABORT_SUPPORTED;
		else if (strcasecmp(ptr, "MDS_NOT_REQUIRED") == 0)
			mds |= MDS_NOT_REQUIRED;
		else
			error = ENOENT;
	}
	if (error == 0) {
		mds_mitigation = mds;
		mds_sysctl_changed();
	}
	return error;
}

SYSCTL_PROC(_machdep, OID_AUTO, mds_mitigation,
	CTLTYPE_STRING | CTLFLAG_RW,
	0, 0, sysctl_mds_mitigation, "A", "MDS exploit mitigation");
SYSCTL_PROC(_machdep, OID_AUTO, mds_support,
	CTLTYPE_STRING | CTLFLAG_RD,
	0, 0, sysctl_mds_mitigation, "A", "MDS supported features");

/*
 * NOTE: Called at SI_BOOT2_MACHDEP and also when the microcode is
 *	 updated.  Microcode updates must be applied to all cpus
 *	 for support to be recognized.
 */
static void
mds_vm_setup(void *arg)
{
	int inconsistent = 0;
	int supmask;

	/*
	 * Fetch tunable in auto mode
	 */
	if (mds_mitigation < 0) {
		TUNABLE_INT_FETCH("machdep.mds_mitigation", &mds_mitigation);
	}

	if ((supmask = mds_check_support()) != 0) {
		/*
		 * Must be supported on all cpus before we
		 * can enable it.  Returns silently if it
		 * isn't.
		 *
		 * NOTE! arg != NULL indicates we were called
		 *	 from cpuctl after a successful microcode
		 *	 update.
		 */
		if (arg != NULL) {
			globaldata_t save_gd;
			int n;

			save_gd = mycpu;
			for (n = 0; n < ncpus; ++n) {
				lwkt_setcpu_self(globaldata_find(n));
				cpu_ccfence();
				if (mds_check_support() != supmask) {
					inconsistent = 1;
					break;
				}
			}
			lwkt_setcpu_self(save_gd);
			cpu_ccfence();
		}
	}

	/*
	 * Be silent while microcode is being loaded on various CPUs,
	 * until all done.
	 */
	if (inconsistent) {
		mds_mitigation = -1;
		mds_support = 0;
		return;
	}

	/*
	 * IBRS support
	 */
	mds_support = supmask;

	/*
	 * Enable mds_mitigation, set defaults if -1, adjust
	 * tuned value according to support if not.
	 *
	 * NOTE!  MDS is not enabled by default.
	 */
	if (mds_support) {
		if (mds_mitigation < 0) {
			mds_mitigation = 0;

			if ((mds_support & MDS_NOT_REQUIRED) == 0 &&
			    (mds_support & MDS_MD_CLEAR_SUPPORTED)) {
				/* mds_mitigation |= MDS_MD_CLEAR_SUPPORTED; */
			}
		}
	} else {
		mds_mitigation = -1;
	}

	/*
	 * Disallow sysctl changes when there is no support (otherwise
	 * the wrmsr will cause a protection fault).
	 */
	if (mds_mitigation < 0)
		sysctl___machdep_mds_mitigation.oid_kind &= ~CTLFLAG_WR;
	else
		sysctl___machdep_mds_mitigation.oid_kind |= CTLFLAG_WR;

	mds_sysctl_changed();
}

/*
 * NOTE: Called at SI_BOOT2_MACHDEP and also when the microcode is
 *	 updated.  Microcode updates must be applied to all cpus
 *	 for support to be recognized.
 */
void
mitigation_vm_setup(void *arg)
{
	spectre_vm_setup(arg);
	mds_vm_setup(arg);
}

SYSINIT(mitigation_vm_setup, SI_BOOT2_MACHDEP, SI_ORDER_ANY,
	mitigation_vm_setup, NULL);

/*
 * platform-specific vmspace initialization (nothing for x86_64)
 */
void
cpu_vmspace_alloc(struct vmspace *vm __unused)
{
}

void
cpu_vmspace_free(struct vmspace *vm __unused)
{
}

int
kvm_access_check(vm_offset_t saddr, vm_offset_t eaddr, int prot)
{
	vm_offset_t addr;

	if (saddr < KvaStart)
		return EFAULT;
	if (eaddr >= KvaEnd)
		return EFAULT;
	for (addr = saddr; addr < eaddr; addr += PAGE_SIZE)  {
		if (pmap_kextract(addr) == 0)
			return EFAULT;
	}
	if (!kernacc((caddr_t)saddr, eaddr - saddr, prot))
		return EFAULT;
	return 0;
}

#if 0

void _test_frame_enter(struct trapframe *frame);
void _test_frame_exit(struct trapframe *frame);

void
_test_frame_enter(struct trapframe *frame)
{
	thread_t td = curthread;

	if (ISPL(frame->tf_cs) == SEL_UPL) {
		KKASSERT(td->td_lwp);
                KASSERT(td->td_lwp->lwp_md.md_regs == frame,
                        ("_test_frame_exit: Frame mismatch %p %p",
			td->td_lwp->lwp_md.md_regs, frame));
	    td->td_lwp->lwp_saveusp = (void *)frame->tf_rsp;
	    td->td_lwp->lwp_saveupc = (void *)frame->tf_rip;
	}
	if ((char *)frame < td->td_kstack ||
	    (char *)frame > td->td_kstack + td->td_kstack_size) {
		panic("_test_frame_exit: frame not on kstack %p kstack=%p",
			frame, td->td_kstack);
	}
}

void
_test_frame_exit(struct trapframe *frame)
{
	thread_t td = curthread;

	if (ISPL(frame->tf_cs) == SEL_UPL) {
		KKASSERT(td->td_lwp);
                KASSERT(td->td_lwp->lwp_md.md_regs == frame,
                        ("_test_frame_exit: Frame mismatch %p %p",
			td->td_lwp->lwp_md.md_regs, frame));
		if (td->td_lwp->lwp_saveusp != (void *)frame->tf_rsp) {
			kprintf("_test_frame_exit: %s:%d usp mismatch %p/%p\n",
				td->td_comm, td->td_proc->p_pid,
				td->td_lwp->lwp_saveusp,
				(void *)frame->tf_rsp);
		}
		if (td->td_lwp->lwp_saveupc != (void *)frame->tf_rip) {
			kprintf("_test_frame_exit: %s:%d upc mismatch %p/%p\n",
				td->td_comm, td->td_proc->p_pid,
				td->td_lwp->lwp_saveupc,
				(void *)frame->tf_rip);
		}

		/*
		 * adulterate the fields to catch entries that
		 * don't run through test_frame_enter
		 */
		td->td_lwp->lwp_saveusp =
			(void *)~(intptr_t)td->td_lwp->lwp_saveusp;
		td->td_lwp->lwp_saveupc =
			(void *)~(intptr_t)td->td_lwp->lwp_saveupc;
	}
	if ((char *)frame < td->td_kstack ||
	    (char *)frame > td->td_kstack + td->td_kstack_size) {
		panic("_test_frame_exit: frame not on kstack %p kstack=%p",
			frame, td->td_kstack);
	}
}

#endif