aboutsummaryrefslogtreecommitdiff
path: root/sys/mips/mips/trap.c
blob: 1475d7b659d1cadc948e3bd8f28b95e469df2f33 (plain) (blame)
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
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
/*	$OpenBSD: trap.c,v 1.19 1998/09/30 12:40:41 pefo Exp $	*/
/* tracked to 1.23 */
/*-
 * Copyright (c) 1988 University of Utah.
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  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 Ralph Campbell.
 *
 * 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.
 * 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: Utah Hdr: trap.c 1.32 91/04/06
 *
 *	from: @(#)trap.c	8.5 (Berkeley) 1/11/94
 *	JNPR: trap.c,v 1.13.2.2 2007/08/29 10:03:49 girish
 */
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_compat.h"
#include "opt_ddb.h"
#include "opt_ktrace.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/sysent.h>
#include <sys/proc.h>
#include <sys/kernel.h>
#include <sys/signalvar.h>
#include <sys/syscall.h>
#include <sys/lock.h>
#include <vm/vm.h>
#include <vm/vm_extern.h>
#include <vm/vm_kern.h>
#include <vm/vm_page.h>
#include <vm/vm_map.h>
#include <vm/vm_param.h>
#include <sys/vmmeter.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <sys/buf.h>
#include <sys/vnode.h>
#include <sys/pioctl.h>
#include <sys/sysctl.h>
#include <sys/syslog.h>
#include <sys/bus.h>
#ifdef KTRACE
#include <sys/ktrace.h>
#endif
#include <net/netisr.h>

#include <machine/trap.h>
#include <machine/cpu.h>
#include <machine/pte.h>
#include <machine/pmap.h>
#include <machine/md_var.h>
#include <machine/mips_opcode.h>
#include <machine/frame.h>
#include <machine/regnum.h>
#include <machine/tls.h>

#ifdef DDB
#include <machine/db_machdep.h>
#include <ddb/db_sym.h>
#include <ddb/ddb.h>
#include <sys/kdb.h>
#endif

#ifdef KDTRACE_HOOKS
#include <sys/dtrace_bsd.h>
#endif

#ifdef TRAP_DEBUG
int trap_debug = 0;
SYSCTL_INT(_machdep, OID_AUTO, trap_debug, CTLFLAG_RW,
    &trap_debug, 0, "Debug information on all traps");
#endif

#define	lbu_macro(data, addr)						\
	__asm __volatile ("lbu %0, 0x0(%1)"				\
			: "=r" (data)	/* outputs */			\
			: "r" (addr));	/* inputs */

#define	lb_macro(data, addr)						\
	__asm __volatile ("lb %0, 0x0(%1)"				\
			: "=r" (data)	/* outputs */			\
			: "r" (addr));	/* inputs */

#define	lwl_macro(data, addr)						\
	__asm __volatile ("lwl %0, 0x0(%1)"				\
			: "=r" (data)	/* outputs */			\
			: "r" (addr));	/* inputs */

#define	lwr_macro(data, addr)						\
	__asm __volatile ("lwr %0, 0x0(%1)"				\
			: "=r" (data)	/* outputs */			\
			: "r" (addr));	/* inputs */

#define	ldl_macro(data, addr)						\
	__asm __volatile ("ldl %0, 0x0(%1)"				\
			: "=r" (data)	/* outputs */			\
			: "r" (addr));	/* inputs */

#define	ldr_macro(data, addr)						\
	__asm __volatile ("ldr %0, 0x0(%1)"				\
			: "=r" (data)	/* outputs */			\
			: "r" (addr));	/* inputs */

#define	sb_macro(data, addr)						\
	__asm __volatile ("sb %0, 0x0(%1)"				\
			:				/* outputs */	\
			: "r" (data), "r" (addr));	/* inputs */

#define	swl_macro(data, addr)						\
	__asm __volatile ("swl %0, 0x0(%1)"				\
			: 				/* outputs */	\
			: "r" (data), "r" (addr));	/* inputs */

#define	swr_macro(data, addr)						\
	__asm __volatile ("swr %0, 0x0(%1)"				\
			: 				/* outputs */	\
			: "r" (data), "r" (addr));	/* inputs */

#define	sdl_macro(data, addr)						\
	__asm __volatile ("sdl %0, 0x0(%1)"				\
			: 				/* outputs */	\
			: "r" (data), "r" (addr));	/* inputs */

#define	sdr_macro(data, addr)						\
	__asm __volatile ("sdr %0, 0x0(%1)"				\
			:				/* outputs */	\
			: "r" (data), "r" (addr));	/* inputs */

static void log_illegal_instruction(const char *, struct trapframe *);
static void log_bad_page_fault(char *, struct trapframe *, int);
static void log_frame_dump(struct trapframe *frame);
static void get_mapping_info(vm_offset_t, pd_entry_t **, pt_entry_t **);

int (*dtrace_invop_jump_addr)(struct trapframe *);

#ifdef TRAP_DEBUG
static void trap_frame_dump(struct trapframe *frame);
#endif

void (*machExceptionTable[]) (void)= {
/*
 * The kernel exception handlers.
 */
	MipsKernIntr,		/* external interrupt */
	MipsKernGenException,	/* TLB modification */
	MipsTLBInvalidException,/* TLB miss (load or instr. fetch) */
	MipsTLBInvalidException,/* TLB miss (store) */
	MipsKernGenException,	/* address error (load or I-fetch) */
	MipsKernGenException,	/* address error (store) */
	MipsKernGenException,	/* bus error (I-fetch) */
	MipsKernGenException,	/* bus error (load or store) */
	MipsKernGenException,	/* system call */
	MipsKernGenException,	/* breakpoint */
	MipsKernGenException,	/* reserved instruction */
	MipsKernGenException,	/* coprocessor unusable */
	MipsKernGenException,	/* arithmetic overflow */
	MipsKernGenException,	/* trap exception */
	MipsKernGenException,	/* virtual coherence exception inst */
	MipsKernGenException,	/* floating point exception */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* watch exception */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* reserved */
	MipsKernGenException,	/* virtual coherence exception data */
/*
 * The user exception handlers.
 */
	MipsUserIntr,		/* 0 */
	MipsUserGenException,	/* 1 */
	MipsTLBInvalidException,/* 2 */
	MipsTLBInvalidException,/* 3 */
	MipsUserGenException,	/* 4 */
	MipsUserGenException,	/* 5 */
	MipsUserGenException,	/* 6 */
	MipsUserGenException,	/* 7 */
	MipsUserGenException,	/* 8 */
	MipsUserGenException,	/* 9 */
	MipsUserGenException,	/* 10 */
	MipsUserGenException,	/* 11 */
	MipsUserGenException,	/* 12 */
	MipsUserGenException,	/* 13 */
	MipsUserGenException,	/* 14 */
	MipsUserGenException,	/* 15 */
	MipsUserGenException,	/* 16 */
	MipsUserGenException,	/* 17 */
	MipsUserGenException,	/* 18 */
	MipsUserGenException,	/* 19 */
	MipsUserGenException,	/* 20 */
	MipsUserGenException,	/* 21 */
	MipsUserGenException,	/* 22 */
	MipsUserGenException,	/* 23 */
	MipsUserGenException,	/* 24 */
	MipsUserGenException,	/* 25 */
	MipsUserGenException,	/* 26 */
	MipsUserGenException,	/* 27 */
	MipsUserGenException,	/* 28 */
	MipsUserGenException,	/* 29 */
	MipsUserGenException,	/* 20 */
	MipsUserGenException,	/* 31 */
};

