aboutsummaryrefslogtreecommitdiff
path: root/hw/xen/xen_pt_config_init.c
blob: 3d8686d550fcdd31fe12884e3960494b331cd8a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
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
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
/*
 * Copyright (c) 2007, Neocleus Corporation.
 * Copyright (c) 2007, Intel Corporation.
 *
 * This work is licensed under the terms of the GNU GPL, version 2.  See
 * the COPYING file in the top-level directory.
 *
 * Alex Novik <alex@neocleus.com>
 * Allen Kay <allen.m.kay@intel.com>
 * Guy Zana <guy@neocleus.com>
 *
 * This file implements direct PCI assignment to a HVM guest
 */

#include "qemu/timer.h"
#include "hw/xen/xen_backend.h"
#include "xen_pt.h"

#define XEN_PT_MERGE_VALUE(value, data, val_mask) \
    (((value) & (val_mask)) | ((data) & ~(val_mask)))

#define XEN_PT_INVALID_REG          0xFFFFFFFF      /* invalid register value */

/* prototype */

static int xen_pt_ptr_reg_init(XenPCIPassthroughState *s, XenPTRegInfo *reg,
                               uint32_t real_offset, uint32_t *data);


/* helper */

/* A return value of 1 means the capability should NOT be exposed to guest. */
static int xen_pt_hide_dev_cap(const XenHostPCIDevice *d, uint8_t grp_id)
{
    switch (grp_id) {
    case PCI_CAP_ID_EXP:
        /* The PCI Express Capability Structure of the VF of Intel 82599 10GbE
         * Controller looks trivial, e.g., the PCI Express Capabilities
         * Register is 0. We should not try to expose it to guest.
         *
         * The datasheet is available at
         * http://download.intel.com/design/network/datashts/82599_datasheet.pdf
         *
         * See 'Table 9.7. VF PCIe Configuration Space' of the datasheet, the
         * PCI Express Capability Structure of the VF of Intel 82599 10GbE
         * Controller looks trivial, e.g., the PCI Express Capabilities
         * Register is 0, so the Capability Version is 0 and
         * xen_pt_pcie_size_init() would fail.
         */
        if (d->vendor_id == PCI_VENDOR_ID_INTEL &&
            d->device_id == PCI_DEVICE_ID_INTEL_82599_SFP_VF) {
            return 1;
        }
        break;
    }
    return 0;
}

/*   find emulate register group entry */
XenPTRegGroup *xen_pt_find_reg_grp(XenPCIPassthroughState *s, uint32_t address)
{
    XenPTRegGroup *entry = NULL;

    /* find register group entry */
    QLIST_FOREACH(entry, &s->reg_grps, entries) {
        /* check address */
        if ((entry->base_offset <= address)
            && ((entry->base_offset + entry->size) > address)) {
            return entry;
        }
    }

    /* group entry not found */
    return NULL;
}

/* find emulate register entry */
XenPTReg *xen_pt_find_reg(XenPTRegGroup *reg_grp, uint32_t address)
{
    XenPTReg *reg_entry = NULL;
    XenPTRegInfo *reg = NULL;
    uint32_t real_offset = 0;

    /* find register entry */
    QLIST_FOREACH(reg_entry, &reg_grp->reg_tbl_list, entries) {
        reg = reg_entry->reg;
        real_offset = reg_grp->base_offset + reg->offset;
        /* check address */
        if ((real_offset <= address)
            && ((real_offset + reg->size) > address)) {
            return reg_entry;
        }
    }

    return NULL;
}

static uint32_t get_throughable_mask(const XenPCIPassthroughState *s,
                                     XenPTRegInfo *reg, uint32_t valid_mask)
{
    uint32_t throughable_mask = ~(reg->emu_mask | reg->ro_mask);

    if (!s->permissive) {
        throughable_mask &= ~reg->res_mask;
    }

    return throughable_mask & valid_mask;
}

/****************
 * general register functions
 */

/* register initialization function */

static int xen_pt_common_reg_init(XenPCIPassthroughState *s,
                                  XenPTRegInfo *reg, uint32_t real_offset,
                                  uint32_t *data)
{
    *data = reg->init_val;
    return 0;
}

/* Read register functions */

static int xen_pt_byte_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
                                uint8_t *value, uint8_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint8_t valid_emu_mask = 0;
    uint8_t *data = cfg_entry->ptr.byte;

    /* emulate byte register */
    valid_emu_mask = reg->emu_mask & valid_mask;
    *value = XEN_PT_MERGE_VALUE(*value, *data, ~valid_emu_mask);

    return 0;
}
static int xen_pt_word_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
                                uint16_t *value, uint16_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint16_t valid_emu_mask = 0;
    uint16_t *data = cfg_entry->ptr.half_word;

    /* emulate word register */
    valid_emu_mask = reg->emu_mask & valid_mask;
    *value = XEN_PT_MERGE_VALUE(*value, *data, ~valid_emu_mask);

    return 0;
}
static int xen_pt_long_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
                                uint32_t *value, uint32_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint32_t valid_emu_mask = 0;
    uint32_t *data = cfg_entry->ptr.word;

    /* emulate long register */
    valid_emu_mask = reg->emu_mask & valid_mask;
    *value = XEN_PT_MERGE_VALUE(*value, *data, ~valid_emu_mask);

    return 0;
}

/* Write register functions */

static int xen_pt_byte_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
                                 uint8_t *val, uint8_t dev_value,
                                 uint8_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint8_t writable_mask = 0;
    uint8_t throughable_mask = get_throughable_mask(s, reg, valid_mask);
    uint8_t *data = cfg_entry->ptr.byte;

    /* modify emulate register */
    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    return 0;
}
static int xen_pt_word_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
                                 uint16_t *val, uint16_t dev_value,
                                 uint16_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint16_t writable_mask = 0;
    uint16_t throughable_mask = get_throughable_mask(s, reg, valid_mask);
    uint16_t *data = cfg_entry->ptr.half_word;

    /* modify emulate register */
    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    return 0;
}
static int xen_pt_long_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
                                 uint32_t *val, uint32_t dev_value,
                                 uint32_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint32_t writable_mask = 0;
    uint32_t throughable_mask = get_throughable_mask(s, reg, valid_mask);
    uint32_t *data = cfg_entry->ptr.word;

    /* modify emulate register */
    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    return 0;
}


/* XenPTRegInfo declaration
 * - only for emulated register (either a part or whole bit).
 * - for passthrough register that need special behavior (like interacting with
 *   other component), set emu_mask to all 0 and specify r/w func properly.
 * - do NOT use ALL F for init_val, otherwise the tbl will not be registered.
 */

/********************
 * Header Type0
 */

static int xen_pt_vendor_reg_init(XenPCIPassthroughState *s,
                                  XenPTRegInfo *reg, uint32_t real_offset,
                                  uint32_t *data)
{
    *data = s->real_device.vendor_id;
    return 0;
}
static int xen_pt_device_reg_init(XenPCIPassthroughState *s,
                                  XenPTRegInfo *reg, uint32_t real_offset,
                                  uint32_t *data)
{
    *data = s->real_device.device_id;
    return 0;
}
static int xen_pt_status_reg_init(XenPCIPassthroughState *s,
                                  XenPTRegInfo *reg, uint32_t real_offset,
                                  uint32_t *data)
{
    XenPTRegGroup *reg_grp_entry = NULL;
    XenPTReg *reg_entry = NULL;
    uint32_t reg_field = 0;

    /* find Header register group */
    reg_grp_entry = xen_pt_find_reg_grp(s, PCI_CAPABILITY_LIST);
    if (reg_grp_entry) {
        /* find Capabilities Pointer register */
        reg_entry = xen_pt_find_reg(reg_grp_entry, PCI_CAPABILITY_LIST);
        if (reg_entry) {
            /* check Capabilities Pointer register */
            if (*reg_entry->ptr.half_word) {
                reg_field |= PCI_STATUS_CAP_LIST;
            } else {
                reg_field &= ~PCI_STATUS_CAP_LIST;
            }
        } else {
            xen_shutdown_fatal_error("Internal error: Couldn't find XenPTReg*"
                                     " for Capabilities Pointer register."
                                     " (%s)\n", __func__);
            return -1;
        }
    } else {
        xen_shutdown_fatal_error("Internal error: Couldn't find XenPTRegGroup"
                                 " for Header. (%s)\n", __func__);
        return -1;
    }

    *data = reg_field;
    return 0;
}
static int xen_pt_header_type_reg_init(XenPCIPassthroughState *s,
                                       XenPTRegInfo *reg, uint32_t real_offset,
                                       uint32_t *data)
{
    /* read PCI_HEADER_TYPE */
    *data = reg->init_val | 0x80;
    return 0;
}

