aboutsummaryrefslogtreecommitdiff
path: root/sys/arm64/arm64/gicv3_its.c
blob: 8ba7aa3b2047983b95ba1929eb195307e3550b66 (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
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
/*-
 * Copyright (c) 2015-2016 The FreeBSD Foundation
 * All rights reserved.
 *
 * This software was developed by Andrew Turner under
 * the sponsorship of the FreeBSD Foundation.
 *
 * This software was developed by Semihalf under
 * the sponsorship of the FreeBSD Foundation.
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 */

#include "opt_acpi.h"
#include "opt_platform.h"
#include "opt_iommu.h"

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/bus.h>
#include <sys/cpuset.h>
#include <sys/domainset.h>
#include <sys/endian.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/mutex.h>
#include <sys/proc.h>
#include <sys/taskqueue.h>
#include <sys/tree.h>
#include <sys/queue.h>
#include <sys/rman.h>
#include <sys/sbuf.h>
#include <sys/smp.h>
#include <sys/sysctl.h>
#include <sys/vmem.h>

#include <vm/vm.h>
#include <vm/pmap.h>
#include <vm/vm_page.h>

#include <machine/bus.h>
#include <machine/intr.h>

#include <arm/arm/gic_common.h>
#include <arm64/arm64/gic_v3_reg.h>
#include <arm64/arm64/gic_v3_var.h>

#ifdef FDT
#include <dev/ofw/openfirm.h>
#include <dev/ofw/ofw_bus.h>
#include <dev/ofw/ofw_bus_subr.h>
#endif
#include <dev/pci/pcireg.h>
#include <dev/pci/pcivar.h>

#ifdef IOMMU
#include <dev/iommu/iommu.h>
#include <dev/iommu/iommu_gas.h>
#endif

#include "pcib_if.h"
#include "pic_if.h"
#include "msi_if.h"

MALLOC_DEFINE(M_GICV3_ITS, "GICv3 ITS",
    "ARM GICv3 Interrupt Translation Service");

#define	LPI_NIRQS		(64 * 1024)

/* The size and alignment of the command circular buffer */
#define	ITS_CMDQ_SIZE		(64 * 1024)	/* Must be a multiple of 4K */
#define	ITS_CMDQ_ALIGN		(64 * 1024)

#define	LPI_CONFTAB_SIZE	LPI_NIRQS
#define	LPI_CONFTAB_ALIGN	(64 * 1024)
#define	LPI_CONFTAB_MAX_ADDR	((1ul << 48) - 1) /* We need a 47 bit PA */

/* 1 bit per SPI, PPI, and SGI (8k), and 1 bit per LPI (LPI_CONFTAB_SIZE) */
#define	LPI_PENDTAB_SIZE	((LPI_NIRQS + GIC_FIRST_LPI) / 8)
#define	LPI_PENDTAB_ALIGN	(64 * 1024)
#define	LPI_PENDTAB_MAX_ADDR	((1ul << 48) - 1) /* We need a 47 bit PA */

#define	LPI_INT_TRANS_TAB_ALIGN	256
#define	LPI_INT_TRANS_TAB_MAX_ADDR ((1ul << 48) - 1)

/* ITS commands encoding */
#define	ITS_CMD_MOVI		(0x01)
#define	ITS_CMD_SYNC		(0x05)
#define	ITS_CMD_MAPD		(0x08)
#define	ITS_CMD_MAPC		(0x09)
#define	ITS_CMD_MAPTI		(0x0a)
#define	ITS_CMD_MAPI		(0x0b)
#define	ITS_CMD_INV		(0x0c)
#define	ITS_CMD_INVALL		(0x0d)
/* Command */
#define	CMD_COMMAND_MASK	(0xFFUL)
/* PCI device ID */
#define	CMD_DEVID_SHIFT		(32)
#define	CMD_DEVID_MASK		(0xFFFFFFFFUL << CMD_DEVID_SHIFT)
/* Size of IRQ ID bitfield */
#define	CMD_SIZE_MASK		(0xFFUL)
/* Virtual LPI ID */
#define	CMD_ID_MASK		(0xFFFFFFFFUL)
/* Physical LPI ID */
#define	CMD_PID_SHIFT		(32)
#define	CMD_PID_MASK		(0xFFFFFFFFUL << CMD_PID_SHIFT)
/* Collection */
#define	CMD_COL_MASK		(0xFFFFUL)
/* Target (CPU or Re-Distributor) */
#define	CMD_TARGET_SHIFT	(16)
#define	CMD_TARGET_MASK		(0xFFFFFFFFUL << CMD_TARGET_SHIFT)
/* Interrupt Translation Table address */
#define	CMD_ITT_MASK		(0xFFFFFFFFFF00UL)
/* Valid command bit */
#define	CMD_VALID_SHIFT		(63)
#define	CMD_VALID_MASK		(1UL << CMD_VALID_SHIFT)

#define	ITS_TARGET_NONE		0xFBADBEEF

/* LPI chunk owned by ITS device */
struct lpi_chunk {
	u_int	lpi_base;
	u_int	lpi_free;	/* First free LPI in set */
	u_int	lpi_num;	/* Total number of LPIs in chunk */
	u_int	lpi_busy;	/* Number of busy LPIs in chink */
};

/* ITS device */
struct its_dev {
	TAILQ_ENTRY(its_dev)	entry;
	/* PCI device */
	device_t		pci_dev;
	/* Device ID (i.e. PCI device ID) */
	uint32_t		devid;
	/* List of assigned LPIs */
	struct lpi_chunk	lpis;
	/* Virtual address of ITT */
	vm_offset_t		itt;
	size_t			itt_size;
};

/*
 * ITS command descriptor.
 * Idea for command description passing taken from Linux.
 */
struct its_cmd_desc {
	uint8_t cmd_type;

	union {
		struct {
			struct its_dev *its_dev;
			struct its_col *col;
			uint32_t id;
		} cmd_desc_movi;

		struct {
			struct its_col *col;
		} cmd_desc_sync;

		struct {
			struct its_col *col;
			uint8_t valid;
		} cmd_desc_mapc;

		struct {
			struct its_dev *its_dev;
			struct its_col *col;
			uint32_t pid;
			uint32_t id;
		} cmd_desc_mapvi;

		struct {
			struct its_dev *its_dev;
			struct its_col *col;
			uint32_t pid;
		} cmd_desc_mapi;

		struct {
			struct its_dev *its_dev;
			uint8_t valid;
		} cmd_desc_mapd;

		struct {
			struct its_dev *its_dev;
			struct its_col *col;
			uint32_t pid;
		} cmd_desc_inv;

		struct {
			struct its_col *col;
		} cmd_desc_invall;
	};
};

/* ITS command. Each command is 32 bytes long */
struct its_cmd {
	uint64_t	cmd_dword[4];	/* ITS command double word */
};

/* An ITS private table */
struct its_ptable {
	vm_offset_t	ptab_vaddr;
	unsigned long	ptab_size;
};

/* ITS collection description. */
struct its_col {
	uint64_t	col_target;	/* Target Re-Distributor */
	uint64_t	col_id;		/* Collection ID */
};

struct gicv3_its_irqsrc {
	struct intr_irqsrc	gi_isrc;
	u_int			gi_id;
	u_int			gi_lpi;
	struct its_dev		*gi_its_dev;
	TAILQ_ENTRY(gicv3_its_irqsrc) gi_link;
};

struct gicv3_its_softc {
	device_t	dev;
	struct intr_pic *sc_pic;
	struct resource *sc_its_res;

	cpuset_t	sc_cpus;
	struct domainset *sc_ds;
	u_int		gic_irq_cpu;

	struct its_ptable sc_its_ptab[GITS_BASER_NUM];
	struct its_col *sc_its_cols[MAXCPU];	/* Per-CPU collections */

	/*
	 * TODO: We should get these from the parent as we only want a
	 * single copy of each across the interrupt controller.
	 */
	uint8_t		*sc_conf_base;
	vm_offset_t sc_pend_base[MAXCPU];

	/* Command handling */
	struct mtx sc_its_cmd_lock;
	struct its_cmd *sc_its_cmd_base; /* Command circular buffer address */
	size_t sc_its_cmd_next_idx;

	vmem_t *sc_irq_alloc;
	struct gicv3_its_irqsrc	**sc_irqs;
	u_int	sc_irq_base;
	u_int	sc_irq_length;
	u_int	sc_irq_count;

	struct mtx sc_its_dev_lock;
	TAILQ_HEAD(its_dev_list, its_dev) sc_its_dev_list;
	TAILQ_HEAD(free_irqs, gicv3_its_irqsrc) sc_free_irqs;

#define	ITS_FLAGS_CMDQ_FLUSH		0x00000001
#define	ITS_FLAGS_LPI_CONF_FLUSH	0x00000002
#define	ITS_FLAGS_ERRATA_CAVIUM_22375	0x00000004
	u_int sc_its_flags;
	bool	trace_enable;
	vm_page_t ma; /* fake msi page */
};

static void *conf_base;

typedef void (its_quirk_func_t)(device_t);
static its_quirk_func_t its_quirk_cavium_22375;

static const struct {
	const char *desc;
	uint32_t iidr;
	uint32_t iidr_mask;
	its_quirk_func_t *func;
} its_quirks[] = {
	{
		/* Cavium ThunderX Pass 1.x */
		.desc = "Cavium ThunderX errata: 22375, 24313",
		.iidr = GITS_IIDR_RAW(GITS_IIDR_IMPL_CAVIUM,
		    GITS_IIDR_PROD_THUNDER, GITS_IIDR_VAR_THUNDER_1, 0),
		.iidr_mask = ~GITS_IIDR_REVISION_MASK,
		.func = its_quirk_cavium_22375,
	},
};

#define	gic_its_read_4(sc, reg)			\
    bus_read_4((sc)->sc_its_res, (reg))
#define	gic_its_read_8(sc, reg)			\
    bus_read_8((sc)->sc_its_res, (reg))

#define	gic_its_write_4(sc, reg, val)		\
    bus_write_4((sc)->sc_its_res, (reg), (val))
#define	gic_its_write_8(sc, reg, val)		\
    bus_write_8((sc)->sc_its_res, (reg), (val))

static device_attach_t gicv3_its_attach;
static device_detach_t gicv3_its_detach;

static pic_disable_intr_t gicv3_its_disable_intr;
static pic_enable_intr_t gicv3_its_enable_intr;
static pic_map_intr_t gicv3_its_map_intr;
static pic_setup_intr_t gicv3_its_setup_intr;
static pic_post_filter_t gicv3_its_post_filter;
static pic_post_ithread_t gicv3_its_post_ithread;
static pic_pre_ithread_t gicv3_its_pre_ithread;
static pic_bind_intr_t gicv3_its_bind_intr;
#ifdef SMP
static pic_init_secondary_t gicv3_its_init_secondary;
#endif
static msi_alloc_msi_t gicv3_its_alloc_msi;
static msi_release_msi_t gicv3_its_release_msi;
static msi_alloc_msix_t gicv3_its_alloc_msix;
static msi_release_msix_t gicv3_its_release_msix;
static msi_map_msi_t gicv3_its_map_msi;
#ifdef IOMMU
static msi_iommu_init_t gicv3_iommu_init;
static msi_iommu_deinit_t gicv3_iommu_deinit;
#endif

static void its_cmd_movi(device_t, struct gicv3_its_irqsrc *);
static void its_cmd_mapc(device_t, struct its_col *, uint8_t);
static void its_cmd_mapti(device_t, struct gicv3_its_irqsrc *);
static void its_cmd_mapd(device_t, struct its_dev *, uint8_t);
static void its_cmd_inv(device_t, struct its_dev *, struct gicv3_its_irqsrc *);
static void its_cmd_invall(device_t, struct its_col *);

static device_method_t gicv3_its_methods[] = {
	/* Device interface */
	DEVMETHOD(device_detach,	gicv3_its_detach),

	/* Interrupt controller interface */
	DEVMETHOD(pic_disable_intr,	gicv3_its_disable_intr),
	DEVMETHOD(pic_enable_intr,	gicv3_its_enable_intr),
	DEVMETHOD(pic_map_intr,		gicv3_its_map_intr),
	DEVMETHOD(pic_setup_intr,	gicv3_its_setup_intr),
	DEVMETHOD(pic_post_filter,	gicv3_its_post_filter),
	DEVMETHOD(pic_post_ithread,	gicv3_its_post_ithread),
	DEVMETHOD(pic_pre_ithread,	gicv3_its_pre_ithread),
#ifdef SMP
	DEVMETHOD(pic_bind_intr,	gicv3_its_bind_intr),
	DEVMETHOD(pic_init_secondary,	gicv3_its_init_secondary),
#endif

	/* MSI/MSI-X */
	DEVMETHOD(msi_alloc_msi,	gicv3_its_alloc_msi),
	DEVMETHOD(msi_release_msi,	gicv3_its_release_msi),
	DEVMETHOD(msi_alloc_msix,	gicv3_its_alloc_msix),
	DEVMETHOD(msi_release_msix,	gicv3_its_release_msix),
	DEVMETHOD(msi_map_msi,		gicv3_its_map_msi),
#ifdef IOMMU
	DEVMETHOD(msi_iommu_init,	gicv3_iommu_init),
	DEVMETHOD(msi_iommu_deinit,	gicv3_iommu_deinit),
#endif

	/* End */
	DEVMETHOD_END
};

static DEFINE_CLASS_0(gic, gicv3_its_driver, gicv3_its_methods,
    sizeof(struct gicv3_its_softc));

static void
gicv3_its_cmdq_init(struct gicv3_its_softc *sc)
{
	vm_paddr_t cmd_paddr;
	uint64_t reg, tmp;

	/* Set up the command circular buffer */
	sc->sc_its_cmd_base = contigmalloc_domainset(ITS_CMDQ_SIZE, M_GICV3_ITS,
	    sc->sc_ds, M_WAITOK | M_ZERO, 0, (1ul << 48) - 1, ITS_CMDQ_ALIGN,
	    0);
	sc->sc_its_cmd_next_idx = 0;

	cmd_paddr = vtophys(sc->sc_its_cmd_base);

	/* Set the base of the command buffer */
	reg = GITS_CBASER_VALID |
	    (GITS_CBASER_CACHE_NIWAWB << GITS_CBASER_CACHE_SHIFT) |
	    cmd_paddr | (GITS_CBASER_SHARE_IS << GITS_CBASER_SHARE_SHIFT) |
	    (ITS_CMDQ_SIZE / 4096 - 1);
	gic_its_write_8(sc, GITS_CBASER, reg);

	/* Read back to check for fixed value fields */
	tmp = gic_its_read_8(sc, GITS_CBASER);

	if ((tmp & GITS_CBASER_SHARE_MASK) !=
	    (GITS_CBASER_SHARE_IS << GITS_CBASER_SHARE_SHIFT)) {
		/* Check if the hardware reported non-shareable */
		if ((tmp & GITS_CBASER_SHARE_MASK) ==
		    (GITS_CBASER_SHARE_NS << GITS_CBASER_SHARE_SHIFT)) {
			/* If so remove the cache attribute */
			reg &= ~GITS_CBASER_CACHE_MASK;
			reg &= ~GITS_CBASER_SHARE_MASK;
			/* Set to Non-cacheable, Non-shareable */
			reg |= GITS_CBASER_CACHE_NIN << GITS_CBASER_CACHE_SHIFT;
			reg |= GITS_CBASER_SHARE_NS << GITS_CBASER_SHARE_SHIFT;

			gic_its_write_8(sc, GITS_CBASER, reg);
		}

		/* The command queue has to be flushed after each command */
		sc->sc_its_flags |= ITS_FLAGS_CMDQ_FLUSH;
	}

	/* Get the next command from the start of the buffer */
	gic_its_write_8(sc, GITS_CWRITER, 0x0);
}

static int
gicv3_its_table_init(device_t dev, struct gicv3_its_softc *sc)
{
	vm_offset_t table;
	vm_paddr_t paddr;
	uint64_t cache, reg, share, tmp, type;
	size_t esize, its_tbl_size, nidents, nitspages, npages;
	int i, page_size;
	int devbits;

	if ((sc->sc_its_flags & ITS_FLAGS_ERRATA_CAVIUM_22375) != 0) {
		/*
		 * GITS_TYPER[17:13] of ThunderX reports that device IDs
		 * are to be 21 bits in length. The entry size of the ITS
		 * table can be read from GITS_BASERn[52:48] and on ThunderX
		 * is supposed to be 8 bytes in length (for device table).
		 * Finally the page size that is to be used by ITS to access
		 * this table will be set to 64KB.
		 *
		 * This gives 0x200000 entries of size 0x8 bytes covered by
		 * 256 pages each of which 64KB in size. The number of pages
		 * (minus 1) should then be written to GITS_BASERn[7:0]. In
		 * that case this value would be 0xFF but on ThunderX the
		 * maximum value that HW accepts is 0xFD.
		 *
		 * Set an arbitrary number of device ID bits to 20 in order
		 * to limit the number of entries in ITS device table to
		 * 0x100000 and the table size to 8MB.
		 */
		devbits = 20;
		cache = 0;
	} else {
		devbits = GITS_TYPER_DEVB(gic_its_read_8(sc, GITS_TYPER));
		cache = GITS_BASER_CACHE_WAWB;
	}
	share = GITS_BASER_SHARE_IS;
	page_size = PAGE_SIZE_64K;

	for (i = 0; i < GITS_BASER_NUM; i++) {
		reg = gic_its_read_8(sc, GITS_BASER(i));
		/* The type of table */
		type = GITS_BASER_TYPE(reg);
		/* The table entry size */
		esize = GITS_BASER_ESIZE(reg);

		switch(type) {
		case GITS_BASER_TYPE_DEV:
			nidents = (1 << devbits);
			its_tbl_size = esize * nidents;
			its_tbl_size = roundup2(its_tbl_size, PAGE_SIZE_64K);
			break;
		case GITS_BASER_TYPE_VP:
		case GITS_BASER_TYPE_PP: /* Undocumented? */
		case GITS_BASER_TYPE_IC:
			its_tbl_size = page_size;
			break;
		default:
			continue;
		}
		npages = howmany(its_tbl_size, PAGE_SIZE);

		/* Allocate the table */
		table = (vm_offset_t)contigmalloc_domainset(npages * PAGE_SIZE,
		    M_GICV3_ITS, sc->sc_ds, M_WAITOK | M_ZERO, 0,
		    (1ul << 48) - 1, PAGE_SIZE_64K, 0);

		sc->sc_its_ptab[i].ptab_vaddr = table;
		sc->sc_its_ptab[i].ptab_size = npages * PAGE_SIZE;

		paddr = vtophys(table);

		while (1) {
			nitspages = howmany(its_tbl_size, page_size);

			/* Clear the fields we will be setting */
			reg &= ~(GITS_BASER_VALID |
			    GITS_BASER_CACHE_MASK | GITS_BASER_TYPE_MASK |
			    GITS_BASER_ESIZE_MASK | GITS_BASER_PA_MASK |
			    GITS_BASER_SHARE_MASK | GITS_BASER_PSZ_MASK |
			    GITS_BASER_SIZE_MASK);
			/* Set the new values */
			reg |= GITS_BASER_VALID |
			    (cache << GITS_BASER_CACHE_SHIFT) |
			    (type << GITS_BASER_TYPE_SHIFT) |
			    ((esize - 1) << GITS_BASER_ESIZE_SHIFT) |
			    paddr | (share << GITS_BASER_SHARE_SHIFT) |
			    (nitspages - 1);

			switch (page_size) {
			case PAGE_SIZE_4K:	/* 4KB */
				reg |=
				    GITS_BASER_PSZ_4K << GITS_BASER_PSZ_SHIFT;
				break;
			case PAGE_SIZE_16K:	/* 16KB */
				reg |=
				    GITS_BASER_PSZ_16K << GITS_BASER_PSZ_SHIFT;
				break;
			case PAGE_SIZE_64K:	/* 64KB */
				reg |=
				    GITS_BASER_PSZ_64K << GITS_BASER_PSZ_SHIFT;
				break;
			}

			gic_its_write_8(sc, GITS_BASER(i), reg);

			/* Read back to check */
			tmp = gic_its_read_8(sc, GITS_BASER(i));

			/* Do the shareability masks line up? */
			if ((tmp & GITS_BASER_SHARE_MASK) !=
			    (reg & GITS_BASER_SHARE_MASK)) {
				share = (tmp & GITS_BASER_SHARE_MASK) >>
				    GITS_BASER_SHARE_SHIFT;
				continue;
			}

			if ((tmp & GITS_BASER_PSZ_MASK) !=
			    (reg & GITS_BASER_PSZ_MASK)) {
				switch (page_size) {
				case PAGE_SIZE_16K:
					page_size = PAGE_SIZE_4K;
					continue;
				case PAGE_SIZE_64K:
					page_size = PAGE_SIZE_16K;
					continue;
				}
			}

			if (tmp != reg) {
				device_printf(dev, "GITS_BASER%d: "
				    "unable to be updated: %lx != %lx\n",
				    i, reg, tmp);
				return (ENXIO);
			}

			/* We should have made all needed changes */
			break;
		}
	}

	return (0);
}

static void
gicv3_its_conftable_init(struct gicv3_its_softc *sc)
{
	void *conf_table;

	conf_table = atomic_load_ptr(&conf_base);
	if (conf_table == NULL) {
		conf_table = contigmalloc(LPI_CONFTAB_SIZE,
		    M_GICV3_ITS, M_WAITOK, 0, LPI_CONFTAB_MAX_ADDR,
		    LPI_CONFTAB_ALIGN, 0);

		if (atomic_cmpset_ptr((uintptr_t *)&conf_base,
		    (uintptr_t)NULL, (uintptr_t)conf_table) == 0) {
			contigfree(conf_table, LPI_CONFTAB_SIZE, M_GICV3_ITS);
			conf_table = atomic_load_ptr(&conf_base);
		}
	}
	sc->sc_conf_base = conf_table;

	/* Set the default configuration */
	memset(sc->sc_conf_base, GIC_PRIORITY_MAX | LPI_CONF_GROUP1,
	    LPI_CONFTAB_SIZE);

	/* Flush the table to memory */
	cpu_dcache_wb_range((vm_offset_t)sc->sc_conf_base, LPI_CONFTAB_SIZE);
}

static void
gicv3_its_pendtables_init(struct gicv3_its_softc *sc)
{
	int i;

	for (i = 0; i <= mp_maxid; i++) {
		if (CPU_ISSET(i, &sc->sc_cpus) == 0)
			continue;

		sc->sc_pend_base[i] = (vm_offset_t)contigmalloc(
		    LPI_PENDTAB_SIZE, M_GICV3_ITS, M_WAITOK | M_ZERO,
		    0, LPI_PENDTAB_MAX_ADDR, LPI_PENDTAB_ALIGN, 0);

		/* Flush so the ITS can see the memory */
		cpu_dcache_wb_range((vm_offset_t)sc->sc_pend_base[i],
		    LPI_PENDTAB_SIZE);
	}
}

static void
its_init_cpu_lpi(device_t dev, struct gicv3_its_softc *sc)
{
	device_t gicv3;
	uint64_t xbaser, tmp;
	uint32_t ctlr;
	u_int cpuid;

	gicv3 = device_get_parent(dev);
	cpuid = PCPU_GET(cpuid);

	/* Disable LPIs */
	ctlr = gic_r_read_4(gicv3, GICR_CTLR);
	ctlr &= ~GICR_CTLR_LPI_ENABLE;
	gic_r_write_4(gicv3, GICR_CTLR, ctlr);

	/* Make sure changes are observable my the GIC */
	dsb(sy);

	/*
	 * Set the redistributor base
	 */
	xbaser = vtophys(sc->sc_conf_base) |
	    (GICR_PROPBASER_SHARE_IS << GICR_PROPBASER_SHARE_SHIFT) |
	    (GICR_PROPBASER_CACHE_NIWAWB << GICR_PROPBASER_CACHE_SHIFT) |
	    (flsl(LPI_CONFTAB_SIZE | GIC_FIRST_LPI) - 1);
	gic_r_write_8(gicv3, GICR_PROPBASER, xbaser);

	/* Check the cache attributes we set */
	tmp = gic_r_read_8(gicv3, GICR_PROPBASER);

	if ((tmp & GICR_PROPBASER_SHARE_MASK) !=
	    (xbaser & GICR_PROPBASER_SHARE_MASK)) {
		if ((tmp & GICR_PROPBASER_SHARE_MASK) ==
		    (GICR_PROPBASER_SHARE_NS << GICR_PROPBASER_SHARE_SHIFT)) {
			/* We need to mark as non-cacheable */
			xbaser &= ~(GICR_PROPBASER_SHARE_MASK |
			    GICR_PROPBASER_CACHE_MASK);
			/* Non-cacheable */
			xbaser |= GICR_PROPBASER_CACHE_NIN <<
			    GICR_PROPBASER_CACHE_SHIFT;
			/* Non-sareable */
			xbaser |= GICR_PROPBASER_SHARE_NS <<
			    GICR_PROPBASER_SHARE_SHIFT;
			gic_r_write_8(gicv3, GICR_PROPBASER, xbaser);
		}
		sc->sc_its_flags |= ITS_FLAGS_LPI_CONF_FLUSH;
	}

	/*
	 * Set the LPI pending table base
	 */
	xbaser = vtophys(sc->sc_pend_base[cpuid]) |
	    (GICR_PENDBASER_CACHE_NIWAWB << GICR_PENDBASER_CACHE_SHIFT) |
	    (GICR_PENDBASER_SHARE_IS << GICR_PENDBASER_SHARE_SHIFT);

	gic_r_write_8(gicv3, GICR_PENDBASER, xbaser);

	tmp = gic_r_read_8(gicv3, GICR_PENDBASER);

	if ((tmp & GICR_PENDBASER_SHARE_MASK) ==
	    (GICR_PENDBASER_SHARE_NS << GICR_PENDBASER_SHARE_SHIFT)) {
		/* Clear the cahce and shareability bits */
		xbaser &= ~(GICR_PENDBASER_CACHE_MASK |
		    GICR_PENDBASER_SHARE_MASK);
		/* Mark as non-shareable */
		xbaser |= GICR_PENDBASER_SHARE_NS << GICR_PENDBASER_SHARE_SHIFT;
		/* And non-cacheable */
		xbaser |= GICR_PENDBASER_CACHE_NIN <<
		    GICR_PENDBASER_CACHE_SHIFT;
	}

	/* Enable LPIs */
	ctlr = gic_r_read_4(gicv3, GICR_CTLR);
	ctlr |= GICR_CTLR_LPI_ENABLE;
	gic_r_write_4(gicv3, GICR_CTLR, ctlr);

	/* Make sure the GIC has seen everything */
	dsb(sy);
}

static int
its_init_cpu(device_t dev, struct gicv3_its_softc *sc)
{
	device_t gicv3;
	vm_paddr_t target;
	u_int cpuid;
	struct redist_pcpu *rpcpu;

	gicv3 = device_get_parent(dev);
	cpuid = PCPU_GET(cpuid);
	if (!CPU_ISSET(cpuid, &sc->sc_cpus))
		return (0);

	/* Check if the ITS is enabled on this CPU */
	if ((gic_r_read_4(gicv3, GICR_TYPER) & GICR_TYPER_PLPIS) == 0)
		return (ENXIO);

	rpcpu = gicv3_get_redist(dev);

	/* Do per-cpu LPI init once */
	if (!rpcpu->lpi_enabled) {
		its_init_cpu_lpi(dev, sc);
		rpcpu->lpi_enabled = true;
	}

	if ((gic_its_read_8(sc, GITS_TYPER) & GITS_TYPER_PTA) != 0) {
		/* This ITS wants the redistributor physical address */
		target = vtophys(rman_get_virtual(&rpcpu->res));
	} else {
		/* This ITS wants the unique processor number */
		target = GICR_TYPER_CPUNUM(gic_r_read_8(gicv3, GICR_TYPER)) <<
		    CMD_TARGET_SHIFT;
	}

	sc->sc_its_cols[cpuid]->col_target = target;
	sc->sc_its_cols[cpuid]->col_id = cpuid;

	its_cmd_mapc(dev, sc->sc_its_cols[cpuid], 1);
	its_cmd_invall(dev, sc->sc_its_cols[cpuid]);

	return (0);
}

static int
gicv3_its_sysctl_trace_enable(SYSCTL_HANDLER_ARGS)
{
	struct gicv3_its_softc *sc;
	int rv;

	sc = arg1;

	rv = sysctl_handle_bool(oidp, &sc->trace_enable, 0, req);
	if (rv != 0 || req->newptr == NULL)
		return (rv);
	if (sc->trace_enable)
		gic_its_write_8(sc, GITS_TRKCTLR, 3);
	else
		gic_its_write_8(sc, GITS_TRKCTLR, 0);

	return (0);
}

static int
gicv3_its_sysctl_trace_regs(SYSCTL_HANDLER_ARGS)
{
	struct gicv3_its_softc *sc;
	struct sbuf *sb;
	int err;

	sc = arg1;
	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
	if (sb == NULL) {
		device_printf(sc->dev, "Could not allocate sbuf for output.\n");
		return (ENOMEM);
	}
	sbuf_cat(sb, "\n");
	sbuf_printf(sb, "GITS_TRKCTLR: 0x%08X\n",
	    gic_its_read_4(sc, GITS_TRKCTLR));
	sbuf_printf(sb, "GITS_TRKR:    0x%08X\n",
	    gic_its_read_4(sc, GITS_TRKR));
	sbuf_printf(sb, "GITS_TRKDIDR: 0x%08X\n",
	    gic_its_read_4(sc, GITS_TRKDIDR));
	sbuf_printf(sb, "GITS_TRKPIDR: 0x%08X\n",
	    gic_its_read_4(sc, GITS_TRKPIDR));
	sbuf_printf(sb, "GITS_TRKVIDR: 0x%08X\n",
	    gic_its_read_4(sc, GITS_TRKVIDR));
	sbuf_printf(sb, "GITS_TRKTGTR: 0x%08X\n",
	   gic_its_read_4(sc, GITS_TRKTGTR));

	err = sbuf_finish(sb);
	if (err)
		device_printf(sc->dev, "Error finishing sbuf: %d\n", err);
	sbuf_delete(sb);
	return(err);
}

static int
gicv3_its_init_sysctl(struct gicv3_its_softc *sc)
{
	struct sysctl_oid *oid, *child;
	struct sysctl_ctx_list *ctx_list;

	ctx_list = device_get_sysctl_ctx(sc->dev);
	child = device_get_sysctl_tree(sc->dev);
	oid = SYSCTL_ADD_NODE(ctx_list,
	    SYSCTL_CHILDREN(child), OID_AUTO, "tracing",
	    CTLFLAG_RD| CTLFLAG_MPSAFE, NULL, "Messages tracing");
	if (oid == NULL)
		return (ENXIO);

	/* Add registers */
	SYSCTL_ADD_PROC(ctx_list,
	    SYSCTL_CHILDREN(oid), OID_AUTO, "enable",
	    CTLTYPE_U8 | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
	    gicv3_its_sysctl_trace_enable, "CU", "Enable tracing");
	SYSCTL_ADD_PROC(ctx_list,
	    SYSCTL_CHILDREN(oid), OID_AUTO, "capture",
	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
	    gicv3_its_sysctl_trace_regs, "", "Captured tracing registers.");

	return (0);
}

static int
gicv3_its_attach(device_t dev)
{
	struct gicv3_its_softc *sc;
	int domain, err, i, rid;
	uint64_t phys;
	uint32_t iidr;

	sc = device_get_softc(dev);

	sc->sc_irq_length = gicv3_get_nirqs(dev);
	sc->sc_irq_base = GIC_FIRST_LPI;
	sc->sc_irq_base += device_get_unit(dev) * sc->sc_irq_length;

	rid = 0;
	sc->sc_its_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
	    RF_ACTIVE);
	if (sc->sc_its_res == NULL) {
		device_printf(dev, "Could not allocate memory\n");
		return (ENXIO);
	}

	phys = rounddown2(vtophys(rman_get_virtual(sc->sc_its_res)) +
	    GITS_TRANSLATER, PAGE_SIZE);
	sc->ma = malloc(sizeof(struct vm_page), M_DEVBUF, M_WAITOK | M_ZERO);
	vm_page_initfake(sc->ma, phys, VM_MEMATTR_DEFAULT);

	CPU_COPY(&all_cpus, &sc->sc_cpus);
	iidr = gic_its_read_4(sc, GITS_IIDR);
	for (i = 0; i < nitems(its_quirks); i++) {
		if ((iidr & its_quirks[i].iidr_mask) == its_quirks[i].iidr) {
			if (bootverbose) {
				device_printf(dev, "Applying %s\n",
				    its_quirks[i].desc);
			}
			its_quirks[i].func(dev);
			break;
		}
	}

	if (bus_get_domain(dev, &domain) == 0 && domain < MAXMEMDOM) {
		sc->sc_ds = DOMAINSET_PREF(domain);
	} else {
		sc->sc_ds = DOMAINSET_RR();
	}

	/* Allocate the private tables */
	err = gicv3_its_table_init(dev, sc);
	if (err != 0)
		return (err);

	/* Protects access to the device list */
	mtx_init(&sc->sc_its_dev_lock, "ITS device lock", NULL, MTX_SPIN);

	/* Protects access to the ITS command circular buffer. */
	mtx_init(&sc->sc_its_cmd_lock, "ITS cmd lock", NULL, MTX_SPIN);

	/* Allocate the command circular buffer */
	gicv3_its_cmdq_init(sc);

	/* Allocate the per-CPU collections */
	for (int cpu = 0; cpu <= mp_maxid; cpu++)
		if (CPU_ISSET(cpu, &sc->sc_cpus) != 0)
			sc->sc_its_cols[cpu] = malloc_domainset(
			    sizeof(*sc->sc_its_cols[0]), M_GICV3_ITS,
			    DOMAINSET_PREF(pcpu_find(cpu)->pc_domain),
			    M_WAITOK | M_ZERO);
		else
			sc->sc_its_cols[cpu] = NULL;

	/* Enable the ITS */
	gic_its_write_4(sc, GITS_CTLR,
	    gic_its_read_4(sc, GITS_CTLR) | GITS_CTLR_EN);

	/* Create the LPI configuration table */
	gicv3_its_conftable_init(sc);

	/* And the pending tebles */
	gicv3_its_pendtables_init(sc);

	/* Enable LPIs on this CPU */
	its_init_cpu(dev, sc);

	TAILQ_INIT(&sc->sc_its_dev_list);
	TAILQ_INIT(&sc->sc_free_irqs);

	/*
	 * Create the vmem object to allocate INTRNG IRQs from. We try to
	 * use all IRQs not already used by the GICv3.
	 * XXX: This assumes there are no other interrupt controllers in the
	 * system.
	 */
	sc->sc_irq_alloc = vmem_create(device_get_nameunit(dev), 0,
	    gicv3_get_nirqs(dev), 1, 0, M_FIRSTFIT | M_WAITOK);

	sc->sc_irqs = malloc(sizeof(*sc->sc_irqs) * sc->sc_irq_length,
	    M_GICV3_ITS, M_WAITOK | M_ZERO);

	/* For GIC-500 install tracking sysctls. */
	if ((iidr & (GITS_IIDR_PRODUCT_MASK | GITS_IIDR_IMPLEMENTOR_MASK)) ==
	    GITS_IIDR_RAW(GITS_IIDR_IMPL_ARM, GITS_IIDR_PROD_GIC500, 0, 0))
		gicv3_its_init_sysctl(sc);

	return (0);
}