char *trap_type[] = {
	"external interrupt",
	"TLB modification",
	"TLB miss (load or instr. fetch)",
	"TLB miss (store)",
	"address error (load or I-fetch)",
	"address error (store)",
	"bus error (I-fetch)",
	"bus error (load or store)",
	"system call",
	"breakpoint",
	"reserved instruction",
	"coprocessor unusable",
	"arithmetic overflow",
	"trap",
	"virtual coherency instruction",
	"floating point",
	"reserved 16",
	"reserved 17",
	"reserved 18",
	"reserved 19",
	"reserved 20",
	"reserved 21",
	"reserved 22",
	"watch",
	"reserved 24",
	"reserved 25",
	"reserved 26",
	"reserved 27",
	"reserved 28",
	"reserved 29",
	"reserved 30",
	"virtual coherency data",
};

#if !defined(SMP) && (defined(DDB) || defined(DEBUG))
struct trapdebug trapdebug[TRAPSIZE], *trp = trapdebug;
#endif

#define	KERNLAND(x)	((vm_offset_t)(x) >= VM_MIN_KERNEL_ADDRESS && (vm_offset_t)(x) < VM_MAX_KERNEL_ADDRESS)
#define	DELAYBRANCH(x)	((int)(x) < 0)

/*
 * MIPS load/store access type
 */
enum {
	MIPS_LHU_ACCESS = 1,
	MIPS_LH_ACCESS,
	MIPS_LWU_ACCESS,
	MIPS_LW_ACCESS,
	MIPS_LD_ACCESS,
	MIPS_SH_ACCESS,
	MIPS_SW_ACCESS,
	MIPS_SD_ACCESS
};

char *access_name[] = {
	"Load Halfword Unsigned",
	"Load Halfword",
	"Load Word Unsigned",
	"Load Word",
	"Load Doubleword",
	"Store Halfword",
	"Store Word",
	"Store Doubleword"
};

#ifdef	CPU_CNMIPS
#include <machine/octeon_cop2.h>
#endif

static int allow_unaligned_acc = 1;

SYSCTL_INT(_vm, OID_AUTO, allow_unaligned_acc, CTLFLAG_RW,
    &allow_unaligned_acc, 0, "Allow unaligned accesses");

/*
 * FP emulation is assumed to work on O32, but the code is outdated and crufty
 * enough that it's a more sensible default to have it disabled when using
 * other ABIs.  At the very least, it needs a lot of help in using
 * type-semantic ABI-oblivious macros for everything it does.
 */
#if defined(__mips_o32)
static int emulate_fp = 1;
#else
static int emulate_fp = 0;
#endif
SYSCTL_INT(_machdep, OID_AUTO, emulate_fp, CTLFLAG_RW,
    &emulate_fp, 0, "Emulate unimplemented FPU instructions");

static int emulate_unaligned_access(struct trapframe *frame, int mode);

extern void fswintrberr(void); /* XXX */

int
cpu_fetch_syscall_args(struct thread *td, struct syscall_args *sa)
{
	struct trapframe *locr0 = td->td_frame;
	struct sysentvec *se;
	int error, nsaved;

	bzero(sa->args, sizeof(sa->args));

	/* compute next PC after syscall instruction */
	td->td_pcb->pcb_tpc = sa->trapframe->pc; /* Remember if restart */
	if (DELAYBRANCH(sa->trapframe->cause))	 /* Check BD bit */
		locr0->pc = MipsEmulateBranch(locr0, sa->trapframe->pc, 0, 0);
	else
		locr0->pc += sizeof(int);
	sa->code = locr0->v0;

	switch (sa->code) {
	case SYS___syscall:
	case SYS_syscall:
		/*
		 * This is an indirect syscall, in which the code is the first argument.
		 */
#if (!defined(__mips_n32) && !defined(__mips_n64)) || defined(COMPAT_FREEBSD32)
		if (sa->code == SYS___syscall && SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
			/*
			 * Like syscall, but code is a quad, so as to maintain alignment
			 * for the rest of the arguments.
			 */
			if (_QUAD_LOWWORD == 0)
				sa->code = locr0->a0;
			else
				sa->code = locr0->a1;
			sa->args[0] = locr0->a2;
			sa->args[1] = locr0->a3;
			nsaved = 2;
			break;
		} 
#endif
		/*
		 * This is either not a quad syscall, or is a quad syscall with a
		 * new ABI in which quads fit in a single register.
		 */
		sa->code = locr0->a0;
		sa->args[0] = locr0->a1;
		sa->args[1] = locr0->a2;
		sa->args[2] = locr0->a3;
		nsaved = 3;
#if defined(__mips_n32) || defined(__mips_n64)
#ifdef COMPAT_FREEBSD32
		if (!SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
#endif
			/*
			 * Non-o32 ABIs support more arguments in registers.
			 */
			sa->args[3] = locr0->a4;
			sa->args[4] = locr0->a5;
			sa->args[5] = locr0->a6;
			sa->args[6] = locr0->a7;
			nsaved += 4;
#ifdef COMPAT_FREEBSD32
		}
#endif
#endif
		break;
	default:
		/*
		 * A direct syscall, arguments are just parameters to the syscall.
		 */
		sa->args[0] = locr0->a0;
		sa->args[1] = locr0->a1;
		sa->args[2] = locr0->a2;
		sa->args[3] = locr0->a3;
		nsaved = 4;
#if defined (__mips_n32) || defined(__mips_n64)
#ifdef COMPAT_FREEBSD32
		if (!SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
#endif
			/*
			 * Non-o32 ABIs support more arguments in registers.
			 */
			sa->args[4] = locr0->a4;
			sa->args[5] = locr0->a5;
			sa->args[6] = locr0->a6;
			sa->args[7] = locr0->a7;
			nsaved += 4;
#ifdef COMPAT_FREEBSD32
		}
#endif
#endif
		break;
	}

#ifdef TRAP_DEBUG
	if (trap_debug)
		printf("SYSCALL #%d pid:%u\n", sa->code, td->td_proc->p_pid);
#endif

	se = td->td_proc->p_sysent;
	/*
	 * XXX
	 * Shouldn't this go before switching on the code?
	 */
	if (se->sv_mask)
		sa->code &= se->sv_mask;

	if (sa->code >= se->sv_size)
		sa->callp = &se->sv_table[0];
	else
		sa->callp = &se->sv_table[sa->code];

	sa->narg = sa->callp->sy_narg;

	if (sa->narg > nsaved) {
#if defined(__mips_n32) || defined(__mips_n64)
		/*
		 * XXX
		 * Is this right for new ABIs?  I think the 4 there
		 * should be 8, size there are 8 registers to skip,
		 * not 4, but I'm not certain.
		 */
#ifdef COMPAT_FREEBSD32
		if (!SV_PROC_FLAG(td->td_proc, SV_ILP32))
#endif
			printf("SYSCALL #%u pid:%u, narg (%u) > nsaved (%u).\n",
			    sa->code, td->td_proc->p_pid, sa->narg, nsaved);
#endif
#if (defined(__mips_n32) || defined(__mips_n64)) && defined(COMPAT_FREEBSD32)
		if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
			unsigned i;
			int32_t arg;

			error = 0; /* XXX GCC is awful.  */
			for (i = nsaved; i < sa->narg; i++) {
				error = copyin((caddr_t)(intptr_t)(locr0->sp +
				    (4 + (i - nsaved)) * sizeof(int32_t)),
				    (caddr_t)&arg, sizeof arg);
				if (error != 0)
					break;
				sa->args[i] = arg;
			}
		} else
#endif
		error = copyin((caddr_t)(intptr_t)(locr0->sp +
		    4 * sizeof(register_t)), (caddr_t)&sa->args[nsaved],
		   (u_int)(sa->narg - nsaved) * sizeof(register_t));
		if (error != 0) {
			locr0->v0 = error;
			locr0->a3 = 1;
		}
	} else
		error = 0;

	if (error == 0) {
		td->td_retval[0] = 0;
		td->td_retval[1] = locr0->v1;
	}

	return (error);
}