/* initialize Interrupt Pin register */
static int xen_pt_irqpin_reg_init(XenPCIPassthroughState *s,
                                  XenPTRegInfo *reg, uint32_t real_offset,
                                  uint32_t *data)
{
    *data = xen_pt_pci_read_intx(s);
    return 0;
}

/* Command register */
static int xen_pt_cmd_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
                                uint16_t *val, uint16_t dev_value,
                                uint16_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint16_t writable_mask = 0;
    uint16_t throughable_mask = get_throughable_mask(s, reg, valid_mask);
    uint16_t *data = cfg_entry->ptr.half_word;

    /* modify emulate register */
    writable_mask = ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);

    /* create value for writing to I/O device register */
    if (*val & PCI_COMMAND_INTX_DISABLE) {
        throughable_mask |= PCI_COMMAND_INTX_DISABLE;
    } else {
        if (s->machine_irq) {
            throughable_mask |= PCI_COMMAND_INTX_DISABLE;
        }
    }

    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    return 0;
}

/* BAR */
#define XEN_PT_BAR_MEM_RO_MASK    0x0000000F  /* BAR ReadOnly mask(Memory) */
#define XEN_PT_BAR_MEM_EMU_MASK   0xFFFFFFF0  /* BAR emul mask(Memory) */
#define XEN_PT_BAR_IO_RO_MASK     0x00000003  /* BAR ReadOnly mask(I/O) */
#define XEN_PT_BAR_IO_EMU_MASK    0xFFFFFFFC  /* BAR emul mask(I/O) */

static bool is_64bit_bar(PCIIORegion *r)
{
    return !!(r->type & PCI_BASE_ADDRESS_MEM_TYPE_64);
}

static uint64_t xen_pt_get_bar_size(PCIIORegion *r)
{
    if (is_64bit_bar(r)) {
        uint64_t size64;
        size64 = (r + 1)->size;
        size64 <<= 32;
        size64 += r->size;
        return size64;
    }
    return r->size;
}

static XenPTBarFlag xen_pt_bar_reg_parse(XenPCIPassthroughState *s,
                                         int index)
{
    PCIDevice *d = &s->dev;
    XenPTRegion *region = NULL;
    PCIIORegion *r;

    /* check 64bit BAR */
    if ((0 < index) && (index < PCI_ROM_SLOT)) {
        int type = s->real_device.io_regions[index - 1].type;

        if ((type & XEN_HOST_PCI_REGION_TYPE_MEM)
            && (type & XEN_HOST_PCI_REGION_TYPE_MEM_64)) {
            region = &s->bases[index - 1];
            if (region->bar_flag != XEN_PT_BAR_FLAG_UPPER) {
                return XEN_PT_BAR_FLAG_UPPER;
            }
        }
    }

    /* check unused BAR */
    r = &d->io_regions[index];
    if (!xen_pt_get_bar_size(r)) {
        return XEN_PT_BAR_FLAG_UNUSED;
    }

    /* for ExpROM BAR */
    if (index == PCI_ROM_SLOT) {
        return XEN_PT_BAR_FLAG_MEM;
    }

    /* check BAR I/O indicator */
    if (s->real_device.io_regions[index].type & XEN_HOST_PCI_REGION_TYPE_IO) {
        return XEN_PT_BAR_FLAG_IO;
    } else {
        return XEN_PT_BAR_FLAG_MEM;
    }
}

static inline uint32_t base_address_with_flags(XenHostPCIIORegion *hr)
{
    if (hr->type & XEN_HOST_PCI_REGION_TYPE_IO) {
        return hr->base_addr | (hr->bus_flags & ~PCI_BASE_ADDRESS_IO_MASK);
    } else {
        return hr->base_addr | (hr->bus_flags & ~PCI_BASE_ADDRESS_MEM_MASK);
    }
}

static int xen_pt_bar_reg_init(XenPCIPassthroughState *s, XenPTRegInfo *reg,
                               uint32_t real_offset, uint32_t *data)
{
    uint32_t reg_field = 0;
    int index;

    index = xen_pt_bar_offset_to_index(reg->offset);
    if (index < 0 || index >= PCI_NUM_REGIONS) {
        XEN_PT_ERR(&s->dev, "Internal error: Invalid BAR index [%d].\n", index);
        return -1;
    }

    /* set BAR flag */
    s->bases[index].bar_flag = xen_pt_bar_reg_parse(s, index);
    if (s->bases[index].bar_flag == XEN_PT_BAR_FLAG_UNUSED) {
        reg_field = XEN_PT_INVALID_REG;
    }

    *data = reg_field;
    return 0;
}
static int xen_pt_bar_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
                               uint32_t *value, uint32_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint32_t valid_emu_mask = 0;
    uint32_t bar_emu_mask = 0;
    int index;

    /* get BAR index */
    index = xen_pt_bar_offset_to_index(reg->offset);
    if (index < 0 || index >= PCI_NUM_REGIONS - 1) {
        XEN_PT_ERR(&s->dev, "Internal error: Invalid BAR index [%d].\n", index);
        return -1;
    }

    /* use fixed-up value from kernel sysfs */
    *value = base_address_with_flags(&s->real_device.io_regions[index]);

    /* set emulate mask depend on BAR flag */
    switch (s->bases[index].bar_flag) {
    case XEN_PT_BAR_FLAG_MEM:
        bar_emu_mask = XEN_PT_BAR_MEM_EMU_MASK;
        break;
    case XEN_PT_BAR_FLAG_IO:
        bar_emu_mask = XEN_PT_BAR_IO_EMU_MASK;
        break;
    case XEN_PT_BAR_FLAG_UPPER:
        bar_emu_mask = XEN_PT_BAR_ALLF;
        break;
    default:
        break;
    }

    /* emulate BAR */
    valid_emu_mask = bar_emu_mask & valid_mask;
    *value = XEN_PT_MERGE_VALUE(*value, *cfg_entry->ptr.word, ~valid_emu_mask);

    return 0;
}
static int xen_pt_bar_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,
                                uint32_t *val, uint32_t dev_value,
                                uint32_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    XenPTRegion *base = NULL;
    PCIDevice *d = &s->dev;
    const PCIIORegion *r;
    uint32_t writable_mask = 0;
    uint32_t bar_emu_mask = 0;
    uint32_t bar_ro_mask = 0;
    uint32_t r_size = 0;
    int index = 0;
    uint32_t *data = cfg_entry->ptr.word;

    index = xen_pt_bar_offset_to_index(reg->offset);
    if (index < 0 || index >= PCI_NUM_REGIONS) {
        XEN_PT_ERR(d, "Internal error: Invalid BAR index [%d].\n", index);
        return -1;
    }

    r = &d->io_regions[index];
    base = &s->bases[index];
    r_size = xen_pt_get_emul_size(base->bar_flag, r->size);

    /* set emulate mask and read-only mask values depend on the BAR flag */
    switch (s->bases[index].bar_flag) {
    case XEN_PT_BAR_FLAG_MEM:
        bar_emu_mask = XEN_PT_BAR_MEM_EMU_MASK;
        if (!r_size) {
            /* low 32 bits mask for 64 bit bars */
            bar_ro_mask = XEN_PT_BAR_ALLF;
        } else {
            bar_ro_mask = XEN_PT_BAR_MEM_RO_MASK | (r_size - 1);
        }
        break;
    case XEN_PT_BAR_FLAG_IO:
        bar_emu_mask = XEN_PT_BAR_IO_EMU_MASK;
        bar_ro_mask = XEN_PT_BAR_IO_RO_MASK | (r_size - 1);
        break;
    case XEN_PT_BAR_FLAG_UPPER:
        bar_emu_mask = XEN_PT_BAR_ALLF;
        bar_ro_mask = r_size ? r_size - 1 : 0;
        break;
    default:
        break;
    }

    /* modify emulate register */
    writable_mask = bar_emu_mask & ~bar_ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);

    /* check whether we need to update the virtual region address or not */
    switch (s->bases[index].bar_flag) {
    case XEN_PT_BAR_FLAG_UPPER:
    case XEN_PT_BAR_FLAG_MEM:
        /* nothing to do */
        break;
    case XEN_PT_BAR_FLAG_IO:
        /* nothing to do */
        break;
    default:
        break;
    }

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, 0);

    return 0;
}