static int
gicv3_its_detach(device_t dev)
{

	return (ENXIO);
}

static void
its_quirk_cavium_22375(device_t dev)
{
	struct gicv3_its_softc *sc;
	int domain;

	sc = device_get_softc(dev);
	sc->sc_its_flags |= ITS_FLAGS_ERRATA_CAVIUM_22375;

	/*
	 * We need to limit which CPUs we send these interrupts to on
	 * the original dual socket ThunderX as it is unable to
	 * forward them between the two sockets.
	 */
	if (bus_get_domain(dev, &domain) == 0) {
		if (domain < MAXMEMDOM) {
			CPU_COPY(&cpuset_domain[domain], &sc->sc_cpus);
		} else {
			CPU_ZERO(&sc->sc_cpus);
		}
	}
}

static void
gicv3_its_disable_intr(device_t dev, struct intr_irqsrc *isrc)
{
	struct gicv3_its_softc *sc;
	struct gicv3_its_irqsrc *girq;
	uint8_t *conf;

	sc = device_get_softc(dev);
	girq = (struct gicv3_its_irqsrc *)isrc;
	conf = sc->sc_conf_base;

	conf[girq->gi_lpi] &= ~LPI_CONF_ENABLE;

	if ((sc->sc_its_flags & ITS_FLAGS_LPI_CONF_FLUSH) != 0) {
		/* Clean D-cache under command. */
		cpu_dcache_wb_range((vm_offset_t)&conf[girq->gi_lpi], 1);
	} else {
		/* DSB inner shareable, store */
		dsb(ishst);
	}

	its_cmd_inv(dev, girq->gi_its_dev, girq);
}