#undef __FBSDID
#define __FBSDID(x)
#include "../../kern/subr_syscall.c"

/*
 * Handle an exception.
 * Called from MipsKernGenException() or MipsUserGenException()
 * when a processor trap occurs.
 * In the case of a kernel trap, we return the pc where to resume if
 * p->p_addr->u_pcb.pcb_onfault is set, otherwise, return old pc.
 */
register_t
trap(struct trapframe *trapframe)
{
	int type, usermode;
	int i = 0;
	unsigned ucode = 0;
	struct thread *td = curthread;
	struct proc *p = curproc;
	vm_prot_t ftype;
	pmap_t pmap;
	int access_type;
	ksiginfo_t ksi;
	char *msg = NULL;
	intptr_t addr = 0;
	register_t pc;
	int cop;
	register_t *frame_regs;

	trapdebug_enter(trapframe, 0);
	
	type = (trapframe->cause & MIPS_CR_EXC_CODE) >> MIPS_CR_EXC_CODE_SHIFT;
	if (TRAPF_USERMODE(trapframe)) {
		type |= T_USER;
		usermode = 1;
	} else {
		usermode = 0;
	}

	/*
	 * Enable hardware interrupts if they were on before the trap. If it
	 * was off disable all so we don't accidently enable it when doing a
	 * return to userland.
	 */
	if (trapframe->sr & MIPS_SR_INT_IE) {
		set_intr_mask(trapframe->sr & MIPS_SR_INT_MASK);
		intr_enable();
	} else {
		intr_disable();
	}

#ifdef TRAP_DEBUG
	if (trap_debug) {
		static vm_offset_t last_badvaddr = 0;
		static vm_offset_t this_badvaddr = 0;
		static int count = 0;
		u_int32_t pid;

		printf("trap type %x (%s - ", type,
		    trap_type[type & (~T_USER)]);

		if (type & T_USER)
			printf("user mode)\n");
		else
			printf("kernel mode)\n");

#ifdef SMP
		printf("cpuid = %d\n", PCPU_GET(cpuid));
#endif
		pid = mips_rd_entryhi() & TLBHI_ASID_MASK;
		printf("badaddr = %#jx, pc = %#jx, ra = %#jx, sp = %#jx, sr = %jx, pid = %d, ASID = %u\n",
		    (intmax_t)trapframe->badvaddr, (intmax_t)trapframe->pc, (intmax_t)trapframe->ra,
		    (intmax_t)trapframe->sp, (intmax_t)trapframe->sr,
		    (curproc ? curproc->p_pid : -1), pid);

		switch (type & ~T_USER) {
		case T_TLB_MOD:
		case T_TLB_LD_MISS:
		case T_TLB_ST_MISS:
		case T_ADDR_ERR_LD:
		case T_ADDR_ERR_ST:
			this_badvaddr = trapframe->badvaddr;
			break;
		case T_SYSCALL:
			this_badvaddr = trapframe->ra;
			break;
		default:
			this_badvaddr = trapframe->pc;
			break;
		}
		if ((last_badvaddr == this_badvaddr) &&
		    ((type & ~T_USER) != T_SYSCALL) &&
		    ((type & ~T_USER) != T_COP_UNUSABLE)) {
			if (++count == 3) {
				trap_frame_dump(trapframe);
				panic("too many faults at %p\n", (void *)last_badvaddr);
			}
		} else {
			last_badvaddr = this_badvaddr;
			count = 0;
		}
	}
#endif

#ifdef KDTRACE_HOOKS
	/*
	 * A trap can occur while DTrace executes a probe. Before
	 * executing the probe, DTrace blocks re-scheduling and sets
	 * a flag in its per-cpu flags to indicate that it doesn't
	 * want to fault. On returning from the probe, the no-fault
	 * flag is cleared and finally re-scheduling is enabled.
	 *
	 * If the DTrace kernel module has registered a trap handler,
	 * call it and if it returns non-zero, assume that it has
	 * handled the trap and modified the trap frame so that this
	 * function can return normally.
	 */
	/*
	 * XXXDTRACE: add pid probe handler here (if ever)
	 */
	if (!usermode) {
		if (dtrace_trap_func != NULL &&
		    (*dtrace_trap_func)(trapframe, type) != 0)
			return (trapframe->pc);
	}
#endif

	switch (type) {
	case T_MCHECK:
#ifdef DDB
		kdb_trap(type, 0, trapframe);
#endif
		panic("MCHECK\n");
		break;
	case T_TLB_MOD:
		/* check for kernel address */
		if (KERNLAND(trapframe->badvaddr)) {
			if (pmap_emulate_modified(kernel_pmap, 
			    trapframe->badvaddr) != 0) {
				ftype = VM_PROT_WRITE;
				goto kernel_fault;
			}
			return (trapframe->pc);
		}
		/* FALLTHROUGH */

	case T_TLB_MOD + T_USER:
		pmap = &p->p_vmspace->vm_pmap;
		if (pmap_emulate_modified(pmap, trapframe->badvaddr) != 0) {
			ftype = VM_PROT_WRITE;
			goto dofault;
		}
		if (!usermode)
			return (trapframe->pc);
		goto out;

	case T_TLB_LD_MISS:
	case T_TLB_ST_MISS:
		ftype = (type == T_TLB_ST_MISS) ? VM_PROT_WRITE : VM_PROT_READ;
		/* check for kernel address */
		if (KERNLAND(trapframe->badvaddr)) {
			vm_offset_t va;
			int rv;

	kernel_fault:
			va = trunc_page((vm_offset_t)trapframe->badvaddr);
			rv = vm_fault(kernel_map, va, ftype, VM_FAULT_NORMAL);
			if (rv == KERN_SUCCESS)
				return (trapframe->pc);
			if (td->td_pcb->pcb_onfault != NULL) {
				pc = (register_t)(intptr_t)td->td_pcb->pcb_onfault;
				td->td_pcb->pcb_onfault = NULL;
				return (pc);
			}
			goto err;
		}

		/*
		 * It is an error for the kernel to access user space except
		 * through the copyin/copyout routines.
		 */
		if (td->td_pcb->pcb_onfault == NULL)
			goto err;

		/* check for fuswintr() or suswintr() getting a page fault */
		/* XXX There must be a nicer way to do this.  */
		if (td->td_pcb->pcb_onfault == fswintrberr) {
			pc = (register_t)(intptr_t)td->td_pcb->pcb_onfault;
			td->td_pcb->pcb_onfault = NULL;
			return (pc);
		}

		goto dofault;

	case T_TLB_LD_MISS + T_USER:
		ftype = VM_PROT_READ;
		goto dofault;

	case T_TLB_ST_MISS + T_USER:
		ftype = VM_PROT_WRITE;
dofault:
		{
			vm_offset_t va;
			struct vmspace *vm;
			vm_map_t map;
			int rv = 0;

			vm = p->p_vmspace;
			map = &vm->vm_map;
			va = trunc_page((vm_offset_t)trapframe->badvaddr);
			if (KERNLAND(trapframe->badvaddr)) {
				/*
				 * Don't allow user-mode faults in kernel
				 * address space.
				 */
				goto nogo;
			}

			rv = vm_fault(map, va, ftype, VM_FAULT_NORMAL);
			/*
			 * XXXDTRACE: add dtrace_doubletrap_func here?
			 */
#ifdef VMFAULT_TRACE
			printf("vm_fault(%p (pmap %p), %p (%p), %x, %d) -> %x at pc %p\n",
			    map, &vm->vm_pmap, (void *)va, (void *)(intptr_t)trapframe->badvaddr,
			    ftype, VM_FAULT_NORMAL, rv, (void *)(intptr_t)trapframe->pc);
#endif

			if (rv == KERN_SUCCESS) {
				if (!usermode) {
					return (trapframe->pc);
				}
				goto out;
			}
	nogo:
			if (!usermode) {
				if (td->td_pcb->pcb_onfault != NULL) {
					pc = (register_t)(intptr_t)td->td_pcb->pcb_onfault;
					td->td_pcb->pcb_onfault = NULL;
					return (pc);
				}
				goto err;
			}
			i = SIGSEGV;
			if (rv == KERN_PROTECTION_FAILURE)
				ucode = SEGV_ACCERR;
			else
				ucode = SEGV_MAPERR;
			addr = trapframe->pc;

			msg = "BAD_PAGE_FAULT";
			log_bad_page_fault(msg, trapframe, type);

			break;
		}

	case T_ADDR_ERR_LD + T_USER:	/* misaligned or kseg access */
	case T_ADDR_ERR_ST + T_USER:	/* misaligned or kseg access */
		if (trapframe->badvaddr < 0 ||
		    trapframe->badvaddr >= VM_MAXUSER_ADDRESS) {
			msg = "ADDRESS_SPACE_ERR";
		} else if (allow_unaligned_acc) {
			int mode;

			if (type == (T_ADDR_ERR_LD + T_USER))
				mode = VM_PROT_READ;
			else
				mode = VM_PROT_WRITE;

			access_type = emulate_unaligned_access(trapframe, mode);
			if (access_type != 0)
				goto out;
			msg = "ALIGNMENT_FIX_ERR";
		} else {
			msg = "ADDRESS_ERR";
		}

		/* FALL THROUGH */

	case T_BUS_ERR_IFETCH + T_USER:	/* BERR asserted to cpu */
	case T_BUS_ERR_LD_ST + T_USER:	/* BERR asserted to cpu */
		ucode = 0;	/* XXX should be VM_PROT_something */
		i = SIGBUS;
		addr = trapframe->pc;
		if (!msg)
			msg = "BUS_ERR";
		log_bad_page_fault(msg, trapframe, type);
		break;

	case T_SYSCALL + T_USER:
		{
			struct syscall_args sa;
			int error;

			sa.trapframe = trapframe;
			error = syscallenter(td, &sa);

#if !defined(SMP) && (defined(DDB) || defined(DEBUG))
			if (trp == trapdebug)
				trapdebug[TRAPSIZE - 1].code = sa.code;
			else
				trp[-1].code = sa.code;
#endif
			trapdebug_enter(td->td_frame, -sa.code);

			/*
			 * The sync'ing of I & D caches for SYS_ptrace() is
			 * done by procfs_domem() through procfs_rwmem()
			 * instead of being done here under a special check
			 * for SYS_ptrace().
			 */
			syscallret(td, error, &sa);
			return (trapframe->pc);
		}

#if defined(KDTRACE_HOOKS) || defined(DDB)
	case T_BREAK:
#ifdef KDTRACE_HOOKS
		if (!usermode && dtrace_invop_jump_addr != 0) {
			dtrace_invop_jump_addr(trapframe);
			return (trapframe->pc);
		}
#endif
#ifdef DDB
		kdb_trap(type, 0, trapframe);
		return (trapframe->pc);
#endif
#endif

	case T_BREAK + T_USER:
		{
			intptr_t va;
			uint32_t instr;

			/* compute address of break instruction */
			va = trapframe->pc;
			if (DELAYBRANCH(trapframe->cause))
				va += sizeof(int);

			/* read break instruction */
			instr = fuword32((caddr_t)va);
#if 0
			printf("trap: %s (%d) breakpoint %x at %x: (adr %x ins %x)\n",
			    p->p_comm, p->p_pid, instr, trapframe->pc,
			    p->p_md.md_ss_addr, p->p_md.md_ss_instr);	/* XXX */
#endif
			if (td->td_md.md_ss_addr != va ||
			    instr != MIPS_BREAK_SSTEP) {
				i = SIGTRAP;
				addr = trapframe->pc;
				break;
			}
			/*
			 * The restoration of the original instruction and
			 * the clearing of the breakpoint will be done later
			 * by the call to ptrace_clear_single_step() in
			 * issignal() when SIGTRAP is processed.
			 */
			addr = trapframe->pc;
			i = SIGTRAP;
			break;
		}

	case T_IWATCH + T_USER:
	case T_DWATCH + T_USER:
		{
			intptr_t va;

			/* compute address of trapped instruction */
			va = trapframe->pc;
			if (DELAYBRANCH(trapframe->cause))
				va += sizeof(int);
			printf("watch exception @ %p\n", (void *)va);
			i = SIGTRAP;
			addr = va;
			break;
		}

	case T_TRAP + T_USER:
		{
			intptr_t va;
			uint32_t instr;
			struct trapframe *locr0 = td->td_frame;

			/* compute address of trap instruction */
			va = trapframe->pc;
			if (DELAYBRANCH(trapframe->cause))
				va += sizeof(int);
			/* read break instruction */
			instr = fuword32((caddr_t)va);

			if (DELAYBRANCH(trapframe->cause)) {	/* Check BD bit */
				locr0->pc = MipsEmulateBranch(locr0, trapframe->pc, 0,
				    0);
			} else {
				locr0->pc += sizeof(int);
			}
			addr = va;
			i = SIGEMT;	/* Stuff it with something for now */
			break;
		}

	case T_RES_INST + T_USER:
		{
			InstFmt inst;
			inst = *(InstFmt *)(intptr_t)trapframe->pc;
			switch (inst.RType.op) {
			case OP_SPECIAL3:
				switch (inst.RType.func) {
				case OP_RDHWR:
					/* Register 29 used for TLS */
					if (inst.RType.rd == 29) {
						frame_regs = &(trapframe->zero);
						frame_regs[inst.RType.rt] = (register_t)(intptr_t)td->td_md.md_tls;
						frame_regs[inst.RType.rt] += td->td_md.md_tls_tcb_offset;
						trapframe->pc += sizeof(int);
						goto out;
					}
				break;
				}
			break;
			}

			log_illegal_instruction("RES_INST", trapframe);
			i = SIGILL;
			addr = trapframe->pc;
		}
		break;
	case T_C2E:
	case T_C2E + T_USER:
		goto err;
		break;
	case T_COP_UNUSABLE:
#ifdef	CPU_CNMIPS
		cop = (trapframe->cause & MIPS_CR_COP_ERR) >> MIPS_CR_COP_ERR_SHIFT;
		/* Handle only COP2 exception */
		if (cop != 2)
			goto err;

		addr = trapframe->pc;
		/* save userland cop2 context if it has been touched */
		if ((td->td_md.md_flags & MDTD_COP2USED) &&
		    (td->td_md.md_cop2owner == COP2_OWNER_USERLAND)) {
			if (td->td_md.md_ucop2)
				octeon_cop2_save(td->td_md.md_ucop2);
			else
				panic("COP2 was used in user mode but md_ucop2 is NULL");
		}

		if (td->td_md.md_cop2 == NULL) {
			td->td_md.md_cop2 = octeon_cop2_alloc_ctx();
			if (td->td_md.md_cop2 == NULL)
				panic("Failed to allocate COP2 context");
			memset(td->td_md.md_cop2, 0, sizeof(*td->td_md.md_cop2));
		}

		octeon_cop2_restore(td->td_md.md_cop2);
		
		/* Make userland re-request its context */
		td->td_frame->sr &= ~MIPS_SR_COP_2_BIT;
		td->td_md.md_flags |= MDTD_COP2USED;
		td->td_md.md_cop2owner = COP2_OWNER_KERNEL;
		/* Enable COP2, it will be disabled in cpu_switch */
		mips_wr_status(mips_rd_status() | MIPS_SR_COP_2_BIT);
		return (trapframe->pc);
#else
		goto err;
		break;
#endif

	case T_COP_UNUSABLE + T_USER:
		cop = (trapframe->cause & MIPS_CR_COP_ERR) >> MIPS_CR_COP_ERR_SHIFT;
		if (cop == 1) {
#if !defined(CPU_HAVEFPU)
		/* FP (COP1) instruction */
			log_illegal_instruction("COP1_UNUSABLE", trapframe);
			i = SIGILL;
			break;
#else
			addr = trapframe->pc;
			MipsSwitchFPState(PCPU_GET(fpcurthread), td->td_frame);
			PCPU_SET(fpcurthread, td);
#if defined(__mips_n64)
			td->td_frame->sr |= MIPS_SR_COP_1_BIT | MIPS_SR_FR;
#else
			td->td_frame->sr |= MIPS_SR_COP_1_BIT;
#endif
			td->td_md.md_flags |= MDTD_FPUSED;
			goto out;
#endif
		}
#ifdef	CPU_CNMIPS
		else  if (cop == 2) {
			addr = trapframe->pc;
			if ((td->td_md.md_flags & MDTD_COP2USED) &&
			    (td->td_md.md_cop2owner == COP2_OWNER_KERNEL)) {
				if (td->td_md.md_cop2)
					octeon_cop2_save(td->td_md.md_cop2);
				else
					panic("COP2 was used in kernel mode but md_cop2 is NULL");
			}

			if (td->td_md.md_ucop2 == NULL) {
				td->td_md.md_ucop2 = octeon_cop2_alloc_ctx();
				if (td->td_md.md_ucop2 == NULL)
					panic("Failed to allocate userland COP2 context");
				memset(td->td_md.md_ucop2, 0, sizeof(*td->td_md.md_ucop2));
			}

			octeon_cop2_restore(td->td_md.md_ucop2);

			td->td_frame->sr |= MIPS_SR_COP_2_BIT;
			td->td_md.md_flags |= MDTD_COP2USED;
			td->td_md.md_cop2owner = COP2_OWNER_USERLAND;
			goto out;
		}
#endif
		else {
			log_illegal_instruction("COPn_UNUSABLE", trapframe);
			i = SIGILL;	/* only FPU instructions allowed */
			break;
		}

	case T_FPE:
#if !defined(SMP) && (defined(DDB) || defined(DEBUG))
		trapDump("fpintr");
#else
		printf("FPU Trap: PC %#jx CR %x SR %x\n",
		    (intmax_t)trapframe->pc, (unsigned)trapframe->cause, (unsigned)trapframe->sr);
		goto err;
#endif

	case T_FPE + T_USER:
		if (!emulate_fp) {
			i = SIGFPE;
			addr = trapframe->pc;
			break;
		}
		MipsFPTrap(trapframe->sr, trapframe->cause, trapframe->pc);
		goto out;

	case T_OVFLOW + T_USER:
		i = SIGFPE;
		addr = trapframe->pc;
		break;

	case T_ADDR_ERR_LD:	/* misaligned access */
	case T_ADDR_ERR_ST:	/* misaligned access */
#ifdef TRAP_DEBUG
		if (trap_debug) {
			printf("+++ ADDR_ERR: type = %d, badvaddr = %#jx\n", type,
			    (intmax_t)trapframe->badvaddr);
		}
#endif
		/* Only allow emulation on a user address */
		if (allow_unaligned_acc &&
		    ((vm_offset_t)trapframe->badvaddr < VM_MAXUSER_ADDRESS)) {
			int mode;

			if (type == T_ADDR_ERR_LD)
				mode = VM_PROT_READ;
			else
				mode = VM_PROT_WRITE;

			access_type = emulate_unaligned_access(trapframe, mode);
			if (access_type != 0)
				return (trapframe->pc);
		}
		/* FALLTHROUGH */

	case T_BUS_ERR_LD_ST:	/* BERR asserted to cpu */
		if (td->td_pcb->pcb_onfault != NULL) {
			pc = (register_t)(intptr_t)td->td_pcb->pcb_onfault;
			td->td_pcb->pcb_onfault = NULL;
			return (pc);
		}

		/* FALLTHROUGH */

	default:
err:

#if !defined(SMP) && defined(DEBUG)
		trapDump("trap");
#endif
#ifdef SMP
		printf("cpu:%d-", PCPU_GET(cpuid));
#endif
		printf("Trap cause = %d (%s - ", type,
		    trap_type[type & (~T_USER)]);

		if (type & T_USER)
			printf("user mode)\n");
		else
			printf("kernel mode)\n");

#ifdef TRAP_DEBUG
		if (trap_debug)
			printf("badvaddr = %#jx, pc = %#jx, ra = %#jx, sr = %#jxx\n",
			       (intmax_t)trapframe->badvaddr, (intmax_t)trapframe->pc, (intmax_t)trapframe->ra,
			       (intmax_t)trapframe->sr);
#endif

#ifdef KDB
		if (debugger_on_panic || kdb_active) {
			kdb_trap(type, 0, trapframe);
		}
#endif
		panic("trap");
	}
	td->td_frame->pc = trapframe->pc;
	td->td_frame->cause = trapframe->cause;
	td->td_frame->badvaddr = trapframe->badvaddr;
	ksiginfo_init_trap(&ksi);
	ksi.ksi_signo = i;
	ksi.ksi_code = ucode;
	ksi.ksi_addr = (void *)addr;
	ksi.ksi_trapno = type;
	trapsignal(td, &ksi);
out:

	/*
	 * Note: we should only get here if returning to user mode.
	 */
	userret(td, trapframe);
	return (trapframe->pc);
}