/* write Exp ROM BAR */
static int xen_pt_exp_rom_bar_reg_write(XenPCIPassthroughState *s,
                                        XenPTReg *cfg_entry, uint32_t *val,
                                        uint32_t dev_value, uint32_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    XenPTRegion *base = NULL;
    PCIDevice *d = (PCIDevice *)&s->dev;
    uint32_t writable_mask = 0;
    uint32_t throughable_mask = get_throughable_mask(s, reg, valid_mask);
    pcibus_t r_size = 0;
    uint32_t bar_ro_mask = 0;
    uint32_t *data = cfg_entry->ptr.word;

    r_size = d->io_regions[PCI_ROM_SLOT].size;
    base = &s->bases[PCI_ROM_SLOT];
    /* align memory type resource size */
    r_size = xen_pt_get_emul_size(base->bar_flag, r_size);

    /* set emulate mask and read-only mask */
    bar_ro_mask = (reg->ro_mask | (r_size - 1)) & ~PCI_ROM_ADDRESS_ENABLE;

    /* modify emulate register */
    writable_mask = ~bar_ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    return 0;
}

static int xen_pt_intel_opregion_read(XenPCIPassthroughState *s,
                                      XenPTReg *cfg_entry,
                                      uint32_t *value, uint32_t valid_mask)
{
    *value = igd_read_opregion(s);
    return 0;
}

static int xen_pt_intel_opregion_write(XenPCIPassthroughState *s,
                                       XenPTReg *cfg_entry, uint32_t *value,
                                       uint32_t dev_value, uint32_t valid_mask)
{
    igd_write_opregion(s, *value);
    return 0;
}