static void
gicv3_its_enable_intr(device_t dev, struct intr_irqsrc *isrc)
{
	struct gicv3_its_softc *sc;
	struct gicv3_its_irqsrc *girq;
	uint8_t *conf;

	sc = device_get_softc(dev);
	girq = (struct gicv3_its_irqsrc *)isrc;
	conf = sc->sc_conf_base;

	conf[girq->gi_lpi] |= LPI_CONF_ENABLE;

	if ((sc->sc_its_flags & ITS_FLAGS_LPI_CONF_FLUSH) != 0) {
		/* Clean D-cache under command. */
		cpu_dcache_wb_range((vm_offset_t)&conf[girq->gi_lpi], 1);
	} else {
		/* DSB inner shareable, store */
		dsb(ishst);
	}

	its_cmd_inv(dev, girq->gi_its_dev, girq);
}

static int
gicv3_its_intr(void *arg, uintptr_t irq)
{
	struct gicv3_its_softc *sc = arg;
	struct gicv3_its_irqsrc *girq;
	struct trapframe *tf;

	irq -= sc->sc_irq_base;
	girq = sc->sc_irqs[irq];
	if (girq == NULL)
		panic("gicv3_its_intr: Invalid interrupt %ld",
		    irq + sc->sc_irq_base);

	tf = curthread->td_intr_frame;
	intr_isrc_dispatch(&girq->gi_isrc, tf);
	return (FILTER_HANDLED);
}