#if !defined(SMP) && (defined(DDB) || defined(DEBUG))
void
trapDump(char *msg)
{
	register_t s;
	int i;

	s = intr_disable();
	printf("trapDump(%s)\n", msg);
	for (i = 0; i < TRAPSIZE; i++) {
		if (trp == trapdebug) {
			trp = &trapdebug[TRAPSIZE - 1];
		} else {
			trp--;
		}

		if (trp->cause == 0)
			break;

		printf("%s: ADR %jx PC %jx CR %jx SR %jx\n",
		    trap_type[(trp->cause & MIPS_CR_EXC_CODE) >> 
			MIPS_CR_EXC_CODE_SHIFT],
		    (intmax_t)trp->vadr, (intmax_t)trp->pc,
		    (intmax_t)trp->cause, (intmax_t)trp->status);

		printf("   RA %jx SP %jx code %d\n", (intmax_t)trp->ra,
		    (intmax_t)trp->sp, (int)trp->code);
	}
	intr_restore(s);
}
#endif


/*
 * Return the resulting PC as if the branch was executed.
 */
uintptr_t
MipsEmulateBranch(struct trapframe *framePtr, uintptr_t instPC, int fpcCSR,
    uintptr_t instptr)
{
	InstFmt inst;
	register_t *regsPtr = (register_t *) framePtr;
	uintptr_t retAddr = 0;
	int condition;

#define	GetBranchDest(InstPtr, inst) \
	(InstPtr + 4 + ((short)inst.IType.imm << 2))


	if (instptr) {
		if (instptr < MIPS_KSEG0_START)
			inst.word = fuword32((void *)instptr);
		else
			inst = *(InstFmt *) instptr;
	} else {
		if ((vm_offset_t)instPC < MIPS_KSEG0_START)
			inst.word = fuword32((void *)instPC);
		else
			inst = *(InstFmt *) instPC;
	}

	switch ((int)inst.JType.op) {
	case OP_SPECIAL:
		switch ((int)inst.RType.func) {
		case OP_JR:
		case OP_JALR:
			retAddr = regsPtr[inst.RType.rs];
			break;

		default:
			retAddr = instPC + 4;
			break;
		}
		break;

	case OP_BCOND:
		switch ((int)inst.IType.rt) {
		case OP_BLTZ:
		case OP_BLTZL:
		case OP_BLTZAL:
		case OP_BLTZALL:
			if ((int)(regsPtr[inst.RType.rs]) < 0)
				retAddr = GetBranchDest(instPC, inst);
			else
				retAddr = instPC + 8;
			break;

		case OP_BGEZ:
		case OP_BGEZL:
		case OP_BGEZAL:
		case OP_BGEZALL:
			if ((int)(regsPtr[inst.RType.rs]) >= 0)
				retAddr = GetBranchDest(instPC, inst);
			else
				retAddr = instPC + 8;
			break;

		case OP_TGEI:
		case OP_TGEIU:
		case OP_TLTI:
		case OP_TLTIU:
		case OP_TEQI:
		case OP_TNEI:
			retAddr = instPC + 4;	/* Like syscall... */
			break;

		default:
			panic("MipsEmulateBranch: Bad branch cond");
		}
		break;

	case OP_J:
	case OP_JAL:
		retAddr = (inst.JType.target << 2) |
		    ((unsigned)(instPC + 4) & 0xF0000000);
		break;

	case OP_BEQ:
	case OP_BEQL:
		if (regsPtr[inst.RType.rs] == regsPtr[inst.RType.rt])
			retAddr = GetBranchDest(instPC, inst);
		else
			retAddr = instPC + 8;
		break;

	case OP_BNE:
	case OP_BNEL:
		if (regsPtr[inst.RType.rs] != regsPtr[inst.RType.rt])
			retAddr = GetBranchDest(instPC, inst);
		else
			retAddr = instPC + 8;
		break;

	case OP_BLEZ:
	case OP_BLEZL:
		if ((int)(regsPtr[inst.RType.rs]) <= 0)
			retAddr = GetBranchDest(instPC, inst);
		else
			retAddr = instPC + 8;
		break;

	case OP_BGTZ:
	case OP_BGTZL:
		if ((int)(regsPtr[inst.RType.rs]) > 0)
			retAddr = GetBranchDest(instPC, inst);
		else
			retAddr = instPC + 8;
		break;

	case OP_COP1:
		switch (inst.RType.rs) {
		case OP_BCx:
		case OP_BCy:
			if ((inst.RType.rt & COPz_BC_TF_MASK) == COPz_BC_TRUE)
				condition = fpcCSR & MIPS_FPU_COND_BIT;
			else
				condition = !(fpcCSR & MIPS_FPU_COND_BIT);
			if (condition)
				retAddr = GetBranchDest(instPC, inst);
			else
				retAddr = instPC + 8;
			break;

		default:
			retAddr = instPC + 4;
		}
		break;

	default:
		retAddr = instPC + 4;
	}
	return (retAddr);
}

