summaryrefslogtreecommitdiff
path: root/usr/src/uts/intel/ia32/os/archdep.c
blob: f4bbd804207f04f2c94f2adebd6f6e56d4864ce5 (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
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
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved  	*/


#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <sys/param.h>
#include <sys/types.h>
#include <sys/vmparam.h>
#include <sys/systm.h>
#include <sys/signal.h>
#include <sys/stack.h>
#include <sys/regset.h>
#include <sys/privregs.h>
#include <sys/frame.h>
#include <sys/proc.h>
#include <sys/psw.h>
#include <sys/siginfo.h>
#include <sys/cpuvar.h>
#include <sys/asm_linkage.h>
#include <sys/kmem.h>
#include <sys/errno.h>
#include <sys/bootconf.h>
#include <sys/archsystm.h>
#include <sys/debug.h>
#include <sys/elf.h>
#include <sys/spl.h>
#include <sys/time.h>
#include <sys/atomic.h>
#include <sys/sysmacros.h>
#include <sys/cmn_err.h>
#include <sys/modctl.h>
#include <sys/kobj.h>
#include <sys/panic.h>
#include <sys/reboot.h>
#include <sys/time.h>
#include <sys/fp.h>
#include <sys/x86_archext.h>
#include <sys/auxv.h>
#include <sys/auxv_386.h>
#include <sys/dtrace.h>
#include <sys/brand.h>
#include <sys/machbrand.h>

extern const struct fnsave_state x87_initial;
extern const struct fxsave_state sse_initial;

/*
 * Map an fnsave-formatted save area into an fxsave-formatted save area.
 *
 * Most fields are the same width, content and semantics.  However
 * the tag word is compressed.
 */
static void
fnsave_to_fxsave(const struct fnsave_state *fn, struct fxsave_state *fx)
{
	uint_t i, tagbits;

	fx->fx_fcw = fn->f_fcw;
	fx->fx_fsw = fn->f_fsw;

	/*
	 * copy element by element (because of holes)
	 */
	for (i = 0; i < 8; i++)
		bcopy(&fn->f_st[i].fpr_16[0], &fx->fx_st[i].fpr_16[0],
		    sizeof (fn->f_st[0].fpr_16)); /* 80-bit x87-style floats */

	/*
	 * synthesize compressed tag bits
	 */
	fx->fx_fctw = 0;
	for (tagbits = fn->f_ftw, i = 0; i < 8; i++, tagbits >>= 2)
		if ((tagbits & 3) != 3)
			fx->fx_fctw |= (1 << i);

	fx->fx_fop = fn->f_fop;

#if defined(__amd64)
	fx->fx_rip = (uint64_t)fn->f_eip;
	fx->fx_rdp = (uint64_t)fn->f_dp;
#else
	fx->fx_eip = fn->f_eip;
	fx->fx_cs = fn->f_cs;
	fx->__fx_ign0 = 0;
	fx->fx_dp = fn->f_dp;
	fx->fx_ds = fn->f_ds;
	fx->__fx_ign1 = 0;
#endif
}

/*
 * Map from an fxsave-format save area to an fnsave-format save area.
 */
static void
fxsave_to_fnsave(const struct fxsave_state *fx, struct fnsave_state *fn)
{
	uint_t i, top, tagbits;

	fn->f_fcw = fx->fx_fcw;
	fn->__f_ign0 = 0;
	fn->f_fsw = fx->fx_fsw;
	fn->__f_ign1 = 0;

	top = (fx->fx_fsw & FPS_TOP) >> 11;

	/*
	 * copy element by element (because of holes)
	 */
	for (i = 0; i < 8; i++)
		bcopy(&fx->fx_st[i].fpr_16[0], &fn->f_st[i].fpr_16[0],
		    sizeof (fn->f_st[0].fpr_16)); /* 80-bit x87-style floats */

	/*
	 * synthesize uncompressed tag bits
	 */
	fn->f_ftw = 0;
	for (tagbits = fx->fx_fctw, i = 0; i < 8; i++, tagbits >>= 1) {
		uint_t ibit, expo;
		const uint16_t *fpp;
		static const uint16_t zero[5] = { 0, 0, 0, 0, 0 };

		if ((tagbits & 1) == 0) {
			fn->f_ftw |= 3 << (i << 1);	/* empty */
			continue;
		}

		/*
		 * (tags refer to *physical* registers)
		 */
		fpp = &fx->fx_st[(i - top + 8) & 7].fpr_16[0];
		ibit = fpp[3] >> 15;
		expo = fpp[4] & 0x7fff;

		if (ibit && expo != 0 && expo != 0x7fff)
			continue;			/* valid fp number */

		if (bcmp(fpp, &zero, sizeof (zero)))
			fn->f_ftw |= 2 << (i << 1);	/* NaN */
		else
			fn->f_ftw |= 1 << (i << 1);	/* fp zero */
	}

	fn->f_fop = fx->fx_fop;

	fn->__f_ign2 = 0;
#if defined(__amd64)
	fn->f_eip = (uint32_t)fx->fx_rip;
	fn->f_cs = U32CS_SEL;
	fn->f_dp = (uint32_t)fx->fx_rdp;
	fn->f_ds = UDS_SEL;
#else
	fn->f_eip = fx->fx_eip;
	fn->f_cs = fx->fx_cs;
	fn->f_dp = fx->fx_dp;
	fn->f_ds = fx->fx_ds;
#endif
	fn->__f_ign3 = 0;
}

/*
 * Map from an fpregset_t into an fxsave-format save area
 */
static void
fpregset_to_fxsave(const fpregset_t *fp, struct fxsave_state *fx)
{
#if defined(__amd64)
	bcopy(fp, fx, sizeof (*fx));
#else
	const struct fpchip_state *fc = &fp->fp_reg_set.fpchip_state;

	fnsave_to_fxsave((const struct fnsave_state *)fc, fx);
	fx->fx_mxcsr = fc->mxcsr;
	bcopy(&fc->xmm[0], &fx->fx_xmm[0], sizeof (fc->xmm));
#endif
	/*
	 * avoid useless #gp exceptions - mask reserved bits
	 */
	fx->fx_mxcsr &= sse_mxcsr_mask;
}

/*
 * Map from an fxsave-format save area into a fpregset_t
 */
static void
fxsave_to_fpregset(const struct fxsave_state *fx, fpregset_t *fp)
{
#if defined(__amd64)
	bcopy(fx, fp, sizeof (*fx));
#else
	struct fpchip_state *fc = &fp->fp_reg_set.fpchip_state;

	fxsave_to_fnsave(fx, (struct fnsave_state *)fc);
	fc->mxcsr = fx->fx_mxcsr;
	bcopy(&fx->fx_xmm[0], &fc->xmm[0], sizeof (fc->xmm));
#endif
}

#if defined(_SYSCALL32_IMPL)
static void
fpregset32_to_fxsave(const fpregset32_t *fp, struct fxsave_state *fx)
{
	const struct fpchip32_state *fc = &fp->fp_reg_set.fpchip_state;

	fnsave_to_fxsave((const struct fnsave_state *)fc, fx);
	/*
	 * avoid useless #gp exceptions - mask reserved bits
	 */
	fx->fx_mxcsr = sse_mxcsr_mask & fc->mxcsr;
	bcopy(&fc->xmm[0], &fx->fx_xmm[0], sizeof (fc->xmm));
}

static void
fxsave_to_fpregset32(const struct fxsave_state *fx, fpregset32_t *fp)
{
	struct fpchip32_state *fc = &fp->fp_reg_set.fpchip_state;

	fxsave_to_fnsave(fx, (struct fnsave_state *)fc);
	fc->mxcsr = fx->fx_mxcsr;
	bcopy(&fx->fx_xmm[0], &fc->xmm[0], sizeof (fc->xmm));
}

static void
fpregset_nto32(const fpregset_t *src, fpregset32_t *dst)
{
	fxsave_to_fpregset32((struct fxsave_state *)src, dst);
	dst->fp_reg_set.fpchip_state.status =
	    src->fp_reg_set.fpchip_state.status;
	dst->fp_reg_set.fpchip_state.xstatus =
	    src->fp_reg_set.fpchip_state.xstatus;
}

static void
fpregset_32ton(const fpregset32_t *src, fpregset_t *dst)
{
	fpregset32_to_fxsave(src, (struct fxsave_state *)dst);
	dst->fp_reg_set.fpchip_state.status =
	    src->fp_reg_set.fpchip_state.status;
	dst->fp_reg_set.fpchip_state.xstatus =
	    src->fp_reg_set.fpchip_state.xstatus;
}
#endif

/*
 * Set floating-point registers from a native fpregset_t.
 */
void
setfpregs(klwp_t *lwp, fpregset_t *fp)
{
	struct fpu_ctx *fpu = &lwp->lwp_pcb.pcb_fpu;

	if (fpu->fpu_flags & FPU_EN) {
		if (!(fpu->fpu_flags & FPU_VALID)) {
			/*
			 * FPU context is still active, release the
			 * ownership.
			 */
			fp_free(fpu, 0);
		}
#if !defined(__amd64)
		if (fp_kind == __FP_SSE) {
#endif
			fpregset_to_fxsave(fp, &fpu->fpu_regs.kfpu_u.kfpu_fx);
			fpu->fpu_regs.kfpu_xstatus =
			    fp->fp_reg_set.fpchip_state.xstatus;
#if !defined(__amd64)
		} else
			bcopy(fp, &fpu->fpu_regs.kfpu_u.kfpu_fn,
			    sizeof (fpu->fpu_regs.kfpu_u.kfpu_fn));
#endif
		fpu->fpu_regs.kfpu_status = fp->fp_reg_set.fpchip_state.status;
		fpu->fpu_flags |= FPU_VALID;
	} else {
		/*
		 * If we are trying to change the FPU state of a thread which
		 * hasn't yet initialized floating point, store the state in
		 * the pcb and indicate that the state is valid.  When the
		 * thread enables floating point, it will use this state instead
		 * of the default state.
		 */
#if !defined(__amd64)
		if (fp_kind == __FP_SSE) {
#endif
			fpregset_to_fxsave(fp, &fpu->fpu_regs.kfpu_u.kfpu_fx);
			fpu->fpu_regs.kfpu_xstatus =
			    fp->fp_reg_set.fpchip_state.xstatus;
#if !defined(__amd64)
		} else
			bcopy(fp, &fpu->fpu_regs.kfpu_u.kfpu_fn,
			    sizeof (fpu->fpu_regs.kfpu_u.kfpu_fn));
#endif
		fpu->fpu_regs.kfpu_status = fp->fp_reg_set.fpchip_state.status;
		fpu->fpu_flags |= FPU_VALID;
	}
}

/*
 * Get floating-point registers into a native fpregset_t.
 */
void
getfpregs(klwp_t *lwp, fpregset_t *fp)
{
	struct fpu_ctx *fpu = &lwp->lwp_pcb.pcb_fpu;

	kpreempt_disable();
	if (fpu->fpu_flags & FPU_EN) {
		/*
		 * If we have FPU hw and the thread's pcb doesn't have
		 * a valid FPU state then get the state from the hw.
		 */
		if (fpu_exists && ttolwp(curthread) == lwp &&
		    !(fpu->fpu_flags & FPU_VALID))
			fp_save(fpu); /* get the current FPU state */
	}

	/*
	 * There are 3 possible cases we have to be aware of here:
	 *
	 * 1. FPU is enabled.  FPU state is stored in the current LWP.
	 *
	 * 2. FPU is not enabled, and there have been no intervening /proc
	 *    modifications.  Return initial FPU state.
	 *
	 * 3. FPU is not enabled, but a /proc consumer has modified FPU state.
	 *    FPU state is stored in the current LWP.
	 */
	if ((fpu->fpu_flags & FPU_EN) || (fpu->fpu_flags & FPU_VALID)) {
		/*
		 * Cases 1 and 3.
		 */
#if !defined(__amd64)
		if (fp_kind == __FP_SSE) {
#endif
			fxsave_to_fpregset(&fpu->fpu_regs.kfpu_u.kfpu_fx, fp);
			fp->fp_reg_set.fpchip_state.xstatus =
			    fpu->fpu_regs.kfpu_xstatus;
#if !defined(__amd64)
		} else
			bcopy(&fpu->fpu_regs.kfpu_u.kfpu_fn, fp,
			    sizeof (fpu->fpu_regs.kfpu_u.kfpu_fn));
#endif
		fp->fp_reg_set.fpchip_state.status = fpu->fpu_regs.kfpu_status;
	} else {
		/*
		 * Case 2.
		 */
#if !defined(__amd64)
		if (fp_kind == __FP_SSE) {
#endif
			fxsave_to_fpregset(&sse_initial, fp);
			fp->fp_reg_set.fpchip_state.xstatus =
			    fpu->fpu_regs.kfpu_xstatus;
#if !defined(__amd64)
		} else
			bcopy(&x87_initial, fp, sizeof (x87_initial));
#endif
		fp->fp_reg_set.fpchip_state.status = fpu->fpu_regs.kfpu_status;
	}
	kpreempt_enable();
}

#if defined(_SYSCALL32_IMPL)

/*
 * Set floating-point registers from an fpregset32_t.
 */
void
setfpregs32(klwp_t *lwp, fpregset32_t *fp)
{
	fpregset_t fpregs;

	fpregset_32ton(fp, &fpregs);
	setfpregs(lwp, &fpregs);
}

/*
 * Get floating-point registers into an fpregset32_t.
 */
void
getfpregs32(klwp_t *lwp, fpregset32_t *fp)
{
	fpregset_t fpregs;

	getfpregs(lwp, &fpregs);
	fpregset_nto32(&fpregs, fp);
}

#endif	/* _SYSCALL32_IMPL */

/*
 * Return the general registers
 */
void
getgregs(klwp_t *lwp, gregset_t grp)
{
	struct regs *rp = lwptoregs(lwp);
#if defined(__amd64)
	struct pcb *pcb = &lwp->lwp_pcb;
	int thisthread = lwptot(lwp) == curthread;

	grp[REG_RDI] = rp->r_rdi;
	grp[REG_RSI] = rp->r_rsi;
	grp[REG_RDX] = rp->r_rdx;
	grp[REG_RCX] = rp->r_rcx;
	grp[REG_R8] = rp->r_r8;
	grp[REG_R9] = rp->r_r9;
	grp[REG_RAX] = rp->r_rax;
	grp[REG_RBX] = rp->r_rbx;
	grp[REG_RBP] = rp->r_rbp;
	grp[REG_R10] = rp->r_r10;
	grp[REG_R11] = rp->r_r11;
	grp[REG_R12] = rp->r_r12;
	grp[REG_R13] = rp->r_r13;
	grp[REG_R14] = rp->r_r14;
	grp[REG_R15] = rp->r_r15;
	grp[REG_FSBASE] = pcb->pcb_fsbase;
	grp[REG_GSBASE] = pcb->pcb_gsbase;
	if (thisthread)
		kpreempt_disable();
	if (pcb->pcb_rupdate == 1) {
		grp[REG_DS] = pcb->pcb_ds;
		grp[REG_ES] = pcb->pcb_es;
		grp[REG_FS] = pcb->pcb_fs;
		grp[REG_GS] = pcb->pcb_gs;
	} else {
		grp[REG_DS] = rp->r_ds;
		grp[REG_ES] = rp->r_es;
		grp[REG_FS] = rp->r_fs;
		grp[REG_GS] = rp->r_gs;
	}
	if (thisthread)
		kpreempt_enable();
	grp[REG_TRAPNO] = rp->r_trapno;
	grp[REG_ERR] = rp->r_err;
	grp[REG_RIP] = rp->r_rip;
	grp[REG_CS] = rp->r_cs;
	grp[REG_SS] = rp->r_ss;
	grp[REG_RFL] = rp->r_rfl;
	grp[REG_RSP] = rp->r_rsp;
#else
	bcopy(&rp->r_gs, grp, sizeof (gregset_t));
#endif
}

#if defined(_SYSCALL32_IMPL)

void
getgregs32(klwp_t *lwp, gregset32_t grp)
{
	struct regs *rp = lwptoregs(lwp);
	struct pcb *pcb = &lwp->lwp_pcb;
	int thisthread = lwptot(lwp) == curthread;

	if (thisthread)
		kpreempt_disable();
	if (pcb->pcb_rupdate == 1) {
		grp[GS] = (uint16_t)pcb->pcb_gs;
		grp[FS] = (uint16_t)pcb->pcb_fs;
		grp[DS] = (uint16_t)pcb->pcb_ds;
		grp[ES] = (uint16_t)pcb->pcb_es;
	} else {
		grp[GS] = (uint16_t)rp->r_gs;
		grp[FS] = (uint16_t)rp->r_fs;
		grp[DS] = (uint16_t)rp->r_ds;
		grp[ES] = (uint16_t)rp->r_es;
	}
	if (thisthread)
		kpreempt_enable();
	grp[EDI] = (greg32_t)rp->r_rdi;
	grp[ESI] = (greg32_t)rp->r_rsi;
	grp[EBP] = (greg32_t)rp->r_rbp;
	grp[ESP] = 0;
	grp[EBX] = (greg32_t)rp->r_rbx;
	grp[EDX] = (greg32_t)rp->r_rdx;
	grp[ECX] = (greg32_t)rp->r_rcx;
	grp[EAX] = (greg32_t)rp->r_rax;
	grp[TRAPNO] = (greg32_t)rp->r_trapno;
	grp[ERR] = (greg32_t)rp->r_err;
	grp[EIP] = (greg32_t)rp->r_rip;
	grp[CS] = (uint16_t)rp->r_cs;
	grp[EFL] = (greg32_t)rp->r_rfl;
	grp[UESP] = (greg32_t)rp->r_rsp;
	grp[SS] = (uint16_t)rp->r_ss;
}

void
ucontext_32ton(const ucontext32_t *src, ucontext_t *dst)
{
	mcontext_t *dmc = &dst->uc_mcontext;
	const mcontext32_t *smc = &src->uc_mcontext;

	bzero(dst, sizeof (*dst));
	dst->uc_flags = src->uc_flags;
	dst->uc_link = (ucontext_t *)(uintptr_t)src->uc_link;

	bcopy(&src->uc_sigmask, &dst->uc_sigmask, sizeof (dst->uc_sigmask));

	dst->uc_stack.ss_sp = (void *)(uintptr_t)src->uc_stack.ss_sp;
	dst->uc_stack.ss_size = (size_t)src->uc_stack.ss_size;
	dst->uc_stack.ss_flags = src->uc_stack.ss_flags;

	dmc->gregs[REG_GS] = (greg_t)(uint32_t)smc->gregs[GS];
	dmc->gregs[REG_FS] = (greg_t)(uint32_t)smc->gregs[FS];
	dmc->gregs[REG_ES] = (greg_t)(uint32_t)smc->gregs[ES];
	dmc->gregs[REG_DS] = (greg_t)(uint32_t)smc->gregs[DS];
	dmc->gregs[REG_RDI] = (greg_t)(uint32_t)smc->gregs[EDI];
	dmc->gregs[REG_RSI] = (greg_t)(uint32_t)smc->gregs[ESI];
	dmc->gregs[REG_RBP] = (greg_t)(uint32_t)smc->gregs[EBP];
	dmc->gregs[REG_RBX] = (greg_t)(uint32_t)smc->gregs[EBX];
	dmc->gregs[REG_RDX] = (greg_t)(uint32_t)smc->gregs[EDX];
	dmc->gregs[REG_RCX] = (greg_t)(uint32_t)smc->gregs[ECX];
	dmc->gregs[REG_RAX] = (greg_t)(uint32_t)smc->gregs[EAX];
	dmc->gregs[REG_TRAPNO] = (greg_t)(uint32_t)smc->gregs[TRAPNO];
	dmc->gregs[REG_ERR] = (greg_t)(uint32_t)smc->gregs[ERR];
	dmc->gregs[REG_RIP] = (greg_t)(uint32_t)smc->gregs[EIP];
	dmc->gregs[REG_CS] = (greg_t)(uint32_t)smc->gregs[CS];
	dmc->gregs[REG_RFL] = (greg_t)(uint32_t)smc->gregs[EFL];
	dmc->gregs[REG_RSP] = (greg_t)(uint32_t)smc->gregs[UESP];
	dmc->gregs[REG_SS] = (greg_t)(uint32_t)smc->gregs[SS];

	/*
	 * A valid fpregs is only copied in if uc.uc_flags has UC_FPU set
	 * otherwise there is no guarantee that anything in fpregs is valid.
	 */
	if (src->uc_flags & UC_FPU)
		fpregset_32ton(&src->uc_mcontext.fpregs,
		    &dst->uc_mcontext.fpregs);
}

#endif	/* _SYSCALL32_IMPL */

/*
 * Return the user-level PC.
 * If in a system call, return the address of the syscall trap.
 */
greg_t
getuserpc()
{
	greg_t upc = lwptoregs(ttolwp(curthread))->r_pc;
	uint32_t insn;

	if (curthread->t_sysnum == 0)
		return (upc);

	/*
	 * We might've gotten here from sysenter (0xf 0x34),
	 * syscall (0xf 0x5) or lcall (0x9a 0 0 0 0 0x27 0).
	 *
	 * Go peek at the binary to figure it out..
	 */
	if (fuword32((void *)(upc - 2), &insn) != -1 &&
	    (insn & 0xffff) == 0x340f || (insn & 0xffff) == 0x050f)
		return (upc - 2);
	return (upc - 7);
}

/*
 * Protect segment registers from non-user privilege levels and GDT selectors
 * other than USER_CS, USER_DS and lwp FS and GS values.  If the segment
 * selector is non-null and not USER_CS/USER_DS, we make sure that the
 * TI bit is set to point into the LDT and that the RPL is set to 3.
 *
 * Since struct regs stores each 16-bit segment register as a 32-bit greg_t, we
 * also explicitly zero the top 16 bits since they may be coming from the
 * user's address space via setcontext(2) or /proc.
 *
 * Note about null selector. When running on the hypervisor if we allow a
 * process to set its %cs to null selector with RPL of 0 the hypervisor will
 * crash the domain. If running on bare metal we would get a #gp fault and
 * be able to kill the process and continue on. Therefore we make sure to
 * force RPL to SEL_UPL even for null selector when setting %cs.
 */

#if defined(IS_CS) || defined(IS_NOT_CS)
#error	"IS_CS and IS_NOT_CS already defined"
#endif

#define	IS_CS		1
#define	IS_NOT_CS	0

/*ARGSUSED*/
static greg_t
fix_segreg(greg_t sr, int iscs, model_t datamodel)
{
	kthread_t *t = curthread;

	switch (sr &= 0xffff) {

	case 0:
		if (iscs == IS_CS)
			return (0 | SEL_UPL);
		else
			return (0);

#if defined(__amd64)
	/*
	 * If lwp attempts to switch data model then force their
	 * code selector to be null selector.
	 */
	case U32CS_SEL:
		if (datamodel == DATAMODEL_NATIVE)
			return (0 | SEL_UPL);
		else
			return (sr);

	case UCS_SEL:
		if (datamodel == DATAMODEL_ILP32)
			return (0 | SEL_UPL);
#elif defined(__i386)
	case UCS_SEL:
#endif
	/*FALLTHROUGH*/
	case UDS_SEL:
	case LWPFS_SEL:
	case LWPGS_SEL:
	case SEL_UPL:
		return (sr);
	default:
		break;
	}

	/*
	 * Allow this process's brand to do any necessary segment register
	 * manipulation.
	 */
	if (PROC_IS_BRANDED(t->t_procp) && BRMOP(t->t_procp)->b_fixsegreg) {
		greg_t bsr = BRMOP(t->t_procp)->b_fixsegreg(sr, datamodel);

		if (bsr == 0 && iscs == IS_CS)
			return (0 | SEL_UPL);
		else
			return (bsr);
	}

	/*
	 * Force it into the LDT in ring 3 for 32-bit processes, which by
	 * default do not have an LDT, so that any attempt to use an invalid
	 * selector will reference the (non-existant) LDT, and cause a #gp
	 * fault for the process.
	 *
	 * 64-bit processes get the null gdt selector since they
	 * are not allowed to have a private LDT.
	 */
#if defined(__amd64)
	if (datamodel == DATAMODEL_ILP32) {
		return (sr | SEL_TI_LDT | SEL_UPL);
	} else {
		if (iscs == IS_CS)
			return (0 | SEL_UPL);
		else
			return (0);
	}

#elif defined(__i386)
	return (sr | SEL_TI_LDT | SEL_UPL);
#endif
}

/*
 * Set general registers.
 */
void
setgregs(klwp_t *lwp, gregset_t grp)
{
	struct regs *rp = lwptoregs(lwp);
	model_t	datamodel = lwp_getdatamodel(lwp);

#if defined(__amd64)
	struct pcb *pcb = &lwp->lwp_pcb;
	int thisthread = lwptot(lwp) == curthread;

	if (datamodel == DATAMODEL_NATIVE) {

		if (thisthread)
			(void) save_syscall_args();	/* copy the args */

		rp->r_rdi = grp[REG_RDI];
		rp->r_rsi = grp[REG_RSI];
		rp->r_rdx = grp[REG_RDX];
		rp->r_rcx = grp[REG_RCX];
		rp->r_r8 = grp[REG_R8];
		rp->r_r9 = grp[REG_R9];
		rp->r_rax = grp[REG_RAX];
		rp->r_rbx = grp[REG_RBX];
		rp->r_rbp = grp[REG_RBP];
		rp->r_r10 = grp[REG_R10];
		rp->r_r11 = grp[REG_R11];
		rp->r_r12 = grp[REG_R12];
		rp->r_r13 = grp[REG_R13];
		rp->r_r14 = grp[REG_R14];
		rp->r_r15 = grp[REG_R15];
		rp->r_trapno = grp[REG_TRAPNO];
		rp->r_err = grp[REG_ERR];
		rp->r_rip = grp[REG_RIP];
		/*
		 * Setting %cs or %ss to anything else is quietly but
		 * quite definitely forbidden!
		 */
		rp->r_cs = UCS_SEL;
		rp->r_ss = UDS_SEL;
		rp->r_rsp = grp[REG_RSP];

		if (thisthread)
			kpreempt_disable();

		pcb->pcb_ds = UDS_SEL;
		pcb->pcb_es = UDS_SEL;

		/*
		 * 64-bit processes -are- allowed to set their fsbase/gsbase
		 * values directly, but only if they're using the segment
		 * selectors that allow that semantic.
		 *
		 * (32-bit processes must use lwp_set_private().)
		 */
		pcb->pcb_fsbase = grp[REG_FSBASE];
		pcb->pcb_gsbase = grp[REG_GSBASE];
		pcb->pcb_fs = fix_segreg(grp[REG_FS], IS_NOT_CS, datamodel);
		pcb->pcb_gs = fix_segreg(grp[REG_GS], IS_NOT_CS, datamodel);

		/*
		 * Ensure that we go out via update_sregs
		 */
		pcb->pcb_rupdate = 1;
		lwptot(lwp)->t_post_sys = 1;
		if (thisthread)
			kpreempt_enable();
#if defined(_SYSCALL32_IMPL)
	} else {
		rp->r_rdi = (uint32_t)grp[REG_RDI];
		rp->r_rsi = (uint32_t)grp[REG_RSI];
		rp->r_rdx = (uint32_t)grp[REG_RDX];
		rp->r_rcx = (uint32_t)grp[REG_RCX];
		rp->r_rax = (uint32_t)grp[REG_RAX];
		rp->r_rbx = (uint32_t)grp[REG_RBX];
		rp->r_rbp = (uint32_t)grp[REG_RBP];
		rp->r_trapno = (uint32_t)grp[REG_TRAPNO];
		rp->r_err = (uint32_t)grp[REG_ERR];
		rp->r_rip = (uint32_t)grp[REG_RIP];

		rp->r_cs = fix_segreg(grp[REG_CS], IS_CS, datamodel);
		rp->r_ss = fix_segreg(grp[REG_DS], IS_NOT_CS, datamodel);

		rp->r_rsp = (uint32_t)grp[REG_RSP];

		if (thisthread)
			kpreempt_disable();

		pcb->pcb_ds = fix_segreg(grp[REG_DS], IS_NOT_CS, datamodel);
		pcb->pcb_es = fix_segreg(grp[REG_ES], IS_NOT_CS, datamodel);

		/*
		 * (See fsbase/gsbase commentary above)
		 */
		pcb->pcb_fs = fix_segreg(grp[REG_FS], IS_NOT_CS, datamodel);
		pcb->pcb_gs = fix_segreg(grp[REG_GS], IS_NOT_CS, datamodel);

		/*
		 * Ensure that we go out via update_sregs
		 */
		pcb->pcb_rupdate = 1;
		lwptot(lwp)->t_post_sys = 1;
		if (thisthread)
			kpreempt_enable();
#endif
	}

	/*
	 * Only certain bits of the flags register can be modified.
	 */
	rp->r_rfl = (rp->r_rfl & ~PSL_USERMASK) |
	    (grp[REG_RFL] & PSL_USERMASK);

#elif defined(__i386)

	/*
	 * Only certain bits of the flags register can be modified.
	 */
	grp[EFL] = (rp->r_efl & ~PSL_USERMASK) | (grp[EFL] & PSL_USERMASK);

	/*
	 * Copy saved registers from user stack.
	 */
	bcopy(grp, &rp->r_gs, sizeof (gregset_t));

	rp->r_cs = fix_segreg(rp->r_cs, IS_CS, datamodel);
	rp->r_ss = fix_segreg(rp->r_ss, IS_NOT_CS, datamodel);
	rp->r_ds = fix_segreg(rp->r_ds, IS_NOT_CS, datamodel);
	rp->r_es = fix_segreg(rp->r_es, IS_NOT_CS, datamodel);
	rp->r_fs = fix_segreg(rp->r_fs, IS_NOT_CS, datamodel);
	rp->r_gs = fix_segreg(rp->r_gs, IS_NOT_CS, datamodel);

#endif	/* __i386 */
}

/*
 * Determine whether eip is likely to have an interrupt frame
 * on the stack.  We do this by comparing the address to the
 * range of addresses spanned by several well-known routines.
 */
extern void _interrupt();
extern void _allsyscalls();
extern void _cmntrap();
extern void fakesoftint();

extern size_t _interrupt_size;
extern size_t _allsyscalls_size;
extern size_t _cmntrap_size;
extern size_t _fakesoftint_size;

/*
 * Get a pc-only stacktrace.  Used for kmem_alloc() buffer ownership tracking.
 * Returns MIN(current stack depth, pcstack_limit).
 */
int
getpcstack(pc_t *pcstack, int pcstack_limit)
{
	struct frame *fp = (struct frame *)getfp();
	struct frame *nextfp, *minfp, *stacktop;
	int depth = 0;
	int on_intr;
	uintptr_t pc;

	if ((on_intr = CPU_ON_INTR(CPU)) != 0)
		stacktop = (struct frame *)(CPU->cpu_intr_stack + SA(MINFRAME));
	else
		stacktop = (struct frame *)curthread->t_stk;
	minfp = fp;

	pc = ((struct regs *)fp)->r_pc;

	while (depth < pcstack_limit) {
		nextfp = (struct frame *)fp->fr_savfp;
		pc = fp->fr_savpc;
		if (nextfp <= minfp || nextfp >= stacktop) {
			if (on_intr) {
				/*
				 * Hop from interrupt stack to thread stack.
				 */
				stacktop = (struct frame *)curthread->t_stk;
				minfp = (struct frame *)curthread->t_stkbase;
				on_intr = 0;
				continue;
			}
			break;
		}
		pcstack[depth++] = (pc_t)pc;
		fp = nextfp;
		minfp = fp;
	}
	return (depth);
}

/*
 * The following ELF header fields are defined as processor-specific
 * in the V8 ABI:
 *
 *	e_ident[EI_DATA]	encoding of the processor-specific
 *				data in the object file
 *	e_machine		processor identification
 *	e_flags			processor-specific flags associated
 *				with the file
 */

/*
 * The value of at_flags reflects a platform's cpu module support.
 * at_flags is used to check for allowing a binary to execute and
 * is passed as the value of the AT_FLAGS auxiliary vector.
 */
int at_flags = 0;

/*
 * Check the processor-specific fields of an ELF header.
 *
 * returns 1 if the fields are valid, 0 otherwise
 */
/*ARGSUSED2*/
int
elfheadcheck(
	unsigned char e_data,
	Elf32_Half e_machine,
	Elf32_Word e_flags)
{
	if (e_data != ELFDATA2LSB)
		return (0);
#if defined(__amd64)
	if (e_machine == EM_AMD64)
		return (1);
#endif
	return (e_machine == EM_386);
}

uint_t auxv_hwcap_include = 0;	/* patch to enable unrecognized features */
uint_t auxv_hwcap_exclude = 0;	/* patch for broken cpus, debugging */
#if defined(_SYSCALL32_IMPL)
uint_t auxv_hwcap32_include = 0;	/* ditto for 32-bit apps */
uint_t auxv_hwcap32_exclude = 0;	/* ditto for 32-bit apps */
#endif

/*
 * Gather information about the processor and place it into auxv_hwcap
 * so that it can be exported to the linker via the aux vector.
 *
 * We use this seemingly complicated mechanism so that we can ensure
 * that /etc/system can be used to override what the system can or
 * cannot discover for itself.
 */
void
bind_hwcap(void)
{
	uint_t cpu_hwcap_flags = cpuid_pass4(NULL);

	auxv_hwcap = (auxv_hwcap_include | cpu_hwcap_flags) &
	    ~auxv_hwcap_exclude;

#if defined(__amd64)
	/*
	 * On AMD processors, sysenter just doesn't work at all
	 * when the kernel is in long mode.  On IA-32e processors
	 * it does, but there's no real point in all the alternate
	 * mechanism when syscall works on both.
	 *
	 * Besides, the kernel's sysenter handler is expecting a
	 * 32-bit lwp ...
	 */
	auxv_hwcap &= ~AV_386_SEP;
#else
	/*
	 * 32-bit processes can -always- use the lahf/sahf instructions
	 */
	auxv_hwcap |= AV_386_AHF;
#endif

	if (auxv_hwcap_include || auxv_hwcap_exclude)
		cmn_err(CE_CONT, "?user ABI extensions: %b\n",
		    auxv_hwcap, FMT_AV_386);

#if defined(_SYSCALL32_IMPL)
	auxv_hwcap32 = (auxv_hwcap32_include | cpu_hwcap_flags) &
	    ~auxv_hwcap32_exclude;

#if defined(__amd64)
	/*
	 * If this is an amd64 architecture machine from Intel, then
	 * syscall -doesn't- work in compatibility mode, only sysenter does.
	 *
	 * Sigh.
	 */
	if (!cpuid_syscall32_insn(NULL))
		auxv_hwcap32 &= ~AV_386_AMD_SYSC;

	/*
	 * 32-bit processes can -always- use the lahf/sahf instructions
	 */
	auxv_hwcap32 |= AV_386_AHF;
#endif

	if (auxv_hwcap32_include || auxv_hwcap32_exclude)
		cmn_err(CE_CONT, "?32-bit user ABI extensions: %b\n",
		    auxv_hwcap32, FMT_AV_386);
#endif
}

/*
 *	sync_icache() - this is called
 *	in proc/fs/prusrio.c. x86 has an unified cache and therefore
 *	this is a nop.
 */
/* ARGSUSED */
void
sync_icache(caddr_t addr, uint_t len)
{
	/* Do nothing for now */
}

/*ARGSUSED*/
void
sync_data_memory(caddr_t va, size_t len)
{
	/* Not implemented for this platform */
}

int
__ipltospl(int ipl)
{
	return (ipltospl(ipl));
}

/*
 * The panic code invokes panic_saveregs() to record the contents of a
 * regs structure into the specified panic_data structure for debuggers.
 */
void
panic_saveregs(panic_data_t *pdp, struct regs *rp)
{
	panic_nv_t *pnv = PANICNVGET(pdp);

	struct cregs	creg;

	getcregs(&creg);

#if defined(__amd64)
	PANICNVADD(pnv, "rdi", rp->r_rdi);
	PANICNVADD(pnv, "rsi", rp->r_rsi);
	PANICNVADD(pnv, "rdx", rp->r_rdx);
	PANICNVADD(pnv, "rcx", rp->r_rcx);
	PANICNVADD(pnv, "r8", rp->r_r8);
	PANICNVADD(pnv, "r9", rp->r_r9);
	PANICNVADD(pnv, "rax", rp->r_rax);
	PANICNVADD(pnv, "rbx", rp->r_rbx);
	PANICNVADD(pnv, "rbp", rp->r_rbp);
	PANICNVADD(pnv, "r10", rp->r_r10);
	PANICNVADD(pnv, "r10", rp->r_r10);
	PANICNVADD(pnv, "r11", rp->r_r11);
	PANICNVADD(pnv, "r12", rp->r_r12);
	PANICNVADD(pnv, "r13", rp->r_r13);
	PANICNVADD(pnv, "r14", rp->r_r14);
	PANICNVADD(pnv, "r15", rp->r_r15);
	PANICNVADD(pnv, "fsbase", rdmsr(MSR_AMD_FSBASE));
	PANICNVADD(pnv, "gsbase", rdmsr(MSR_AMD_GSBASE));
	PANICNVADD(pnv, "ds", rp->r_ds);
	PANICNVADD(pnv, "es", rp->r_es);
	PANICNVADD(pnv, "fs", rp->r_fs);
	PANICNVADD(pnv, "gs", rp->r_gs);
	PANICNVADD(pnv, "trapno", rp->r_trapno);
	PANICNVADD(pnv, "err", rp->r_err);
	PANICNVADD(pnv, "rip", rp->r_rip);
	PANICNVADD(pnv, "cs", rp->r_cs);
	PANICNVADD(pnv, "rflags", rp->r_rfl);
	PANICNVADD(pnv, "rsp", rp->r_rsp);
	PANICNVADD(pnv, "ss", rp->r_ss);
	PANICNVADD(pnv, "gdt_hi", (uint64_t)(creg.cr_gdt._l[3]));
	PANICNVADD(pnv, "gdt_lo", (uint64_t)(creg.cr_gdt._l[0]));
	PANICNVADD(pnv, "idt_hi", (uint64_t)(creg.cr_idt._l[3]));
	PANICNVADD(pnv, "idt_lo", (uint64_t)(creg.cr_idt._l[0]));
#elif defined(__i386)
	PANICNVADD(pnv, "gs", (uint32_t)rp->r_gs);
	PANICNVADD(pnv, "fs", (uint32_t)rp->r_fs);
	PANICNVADD(pnv, "es", (uint32_t)rp->r_es);
	PANICNVADD(pnv, "ds", (uint32_t)rp->r_ds);
	PANICNVADD(pnv, "edi", (uint32_t)rp->r_edi);
	PANICNVADD(pnv, "esi", (uint32_t)rp->r_esi);
	PANICNVADD(pnv, "ebp", (uint32_t)rp->r_ebp);
	PANICNVADD(pnv, "esp", (uint32_t)rp->r_esp);
	PANICNVADD(pnv, "ebx", (uint32_t)rp->r_ebx);
	PANICNVADD(pnv, "edx", (uint32_t)rp->r_edx);
	PANICNVADD(pnv, "ecx", (uint32_t)rp->r_ecx);
	PANICNVADD(pnv, "eax", (uint32_t)rp->r_eax);
	PANICNVADD(pnv, "trapno", (uint32_t)rp->r_trapno);
	PANICNVADD(pnv, "err", (uint32_t)rp->r_err);
	PANICNVADD(pnv, "eip", (uint32_t)rp->r_eip);
	PANICNVADD(pnv, "cs", (uint32_t)rp->r_cs);
	PANICNVADD(pnv, "eflags", (uint32_t)rp->r_efl);
	PANICNVADD(pnv, "uesp", (uint32_t)rp->r_uesp);
	PANICNVADD(pnv, "ss", (uint32_t)rp->r_ss);
	PANICNVADD(pnv, "gdt", creg.cr_gdt);
	PANICNVADD(pnv, "idt", creg.cr_idt);
#endif	/* __i386 */

	PANICNVADD(pnv, "ldt", creg.cr_ldt);
	PANICNVADD(pnv, "task", creg.cr_task);
	PANICNVADD(pnv, "cr0", creg.cr_cr0);
	PANICNVADD(pnv, "cr2", creg.cr_cr2);
	PANICNVADD(pnv, "cr3", creg.cr_cr3);
	if (creg.cr_cr4)
		PANICNVADD(pnv, "cr4", creg.cr_cr4);

	PANICNVSET(pdp, pnv);
}

#define	TR_ARG_MAX 6	/* Max args to print, same as SPARC */

#if !defined(__amd64)

/*
 * Given a return address (%eip), determine the likely number of arguments
 * that were pushed on the stack prior to its execution.  We do this by
 * expecting that a typical call sequence consists of pushing arguments on
 * the stack, executing a call instruction, and then performing an add
 * on %esp to restore it to the value prior to pushing the arguments for
 * the call.  We attempt to detect such an add, and divide the addend
 * by the size of a word to determine the number of pushed arguments.
 *
 * If we do not find such an add, we punt and return TR_ARG_MAX. It is not
 * possible to reliably determine if a function took no arguments (i.e. was
 * void) because assembler routines do not reliably perform an add on %esp
 * immediately upon returning (eg. _sys_call()), so returning TR_ARG_MAX is
 * safer than returning 0.
 */
static ulong_t
argcount(uintptr_t eip)
{
	const uint8_t *ins = (const uint8_t *)eip;
	ulong_t n;

	enum {
		M_MODRM_ESP = 0xc4,	/* Mod/RM byte indicates %esp */
		M_ADD_IMM32 = 0x81,	/* ADD imm32 to r/m32 */
		M_ADD_IMM8  = 0x83	/* ADD imm8 to r/m32 */
	};

	if (eip < KERNELBASE || ins[1] != M_MODRM_ESP)
		return (TR_ARG_MAX);

	switch (ins[0]) {
	case M_ADD_IMM32:
		n = ins[2] + (ins[3] << 8) + (ins[4] << 16) + (ins[5] << 24);
		break;

	case M_ADD_IMM8:
		n = ins[2];
		break;

	default:
		return (TR_ARG_MAX);
	}

	n /= sizeof (long);
	return (MIN(n, TR_ARG_MAX));
}

#endif	/* !__amd64 */

/*
 * Print a stack backtrace using the specified frame pointer.  We delay two
 * seconds before continuing, unless this is the panic traceback.  Note
 * that the frame for the starting stack pointer value is omitted because
 * the corresponding %eip is not known.
 */
#if defined(__amd64)

void
traceback(caddr_t fpreg)
{
	struct frame	*fp = (struct frame *)fpreg;
	struct frame	*nextfp;
	uintptr_t	pc, nextpc;
	ulong_t		off;
	char		args[TR_ARG_MAX * 2 + 16], *sym;

	if (!panicstr)
		printf("traceback: %%fp = %p\n", (void *)fp);

	fp = (struct frame *)plat_traceback(fpreg);
	if ((uintptr_t)fp < KERNELBASE)
		goto out;

	pc = fp->fr_savpc;
	fp = (struct frame *)fp->fr_savfp;

	while ((uintptr_t)fp >= KERNELBASE) {
		/*
		 * XX64 Until port is complete tolerate 8-byte aligned
		 * frame pointers but flag with a warning so they can
		 * be fixed.
		 */
		if (((uintptr_t)fp & (STACK_ALIGN - 1)) != 0) {
			if (((uintptr_t)fp & (8 - 1)) == 0) {
				printf("  >> warning! 8-byte"
				    " aligned %%fp = %p\n", (void *)fp);
			} else {
				printf(
				    "  >> mis-aligned %%fp = %p\n", (void *)fp);
				break;
			}
		}

		args[0] = '\0';
		nextpc = (uintptr_t)fp->fr_savpc;
		nextfp = (struct frame *)fp->fr_savfp;
		if ((sym = kobj_getsymname(pc, &off)) != NULL) {
			printf("%016lx %s:%s+%lx (%s)\n", (uintptr_t)fp,
			    mod_containing_pc((caddr_t)pc), sym, off, args);
		} else {
			printf("%016lx %lx (%s)\n",
			    (uintptr_t)fp, pc, args);
		}

		pc = nextpc;
		fp = nextfp;
	}
out:
	if (!panicstr) {
		printf("end of traceback\n");
		DELAY(2 * MICROSEC);
	}
}

#elif defined(__i386)

void
traceback(caddr_t fpreg)
{
	struct frame *fp = (struct frame *)fpreg;
	struct frame *nextfp, *minfp, *stacktop;
	uintptr_t pc, nextpc;

	cpu_t *cpu;

	/*
	 * args[] holds TR_ARG_MAX hex long args, plus ", " or '\0'.
	 */
	char args[TR_ARG_MAX * 2 + 8], *p;

	int on_intr;
	ulong_t off;
	char *sym;

	if (!panicstr)
		printf("traceback: %%fp = %p\n", (void *)fp);

	/*
	 * If we are panicking, all high-level interrupt information in
	 * CPU was overwritten.  panic_cpu has the correct values.
	 */
	kpreempt_disable();			/* prevent migration */

	cpu = (panicstr && CPU->cpu_id == panic_cpu.cpu_id)? &panic_cpu : CPU;

	if ((on_intr = CPU_ON_INTR(cpu)) != 0)
		stacktop = (struct frame *)(cpu->cpu_intr_stack + SA(MINFRAME));
	else
		stacktop = (struct frame *)curthread->t_stk;

	kpreempt_enable();

	fp = (struct frame *)plat_traceback(fpreg);
	if ((uintptr_t)fp < KERNELBASE)
		goto out;

	minfp = fp;	/* Baseline minimum frame pointer */
	pc = fp->fr_savpc;
	fp = (struct frame *)fp->fr_savfp;

	while ((uintptr_t)fp >= KERNELBASE) {
		ulong_t argc;
		long *argv;

		if (fp <= minfp || fp >= stacktop) {
			if (on_intr) {
				/*
				 * Hop from interrupt stack to thread stack.
				 */
				stacktop = (struct frame *)curthread->t_stk;
				minfp = (struct frame *)curthread->t_stkbase;
				on_intr = 0;
				continue;
			}
			break; /* we're outside of the expected range */
		}

		if ((uintptr_t)fp & (STACK_ALIGN - 1)) {
			printf("  >> mis-aligned %%fp = %p\n", (void *)fp);
			break;
		}

		nextpc = fp->fr_savpc;
		nextfp = (struct frame *)fp->fr_savfp;
		argc = argcount(nextpc);
		argv = (long *)((char *)fp + sizeof (struct frame));

		args[0] = '\0';
		p = args;
		while (argc-- > 0 && argv < (long *)stacktop) {
			p += snprintf(p, args + sizeof (args) - p,
			    "%s%lx", (p == args) ? "" : ", ", *argv++);
		}

		if ((sym = kobj_getsymname(pc, &off)) != NULL) {
			printf("%08lx %s:%s+%lx (%s)\n", (uintptr_t)fp,
			    mod_containing_pc((caddr_t)pc), sym, off, args);
		} else {
			printf("%08lx %lx (%s)\n",
			    (uintptr_t)fp, pc, args);
		}

		minfp = fp;
		pc = nextpc;
		fp = nextfp;
	}
out:
	if (!panicstr) {
		printf("end of traceback\n");
		DELAY(2 * MICROSEC);
	}
}

#endif	/* __i386 */

/*
 * Generate a stack backtrace from a saved register set.
 */
void
traceregs(struct regs *rp)
{
	traceback((caddr_t)rp->r_fp);
}

void
exec_set_sp(size_t stksize)
{
	klwp_t *lwp = ttolwp(curthread);

	lwptoregs(lwp)->r_sp = (uintptr_t)curproc->p_usrstack - stksize;
}

hrtime_t
gethrtime_waitfree(void)
{
	return (dtrace_gethrtime());
}

hrtime_t
gethrtime(void)
{
	return (gethrtimef());
}

hrtime_t
gethrtime_unscaled(void)
{
	return (gethrtimeunscaledf());
}

void
scalehrtime(hrtime_t *hrt)
{
	scalehrtimef(hrt);
}

void
gethrestime(timespec_t *tp)
{
	gethrestimef(tp);
}

#if defined(__amd64)
/*
 * Part of the implementation of hres_tick(); this routine is
 * easier in C than assembler .. called with the hres_lock held.
 *
 * XX64	Many of these timekeeping variables need to be extern'ed in a header
 */

#include <sys/time.h>
#include <sys/machlock.h>

extern int one_sec;
extern int max_hres_adj;

void
__adj_hrestime(void)
{
	long long adj;

	if (hrestime_adj == 0)
		adj = 0;
	else if (hrestime_adj > 0) {
		if (hrestime_adj < max_hres_adj)
			adj = hrestime_adj;
		else
			adj = max_hres_adj;
	} else {
		if (hrestime_adj < -max_hres_adj)
			adj = -max_hres_adj;
		else
			adj = hrestime_adj;
	}

	timedelta -= adj;
	hrestime_adj = timedelta;
	hrestime.tv_nsec += adj;

	while (hrestime.tv_nsec >= NANOSEC) {
		one_sec++;
		hrestime.tv_sec++;
		hrestime.tv_nsec -= NANOSEC;
	}
}
#endif

/*
 * Wrapper functions to maintain backwards compability
 */
int
xcopyin(const void *uaddr, void *kaddr, size_t count)
{
	return (xcopyin_nta(uaddr, kaddr, count, UIO_COPY_CACHED));
}

int
xcopyout(const void *kaddr, void *uaddr, size_t count)
{
	return (xcopyout_nta(kaddr, uaddr, count, UIO_COPY_CACHED));
}