static void
gicv3_its_pre_ithread(device_t dev, struct intr_irqsrc *isrc)
{
	struct gicv3_its_irqsrc *girq;
	struct gicv3_its_softc *sc;

	sc = device_get_softc(dev);
	girq = (struct gicv3_its_irqsrc *)isrc;
	gic_icc_write(EOIR1, girq->gi_lpi + GIC_FIRST_LPI);
}

static void
gicv3_its_post_ithread(device_t dev, struct intr_irqsrc *isrc)
{

}

static void
gicv3_its_post_filter(device_t dev, struct intr_irqsrc *isrc)
{
	struct gicv3_its_irqsrc *girq;
	struct gicv3_its_softc *sc;

	sc = device_get_softc(dev);
	girq = (struct gicv3_its_irqsrc *)isrc;
	gic_icc_write(EOIR1, girq->gi_lpi + GIC_FIRST_LPI);
}

static int
gicv3_its_select_cpu(device_t dev, struct intr_irqsrc *isrc)
{
	struct gicv3_its_softc *sc;

	sc = device_get_softc(dev);
	if (CPU_EMPTY(&isrc->isrc_cpu)) {
		sc->gic_irq_cpu = intr_irq_next_cpu(sc->gic_irq_cpu,
		    &sc->sc_cpus);
		CPU_SETOF(sc->gic_irq_cpu, &isrc->isrc_cpu);
	}

	return (0);
}