static void
log_frame_dump(struct trapframe *frame)
{
	log(LOG_ERR, "Trapframe Register Dump:\n");
	log(LOG_ERR, "\tzero: %#jx\tat: %#jx\tv0: %#jx\tv1: %#jx\n",
	    (intmax_t)0, (intmax_t)frame->ast, (intmax_t)frame->v0, (intmax_t)frame->v1);

	log(LOG_ERR, "\ta0: %#jx\ta1: %#jx\ta2: %#jx\ta3: %#jx\n",
	    (intmax_t)frame->a0, (intmax_t)frame->a1, (intmax_t)frame->a2, (intmax_t)frame->a3);

#if defined(__mips_n32) || defined(__mips_n64)
	log(LOG_ERR, "\ta4: %#jx\ta5: %#jx\ta6: %#jx\ta6: %#jx\n",
	    (intmax_t)frame->a4, (intmax_t)frame->a5, (intmax_t)frame->a6, (intmax_t)frame->a7);

	log(LOG_ERR, "\tt0: %#jx\tt1: %#jx\tt2: %#jx\tt3: %#jx\n",
	    (intmax_t)frame->t0, (intmax_t)frame->t1, (intmax_t)frame->t2, (intmax_t)frame->t3);
#else
	log(LOG_ERR, "\tt0: %#jx\tt1: %#jx\tt2: %#jx\tt3: %#jx\n",
	    (intmax_t)frame->t0, (intmax_t)frame->t1, (intmax_t)frame->t2, (intmax_t)frame->t3);

	log(LOG_ERR, "\tt4: %#jx\tt5: %#jx\tt6: %#jx\tt7: %#jx\n",
	    (intmax_t)frame->t4, (intmax_t)frame->t5, (intmax_t)frame->t6, (intmax_t)frame->t7);
#endif
	log(LOG_ERR, "\tt8: %#jx\tt9: %#jx\ts0: %#jx\ts1: %#jx\n",
	    (intmax_t)frame->t8, (intmax_t)frame->t9, (intmax_t)frame->s0, (intmax_t)frame->s1);

	log(LOG_ERR, "\ts2: %#jx\ts3: %#jx\ts4: %#jx\ts5: %#jx\n",
	    (intmax_t)frame->s2, (intmax_t)frame->s3, (intmax_t)frame->s4, (intmax_t)frame->s5);

	log(LOG_ERR, "\ts6: %#jx\ts7: %#jx\tk0: %#jx\tk1: %#jx\n",
	    (intmax_t)frame->s6, (intmax_t)frame->s7, (intmax_t)frame->k0, (intmax_t)frame->k1);

	log(LOG_ERR, "\tgp: %#jx\tsp: %#jx\ts8: %#jx\tra: %#jx\n",
	    (intmax_t)frame->gp, (intmax_t)frame->sp, (intmax_t)frame->s8, (intmax_t)frame->ra);

	log(LOG_ERR, "\tsr: %#jx\tmullo: %#jx\tmulhi: %#jx\tbadvaddr: %#jx\n",
	    (intmax_t)frame->sr, (intmax_t)frame->mullo, (intmax_t)frame->mulhi, (intmax_t)frame->badvaddr);

#ifdef IC_REG
	log(LOG_ERR, "\tcause: %#jx\tpc: %#jx\tic: %#jx\n",
	    (intmax_t)frame->cause, (intmax_t)frame->pc, (intmax_t)frame->ic);
#else
	log(LOG_ERR, "\tcause: %#jx\tpc: %#jx\n",
	    (intmax_t)frame->cause, (intmax_t)frame->pc);
#endif
}