/* Header Type0 reg static information table */
static XenPTRegInfo xen_pt_emu_reg_header0[] = {
    /* Vendor ID reg */
    {
        .offset     = PCI_VENDOR_ID,
        .size       = 2,
        .init_val   = 0x0000,
        .ro_mask    = 0xFFFF,
        .emu_mask   = 0xFFFF,
        .init       = xen_pt_vendor_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    /* Device ID reg */
    {
        .offset     = PCI_DEVICE_ID,
        .size       = 2,
        .init_val   = 0x0000,
        .ro_mask    = 0xFFFF,
        .emu_mask   = 0xFFFF,
        .init       = xen_pt_device_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    /* Command reg */
    {
        .offset     = PCI_COMMAND,
        .size       = 2,
        .init_val   = 0x0000,
        .res_mask   = 0xF880,
        .emu_mask   = 0x0743,
        .init       = xen_pt_common_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_cmd_reg_write,
    },
    /* Capabilities Pointer reg */
    {
        .offset     = PCI_CAPABILITY_LIST,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0xFF,
        .emu_mask   = 0xFF,
        .init       = xen_pt_ptr_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* Status reg */
    /* use emulated Cap Ptr value to initialize,
     * so need to be declared after Cap Ptr reg
     */
    {
        .offset     = PCI_STATUS,
        .size       = 2,
        .init_val   = 0x0000,
        .res_mask   = 0x0007,
        .ro_mask    = 0x06F8,
        .emu_mask   = 0x0010,
        .init       = xen_pt_status_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    /* Cache Line Size reg */
    {
        .offset     = PCI_CACHE_LINE_SIZE,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0x00,
        .emu_mask   = 0xFF,
        .init       = xen_pt_common_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* Latency Timer reg */
    {
        .offset     = PCI_LATENCY_TIMER,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0x00,
        .emu_mask   = 0xFF,
        .init       = xen_pt_common_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* Header Type reg */
    {
        .offset     = PCI_HEADER_TYPE,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0xFF,
        .emu_mask   = 0x00,
        .init       = xen_pt_header_type_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* Interrupt Line reg */
    {
        .offset     = PCI_INTERRUPT_LINE,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0x00,
        .emu_mask   = 0xFF,
        .init       = xen_pt_common_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* Interrupt Pin reg */
    {
        .offset     = PCI_INTERRUPT_PIN,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0xFF,
        .emu_mask   = 0xFF,
        .init       = xen_pt_irqpin_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* BAR 0 reg */
    /* mask of BAR need to be decided later, depends on IO/MEM type */
    {
        .offset     = PCI_BASE_ADDRESS_0,
        .size       = 4,
        .init_val   = 0x00000000,
        .init       = xen_pt_bar_reg_init,
        .u.dw.read  = xen_pt_bar_reg_read,
        .u.dw.write = xen_pt_bar_reg_write,
    },
    /* BAR 1 reg */
    {
        .offset     = PCI_BASE_ADDRESS_1,
        .size       = 4,
        .init_val   = 0x00000000,
        .init       = xen_pt_bar_reg_init,
        .u.dw.read  = xen_pt_bar_reg_read,
        .u.dw.write = xen_pt_bar_reg_write,
    },
    /* BAR 2 reg */
    {
        .offset     = PCI_BASE_ADDRESS_2,
        .size       = 4,
        .init_val   = 0x00000000,
        .init       = xen_pt_bar_reg_init,
        .u.dw.read  = xen_pt_bar_reg_read,
        .u.dw.write = xen_pt_bar_reg_write,
    },
    /* BAR 3 reg */
    {
        .offset     = PCI_BASE_ADDRESS_3,
        .size       = 4,
        .init_val   = 0x00000000,
        .init       = xen_pt_bar_reg_init,
        .u.dw.read  = xen_pt_bar_reg_read,
        .u.dw.write = xen_pt_bar_reg_write,
    },
    /* BAR 4 reg */
    {
        .offset     = PCI_BASE_ADDRESS_4,
        .size       = 4,
        .init_val   = 0x00000000,
        .init       = xen_pt_bar_reg_init,
        .u.dw.read  = xen_pt_bar_reg_read,
        .u.dw.write = xen_pt_bar_reg_write,
    },
    /* BAR 5 reg */
    {
        .offset     = PCI_BASE_ADDRESS_5,
        .size       = 4,
        .init_val   = 0x00000000,
        .init       = xen_pt_bar_reg_init,
        .u.dw.read  = xen_pt_bar_reg_read,
        .u.dw.write = xen_pt_bar_reg_write,
    },
    /* Expansion ROM BAR reg */
    {
        .offset     = PCI_ROM_ADDRESS,
        .size       = 4,
        .init_val   = 0x00000000,
        .ro_mask    = ~PCI_ROM_ADDRESS_MASK & ~PCI_ROM_ADDRESS_ENABLE,
        .emu_mask   = (uint32_t)PCI_ROM_ADDRESS_MASK,
        .init       = xen_pt_bar_reg_init,
        .u.dw.read  = xen_pt_long_reg_read,
        .u.dw.write = xen_pt_exp_rom_bar_reg_write,
    },
    {
        .size = 0,
    },
};


/*********************************
 * Vital Product Data Capability
 */

/* Vital Product Data Capability Structure reg static information table */
static XenPTRegInfo xen_pt_emu_reg_vpd[] = {
    {
        .offset     = PCI_CAP_LIST_NEXT,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0xFF,
        .emu_mask   = 0xFF,
        .init       = xen_pt_ptr_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    {
        .offset     = PCI_VPD_ADDR,
        .size       = 2,
        .ro_mask    = 0x0003,
        .emu_mask   = 0x0003,
        .init       = xen_pt_common_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    {
        .size = 0,
    },
};


/**************************************
 * Vendor Specific Capability
 */

/* Vendor Specific Capability Structure reg static information table */
static XenPTRegInfo xen_pt_emu_reg_vendor[] = {
    {
        .offset     = PCI_CAP_LIST_NEXT,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0xFF,
        .emu_mask   = 0xFF,
        .init       = xen_pt_ptr_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    {
        .size = 0,
    },
};


/*****************************
 * PCI Express Capability
 */

static inline uint8_t get_capability_version(XenPCIPassthroughState *s,
                                             uint32_t offset)
{
    uint8_t flag;
    if (xen_host_pci_get_byte(&s->real_device, offset + PCI_EXP_FLAGS, &flag)) {
        return 0;
    }
    return flag & PCI_EXP_FLAGS_VERS;
}

static inline uint8_t get_device_type(XenPCIPassthroughState *s,
                                      uint32_t offset)
{
    uint8_t flag;
    if (xen_host_pci_get_byte(&s->real_device, offset + PCI_EXP_FLAGS, &flag)) {
        return 0;
    }
    return (flag & PCI_EXP_FLAGS_TYPE) >> 4;
}

/* initialize Link Control register */
static int xen_pt_linkctrl_reg_init(XenPCIPassthroughState *s,
                                    XenPTRegInfo *reg, uint32_t real_offset,
                                    uint32_t *data)
{
    uint8_t cap_ver = get_capability_version(s, real_offset - reg->offset);
    uint8_t dev_type = get_device_type(s, real_offset - reg->offset);

    /* no need to initialize in case of Root Complex Integrated Endpoint
     * with cap_ver 1.x
     */
    if ((dev_type == PCI_EXP_TYPE_RC_END) && (cap_ver == 1)) {
        *data = XEN_PT_INVALID_REG;
    }

    *data = reg->init_val;
    return 0;
}
/* initialize Device Control 2 register */
static int xen_pt_devctrl2_reg_init(XenPCIPassthroughState *s,
                                    XenPTRegInfo *reg, uint32_t real_offset,
                                    uint32_t *data)
{
    uint8_t cap_ver = get_capability_version(s, real_offset - reg->offset);

    /* no need to initialize in case of cap_ver 1.x */
    if (cap_ver == 1) {
        *data = XEN_PT_INVALID_REG;
    }

    *data = reg->init_val;
    return 0;
}
/* initialize Link Control 2 register */
static int xen_pt_linkctrl2_reg_init(XenPCIPassthroughState *s,
                                     XenPTRegInfo *reg, uint32_t real_offset,
                                     uint32_t *data)
{
    uint8_t cap_ver = get_capability_version(s, real_offset - reg->offset);
    uint32_t reg_field = 0;

    /* no need to initialize in case of cap_ver 1.x */
    if (cap_ver == 1) {
        reg_field = XEN_PT_INVALID_REG;
    } else {
        /* set Supported Link Speed */
        uint8_t lnkcap;
        int rc;
        rc = xen_host_pci_get_byte(&s->real_device,
                                   real_offset - reg->offset + PCI_EXP_LNKCAP,
                                   &lnkcap);
        if (rc) {
            return rc;
        }
        reg_field |= PCI_EXP_LNKCAP_SLS & lnkcap;
    }

    *data = reg_field;
    return 0;
}

/* PCI Express Capability Structure reg static information table */
static XenPTRegInfo xen_pt_emu_reg_pcie[] = {
    /* Next Pointer reg */
    {
        .offset     = PCI_CAP_LIST_NEXT,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0xFF,
        .emu_mask   = 0xFF,
        .init       = xen_pt_ptr_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* Device Capabilities reg */
    {
        .offset     = PCI_EXP_DEVCAP,
        .size       = 4,
        .init_val   = 0x00000000,
        .ro_mask    = 0xFFFFFFFF,
        .emu_mask   = 0x10000000,
        .init       = xen_pt_common_reg_init,
        .u.dw.read  = xen_pt_long_reg_read,
        .u.dw.write = xen_pt_long_reg_write,
    },
    /* Device Control reg */
    {
        .offset     = PCI_EXP_DEVCTL,
        .size       = 2,
        .init_val   = 0x2810,
        .ro_mask    = 0x8400,
        .emu_mask   = 0xFFFF,
        .init       = xen_pt_common_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    /* Device Status reg */
    {
        .offset     = PCI_EXP_DEVSTA,
        .size       = 2,
        .res_mask   = 0xFFC0,
        .ro_mask    = 0x0030,
        .init       = xen_pt_common_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    /* Link Control reg */
    {
        .offset     = PCI_EXP_LNKCTL,
        .size       = 2,
        .init_val   = 0x0000,
        .ro_mask    = 0xFC34,
        .emu_mask   = 0xFFFF,
        .init       = xen_pt_linkctrl_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    /* Link Status reg */
    {
        .offset     = PCI_EXP_LNKSTA,
        .size       = 2,
        .ro_mask    = 0x3FFF,
        .init       = xen_pt_common_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    /* Device Control 2 reg */
    {
        .offset     = 0x28,
        .size       = 2,
        .init_val   = 0x0000,
        .ro_mask    = 0xFFE0,
        .emu_mask   = 0xFFFF,
        .init       = xen_pt_devctrl2_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    /* Link Control 2 reg */
    {
        .offset     = 0x30,
        .size       = 2,
        .init_val   = 0x0000,
        .ro_mask    = 0xE040,
        .emu_mask   = 0xFFFF,
        .init       = xen_pt_linkctrl2_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    {
        .size = 0,
    },
};


/*********************************
 * Power Management Capability
 */

/* write Power Management Control/Status register */
static int xen_pt_pmcsr_reg_write(XenPCIPassthroughState *s,
                                  XenPTReg *cfg_entry, uint16_t *val,
                                  uint16_t dev_value, uint16_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint16_t writable_mask = 0;
    uint16_t throughable_mask = get_throughable_mask(s, reg, valid_mask);
    uint16_t *data = cfg_entry->ptr.half_word;

    /* modify emulate register */
    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value & ~PCI_PM_CTRL_PME_STATUS,
                              throughable_mask);

    return 0;
}

/* Power Management Capability reg static information table */
static XenPTRegInfo xen_pt_emu_reg_pm[] = {
    /* Next Pointer reg */
    {
        .offset     = PCI_CAP_LIST_NEXT,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0xFF,
        .emu_mask   = 0xFF,
        .init       = xen_pt_ptr_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* Power Management Capabilities reg */
    {
        .offset     = PCI_CAP_FLAGS,
        .size       = 2,
        .init_val   = 0x0000,
        .ro_mask    = 0xFFFF,
        .emu_mask   = 0xF9C8,
        .init       = xen_pt_common_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_word_reg_write,
    },
    /* PCI Power Management Control/Status reg */
    {
        .offset     = PCI_PM_CTRL,
        .size       = 2,
        .init_val   = 0x0008,
        .res_mask   = 0x00F0,
        .ro_mask    = 0xE10C,
        .emu_mask   = 0x810B,
        .init       = xen_pt_common_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_pmcsr_reg_write,
    },
    {
        .size = 0,
    },
};


/********************************
 * MSI Capability
 */

/* Helper */
#define xen_pt_msi_check_type(offset, flags, what) \
        ((offset) == ((flags) & PCI_MSI_FLAGS_64BIT ? \
                      PCI_MSI_##what##_64 : PCI_MSI_##what##_32))

/* Message Control register */
static int xen_pt_msgctrl_reg_init(XenPCIPassthroughState *s,
                                   XenPTRegInfo *reg, uint32_t real_offset,
                                   uint32_t *data)
{
    XenPTMSI *msi = s->msi;
    uint16_t reg_field;
    int rc;

    /* use I/O device register's value as initial value */
    rc = xen_host_pci_get_word(&s->real_device, real_offset, &reg_field);
    if (rc) {
        return rc;
    }
    if (reg_field & PCI_MSI_FLAGS_ENABLE) {
        XEN_PT_LOG(&s->dev, "MSI already enabled, disabling it first\n");
        xen_host_pci_set_word(&s->real_device, real_offset,
                              reg_field & ~PCI_MSI_FLAGS_ENABLE);
    }
    msi->flags |= reg_field;
    msi->ctrl_offset = real_offset;
    msi->initialized = false;
    msi->mapped = false;

    *data = reg->init_val;
    return 0;
}
static int xen_pt_msgctrl_reg_write(XenPCIPassthroughState *s,
                                    XenPTReg *cfg_entry, uint16_t *val,
                                    uint16_t dev_value, uint16_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    XenPTMSI *msi = s->msi;
    uint16_t writable_mask = 0;
    uint16_t throughable_mask = get_throughable_mask(s, reg, valid_mask);
    uint16_t *data = cfg_entry->ptr.half_word;

    /* Currently no support for multi-vector */
    if (*val & PCI_MSI_FLAGS_QSIZE) {
        XEN_PT_WARN(&s->dev, "Tries to set more than 1 vector ctrl %x\n", *val);
    }

    /* modify emulate register */
    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);
    msi->flags |= *data & ~PCI_MSI_FLAGS_ENABLE;

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    /* update MSI */
    if (*val & PCI_MSI_FLAGS_ENABLE) {
        /* setup MSI pirq for the first time */
        if (!msi->initialized) {
            /* Init physical one */
            XEN_PT_LOG(&s->dev, "setup MSI (register: %x).\n", *val);
            if (xen_pt_msi_setup(s)) {
                /* We do not broadcast the error to the framework code, so
                 * that MSI errors are contained in MSI emulation code and
                 * QEMU can go on running.
                 * Guest MSI would be actually not working.
                 */
                *val &= ~PCI_MSI_FLAGS_ENABLE;
                XEN_PT_WARN(&s->dev, "Can not map MSI (register: %x)!\n", *val);
                return 0;
            }
            if (xen_pt_msi_update(s)) {
                *val &= ~PCI_MSI_FLAGS_ENABLE;
                XEN_PT_WARN(&s->dev, "Can not bind MSI (register: %x)!\n", *val);
                return 0;
            }
            msi->initialized = true;
            msi->mapped = true;
        }
        msi->flags |= PCI_MSI_FLAGS_ENABLE;
    } else if (msi->mapped) {
        xen_pt_msi_disable(s);
    }

    return 0;
}

/* initialize Message Upper Address register */
static int xen_pt_msgaddr64_reg_init(XenPCIPassthroughState *s,
                                     XenPTRegInfo *reg, uint32_t real_offset,
                                     uint32_t *data)
{
    /* no need to initialize in case of 32 bit type */
    if (!(s->msi->flags & PCI_MSI_FLAGS_64BIT)) {
        *data = XEN_PT_INVALID_REG;
    } else {
        *data = reg->init_val;
    }

    return 0;
}
/* this function will be called twice (for 32 bit and 64 bit type) */
/* initialize Message Data register */
static int xen_pt_msgdata_reg_init(XenPCIPassthroughState *s,
                                   XenPTRegInfo *reg, uint32_t real_offset,
                                   uint32_t *data)
{
    uint32_t flags = s->msi->flags;
    uint32_t offset = reg->offset;

    /* check the offset whether matches the type or not */
    if (xen_pt_msi_check_type(offset, flags, DATA)) {
        *data = reg->init_val;
    } else {
        *data = XEN_PT_INVALID_REG;
    }
    return 0;
}

/* this function will be called twice (for 32 bit and 64 bit type) */
/* initialize Mask register */
static int xen_pt_mask_reg_init(XenPCIPassthroughState *s,
                                XenPTRegInfo *reg, uint32_t real_offset,
                                uint32_t *data)
{
    uint32_t flags = s->msi->flags;

    /* check the offset whether matches the type or not */
    if (!(flags & PCI_MSI_FLAGS_MASKBIT)) {
        *data = XEN_PT_INVALID_REG;
    } else if (xen_pt_msi_check_type(reg->offset, flags, MASK)) {
        *data = reg->init_val;
    } else {
        *data = XEN_PT_INVALID_REG;
    }
    return 0;
}

/* this function will be called twice (for 32 bit and 64 bit type) */
/* initialize Pending register */
static int xen_pt_pending_reg_init(XenPCIPassthroughState *s,
                                   XenPTRegInfo *reg, uint32_t real_offset,
                                   uint32_t *data)
{
    uint32_t flags = s->msi->flags;

    /* check the offset whether matches the type or not */
    if (!(flags & PCI_MSI_FLAGS_MASKBIT)) {
        *data = XEN_PT_INVALID_REG;
    } else if (xen_pt_msi_check_type(reg->offset, flags, PENDING)) {
        *data = reg->init_val;
    } else {
        *data = XEN_PT_INVALID_REG;
    }
    return 0;
}

/* write Message Address register */
static int xen_pt_msgaddr32_reg_write(XenPCIPassthroughState *s,
                                      XenPTReg *cfg_entry, uint32_t *val,
                                      uint32_t dev_value, uint32_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint32_t writable_mask = 0;
    uint32_t old_addr = *cfg_entry->ptr.word;
    uint32_t *data = cfg_entry->ptr.word;

    /* modify emulate register */
    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);
    s->msi->addr_lo = *data;

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, 0);

    /* update MSI */
    if (*data != old_addr) {
        if (s->msi->mapped) {
            xen_pt_msi_update(s);
        }
    }

    return 0;
}
/* write Message Upper Address register */
static int xen_pt_msgaddr64_reg_write(XenPCIPassthroughState *s,
                                      XenPTReg *cfg_entry, uint32_t *val,
                                      uint32_t dev_value, uint32_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint32_t writable_mask = 0;
    uint32_t old_addr = *cfg_entry->ptr.word;
    uint32_t *data = cfg_entry->ptr.word;

    /* check whether the type is 64 bit or not */
    if (!(s->msi->flags & PCI_MSI_FLAGS_64BIT)) {
        XEN_PT_ERR(&s->dev,
                   "Can't write to the upper address without 64 bit support\n");
        return -1;
    }

    /* modify emulate register */
    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);
    /* update the msi_info too */
    s->msi->addr_hi = *data;

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, 0);

    /* update MSI */
    if (*data != old_addr) {
        if (s->msi->mapped) {
            xen_pt_msi_update(s);
        }
    }

    return 0;
}


/* this function will be called twice (for 32 bit and 64 bit type) */
/* write Message Data register */
static int xen_pt_msgdata_reg_write(XenPCIPassthroughState *s,
                                    XenPTReg *cfg_entry, uint16_t *val,
                                    uint16_t dev_value, uint16_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    XenPTMSI *msi = s->msi;
    uint16_t writable_mask = 0;
    uint16_t old_data = *cfg_entry->ptr.half_word;
    uint32_t offset = reg->offset;
    uint16_t *data = cfg_entry->ptr.half_word;

    /* check the offset whether matches the type or not */
    if (!xen_pt_msi_check_type(offset, msi->flags, DATA)) {
        /* exit I/O emulator */
        XEN_PT_ERR(&s->dev, "the offset does not match the 32/64 bit type!\n");
        return -1;
    }

    /* modify emulate register */
    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);
    /* update the msi_info too */
    msi->data = *data;

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, 0);

    /* update MSI */
    if (*data != old_data) {
        if (msi->mapped) {
            xen_pt_msi_update(s);
        }
    }

    return 0;
}

/* MSI Capability Structure reg static information table */
static XenPTRegInfo xen_pt_emu_reg_msi[] = {
    /* Next Pointer reg */
    {
        .offset     = PCI_CAP_LIST_NEXT,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0xFF,
        .emu_mask   = 0xFF,
        .init       = xen_pt_ptr_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* Message Control reg */
    {
        .offset     = PCI_MSI_FLAGS,
        .size       = 2,
        .init_val   = 0x0000,
        .res_mask   = 0xFE00,
        .ro_mask    = 0x018E,
        .emu_mask   = 0x017E,
        .init       = xen_pt_msgctrl_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_msgctrl_reg_write,
    },
    /* Message Address reg */
    {
        .offset     = PCI_MSI_ADDRESS_LO,
        .size       = 4,
        .init_val   = 0x00000000,
        .ro_mask    = 0x00000003,
        .emu_mask   = 0xFFFFFFFF,
        .init       = xen_pt_common_reg_init,
        .u.dw.read  = xen_pt_long_reg_read,
        .u.dw.write = xen_pt_msgaddr32_reg_write,
    },
    /* Message Upper Address reg (if PCI_MSI_FLAGS_64BIT set) */
    {
        .offset     = PCI_MSI_ADDRESS_HI,
        .size       = 4,
        .init_val   = 0x00000000,
        .ro_mask    = 0x00000000,
        .emu_mask   = 0xFFFFFFFF,
        .init       = xen_pt_msgaddr64_reg_init,
        .u.dw.read  = xen_pt_long_reg_read,
        .u.dw.write = xen_pt_msgaddr64_reg_write,
    },
    /* Message Data reg (16 bits of data for 32-bit devices) */
    {
        .offset     = PCI_MSI_DATA_32,
        .size       = 2,
        .init_val   = 0x0000,
        .ro_mask    = 0x0000,
        .emu_mask   = 0xFFFF,
        .init       = xen_pt_msgdata_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_msgdata_reg_write,
    },
    /* Message Data reg (16 bits of data for 64-bit devices) */
    {
        .offset     = PCI_MSI_DATA_64,
        .size       = 2,
        .init_val   = 0x0000,
        .ro_mask    = 0x0000,
        .emu_mask   = 0xFFFF,
        .init       = xen_pt_msgdata_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_msgdata_reg_write,
    },
    /* Mask reg (if PCI_MSI_FLAGS_MASKBIT set, for 32-bit devices) */
    {
        .offset     = PCI_MSI_MASK_32,
        .size       = 4,
        .init_val   = 0x00000000,
        .ro_mask    = 0xFFFFFFFF,
        .emu_mask   = 0xFFFFFFFF,
        .init       = xen_pt_mask_reg_init,
        .u.dw.read  = xen_pt_long_reg_read,
        .u.dw.write = xen_pt_long_reg_write,
    },
    /* Mask reg (if PCI_MSI_FLAGS_MASKBIT set, for 64-bit devices) */
    {
        .offset     = PCI_MSI_MASK_64,
        .size       = 4,
        .init_val   = 0x00000000,
        .ro_mask    = 0xFFFFFFFF,
        .emu_mask   = 0xFFFFFFFF,
        .init       = xen_pt_mask_reg_init,
        .u.dw.read  = xen_pt_long_reg_read,
        .u.dw.write = xen_pt_long_reg_write,
    },
    /* Pending reg (if PCI_MSI_FLAGS_MASKBIT set, for 32-bit devices) */
    {
        .offset     = PCI_MSI_MASK_32 + 4,
        .size       = 4,
        .init_val   = 0x00000000,
        .ro_mask    = 0xFFFFFFFF,
        .emu_mask   = 0x00000000,
        .init       = xen_pt_pending_reg_init,
        .u.dw.read  = xen_pt_long_reg_read,
        .u.dw.write = xen_pt_long_reg_write,
    },
    /* Pending reg (if PCI_MSI_FLAGS_MASKBIT set, for 64-bit devices) */
    {
        .offset     = PCI_MSI_MASK_64 + 4,
        .size       = 4,
        .init_val   = 0x00000000,
        .ro_mask    = 0xFFFFFFFF,
        .emu_mask   = 0x00000000,
        .init       = xen_pt_pending_reg_init,
        .u.dw.read  = xen_pt_long_reg_read,
        .u.dw.write = xen_pt_long_reg_write,
    },
    {
        .size = 0,
    },
};


/**************************************
 * MSI-X Capability
 */

/* Message Control register for MSI-X */
static int xen_pt_msixctrl_reg_init(XenPCIPassthroughState *s,
                                    XenPTRegInfo *reg, uint32_t real_offset,
                                    uint32_t *data)
{
    uint16_t reg_field;
    int rc;

    /* use I/O device register's value as initial value */
    rc = xen_host_pci_get_word(&s->real_device, real_offset, &reg_field);
    if (rc) {
        return rc;
    }
    if (reg_field & PCI_MSIX_FLAGS_ENABLE) {
        XEN_PT_LOG(&s->dev, "MSIX already enabled, disabling it first\n");
        xen_host_pci_set_word(&s->real_device, real_offset,
                              reg_field & ~PCI_MSIX_FLAGS_ENABLE);
    }

    s->msix->ctrl_offset = real_offset;

    *data = reg->init_val;
    return 0;
}
static int xen_pt_msixctrl_reg_write(XenPCIPassthroughState *s,
                                     XenPTReg *cfg_entry, uint16_t *val,
                                     uint16_t dev_value, uint16_t valid_mask)
{
    XenPTRegInfo *reg = cfg_entry->reg;
    uint16_t writable_mask = 0;
    uint16_t throughable_mask = get_throughable_mask(s, reg, valid_mask);
    int debug_msix_enabled_old;
    uint16_t *data = cfg_entry->ptr.half_word;

    /* modify emulate register */
    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;
    *data = XEN_PT_MERGE_VALUE(*val, *data, writable_mask);

    /* create value for writing to I/O device register */
    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    /* update MSI-X */
    if ((*val & PCI_MSIX_FLAGS_ENABLE)
        && !(*val & PCI_MSIX_FLAGS_MASKALL)) {
        xen_pt_msix_update(s);
    } else if (!(*val & PCI_MSIX_FLAGS_ENABLE) && s->msix->enabled) {
        xen_pt_msix_disable(s);
    }

    debug_msix_enabled_old = s->msix->enabled;
    s->msix->enabled = !!(*val & PCI_MSIX_FLAGS_ENABLE);
    if (s->msix->enabled != debug_msix_enabled_old) {
        XEN_PT_LOG(&s->dev, "%s MSI-X\n",
                   s->msix->enabled ? "enable" : "disable");
    }

    return 0;
}

/* MSI-X Capability Structure reg static information table */
static XenPTRegInfo xen_pt_emu_reg_msix[] = {
    /* Next Pointer reg */
    {
        .offset     = PCI_CAP_LIST_NEXT,
        .size       = 1,
        .init_val   = 0x00,
        .ro_mask    = 0xFF,
        .emu_mask   = 0xFF,
        .init       = xen_pt_ptr_reg_init,
        .u.b.read   = xen_pt_byte_reg_read,
        .u.b.write  = xen_pt_byte_reg_write,
    },
    /* Message Control reg */
    {
        .offset     = PCI_MSI_FLAGS,
        .size       = 2,
        .init_val   = 0x0000,
        .res_mask   = 0x3800,
        .ro_mask    = 0x07FF,
        .emu_mask   = 0x0000,
        .init       = xen_pt_msixctrl_reg_init,
        .u.w.read   = xen_pt_word_reg_read,
        .u.w.write  = xen_pt_msixctrl_reg_write,
    },
    {
        .size = 0,
    },
};

static XenPTRegInfo xen_pt_emu_reg_igd_opregion[] = {
    /* Intel IGFX OpRegion reg */
    {
        .offset     = 0x0,
        .size       = 4,
        .init_val   = 0,
        .u.dw.read   = xen_pt_intel_opregion_read,
        .u.dw.write  = xen_pt_intel_opregion_write,
    },
    {
        .size = 0,
    },
};

/****************************
 * Capabilities
 */

/* capability structure register group size functions */

static int xen_pt_reg_grp_size_init(XenPCIPassthroughState *s,
                                    const XenPTRegGroupInfo *grp_reg,
                                    uint32_t base_offset, uint8_t *size)
{
    *size = grp_reg->grp_size;
    return 0;
}
/* get Vendor Specific Capability Structure register group size */
static int xen_pt_vendor_size_init(XenPCIPassthroughState *s,
                                   const XenPTRegGroupInfo *grp_reg,
                                   uint32_t base_offset, uint8_t *size)
{
    return xen_host_pci_get_byte(&s->real_device, base_offset + 0x02, size);
}
/* get PCI Express Capability Structure register group size */
static int xen_pt_pcie_size_init(XenPCIPassthroughState *s,
                                 const XenPTRegGroupInfo *grp_reg,
                                 uint32_t base_offset, uint8_t *size)
{
    PCIDevice *d = &s->dev;
    uint8_t version = get_capability_version(s, base_offset);
    uint8_t type = get_device_type(s, base_offset);
    uint8_t pcie_size = 0;


    /* calculate size depend on capability version and device/port type */
    /* in case of PCI Express Base Specification Rev 1.x */
    if (version == 1) {
        /* The PCI Express Capabilities, Device Capabilities, and Device
         * Status/Control registers are required for all PCI Express devices.
         * The Link Capabilities and Link Status/Control are required for all
         * Endpoints that are not Root Complex Integrated Endpoints. Endpoints
         * are not required to implement registers other than those listed
         * above and terminate the capability structure.
         */
        switch (type) {
        case PCI_EXP_TYPE_ENDPOINT:
        case PCI_EXP_TYPE_LEG_END:
            pcie_size = 0x14;
            break;
        case PCI_EXP_TYPE_RC_END:
            /* has no link */
            pcie_size = 0x0C;
            break;
            /* only EndPoint passthrough is supported */
        case PCI_EXP_TYPE_ROOT_PORT:
        case PCI_EXP_TYPE_UPSTREAM:
        case PCI_EXP_TYPE_DOWNSTREAM:
        case PCI_EXP_TYPE_PCI_BRIDGE:
        case PCI_EXP_TYPE_PCIE_BRIDGE:
        case PCI_EXP_TYPE_RC_EC:
        default:
            XEN_PT_ERR(d, "Unsupported device/port type %#x.\n", type);
            return -1;
        }
    }
    /* in case of PCI Express Base Specification Rev 2.0 */
    else if (version == 2) {
        switch (type) {
        case PCI_EXP_TYPE_ENDPOINT:
        case PCI_EXP_TYPE_LEG_END:
        case PCI_EXP_TYPE_RC_END:
            /* For Functions that do not implement the registers,
             * these spaces must be hardwired to 0b.
             */
            pcie_size = 0x3C;
            break;
            /* only EndPoint passthrough is supported */
        case PCI_EXP_TYPE_ROOT_PORT:
        case PCI_EXP_TYPE_UPSTREAM:
        case PCI_EXP_TYPE_DOWNSTREAM:
        case PCI_EXP_TYPE_PCI_BRIDGE:
        case PCI_EXP_TYPE_PCIE_BRIDGE:
        case PCI_EXP_TYPE_RC_EC:
        default:
            XEN_PT_ERR(d, "Unsupported device/port type %#x.\n", type);
            return -1;
        }
    } else {
        XEN_PT_ERR(d, "Unsupported capability version %#x.\n", version);
        return -1;
    }

    *size = pcie_size;
    return 0;
}
/* get MSI Capability Structure register group size */
static int xen_pt_msi_size_init(XenPCIPassthroughState *s,
                                const XenPTRegGroupInfo *grp_reg,
                                uint32_t base_offset, uint8_t *size)
{
    uint16_t msg_ctrl = 0;
    uint8_t msi_size = 0xa;
    int rc;

    rc = xen_host_pci_get_word(&s->real_device, base_offset + PCI_MSI_FLAGS,
                               &msg_ctrl);
    if (rc) {
        return rc;
    }
    /* check if 64-bit address is capable of per-vector masking */
    if (msg_ctrl & PCI_MSI_FLAGS_64BIT) {
        msi_size += 4;
    }
    if (msg_ctrl & PCI_MSI_FLAGS_MASKBIT) {
        msi_size += 10;
    }

    s->msi = g_new0(XenPTMSI, 1);
    s->msi->pirq = XEN_PT_UNASSIGNED_PIRQ;

    *size = msi_size;
    return 0;
}
/* get MSI-X Capability Structure register group size */
static int xen_pt_msix_size_init(XenPCIPassthroughState *s,
                                 const XenPTRegGroupInfo *grp_reg,
                                 uint32_t base_offset, uint8_t *size)
{
    int rc = 0;

    rc = xen_pt_msix_init(s, base_offset);

    if (rc < 0) {
        XEN_PT_ERR(&s->dev, "Internal error: Invalid xen_pt_msix_init.\n");
        return rc;
    }

    *size = grp_reg->grp_size;
    return 0;
}


static const XenPTRegGroupInfo xen_pt_emu_reg_grps[] = {
    /* Header Type0 reg group */
    {
        .grp_id      = 0xFF,
        .grp_type    = XEN_PT_GRP_TYPE_EMU,
        .grp_size    = 0x40,
        .size_init   = xen_pt_reg_grp_size_init,
        .emu_regs = xen_pt_emu_reg_header0,
    },
    /* PCI PowerManagement Capability reg group */
    {
        .grp_id      = PCI_CAP_ID_PM,
        .grp_type    = XEN_PT_GRP_TYPE_EMU,
        .grp_size    = PCI_PM_SIZEOF,
        .size_init   = xen_pt_reg_grp_size_init,
        .emu_regs = xen_pt_emu_reg_pm,
    },
    /* AGP Capability Structure reg group */
    {
        .grp_id     = PCI_CAP_ID_AGP,
        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
        .grp_size   = 0x30,
        .size_init  = xen_pt_reg_grp_size_init,
    },
    /* Vital Product Data Capability Structure reg group */
    {
        .grp_id      = PCI_CAP_ID_VPD,
        .grp_type    = XEN_PT_GRP_TYPE_EMU,
        .grp_size    = 0x08,
        .size_init   = xen_pt_reg_grp_size_init,
        .emu_regs = xen_pt_emu_reg_vpd,
    },
    /* Slot Identification reg group */
    {
        .grp_id     = PCI_CAP_ID_SLOTID,
        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
        .grp_size   = 0x04,
        .size_init  = xen_pt_reg_grp_size_init,
    },
    /* MSI Capability Structure reg group */
    {
        .grp_id      = PCI_CAP_ID_MSI,
        .grp_type    = XEN_PT_GRP_TYPE_EMU,
        .grp_size    = 0xFF,
        .size_init   = xen_pt_msi_size_init,
        .emu_regs = xen_pt_emu_reg_msi,
    },
    /* PCI-X Capabilities List Item reg group */
    {
        .grp_id     = PCI_CAP_ID_PCIX,
        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
        .grp_size   = 0x18,
        .size_init  = xen_pt_reg_grp_size_init,
    },
    /* Vendor Specific Capability Structure reg group */
    {
        .grp_id      = PCI_CAP_ID_VNDR,
        .grp_type    = XEN_PT_GRP_TYPE_EMU,
        .grp_size    = 0xFF,
        .size_init   = xen_pt_vendor_size_init,
        .emu_regs = xen_pt_emu_reg_vendor,
    },
    /* SHPC Capability List Item reg group */
    {
        .grp_id     = PCI_CAP_ID_SHPC,
        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
        .grp_size   = 0x08,
        .size_init  = xen_pt_reg_grp_size_init,
    },
    /* Subsystem ID and Subsystem Vendor ID Capability List Item reg group */
    {
        .grp_id     = PCI_CAP_ID_SSVID,
        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
        .grp_size   = 0x08,
        .size_init  = xen_pt_reg_grp_size_init,
    },
    /* AGP 8x Capability Structure reg group */
    {
        .grp_id     = PCI_CAP_ID_AGP3,
        .grp_type   = XEN_PT_GRP_TYPE_HARDWIRED,
        .grp_size   = 0x30,
        .size_init  = xen_pt_reg_grp_size_init,
    },
    /* PCI Express Capability Structure reg group */
    {
        .grp_id      = PCI_CAP_ID_EXP,
        .grp_type    = XEN_PT_GRP_TYPE_EMU,
        .grp_size    = 0xFF,
        .size_init   = xen_pt_pcie_size_init,
        .emu_regs = xen_pt_emu_reg_pcie,
    },
    /* MSI-X Capability Structure reg group */
    {
        .grp_id      = PCI_CAP_ID_MSIX,
        .grp_type    = XEN_PT_GRP_TYPE_EMU,
        .grp_size    = 0x0C,
        .size_init   = xen_pt_msix_size_init,
        .emu_regs = xen_pt_emu_reg_msix,
    },
    /* Intel IGD Opregion group */
    {
        .grp_id      = XEN_PCI_INTEL_OPREGION,
        .grp_type    = XEN_PT_GRP_TYPE_EMU,
        .grp_size    = 0x4,
        .size_init   = xen_pt_reg_grp_size_init,
        .emu_regs    = xen_pt_emu_reg_igd_opregion,
    },
    {
        .grp_size = 0,
    },
};

/* initialize Capabilities Pointer or Next Pointer register */
static int xen_pt_ptr_reg_init(XenPCIPassthroughState *s,
                               XenPTRegInfo *reg, uint32_t real_offset,
                               uint32_t *data)
{
    int i, rc;
    uint8_t reg_field;
    uint8_t cap_id = 0;

    rc = xen_host_pci_get_byte(&s->real_device, real_offset, &reg_field);
    if (rc) {
        return rc;
    }
    /* find capability offset */
    while (reg_field) {
        for (i = 0; xen_pt_emu_reg_grps[i].grp_size != 0; i++) {
            if (xen_pt_hide_dev_cap(&s->real_device,
                                    xen_pt_emu_reg_grps[i].grp_id)) {
                continue;
            }

            rc = xen_host_pci_get_byte(&s->real_device,
                                       reg_field + PCI_CAP_LIST_ID, &cap_id);
            if (rc) {
                XEN_PT_ERR(&s->dev, "Failed to read capability @0x%x (rc:%d)\n",
                           reg_field + PCI_CAP_LIST_ID, rc);
                return rc;
            }
            if (xen_pt_emu_reg_grps[i].grp_id == cap_id) {
                if (xen_pt_emu_reg_grps[i].grp_type == XEN_PT_GRP_TYPE_EMU) {
                    goto out;
                }
                /* ignore the 0 hardwired capability, find next one */
                break;
            }
        }

        /* next capability */
        rc = xen_host_pci_get_byte(&s->real_device,
                                   reg_field + PCI_CAP_LIST_NEXT, &reg_field);
        if (rc) {
            return rc;
        }
    }

out:
    *data = reg_field;
    return 0;
}


/*************
 * Main
 */

static uint8_t find_cap_offset(XenPCIPassthroughState *s, uint8_t cap)
{
    uint8_t id;
    unsigned max_cap = XEN_PCI_CAP_MAX;
    uint8_t pos = PCI_CAPABILITY_LIST;
    uint8_t status = 0;

    if (xen_host_pci_get_byte(&s->real_device, PCI_STATUS, &status)) {
        return 0;
    }
    if ((status & PCI_STATUS_CAP_LIST) == 0) {
        return 0;
    }

    while (max_cap--) {
        if (xen_host_pci_get_byte(&s->real_device, pos, &pos)) {
            break;
        }
        if (pos < PCI_CONFIG_HEADER_SIZE) {
            break;
        }

        pos &= ~3;
        if (xen_host_pci_get_byte(&s->real_device,
                                  pos + PCI_CAP_LIST_ID, &id)) {
            break;
        }

        if (id == 0xff) {
            break;
        }
        if (id == cap) {
            return pos;
        }

        pos += PCI_CAP_LIST_NEXT;
    }
    return 0;
}

static int xen_pt_config_reg_init(XenPCIPassthroughState *s,
                                  XenPTRegGroup *reg_grp, XenPTRegInfo *reg)
{
    XenPTReg *reg_entry;
    uint32_t data = 0;
    int rc = 0;

    reg_entry = g_new0(XenPTReg, 1);
    reg_entry->reg = reg;

    if (reg->init) {
        uint32_t host_mask, size_mask;
        unsigned int offset;
        uint32_t val;

        /* initialize emulate register */
        rc = reg->init(s, reg_entry->reg,
                       reg_grp->base_offset + reg->offset, &data);
        if (rc < 0) {
            g_free(reg_entry);
            return rc;
        }
        if (data == XEN_PT_INVALID_REG) {
            /* free unused BAR register entry */
            g_free(reg_entry);
            return 0;
        }
        /* Sync up the data to dev.config */
        offset = reg_grp->base_offset + reg->offset;
        size_mask = 0xFFFFFFFF >> ((4 - reg->size) << 3);

        switch (reg->size) {
        case 1: rc = xen_host_pci_get_byte(&s->real_device, offset, (uint8_t *)&val);
                break;
        case 2: rc = xen_host_pci_get_word(&s->real_device, offset, (uint16_t *)&val);
                break;
        case 4: rc = xen_host_pci_get_long(&s->real_device, offset, &val);
                break;
        default: abort();
        }
        if (rc) {
            /* Serious issues when we cannot read the host values! */
            g_free(reg_entry);
            return rc;
        }
        /* Set bits in emu_mask are the ones we emulate. The dev.config shall
         * contain the emulated view of the guest - therefore we flip the mask
         * to mask out the host values (which dev.config initially has) . */
        host_mask = size_mask & ~reg->emu_mask;

        if ((data & host_mask) != (val & host_mask)) {
            uint32_t new_val;

            /* Mask out host (including past size). */
            new_val = val & host_mask;
            /* Merge emulated ones (excluding the non-emulated ones). */
            new_val |= data & host_mask;
            /* Leave intact host and emulated values past the size - even though
             * we do not care as we write per reg->size granularity, but for the
             * logging below lets have the proper value. */
            new_val |= ((val | data)) & ~size_mask;
            XEN_PT_LOG(&s->dev,"Offset 0x%04x mismatch! Emulated=0x%04x, host=0x%04x, syncing to 0x%04x.\n",
                       offset, data, val, new_val);
            val = new_val;
        } else
            val = data;

        if (val & ~size_mask) {
            XEN_PT_ERR(&s->dev,"Offset 0x%04x:0x%04x expands past register size(%d)!\n",
                       offset, val, reg->size);
            g_free(reg_entry);
            return -ENXIO;
        }
        /* This could be just pci_set_long as we don't modify the bits
         * past reg->size, but in case this routine is run in parallel or the
         * init value is larger, we do not want to over-write registers. */
        switch (reg->size) {
        case 1: pci_set_byte(s->dev.config + offset, (uint8_t)val);
                break;
        case 2: pci_set_word(s->dev.config + offset, (uint16_t)val);
                break;
        case 4: pci_set_long(s->dev.config + offset, val);
                break;
        default: abort();
        }
        /* set register value pointer to the data. */
        reg_entry->ptr.byte = s->dev.config + offset;

    }
    /* list add register entry */
    QLIST_INSERT_HEAD(&reg_grp->reg_tbl_list, reg_entry, entries);

    return 0;
}

int xen_pt_config_init(XenPCIPassthroughState *s)
{
    int i, rc;

    QLIST_INIT(&s->reg_grps);

    for (i = 0; xen_pt_emu_reg_grps[i].grp_size != 0; i++) {
        uint32_t reg_grp_offset = 0;
        XenPTRegGroup *reg_grp_entry = NULL;

        if (xen_pt_emu_reg_grps[i].grp_id != 0xFF
            && xen_pt_emu_reg_grps[i].grp_id != XEN_PCI_INTEL_OPREGION) {
            if (xen_pt_hide_dev_cap(&s->real_device,
                                    xen_pt_emu_reg_grps[i].grp_id)) {
                continue;
            }

            reg_grp_offset = find_cap_offset(s, xen_pt_emu_reg_grps[i].grp_id);

            if (!reg_grp_offset) {
                continue;
            }
        }

        /*
         * By default we will trap up to 0x40 in the cfg space.
         * If an intel device is pass through we need to trap 0xfc,
         * therefore the size should be 0xff.
         */
        if (xen_pt_emu_reg_grps[i].grp_id == XEN_PCI_INTEL_OPREGION) {
            reg_grp_offset = XEN_PCI_INTEL_OPREGION;
        }

        reg_grp_entry = g_new0(XenPTRegGroup, 1);
        QLIST_INIT(&reg_grp_entry->reg_tbl_list);
        QLIST_INSERT_HEAD(&s->reg_grps, reg_grp_entry, entries);

        reg_grp_entry->base_offset = reg_grp_offset;
        reg_grp_entry->reg_grp = xen_pt_emu_reg_grps + i;
        if (xen_pt_emu_reg_grps[i].size_init) {
            /* get register group size */
            rc = xen_pt_emu_reg_grps[i].size_init(s, reg_grp_entry->reg_grp,
                                                  reg_grp_offset,
                                                  &reg_grp_entry->size);
            if (rc < 0) {
                XEN_PT_LOG(&s->dev, "Failed to initialize %d/%ld, type=0x%x, rc:%d\n",
                           i, ARRAY_SIZE(xen_pt_emu_reg_grps),
                           xen_pt_emu_reg_grps[i].grp_type, rc);
                xen_pt_config_delete(s);
                return rc;
            }
        }

        if (xen_pt_emu_reg_grps[i].grp_type == XEN_PT_GRP_TYPE_EMU) {
            if (xen_pt_emu_reg_grps[i].emu_regs) {
                int j = 0;
                XenPTRegInfo *regs = xen_pt_emu_reg_grps[i].emu_regs;
                /* initialize capability register */
                for (j = 0; regs->size != 0; j++, regs++) {
                    /* initialize capability register */
                    rc = xen_pt_config_reg_init(s, reg_grp_entry, regs);
                    if (rc < 0) {
                        XEN_PT_LOG(&s->dev, "Failed to initialize %d/%ld reg 0x%x in grp_type=0x%x (%d/%ld), rc=%d\n",
                                   j, ARRAY_SIZE(xen_pt_emu_reg_grps[i].emu_regs),
                                   regs->offset, xen_pt_emu_reg_grps[i].grp_type,
                                   i, ARRAY_SIZE(xen_pt_emu_reg_grps), rc);
                        xen_pt_config_delete(s);
                        return rc;
                    }
                }
            }
        }
    }

    return 0;
}

/* delete all emulate register */
void xen_pt_config_delete(XenPCIPassthroughState *s)
{
    struct XenPTRegGroup *reg_group, *next_grp;
    struct XenPTReg *reg, *next_reg;

    /* free MSI/MSI-X info table */
    if (s->msix) {
        xen_pt_msix_unmap(s);
    }
    g_free(s->msi);

    /* free all register group entry */
    QLIST_FOREACH_SAFE(reg_group, &s->reg_grps, entries, next_grp) {
        /* free all register entry */
        QLIST_FOREACH_SAFE(reg, &reg_group->reg_tbl_list, entries, next_reg) {
            QLIST_REMOVE(reg, entries);
            g_free(reg);
        }

        QLIST_REMOVE(reg_group, entries);
        g_free(reg_group);
    }
}