static int
gicv3_its_bind_intr(device_t dev, struct intr_irqsrc *isrc)
{
	struct gicv3_its_irqsrc *girq;

	gicv3_its_select_cpu(dev, isrc);

	girq = (struct gicv3_its_irqsrc *)isrc;
	its_cmd_movi(dev, girq);
	return (0);
}

static int
gicv3_its_map_intr(device_t dev, struct intr_map_data *data,
    struct intr_irqsrc **isrcp)
{

	/*
	 * This should never happen, we only call this function to map
	 * interrupts found before the controller driver is ready.
	 */
	panic("gicv3_its_map_intr: Unable to map a MSI interrupt");
}

static int
gicv3_its_setup_intr(device_t dev, struct intr_irqsrc *isrc,
    struct resource *res, struct intr_map_data *data)
{

	/* Bind the interrupt to a CPU */
	gicv3_its_bind_intr(dev, isrc);

	return (0);
}

#ifdef SMP
static void
gicv3_its_init_secondary(device_t dev)
{
	struct gicv3_its_softc *sc;

	sc = device_get_softc(dev);

	/*
	 * This is fatal as otherwise we may bind interrupts to this CPU.
	 * We need a way to tell the interrupt framework to only bind to a
	 * subset of given CPUs when it performs the shuffle.
	 */
	if (its_init_cpu(dev, sc) != 0)
		panic("gicv3_its_init_secondary: No usable ITS on CPU%d",
		    PCPU_GET(cpuid));
}
#endif

static uint32_t
its_get_devid(device_t pci_dev)
{
	uintptr_t id;

	if (pci_get_id(pci_dev, PCI_ID_MSI, &id) != 0)
		panic("its_get_devid: Unable to get the MSI DeviceID");

	return (id);
}

static struct its_dev *
its_device_find(device_t dev, device_t child)
{
	struct gicv3_its_softc *sc;
	struct its_dev *its_dev = NULL;

	sc = device_get_softc(dev);

	mtx_lock_spin(&sc->sc_its_dev_lock);
	TAILQ_FOREACH(its_dev, &sc->sc_its_dev_list, entry) {
		if (its_dev->pci_dev == child)
			break;
	}
	mtx_unlock_spin(&sc->sc_its_dev_lock);

	return (its_dev);
}

static struct its_dev *
its_device_get(device_t dev, device_t child, u_int nvecs)
{
	struct gicv3_its_softc *sc;
	struct its_dev *its_dev;
	vmem_addr_t irq_base;
	size_t esize;

	sc = device_get_softc(dev);

	its_dev = its_device_find(dev, child);
	if (its_dev != NULL)
		return (its_dev);

	its_dev = malloc(sizeof(*its_dev), M_GICV3_ITS, M_NOWAIT | M_ZERO);
	if (its_dev == NULL)
		return (NULL);

	its_dev->pci_dev = child;
	its_dev->devid = its_get_devid(child);

	its_dev->lpis.lpi_busy = 0;
	its_dev->lpis.lpi_num = nvecs;
	its_dev->lpis.lpi_free = nvecs;

	if (vmem_alloc(sc->sc_irq_alloc, nvecs, M_FIRSTFIT | M_NOWAIT,
	    &irq_base) != 0) {
		free(its_dev, M_GICV3_ITS);
		return (NULL);
	}
	its_dev->lpis.lpi_base = irq_base;

	/* Get ITT entry size */
	esize = GITS_TYPER_ITTES(gic_its_read_8(sc, GITS_TYPER));

	/*
	 * Allocate ITT for this device.
	 * PA has to be 256 B aligned. At least two entries for device.
	 */
	its_dev->itt_size = roundup2(MAX(nvecs, 2) * esize, 256);
	its_dev->itt = (vm_offset_t)contigmalloc_domainset(its_dev->itt_size,
	    M_GICV3_ITS, sc->sc_ds, M_NOWAIT | M_ZERO, 0,
	    LPI_INT_TRANS_TAB_MAX_ADDR, LPI_INT_TRANS_TAB_ALIGN, 0);
	if (its_dev->itt == 0) {
		vmem_free(sc->sc_irq_alloc, its_dev->lpis.lpi_base, nvecs);
		free(its_dev, M_GICV3_ITS);
		return (NULL);
	}

	/* Make sure device sees zeroed ITT. */
	if ((sc->sc_its_flags & ITS_FLAGS_CMDQ_FLUSH) != 0)
		cpu_dcache_wb_range(its_dev->itt, its_dev->itt_size);

	mtx_lock_spin(&sc->sc_its_dev_lock);
	TAILQ_INSERT_TAIL(&sc->sc_its_dev_list, its_dev, entry);
	mtx_unlock_spin(&sc->sc_its_dev_lock);

	/* Map device to its ITT */
	its_cmd_mapd(dev, its_dev, 1);

	return (its_dev);
}

static void
its_device_release(device_t dev, struct its_dev *its_dev)
{
	struct gicv3_its_softc *sc;

	KASSERT(its_dev->lpis.lpi_busy == 0,
	    ("its_device_release: Trying to release an inuse ITS device"));

	/* Unmap device in ITS */
	its_cmd_mapd(dev, its_dev, 0);

	sc = device_get_softc(dev);

	/* Remove the device from the list of devices */
	mtx_lock_spin(&sc->sc_its_dev_lock);
	TAILQ_REMOVE(&sc->sc_its_dev_list, its_dev, entry);
	mtx_unlock_spin(&sc->sc_its_dev_lock);

	/* Free ITT */
	KASSERT(its_dev->itt != 0, ("Invalid ITT in valid ITS device"));
	contigfree((void *)its_dev->itt, its_dev->itt_size, M_GICV3_ITS);

	/* Free the IRQ allocation */
	vmem_free(sc->sc_irq_alloc, its_dev->lpis.lpi_base,
	    its_dev->lpis.lpi_num);

	free(its_dev, M_GICV3_ITS);
}