#ifdef TRAP_DEBUG
static void
trap_frame_dump(struct trapframe *frame)
{
	printf("Trapframe Register Dump:\n");
	printf("\tzero: %#jx\tat: %#jx\tv0: %#jx\tv1: %#jx\n",
	    (intmax_t)0, (intmax_t)frame->ast, (intmax_t)frame->v0, (intmax_t)frame->v1);

	printf("\ta0: %#jx\ta1: %#jx\ta2: %#jx\ta3: %#jx\n",
	    (intmax_t)frame->a0, (intmax_t)frame->a1, (intmax_t)frame->a2, (intmax_t)frame->a3);
#if defined(__mips_n32) || defined(__mips_n64)
	printf("\ta4: %#jx\ta5: %#jx\ta6: %#jx\ta7: %#jx\n",
	    (intmax_t)frame->a4, (intmax_t)frame->a5, (intmax_t)frame->a6, (intmax_t)frame->a7);

	printf("\tt0: %#jx\tt1: %#jx\tt2: %#jx\tt3: %#jx\n",
	    (intmax_t)frame->t0, (intmax_t)frame->t1, (intmax_t)frame->t2, (intmax_t)frame->t3);
#else
	printf("\tt0: %#jx\tt1: %#jx\tt2: %#jx\tt3: %#jx\n",
	    (intmax_t)frame->t0, (intmax_t)frame->t1, (intmax_t)frame->t2, (intmax_t)frame->t3);

	printf("\tt4: %#jx\tt5: %#jx\tt6: %#jx\tt7: %#jx\n",
	    (intmax_t)frame->t4, (intmax_t)frame->t5, (intmax_t)frame->t6, (intmax_t)frame->t7);
#endif
	printf("\tt8: %#jx\tt9: %#jx\ts0: %#jx\ts1: %#jx\n",
	    (intmax_t)frame->t8, (intmax_t)frame->t9, (intmax_t)frame->s0, (intmax_t)frame->s1);

	printf("\ts2: %#jx\ts3: %#jx\ts4: %#jx\ts5: %#jx\n",
	    (intmax_t)frame->s2, (intmax_t)frame->s3, (intmax_t)frame->s4, (intmax_t)frame->s5);

	printf("\ts6: %#jx\ts7: %#jx\tk0: %#jx\tk1: %#jx\n",
	    (intmax_t)frame->s6, (intmax_t)frame->s7, (intmax_t)frame->k0, (intmax_t)frame->k1);

	printf("\tgp: %#jx\tsp: %#jx\ts8: %#jx\tra: %#jx\n",
	    (intmax_t)frame->gp, (intmax_t)frame->sp, (intmax_t)frame->s8, (intmax_t)frame->ra);

	printf("\tsr: %#jx\tmullo: %#jx\tmulhi: %#jx\tbadvaddr: %#jx\n",
	    (intmax_t)frame->sr, (intmax_t)frame->mullo, (intmax_t)frame->mulhi, (intmax_t)frame->badvaddr);

#ifdef IC_REG
	printf("\tcause: %#jx\tpc: %#jx\tic: %#jx\n",
	    (intmax_t)frame->cause, (intmax_t)frame->pc, (intmax_t)frame->ic);
#else
	printf("\tcause: %#jx\tpc: %#jx\n",
	    (intmax_t)frame->cause, (intmax_t)frame->pc);
#endif
}