static struct gicv3_its_irqsrc *
gicv3_its_alloc_irqsrc(device_t dev, struct gicv3_its_softc *sc, u_int irq)
{
	struct gicv3_its_irqsrc *girq = NULL;

	KASSERT(sc->sc_irqs[irq] == NULL,
	    ("%s: Interrupt %u already allocated", __func__, irq));
	mtx_lock_spin(&sc->sc_its_dev_lock);
	if (!TAILQ_EMPTY(&sc->sc_free_irqs)) {
		girq = TAILQ_FIRST(&sc->sc_free_irqs);
		TAILQ_REMOVE(&sc->sc_free_irqs, girq, gi_link);
	}
	mtx_unlock_spin(&sc->sc_its_dev_lock);
	if (girq == NULL) {
		girq = malloc(sizeof(*girq), M_GICV3_ITS,
		    M_NOWAIT | M_ZERO);
		if (girq == NULL)
			return (NULL);
		girq->gi_id = -1;
		if (intr_isrc_register(&girq->gi_isrc, dev, 0,
		    "%s,%u", device_get_nameunit(dev), irq) != 0) {
			free(girq, M_GICV3_ITS);
			return (NULL);
		}
	}
	girq->gi_lpi = irq + sc->sc_irq_base - GIC_FIRST_LPI;
	sc->sc_irqs[irq] = girq;

	return (girq);
}

static void
gicv3_its_release_irqsrc(struct gicv3_its_softc *sc,
    struct gicv3_its_irqsrc *girq)
{
	u_int irq;

	mtx_assert(&sc->sc_its_dev_lock, MA_OWNED);

	irq = girq->gi_lpi + GIC_FIRST_LPI - sc->sc_irq_base;
	sc->sc_irqs[irq] = NULL;

	girq->gi_id = -1;
	girq->gi_its_dev = NULL;
	TAILQ_INSERT_TAIL(&sc->sc_free_irqs, girq, gi_link);
}

static int
gicv3_its_alloc_msi(device_t dev, device_t child, int count, int maxcount,
    device_t *pic, struct intr_irqsrc **srcs)
{
	struct gicv3_its_softc *sc;
	struct gicv3_its_irqsrc *girq;
	struct its_dev *its_dev;
	u_int irq;
	int i;

	its_dev = its_device_get(dev, child, count);
	if (its_dev == NULL)
		return (ENXIO);

	KASSERT(its_dev->lpis.lpi_free >= count,
	    ("gicv3_its_alloc_msi: No free LPIs"));
	sc = device_get_softc(dev);
	irq = its_dev->lpis.lpi_base + its_dev->lpis.lpi_num -
	    its_dev->lpis.lpi_free;

	/* Allocate the irqsrc for each MSI */
	for (i = 0; i < count; i++, irq++) {
		its_dev->lpis.lpi_free--;
		srcs[i] = (struct intr_irqsrc *)gicv3_its_alloc_irqsrc(dev,
		    sc, irq);
		if (srcs[i] == NULL)
			break;
	}

	/* The allocation failed, release them */
	if (i != count) {
		mtx_lock_spin(&sc->sc_its_dev_lock);
		for (i = 0; i < count; i++) {
			girq = (struct gicv3_its_irqsrc *)srcs[i];
			if (girq == NULL)
				break;
			gicv3_its_release_irqsrc(sc, girq);
			srcs[i] = NULL;
		}
		mtx_unlock_spin(&sc->sc_its_dev_lock);
		return (ENXIO);
	}

	/* Finish the allocation now we have all MSI irqsrcs */
	for (i = 0; i < count; i++) {
		girq = (struct gicv3_its_irqsrc *)srcs[i];
		girq->gi_id = i;
		girq->gi_its_dev = its_dev;

		/* Map the message to the given IRQ */
		gicv3_its_select_cpu(dev, (struct intr_irqsrc *)girq);
		its_cmd_mapti(dev, girq);
	}
	its_dev->lpis.lpi_busy += count;
	*pic = dev;

	return (0);
}

static int
gicv3_its_release_msi(device_t dev, device_t child, int count,
    struct intr_irqsrc **isrc)
{
	struct gicv3_its_softc *sc;
	struct gicv3_its_irqsrc *girq;
	struct its_dev *its_dev;
	int i;

	its_dev = its_device_find(dev, child);

	KASSERT(its_dev != NULL,
	    ("gicv3_its_release_msi: Releasing a MSI interrupt with "
	     "no ITS device"));
	KASSERT(its_dev->lpis.lpi_busy >= count,
	    ("gicv3_its_release_msi: Releasing more interrupts than "
	     "were allocated: releasing %d, allocated %d", count,
	     its_dev->lpis.lpi_busy));

	sc = device_get_softc(dev);
	mtx_lock_spin(&sc->sc_its_dev_lock);
	for (i = 0; i < count; i++) {
		girq = (struct gicv3_its_irqsrc *)isrc[i];
		gicv3_its_release_irqsrc(sc, girq);
	}
	mtx_unlock_spin(&sc->sc_its_dev_lock);
	its_dev->lpis.lpi_busy -= count;

	if (its_dev->lpis.lpi_busy == 0)
		its_device_release(dev, its_dev);

	return (0);
}

static int
gicv3_its_alloc_msix(device_t dev, device_t child, device_t *pic,
    struct intr_irqsrc **isrcp)
{
	struct gicv3_its_softc *sc;
	struct gicv3_its_irqsrc *girq;
	struct its_dev *its_dev;
	u_int nvecs, irq;

	nvecs = pci_msix_count(child);
	its_dev = its_device_get(dev, child, nvecs);
	if (its_dev == NULL)
		return (ENXIO);

	KASSERT(its_dev->lpis.lpi_free > 0,
	    ("gicv3_its_alloc_msix: No free LPIs"));
	sc = device_get_softc(dev);
	irq = its_dev->lpis.lpi_base + its_dev->lpis.lpi_num -
	    its_dev->lpis.lpi_free;

	girq = gicv3_its_alloc_irqsrc(dev, sc, irq);
	if (girq == NULL)
		return (ENXIO);
	girq->gi_id = its_dev->lpis.lpi_busy;
	girq->gi_its_dev = its_dev;

	its_dev->lpis.lpi_free--;
	its_dev->lpis.lpi_busy++;

	/* Map the message to the given IRQ */
	gicv3_its_select_cpu(dev, (struct intr_irqsrc *)girq);
	its_cmd_mapti(dev, girq);

	*pic = dev;
	*isrcp = (struct intr_irqsrc *)girq;

	return (0);
}

static int
gicv3_its_release_msix(device_t dev, device_t child, struct intr_irqsrc *isrc)
{
	struct gicv3_its_softc *sc;
	struct gicv3_its_irqsrc *girq;
	struct its_dev *its_dev;

	its_dev = its_device_find(dev, child);

	KASSERT(its_dev != NULL,
	    ("gicv3_its_release_msix: Releasing a MSI-X interrupt with "
	     "no ITS device"));
	KASSERT(its_dev->lpis.lpi_busy > 0,
	    ("gicv3_its_release_msix: Releasing more interrupts than "
	     "were allocated: allocated %d", its_dev->lpis.lpi_busy));

	sc = device_get_softc(dev);
	girq = (struct gicv3_its_irqsrc *)isrc;
	mtx_lock_spin(&sc->sc_its_dev_lock);
	gicv3_its_release_irqsrc(sc, girq);
	mtx_unlock_spin(&sc->sc_its_dev_lock);
	its_dev->lpis.lpi_busy--;

	if (its_dev->lpis.lpi_busy == 0)
		its_device_release(dev, its_dev);

	return (0);
}

static int
gicv3_its_map_msi(device_t dev, device_t child, struct intr_irqsrc *isrc,
    uint64_t *addr, uint32_t *data)
{
	struct gicv3_its_softc *sc;
	struct gicv3_its_irqsrc *girq;

	sc = device_get_softc(dev);
	girq = (struct gicv3_its_irqsrc *)isrc;

	*addr = vtophys(rman_get_virtual(sc->sc_its_res)) + GITS_TRANSLATER;
	*data = girq->gi_id;

	return (0);
}

#ifdef IOMMU
static int
gicv3_iommu_init(device_t dev, device_t child, struct iommu_domain **domain)
{
	struct gicv3_its_softc *sc;
	struct iommu_ctx *ctx;
	int error;

	sc = device_get_softc(dev);
	ctx = iommu_get_dev_ctx(child);
	error = iommu_map_msi(ctx, PAGE_SIZE, GITS_TRANSLATER,
	    IOMMU_MAP_ENTRY_WRITE, IOMMU_MF_CANWAIT, &sc->ma);
	*domain = iommu_get_ctx_domain(ctx);

	return (error);
}

static void
gicv3_iommu_deinit(device_t dev, device_t child)
{
	struct iommu_ctx *ctx;

	ctx = iommu_get_dev_ctx(child);
	iommu_unmap_msi(ctx);
}
#endif

/*
 * Commands handling.
 */

static __inline void
cmd_format_command(struct its_cmd *cmd, uint8_t cmd_type)
{
	/* Command field: DW0 [7:0] */
	cmd->cmd_dword[0] &= htole64(~CMD_COMMAND_MASK);
	cmd->cmd_dword[0] |= htole64(cmd_type);
}

static __inline void
cmd_format_devid(struct its_cmd *cmd, uint32_t devid)
{
	/* Device ID field: DW0 [63:32] */
	cmd->cmd_dword[0] &= htole64(~CMD_DEVID_MASK);
	cmd->cmd_dword[0] |= htole64((uint64_t)devid << CMD_DEVID_SHIFT);
}

static __inline void
cmd_format_size(struct its_cmd *cmd, uint16_t size)
{
	/* Size field: DW1 [4:0] */
	cmd->cmd_dword[1] &= htole64(~CMD_SIZE_MASK);
	cmd->cmd_dword[1] |= htole64((size & CMD_SIZE_MASK));
}

static __inline void
cmd_format_id(struct its_cmd *cmd, uint32_t id)
{
	/* ID field: DW1 [31:0] */
	cmd->cmd_dword[1] &= htole64(~CMD_ID_MASK);
	cmd->cmd_dword[1] |= htole64(id);
}

static __inline void
cmd_format_pid(struct its_cmd *cmd, uint32_t pid)
{
	/* Physical ID field: DW1 [63:32] */
	cmd->cmd_dword[1] &= htole64(~CMD_PID_MASK);
	cmd->cmd_dword[1] |= htole64((uint64_t)pid << CMD_PID_SHIFT);
}

static __inline void
cmd_format_col(struct its_cmd *cmd, uint16_t col_id)
{
	/* Collection field: DW2 [16:0] */
	cmd->cmd_dword[2] &= htole64(~CMD_COL_MASK);
	cmd->cmd_dword[2] |= htole64(col_id);
}

static __inline void
cmd_format_target(struct its_cmd *cmd, uint64_t target)
{
	/* Target Address field: DW2 [47:16] */
	cmd->cmd_dword[2] &= htole64(~CMD_TARGET_MASK);
	cmd->cmd_dword[2] |= htole64(target & CMD_TARGET_MASK);
}

static __inline void
cmd_format_itt(struct its_cmd *cmd, uint64_t itt)
{
	/* ITT Address field: DW2 [47:8] */
	cmd->cmd_dword[2] &= htole64(~CMD_ITT_MASK);
	cmd->cmd_dword[2] |= htole64(itt & CMD_ITT_MASK);
}

static __inline void
cmd_format_valid(struct its_cmd *cmd, uint8_t valid)
{
	/* Valid field: DW2 [63] */
	cmd->cmd_dword[2] &= htole64(~CMD_VALID_MASK);
	cmd->cmd_dword[2] |= htole64((uint64_t)valid << CMD_VALID_SHIFT);
}

static inline bool
its_cmd_queue_full(struct gicv3_its_softc *sc)
{
	size_t read_idx, next_write_idx;

	/* Get the index of the next command */
	next_write_idx = (sc->sc_its_cmd_next_idx + 1) %
	    (ITS_CMDQ_SIZE / sizeof(struct its_cmd));
	/* And the index of the current command being read */
	read_idx = gic_its_read_4(sc, GITS_CREADR) / sizeof(struct its_cmd);

	/*
	 * The queue is full when the write offset points
	 * at the command before the current read offset.
	 */
	return (next_write_idx == read_idx);
}

static inline void
its_cmd_sync(struct gicv3_its_softc *sc, struct its_cmd *cmd)
{

	if ((sc->sc_its_flags & ITS_FLAGS_CMDQ_FLUSH) != 0) {
		/* Clean D-cache under command. */
		cpu_dcache_wb_range((vm_offset_t)cmd, sizeof(*cmd));
	} else {
		/* DSB inner shareable, store */
		dsb(ishst);
	}

}

static inline uint64_t
its_cmd_cwriter_offset(struct gicv3_its_softc *sc, struct its_cmd *cmd)
{
	uint64_t off;

	off = (cmd - sc->sc_its_cmd_base) * sizeof(*cmd);

	return (off);
}

static void
its_cmd_wait_completion(device_t dev, struct its_cmd *cmd_first,
    struct its_cmd *cmd_last)
{
	struct gicv3_its_softc *sc;
	uint64_t first, last, read;
	size_t us_left;

	sc = device_get_softc(dev);

	/*
	 * XXX ARM64TODO: This is obviously a significant delay.
	 * The reason for that is that currently the time frames for
	 * the command to complete are not known.
	 */
	us_left = 1000000;

	first = its_cmd_cwriter_offset(sc, cmd_first);
	last = its_cmd_cwriter_offset(sc, cmd_last);

	for (;;) {
		read = gic_its_read_8(sc, GITS_CREADR);
		if (first < last) {
			if (read < first || read >= last)
				break;
		} else if (read < first && read >= last)
			break;

		if (us_left-- == 0) {
			/* This means timeout */
			device_printf(dev,
			    "Timeout while waiting for CMD completion.\n");
			return;
		}
		DELAY(1);
	}
}

static struct its_cmd *
its_cmd_alloc_locked(device_t dev)
{
	struct gicv3_its_softc *sc;
	struct its_cmd *cmd;
	size_t us_left;

	sc = device_get_softc(dev);

	/*
	 * XXX ARM64TODO: This is obviously a significant delay.
	 * The reason for that is that currently the time frames for
	 * the command to complete (and therefore free the descriptor)
	 * are not known.
	 */
	us_left = 1000000;

	mtx_assert(&sc->sc_its_cmd_lock, MA_OWNED);
	while (its_cmd_queue_full(sc)) {
		if (us_left-- == 0) {
			/* Timeout while waiting for free command */
			device_printf(dev,
			    "Timeout while waiting for free command\n");
			return (NULL);
		}
		DELAY(1);
	}

	cmd = &sc->sc_its_cmd_base[sc->sc_its_cmd_next_idx];
	sc->sc_its_cmd_next_idx++;
	sc->sc_its_cmd_next_idx %= ITS_CMDQ_SIZE / sizeof(struct its_cmd);

	return (cmd);
}

static uint64_t
its_cmd_prepare(struct its_cmd *cmd, struct its_cmd_desc *desc)
{
	uint64_t target;
	uint8_t cmd_type;
	u_int size;

	cmd_type = desc->cmd_type;
	target = ITS_TARGET_NONE;

	switch (cmd_type) {
	case ITS_CMD_MOVI:	/* Move interrupt ID to another collection */
		target = desc->cmd_desc_movi.col->col_target;
		cmd_format_command(cmd, ITS_CMD_MOVI);
		cmd_format_id(cmd, desc->cmd_desc_movi.id);
		cmd_format_col(cmd, desc->cmd_desc_movi.col->col_id);
		cmd_format_devid(cmd, desc->cmd_desc_movi.its_dev->devid);
		break;
	case ITS_CMD_SYNC:	/* Wait for previous commands completion */
		target = desc->cmd_desc_sync.col->col_target;
		cmd_format_command(cmd, ITS_CMD_SYNC);
		cmd_format_target(cmd, target);
		break;
	case ITS_CMD_MAPD:	/* Assign ITT to device */
		cmd_format_command(cmd, ITS_CMD_MAPD);
		cmd_format_itt(cmd, vtophys(desc->cmd_desc_mapd.its_dev->itt));
		/*
		 * Size describes number of bits to encode interrupt IDs
		 * supported by the device minus one.
		 * When V (valid) bit is zero, this field should be written
		 * as zero.
		 */
		if (desc->cmd_desc_mapd.valid != 0) {
			size = fls(desc->cmd_desc_mapd.its_dev->lpis.lpi_num);
			size = MAX(1, size) - 1;
		} else
			size = 0;

		cmd_format_size(cmd, size);
		cmd_format_devid(cmd, desc->cmd_desc_mapd.its_dev->devid);
		cmd_format_valid(cmd, desc->cmd_desc_mapd.valid);
		break;
	case ITS_CMD_MAPC:	/* Map collection to Re-Distributor */
		target = desc->cmd_desc_mapc.col->col_target;
		cmd_format_command(cmd, ITS_CMD_MAPC);
		cmd_format_col(cmd, desc->cmd_desc_mapc.col->col_id);
		cmd_format_valid(cmd, desc->cmd_desc_mapc.valid);
		cmd_format_target(cmd, target);
		break;
	case ITS_CMD_MAPTI:
		target = desc->cmd_desc_mapvi.col->col_target;
		cmd_format_command(cmd, ITS_CMD_MAPTI);
		cmd_format_devid(cmd, desc->cmd_desc_mapvi.its_dev->devid);
		cmd_format_id(cmd, desc->cmd_desc_mapvi.id);
		cmd_format_pid(cmd, desc->cmd_desc_mapvi.pid);
		cmd_format_col(cmd, desc->cmd_desc_mapvi.col->col_id);
		break;
	case ITS_CMD_MAPI:
		target = desc->cmd_desc_mapi.col->col_target;
		cmd_format_command(cmd, ITS_CMD_MAPI);
		cmd_format_devid(cmd, desc->cmd_desc_mapi.its_dev->devid);
		cmd_format_id(cmd, desc->cmd_desc_mapi.pid);
		cmd_format_col(cmd, desc->cmd_desc_mapi.col->col_id);
		break;
	case ITS_CMD_INV:
		target = desc->cmd_desc_inv.col->col_target;
		cmd_format_command(cmd, ITS_CMD_INV);
		cmd_format_devid(cmd, desc->cmd_desc_inv.its_dev->devid);
		cmd_format_id(cmd, desc->cmd_desc_inv.pid);
		break;
	case ITS_CMD_INVALL:
		cmd_format_command(cmd, ITS_CMD_INVALL);
		cmd_format_col(cmd, desc->cmd_desc_invall.col->col_id);
		break;
	default:
		panic("its_cmd_prepare: Invalid command: %x", cmd_type);
	}

	return (target);
}