#endif


static void
get_mapping_info(vm_offset_t va, pd_entry_t **pdepp, pt_entry_t **ptepp)
{
	pt_entry_t *ptep;
	pd_entry_t *pdep;
	struct proc *p = curproc;

	pdep = (&(p->p_vmspace->vm_pmap.pm_segtab[(va >> SEGSHIFT) & (NPDEPG - 1)]));
	if (*pdep)
		ptep = pmap_pte(&p->p_vmspace->vm_pmap, va);
	else
		ptep = (pt_entry_t *)0;

	*pdepp = pdep;
	*ptepp = ptep;
}

static void
log_illegal_instruction(const char *msg, struct trapframe *frame)
{
	pt_entry_t *ptep;
	pd_entry_t *pdep;
	unsigned int *addr;
	struct thread *td;
	struct proc *p;
	register_t pc;

	td = curthread;
	p = td->td_proc;

#ifdef SMP
	printf("cpuid = %d\n", PCPU_GET(cpuid));
#endif
	pc = frame->pc + (DELAYBRANCH(frame->cause) ? 4 : 0);
	log(LOG_ERR, "%s: pid %d tid %ld (%s), uid %d: pc %#jx ra %#jx\n",
	    msg, p->p_pid, (long)td->td_tid, p->p_comm,
	    p->p_ucred ? p->p_ucred->cr_uid : -1,
	    (intmax_t)pc,
	    (intmax_t)frame->ra);

	/* log registers in trap frame */
	log_frame_dump(frame);

	get_mapping_info((vm_offset_t)pc, &pdep, &ptep);

	/*
	 * Dump a few words around faulting instruction, if the addres is
	 * valid.
	 */
	if (!(pc & 3) &&
	    useracc((caddr_t)(intptr_t)pc, sizeof(int) * 4, VM_PROT_READ)) {
		/* dump page table entry for faulting instruction */
		log(LOG_ERR, "Page table info for pc address %#jx: pde = %p, pte = %#jx\n",
		    (intmax_t)pc, (void *)(intptr_t)*pdep, (uintmax_t)(ptep ? *ptep : 0));

		addr = (unsigned int *)(intptr_t)pc;
		log(LOG_ERR, "Dumping 4 words starting at pc address %p: \n",
		    addr);
		log(LOG_ERR, "%08x %08x %08x %08x\n",
		    addr[0], addr[1], addr[2], addr[3]);
	} else {
		log(LOG_ERR, "pc address %#jx is inaccessible, pde = %p, pte = %#jx\n",
		    (intmax_t)pc, (void *)(intptr_t)*pdep, (uintmax_t)(ptep ? *ptep : 0));
	}
}