static int
its_cmd_send(device_t dev, struct its_cmd_desc *desc)
{
	struct gicv3_its_softc *sc;
	struct its_cmd *cmd, *cmd_sync, *cmd_write;
	struct its_col col_sync;
	struct its_cmd_desc desc_sync;
	uint64_t target, cwriter;

	sc = device_get_softc(dev);
	mtx_lock_spin(&sc->sc_its_cmd_lock);
	cmd = its_cmd_alloc_locked(dev);
	if (cmd == NULL) {
		device_printf(dev, "could not allocate ITS command\n");
		mtx_unlock_spin(&sc->sc_its_cmd_lock);
		return (EBUSY);
	}

	target = its_cmd_prepare(cmd, desc);
	its_cmd_sync(sc, cmd);

	if (target != ITS_TARGET_NONE) {
		cmd_sync = its_cmd_alloc_locked(dev);
		if (cmd_sync != NULL) {
			desc_sync.cmd_type = ITS_CMD_SYNC;
			col_sync.col_target = target;
			desc_sync.cmd_desc_sync.col = &col_sync;
			its_cmd_prepare(cmd_sync, &desc_sync);
			its_cmd_sync(sc, cmd_sync);
		}
	}

	/* Update GITS_CWRITER */
	cwriter = sc->sc_its_cmd_next_idx * sizeof(struct its_cmd);
	gic_its_write_8(sc, GITS_CWRITER, cwriter);
	cmd_write = &sc->sc_its_cmd_base[sc->sc_its_cmd_next_idx];
	mtx_unlock_spin(&sc->sc_its_cmd_lock);

	its_cmd_wait_completion(dev, cmd, cmd_write);

	return (0);
}

/* Handlers to send commands */
static void
its_cmd_movi(device_t dev, struct gicv3_its_irqsrc *girq)
{
	struct gicv3_its_softc *sc;
	struct its_cmd_desc desc;
	struct its_col *col;

	sc = device_get_softc(dev);
	col = sc->sc_its_cols[CPU_FFS(&girq->gi_isrc.isrc_cpu) - 1];

	desc.cmd_type = ITS_CMD_MOVI;
	desc.cmd_desc_movi.its_dev = girq->gi_its_dev;
	desc.cmd_desc_movi.col = col;
	desc.cmd_desc_movi.id = girq->gi_id;

	its_cmd_send(dev, &desc);
}

static void
its_cmd_mapc(device_t dev, struct its_col *col, uint8_t valid)
{
	struct its_cmd_desc desc;

	desc.cmd_type = ITS_CMD_MAPC;
	desc.cmd_desc_mapc.col = col;
	/*
	 * Valid bit set - map the collection.
	 * Valid bit cleared - unmap the collection.
	 */
	desc.cmd_desc_mapc.valid = valid;

	its_cmd_send(dev, &desc);
}

static void
its_cmd_mapti(device_t dev, struct gicv3_its_irqsrc *girq)
{
	struct gicv3_its_softc *sc;
	struct its_cmd_desc desc;
	struct its_col *col;
	u_int col_id;

	sc = device_get_softc(dev);

	col_id = CPU_FFS(&girq->gi_isrc.isrc_cpu) - 1;
	col = sc->sc_its_cols[col_id];

	desc.cmd_type = ITS_CMD_MAPTI;
	desc.cmd_desc_mapvi.its_dev = girq->gi_its_dev;
	desc.cmd_desc_mapvi.col = col;
	/* The EventID sent to the device */
	desc.cmd_desc_mapvi.id = girq->gi_id;
	/* The physical interrupt presented to softeware */
	desc.cmd_desc_mapvi.pid = girq->gi_lpi + GIC_FIRST_LPI;

	its_cmd_send(dev, &desc);
}

static void
its_cmd_mapd(device_t dev, struct its_dev *its_dev, uint8_t valid)
{
	struct its_cmd_desc desc;

	desc.cmd_type = ITS_CMD_MAPD;
	desc.cmd_desc_mapd.its_dev = its_dev;
	desc.cmd_desc_mapd.valid = valid;

	its_cmd_send(dev, &desc);
}

static void
its_cmd_inv(device_t dev, struct its_dev *its_dev,
    struct gicv3_its_irqsrc *girq)
{
	struct gicv3_its_softc *sc;
	struct its_cmd_desc desc;
	struct its_col *col;

	sc = device_get_softc(dev);
	col = sc->sc_its_cols[CPU_FFS(&girq->gi_isrc.isrc_cpu) - 1];

	desc.cmd_type = ITS_CMD_INV;
	/* The EventID sent to the device */
	desc.cmd_desc_inv.pid = girq->gi_id;
	desc.cmd_desc_inv.its_dev = its_dev;
	desc.cmd_desc_inv.col = col;

	its_cmd_send(dev, &desc);
}

static void
its_cmd_invall(device_t dev, struct its_col *col)
{
	struct its_cmd_desc desc;

	desc.cmd_type = ITS_CMD_INVALL;
	desc.cmd_desc_invall.col = col;

	its_cmd_send(dev, &desc);
}

#ifdef FDT
static device_probe_t gicv3_its_fdt_probe;
static device_attach_t gicv3_its_fdt_attach;

static device_method_t gicv3_its_fdt_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe,		gicv3_its_fdt_probe),
	DEVMETHOD(device_attach,	gicv3_its_fdt_attach),

	/* End */
	DEVMETHOD_END
};

#define its_baseclasses its_fdt_baseclasses
DEFINE_CLASS_1(its, gicv3_its_fdt_driver, gicv3_its_fdt_methods,
    sizeof(struct gicv3_its_softc), gicv3_its_driver);
#undef its_baseclasses
static devclass_t gicv3_its_fdt_devclass;

EARLY_DRIVER_MODULE(its_fdt, gic, gicv3_its_fdt_driver,
    gicv3_its_fdt_devclass, 0, 0, BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE);

static int
gicv3_its_fdt_probe(device_t dev)
{

	if (!ofw_bus_status_okay(dev))
		return (ENXIO);

	if (!ofw_bus_is_compatible(dev, "arm,gic-v3-its"))
		return (ENXIO);

	device_set_desc(dev, "ARM GIC Interrupt Translation Service");
	return (BUS_PROBE_DEFAULT);
}

static int
gicv3_its_fdt_attach(device_t dev)
{
	struct gicv3_its_softc *sc;
	phandle_t xref;
	int err;

	sc = device_get_softc(dev);
	sc->dev = dev;
	err = gicv3_its_attach(dev);
	if (err != 0)
		return (err);

	/* Register this device as a interrupt controller */
	xref = OF_xref_from_node(ofw_bus_get_node(dev));
	sc->sc_pic = intr_pic_register(dev, xref);
	intr_pic_add_handler(device_get_parent(dev), sc->sc_pic,
	    gicv3_its_intr, sc, sc->sc_irq_base, sc->sc_irq_length);

	/* Register this device to handle MSI interrupts */
	intr_msi_register(dev, xref);

	return (0);
}
#endif

#ifdef DEV_ACPI
static device_probe_t gicv3_its_acpi_probe;
static device_attach_t gicv3_its_acpi_attach;

static device_method_t gicv3_its_acpi_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe,		gicv3_its_acpi_probe),
	DEVMETHOD(device_attach,	gicv3_its_acpi_attach),

	/* End */
	DEVMETHOD_END
};

#define its_baseclasses its_acpi_baseclasses
DEFINE_CLASS_1(its, gicv3_its_acpi_driver, gicv3_its_acpi_methods,
    sizeof(struct gicv3_its_softc), gicv3_its_driver);
#undef its_baseclasses
static devclass_t gicv3_its_acpi_devclass;

EARLY_DRIVER_MODULE(its_acpi, gic, gicv3_its_acpi_driver,
    gicv3_its_acpi_devclass, 0, 0, BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE);

static int
gicv3_its_acpi_probe(device_t dev)
{

	if (gic_get_bus(dev) != GIC_BUS_ACPI)
		return (EINVAL);

	if (gic_get_hw_rev(dev) < 3)
		return (EINVAL);

	device_set_desc(dev, "ARM GIC Interrupt Translation Service");
	return (BUS_PROBE_DEFAULT);
}

static int
gicv3_its_acpi_attach(device_t dev)
{
	struct gicv3_its_softc *sc;
	struct gic_v3_devinfo *di;
	int err;

	sc = device_get_softc(dev);
	sc->dev = dev;
	err = gicv3_its_attach(dev);
	if (err != 0)
		return (err);

	di = device_get_ivars(dev);
	sc->sc_pic = intr_pic_register(dev, di->msi_xref);
	intr_pic_add_handler(device_get_parent(dev), sc->sc_pic,
	    gicv3_its_intr, sc, sc->sc_irq_base, sc->sc_irq_length);

	/* Register this device to handle MSI interrupts */
	intr_msi_register(dev, di->msi_xref);

	return (0);
}
#endif