static void
log_bad_page_fault(char *msg, struct trapframe *frame, int trap_type)
{
	pt_entry_t *ptep;
	pd_entry_t *pdep;
	unsigned int *addr;
	struct thread *td;
	struct proc *p;
	char *read_or_write;
	register_t pc;

	trap_type &= ~T_USER;

	td = curthread;
	p = td->td_proc;

#ifdef SMP
	printf("cpuid = %d\n", PCPU_GET(cpuid));
#endif
	switch (trap_type) {
	case T_TLB_MOD:
	case T_TLB_ST_MISS:
	case T_ADDR_ERR_ST:
		read_or_write = "write";
		break;
	case T_TLB_LD_MISS:
	case T_ADDR_ERR_LD:
	case T_BUS_ERR_IFETCH:
		read_or_write = "read";
		break;
	default:
		read_or_write = "unknown";
	}

	pc = frame->pc + (DELAYBRANCH(frame->cause) ? 4 : 0);
	log(LOG_ERR, "%s: pid %d tid %ld (%s), uid %d: pc %#jx got a %s fault "
	    "(type %#x) at %#jx\n",
	    msg, p->p_pid, (long)td->td_tid, p->p_comm,
	    p->p_ucred ? p->p_ucred->cr_uid : -1,
	    (intmax_t)pc,
	    read_or_write,
	    trap_type,
	    (intmax_t)frame->badvaddr);

	/* log registers in trap frame */
	log_frame_dump(frame);

	get_mapping_info((vm_offset_t)pc, &pdep, &ptep);

	/*
	 * Dump a few words around faulting instruction, if the addres is
	 * valid.
	 */
	if (!(pc & 3) && (pc != frame->badvaddr) &&
	    (trap_type != T_BUS_ERR_IFETCH) &&
	    useracc((caddr_t)(intptr_t)pc, sizeof(int) * 4, VM_PROT_READ)) {
		/* dump page table entry for faulting instruction */
		log(LOG_ERR, "Page table info for pc address %#jx: pde = %p, pte = %#jx\n",
		    (intmax_t)pc, (void *)(intptr_t)*pdep, (uintmax_t)(ptep ? *ptep : 0));

		addr = (unsigned int *)(intptr_t)pc;
		log(LOG_ERR, "Dumping 4 words starting at pc address %p: \n",
		    addr);
		log(LOG_ERR, "%08x %08x %08x %08x\n",
		    addr[0], addr[1], addr[2], addr[3]);
	} else {
		log(LOG_ERR, "pc address %#jx is inaccessible, pde = %p, pte = %#jx\n",
		    (intmax_t)pc, (void *)(intptr_t)*pdep, (uintmax_t)(ptep ? *ptep : 0));
	}

	get_mapping_info((vm_offset_t)frame->badvaddr, &pdep, &ptep);
	log(LOG_ERR, "Page table info for bad address %#jx: pde = %p, pte = %#jx\n",
	    (intmax_t)frame->badvaddr, (void *)(intptr_t)*pdep, (uintmax_t)(ptep ? *ptep : 0));
}


/*
 * Unaligned load/store emulation
 */
static int
mips_unaligned_load_store(struct trapframe *frame, int mode, register_t addr, register_t pc)
{
	register_t *reg = (register_t *) frame;
	u_int32_t inst = *((u_int32_t *)(intptr_t)pc);
	register_t value_msb, value;
	unsigned size;

	/*
	 * ADDR_ERR faults have higher priority than TLB
	 * Miss faults.  Therefore, it is necessary to
	 * verify that the faulting address is a valid
	 * virtual address within the process' address space
	 * before trying to emulate the unaligned access.
	 */
	switch (MIPS_INST_OPCODE(inst)) {
	case OP_LHU: case OP_LH:
	case OP_SH:
		size = 2;
		break;
	case OP_LWU: case OP_LW:
	case OP_SW:
		size = 4;
		break;
	case OP_LD:
	case OP_SD:
		size = 8;
		break;
	default:
		printf("%s: unhandled opcode in address error: %#x\n", __func__, MIPS_INST_OPCODE(inst));
		return (0);
	}

	if (!useracc((void *)rounddown2((vm_offset_t)addr, size), size * 2, mode))
		return (0);

	/*
	 * XXX
	 * Handle LL/SC LLD/SCD.
	 */
	switch (MIPS_INST_OPCODE(inst)) {
	case OP_LHU:
		KASSERT(mode == VM_PROT_READ, ("access mode must be read for load instruction."));
		lbu_macro(value_msb, addr);
		addr += 1;
		lbu_macro(value, addr);
		value |= value_msb << 8;
		reg[MIPS_INST_RT(inst)] = value;
		return (MIPS_LHU_ACCESS);

	case OP_LH:
		KASSERT(mode == VM_PROT_READ, ("access mode must be read for load instruction."));
		lb_macro(value_msb, addr);
		addr += 1;
		lbu_macro(value, addr);
		value |= value_msb << 8;
		reg[MIPS_INST_RT(inst)] = value;
		return (MIPS_LH_ACCESS);

	case OP_LWU:
		KASSERT(mode == VM_PROT_READ, ("access mode must be read for load instruction."));
		lwl_macro(value, addr);
		addr += 3;
		lwr_macro(value, addr);
		value &= 0xffffffff;
		reg[MIPS_INST_RT(inst)] = value;
		return (MIPS_LWU_ACCESS);

	case OP_LW:
		KASSERT(mode == VM_PROT_READ, ("access mode must be read for load instruction."));
		lwl_macro(value, addr);
		addr += 3;
		lwr_macro(value, addr);
		reg[MIPS_INST_RT(inst)] = value;
		return (MIPS_LW_ACCESS);

#if defined(__mips_n32) || defined(__mips_n64)
	case OP_LD:
		KASSERT(mode == VM_PROT_READ, ("access mode must be read for load instruction."));
		ldl_macro(value, addr);
		addr += 7;
		ldr_macro(value, addr);
		reg[MIPS_INST_RT(inst)] = value;
		return (MIPS_LD_ACCESS);
#endif

	case OP_SH:
		KASSERT(mode == VM_PROT_WRITE, ("access mode must be write for store instruction."));
		value = reg[MIPS_INST_RT(inst)];
		value_msb = value >> 8;
		sb_macro(value_msb, addr);
		addr += 1;
		sb_macro(value, addr);
		return (MIPS_SH_ACCESS);

	case OP_SW:
		KASSERT(mode == VM_PROT_WRITE, ("access mode must be write for store instruction."));
		value = reg[MIPS_INST_RT(inst)];
		swl_macro(value, addr);
		addr += 3;
		swr_macro(value, addr);
		return (MIPS_SW_ACCESS);

#if defined(__mips_n32) || defined(__mips_n64)
	case OP_SD:
		KASSERT(mode == VM_PROT_WRITE, ("access mode must be write for store instruction."));
		value = reg[MIPS_INST_RT(inst)];
		sdl_macro(value, addr);
		addr += 7;
		sdr_macro(value, addr);
		return (MIPS_SD_ACCESS);
#endif
	}
	panic("%s: should not be reached.", __func__);
}


/*
 * XXX TODO: SMP?
 */
static struct timeval unaligned_lasterr;
static int unaligned_curerr;

static int unaligned_pps_log_limit = 4;

SYSCTL_INT(_machdep, OID_AUTO, unaligned_log_pps_limit, CTLFLAG_RWTUN,
    &unaligned_pps_log_limit, 0,
    "limit number of userland unaligned log messages per second");

static int
emulate_unaligned_access(struct trapframe *frame, int mode)
{
	register_t pc;
	int access_type = 0;
	struct thread *td = curthread;
	struct proc *p = curproc;

	pc = frame->pc + (DELAYBRANCH(frame->cause) ? 4 : 0);

	/*
	 * Fall through if it's instruction fetch exception
	 */
	if (!((pc & 3) || (pc == frame->badvaddr))) {

		/*
		 * Handle unaligned load and store
		 */

		/*
		 * Return access type if the instruction was emulated.
		 * Otherwise restore pc and fall through.
		 */
		access_type = mips_unaligned_load_store(frame,
		    mode, frame->badvaddr, pc);

		if (access_type) {
			if (DELAYBRANCH(frame->cause))
				frame->pc = MipsEmulateBranch(frame, frame->pc,
				    0, 0);
			else
				frame->pc += 4;

			if (ppsratecheck(&unaligned_lasterr,
			    &unaligned_curerr, unaligned_pps_log_limit)) {
				/* XXX TODO: keep global/tid/pid counters? */
				log(LOG_INFO,
				    "Unaligned %s: pid=%ld (%s), tid=%ld, "
				    "pc=%#jx, badvaddr=%#jx\n",
				    access_name[access_type - 1],
				    (long) p->p_pid,
				    p->p_comm,
				    (long) td->td_tid,
				    (intmax_t)pc,
				    (intmax_t)frame->badvaddr);
			}
		}
	}
	return access_type;
}