summaryrefslogtreecommitdiffstats
path: root/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c
blob: 9251388bc26836f6422656cf7b5a4b32bb3001e0 (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
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
/** @file
  PCI emumeration support functions implementation for PCI Bus module.

Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.<BR>
(C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent

**/

#include "PciBus.h"

extern CHAR16                          *mBarTypeStr[];
extern EDKII_DEVICE_SECURITY_PROTOCOL  *mDeviceSecurityProtocol;

#define OLD_ALIGN    0xFFFFFFFFFFFFFFFFULL
#define EVEN_ALIGN   0xFFFFFFFFFFFFFFFEULL
#define SQUAD_ALIGN  0xFFFFFFFFFFFFFFFDULL
#define DQUAD_ALIGN  0xFFFFFFFFFFFFFFFCULL

/**
  This routine is used to check whether the pci device is present.

  @param PciRootBridgeIo   Pointer to instance of EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL.
  @param Pci               Output buffer for PCI device configuration space.
  @param Bus               PCI bus NO.
  @param Device            PCI device NO.
  @param Func              PCI Func NO.

  @retval EFI_NOT_FOUND    PCI device not present.
  @retval EFI_SUCCESS      PCI device is found.

**/
EFI_STATUS
PciDevicePresent (
  IN  EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL  *PciRootBridgeIo,
  OUT PCI_TYPE00                       *Pci,
  IN  UINT8                            Bus,
  IN  UINT8                            Device,
  IN  UINT8                            Func
  )
{
  UINT64      Address;
  EFI_STATUS  Status;

  //
  // Create PCI address map in terms of Bus, Device and Func
  //
  Address = EFI_PCI_ADDRESS (Bus, Device, Func, 0);

  //
  // Read the Vendor ID register
  //
  Status = PciRootBridgeIo->Pci.Read (
                                  PciRootBridgeIo,
                                  EfiPciWidthUint32,
                                  Address,
                                  1,
                                  Pci
                                  );

  if (!EFI_ERROR (Status) && ((Pci->Hdr).VendorId != 0xffff)) {
    //
    // Read the entire config header for the device
    //
    Status = PciRootBridgeIo->Pci.Read (
                                    PciRootBridgeIo,
                                    EfiPciWidthUint32,
                                    Address,
                                    sizeof (PCI_TYPE00) / sizeof (UINT32),
                                    Pci
                                    );

    return EFI_SUCCESS;
  }

  return EFI_NOT_FOUND;
}

/**
  Collect all the resource information under this root bridge.

  A database that records all the information about pci device subject to this
  root bridge will then be created.

  @param Bridge         Parent bridge instance.
  @param StartBusNumber Bus number of beginning.

  @retval EFI_SUCCESS   PCI device is found.
  @retval other         Some error occurred when reading PCI bridge information.

**/
EFI_STATUS
PciPciDeviceInfoCollector (
  IN PCI_IO_DEVICE  *Bridge,
  IN UINT8          StartBusNumber
  )
{
  EFI_STATUS           Status;
  PCI_TYPE00           Pci;
  UINT8                Device;
  UINT8                Func;
  UINT8                SecBus;
  PCI_IO_DEVICE        *PciIoDevice;
  EFI_PCI_IO_PROTOCOL  *PciIo;

  Status = EFI_SUCCESS;
  SecBus = 0;

  for (Device = 0; Device <= PCI_MAX_DEVICE; Device++) {
    for (Func = 0; Func <= PCI_MAX_FUNC; Func++) {
      //
      // Check to see whether PCI device is present
      //
      Status = PciDevicePresent (
                 Bridge->PciRootBridgeIo,
                 &Pci,
                 (UINT8)StartBusNumber,
                 (UINT8)Device,
                 (UINT8)Func
                 );

      if (EFI_ERROR (Status) && (Func == 0)) {
        //
        // go to next device if there is no Function 0
        //
        break;
      }

      if (!EFI_ERROR (Status)) {
        //
        // Call back to host bridge function
        //
        PreprocessController (Bridge, (UINT8)StartBusNumber, Device, Func, EfiPciBeforeResourceCollection);

        //
        // Collect all the information about the PCI device discovered
        //
        Status = PciSearchDevice (
                   Bridge,
                   &Pci,
                   (UINT8)StartBusNumber,
                   Device,
                   Func,
                   &PciIoDevice
                   );

        //
        // Recursively scan PCI busses on the other side of PCI-PCI bridges
        //
        //
        if (!EFI_ERROR (Status) && (IS_PCI_BRIDGE (&Pci) || IS_CARDBUS_BRIDGE (&Pci))) {
          //
          // If it is PPB, we need to get the secondary bus to continue the enumeration
          //
          PciIo = &(PciIoDevice->PciIo);

          Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, PCI_BRIDGE_SECONDARY_BUS_REGISTER_OFFSET, 1, &SecBus);

          if (EFI_ERROR (Status)) {
            return Status;
          }

          //
          // Ensure secondary bus number is greater than the primary bus number to avoid
          // any potential dead loop when PcdPciDisableBusEnumeration is set to TRUE
          //
          if (SecBus <= StartBusNumber) {
            break;
          }

          //
          // Get resource padding for PPB
          //
          GetResourcePaddingPpb (PciIoDevice);

          //
          // Deep enumerate the next level bus
          //
          Status = PciPciDeviceInfoCollector (
                     PciIoDevice,
                     (UINT8)(SecBus)
                     );
        }

        if ((Func == 0) && !IS_PCI_MULTI_FUNC (&Pci)) {
          //
          // Skip sub functions, this is not a multi function device
          //
          Func = PCI_MAX_FUNC;
        }
      }
    }
  }

  return EFI_SUCCESS;
}

/**
  Search required device and create PCI device instance.

  @param Bridge     Parent bridge instance.
  @param Pci        Input PCI device information block.
  @param Bus        PCI bus NO.
  @param Device     PCI device NO.
  @param Func       PCI func  NO.
  @param PciDevice  Output of searched PCI device instance.

  @retval EFI_SUCCESS           Successfully created PCI device instance.
  @retval EFI_OUT_OF_RESOURCES  Cannot get PCI device information.

**/
EFI_STATUS
PciSearchDevice (
  IN  PCI_IO_DEVICE  *Bridge,
  IN  PCI_TYPE00     *Pci,
  IN  UINT8          Bus,
  IN  UINT8          Device,
  IN  UINT8          Func,
  OUT PCI_IO_DEVICE  **PciDevice
  )
{
  PCI_IO_DEVICE  *PciIoDevice;

  PciIoDevice = NULL;

  DEBUG ((
    DEBUG_INFO,
    "PciBus: Discovered %s @ [%02x|%02x|%02x]\n",
    IS_PCI_BRIDGE (Pci) ?     L"PPB" :
    IS_CARDBUS_BRIDGE (Pci) ? L"P2C" :
    L"PCI",
    Bus,
    Device,
    Func
    ));

  if (!IS_PCI_BRIDGE (Pci)) {
    if (IS_CARDBUS_BRIDGE (Pci)) {
      PciIoDevice = GatherP2CInfo (
                      Bridge,
                      Pci,
                      Bus,
                      Device,
                      Func
                      );
      if ((PciIoDevice != NULL) && gFullEnumeration) {
        InitializeP2C (PciIoDevice);
      }
    } else {
      //
      // Create private data for Pci Device
      //
      PciIoDevice = GatherDeviceInfo (
                      Bridge,
                      Pci,
                      Bus,
                      Device,
                      Func
                      );
    }
  } else {
    //
    // Create private data for PPB
    //
    PciIoDevice = GatherPpbInfo (
                    Bridge,
                    Pci,
                    Bus,
                    Device,
                    Func
                    );

    //
    // Special initialization for PPB including making the PPB quiet
    //
    if ((PciIoDevice != NULL) && gFullEnumeration) {
      InitializePpb (PciIoDevice);
    }
  }

  if (PciIoDevice == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  //
  // Update the bar information for this PCI device so as to support some specific device
  //
  UpdatePciInfo (PciIoDevice);

  if (PciIoDevice->DevicePath == NULL) {
    return EFI_OUT_OF_RESOURCES;
  }

  //
  // Detect this function has option rom
  //
  if (gFullEnumeration) {
    if (!IS_CARDBUS_BRIDGE (Pci)) {
      GetOpRomInfo (PciIoDevice);
    }

    ResetPowerManagementFeature (PciIoDevice);
  }

  //
  // Insert it into a global tree for future reference
  //
  InsertPciDevice (Bridge, PciIoDevice);

  //
  // Determine PCI device attributes
  //

  if (PciDevice != NULL) {
    *PciDevice = PciIoDevice;
  }

  return EFI_SUCCESS;
}

/**
  Dump the PPB padding resource information.

  @param PciIoDevice     PCI IO instance.
  @param ResourceType    The desired resource type to dump.
                         PciBarTypeUnknown means to dump all types of resources.
**/
VOID
DumpPpbPaddingResource (
  IN PCI_IO_DEVICE  *PciIoDevice,
  IN PCI_BAR_TYPE   ResourceType
  )
{
  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR  *Descriptor;
  PCI_BAR_TYPE                       Type;

  if (PciIoDevice->ResourcePaddingDescriptors == NULL) {
    return;
  }

  if ((ResourceType == PciBarTypeIo16) || (ResourceType == PciBarTypeIo32)) {
    ResourceType = PciBarTypeIo;
  }

  for (Descriptor = PciIoDevice->ResourcePaddingDescriptors; Descriptor->Desc != ACPI_END_TAG_DESCRIPTOR; Descriptor++) {
    Type = PciBarTypeUnknown;
    if ((Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR) && (Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_IO)) {
      Type = PciBarTypeIo;
    } else if ((Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR) && (Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM)) {
      if (Descriptor->AddrSpaceGranularity == 32) {
        //
        // prefetchable
        //
        if (Descriptor->SpecificFlag == EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE) {
          Type = PciBarTypePMem32;
        }

        //
        // Non-prefetchable
        //
        if (Descriptor->SpecificFlag == 0) {
          Type = PciBarTypeMem32;
        }
      }

      if (Descriptor->AddrSpaceGranularity == 64) {
        //
        // prefetchable
        //
        if (Descriptor->SpecificFlag == EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE) {
          Type = PciBarTypePMem64;
        }

        //
        // Non-prefetchable
        //
        if (Descriptor->SpecificFlag == 0) {
          Type = PciBarTypeMem64;
        }
      }
    }

    if ((Type != PciBarTypeUnknown) && ((ResourceType == PciBarTypeUnknown) || (ResourceType == Type))) {
      DEBUG ((
        DEBUG_INFO,
        "   Padding: Type = %s; Alignment = 0x%lx;\tLength = 0x%lx\n",
        mBarTypeStr[Type],
        Descriptor->AddrRangeMax,
        Descriptor->AddrLen
        ));
    }
  }
}

/**
  Dump the PCI BAR information.

  @param PciIoDevice     PCI IO instance.
**/
VOID
DumpPciBars (
  IN PCI_IO_DEVICE  *PciIoDevice
  )
{
  UINTN  Index;

  for (Index = 0; Index < PCI_MAX_BAR; Index++) {
    if (PciIoDevice->PciBar[Index].BarType == PciBarTypeUnknown) {
      continue;
    }

    DEBUG ((
      DEBUG_INFO,
      "   BAR[%d]: Type = %s; Alignment = 0x%lx;\tLength = 0x%lx;\tOffset = 0x%02x\n",
      Index,
      mBarTypeStr[MIN (PciIoDevice->PciBar[Index].BarType, PciBarTypeMaxType)],
      PciIoDevice->PciBar[Index].Alignment,
      PciIoDevice->PciBar[Index].Length,
      PciIoDevice->PciBar[Index].Offset
      ));
  }

  for (Index = 0; Index < PCI_MAX_BAR; Index++) {
    if ((PciIoDevice->VfPciBar[Index].BarType == PciBarTypeUnknown) && (PciIoDevice->VfPciBar[Index].Length == 0)) {
      continue;
    }

    DEBUG ((
      DEBUG_INFO,
      " VFBAR[%d]: Type = %s; Alignment = 0x%lx;\tLength = 0x%lx;\tOffset = 0x%02x\n",
      Index,
      mBarTypeStr[MIN (PciIoDevice->VfPciBar[Index].BarType, PciBarTypeMaxType)],
      PciIoDevice->VfPciBar[Index].Alignment,
      PciIoDevice->VfPciBar[Index].Length,
      PciIoDevice->VfPciBar[Index].Offset
      ));
  }

  DEBUG ((DEBUG_INFO, "\n"));
}

/**
  Create PCI device instance for PCI device.

  @param Bridge   Parent bridge instance.
  @param Pci      Input PCI device information block.
  @param Bus      PCI device Bus NO.
  @param Device   PCI device Device NO.
  @param Func     PCI device's func NO.

  @return  Created PCI device instance.

**/
PCI_IO_DEVICE *
GatherDeviceInfo (
  IN PCI_IO_DEVICE  *Bridge,
  IN PCI_TYPE00     *Pci,
  IN UINT8          Bus,
  IN UINT8          Device,
  IN UINT8          Func
  )
{
  UINTN          Offset;
  UINTN          BarIndex;
  PCI_IO_DEVICE  *PciIoDevice;

  PciIoDevice = CreatePciIoDevice (
                  Bridge,
                  Pci,
                  Bus,
                  Device,
                  Func
                  );

  if (PciIoDevice == NULL) {
    return NULL;
  }

  //
  // If it is a full enumeration, disconnect the device in advance
  //
  if (gFullEnumeration) {
    PCI_DISABLE_COMMAND_REGISTER (PciIoDevice, EFI_PCI_COMMAND_BITS_OWNED);
  }

  //
  // Start to parse the bars
  //
  for (Offset = 0x10, BarIndex = 0; Offset <= 0x24 && BarIndex < PCI_MAX_BAR; BarIndex++) {
    Offset = PciParseBar (PciIoDevice, Offset, BarIndex);
  }

  //
  // Parse the SR-IOV VF bars
  //
  if (PcdGetBool (PcdSrIovSupport) && (PciIoDevice->SrIovCapabilityOffset != 0)) {
    for (Offset = PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_BAR0, BarIndex = 0;
         Offset <= PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_BAR5;
         BarIndex++)
    {
      ASSERT (BarIndex < PCI_MAX_BAR);
      Offset = PciIovParseVfBar (PciIoDevice, Offset, BarIndex);
    }
  }

  DEBUG_CODE (
    DumpPciBars (PciIoDevice);
    );
  return PciIoDevice;
}

/**
  Create PCI device instance for PCI-PCI bridge.

  @param Bridge   Parent bridge instance.
  @param Pci      Input PCI device information block.
  @param Bus      PCI device Bus NO.
  @param Device   PCI device Device NO.
  @param Func     PCI device's func NO.

  @return  Created PCI device instance.

**/
PCI_IO_DEVICE *
GatherPpbInfo (
  IN PCI_IO_DEVICE  *Bridge,
  IN PCI_TYPE00     *Pci,
  IN UINT8          Bus,
  IN UINT8          Device,
  IN UINT8          Func
  )
{
  PCI_IO_DEVICE        *PciIoDevice;
  EFI_STATUS           Status;
  UINT8                Value;
  EFI_PCI_IO_PROTOCOL  *PciIo;
  UINT8                Temp;
  UINT32               PMemBaseLimit;
  UINT16               PrefetchableMemoryBase;
  UINT16               PrefetchableMemoryLimit;

  PciIoDevice = CreatePciIoDevice (
                  Bridge,
                  Pci,
                  Bus,
                  Device,
                  Func
                  );

  if (PciIoDevice == NULL) {
    return NULL;
  }

  if (gFullEnumeration) {
    PCI_DISABLE_COMMAND_REGISTER (PciIoDevice, EFI_PCI_COMMAND_BITS_OWNED);

    //
    // Initialize the bridge control register
    //
    PCI_DISABLE_BRIDGE_CONTROL_REGISTER (PciIoDevice, EFI_PCI_BRIDGE_CONTROL_BITS_OWNED);
  }

  //
  // PPB can have two BARs
  //
  if (PciParseBar (PciIoDevice, 0x10, PPB_BAR_0) == 0x14) {
    //
    // Not 64-bit bar
    //
    PciParseBar (PciIoDevice, 0x14, PPB_BAR_1);
  }

  PciIo = &PciIoDevice->PciIo;

  //
  // Test whether it support 32 decode or not
  //
  PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, 0x1C, 1, &Temp);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint8, 0x1C, 1, &gAllOne);
  PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, 0x1C, 1, &Value);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint8, 0x1C, 1, &Temp);

  if (Value != 0) {
    if ((Value & 0x01) != 0) {
      PciIoDevice->Decodes |= EFI_BRIDGE_IO32_DECODE_SUPPORTED;
    } else {
      PciIoDevice->Decodes |= EFI_BRIDGE_IO16_DECODE_SUPPORTED;
    }
  }

  //
  // if PcdPciBridgeIoAlignmentProbe is TRUE, PCI bus driver probes
  // PCI bridge supporting non-standard I/O window alignment less than 4K.
  //

  PciIoDevice->BridgeIoAlignment = 0xFFF;
  if (FeaturePcdGet (PcdPciBridgeIoAlignmentProbe)) {
    //
    // Check any bits of bit 3-1 of I/O Base Register are writable.
    // if so, it is assumed non-standard I/O window alignment is supported by this bridge.
    // Per spec, bit 3-1 of I/O Base Register are reserved bits, so its content can't be assumed.
    //
    Value = (UINT8)(Temp ^ (BIT3 | BIT2 | BIT1));
    PciIo->Pci.Write (PciIo, EfiPciIoWidthUint8, 0x1C, 1, &Value);
    PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, 0x1C, 1, &Value);
    PciIo->Pci.Write (PciIo, EfiPciIoWidthUint8, 0x1C, 1, &Temp);
    Value = (UINT8)((Value ^ Temp) & (BIT3 | BIT2 | BIT1));
    switch (Value) {
      case BIT3:
        PciIoDevice->BridgeIoAlignment = 0x7FF;
        break;
      case BIT3 | BIT2:
        PciIoDevice->BridgeIoAlignment = 0x3FF;
        break;
      case BIT3 | BIT2 | BIT1:
        PciIoDevice->BridgeIoAlignment = 0x1FF;
        break;
    }
  }

  Status = BarExisted (
             PciIoDevice,
             0x24,
             NULL,
             &PMemBaseLimit
             );

  //
  // Test if it supports 64 memory or not
  //
  // The bottom 4 bits of both the Prefetchable Memory Base and Prefetchable Memory Limit
  // registers:
  //   0 - the bridge supports only 32 bit addresses.
  //   1 - the bridge supports 64-bit addresses.
  //
  PrefetchableMemoryBase  = (UINT16)(PMemBaseLimit & 0xffff);
  PrefetchableMemoryLimit = (UINT16)(PMemBaseLimit >> 16);
  if (!EFI_ERROR (Status) &&
      ((PrefetchableMemoryBase & 0x000f) == 0x0001) &&
      ((PrefetchableMemoryLimit & 0x000f) == 0x0001))
  {
    Status = BarExisted (
               PciIoDevice,
               0x28,
               NULL,
               NULL
               );

    if (!EFI_ERROR (Status)) {
      PciIoDevice->Decodes |= EFI_BRIDGE_PMEM32_DECODE_SUPPORTED;
      PciIoDevice->Decodes |= EFI_BRIDGE_PMEM64_DECODE_SUPPORTED;
    } else {
      PciIoDevice->Decodes |= EFI_BRIDGE_PMEM32_DECODE_SUPPORTED;
    }
  }

  //
  // Memory 32 code is required for ppb
  //
  PciIoDevice->Decodes |= EFI_BRIDGE_MEM32_DECODE_SUPPORTED;

  GetResourcePaddingPpb (PciIoDevice);

  DEBUG_CODE (
    DumpPpbPaddingResource (PciIoDevice, PciBarTypeUnknown);
    DumpPciBars (PciIoDevice);
    );

  return PciIoDevice;
}

/**
  Create PCI device instance for PCI Card bridge device.

  @param Bridge   Parent bridge instance.
  @param Pci      Input PCI device information block.
  @param Bus      PCI device Bus NO.
  @param Device   PCI device Device NO.
  @param Func     PCI device's func NO.

  @return  Created PCI device instance.

**/
PCI_IO_DEVICE *
GatherP2CInfo (
  IN PCI_IO_DEVICE  *Bridge,
  IN PCI_TYPE00     *Pci,
  IN UINT8          Bus,
  IN UINT8          Device,
  IN UINT8          Func
  )
{
  PCI_IO_DEVICE  *PciIoDevice;

  PciIoDevice = CreatePciIoDevice (
                  Bridge,
                  Pci,
                  Bus,
                  Device,
                  Func
                  );

  if (PciIoDevice == NULL) {
    return NULL;
  }

  if (gFullEnumeration) {
    PCI_DISABLE_COMMAND_REGISTER (PciIoDevice, EFI_PCI_COMMAND_BITS_OWNED);

    //
    // Initialize the bridge control register
    //
    PCI_DISABLE_BRIDGE_CONTROL_REGISTER (PciIoDevice, EFI_PCCARD_BRIDGE_CONTROL_BITS_OWNED);
  }

  //
  // P2C only has one bar that is in 0x10
  //
  PciParseBar (PciIoDevice, 0x10, P2C_BAR_0);

  //
  // Read PciBar information from the bar register
  //
  GetBackPcCardBar (PciIoDevice);
  PciIoDevice->Decodes = EFI_BRIDGE_MEM32_DECODE_SUPPORTED  |
                         EFI_BRIDGE_PMEM32_DECODE_SUPPORTED |
                         EFI_BRIDGE_IO32_DECODE_SUPPORTED;

  DEBUG_CODE (
    DumpPciBars (PciIoDevice);
    );

  return PciIoDevice;
}

/**
  Create device path for pci device.

  @param ParentDevicePath  Parent bridge's path.
  @param PciIoDevice       Pci device instance.

  @return Device path protocol instance for specific pci device.

**/
EFI_DEVICE_PATH_PROTOCOL *
CreatePciDevicePath (
  IN  EFI_DEVICE_PATH_PROTOCOL  *ParentDevicePath,
  IN  PCI_IO_DEVICE             *PciIoDevice
  )
{
  PCI_DEVICE_PATH  PciNode;

  //
  // Create PCI device path
  //
  PciNode.Header.Type    = HARDWARE_DEVICE_PATH;
  PciNode.Header.SubType = HW_PCI_DP;
  SetDevicePathNodeLength (&PciNode.Header, sizeof (PciNode));

  PciNode.Device          = PciIoDevice->DeviceNumber;
  PciNode.Function        = PciIoDevice->FunctionNumber;
  PciIoDevice->DevicePath = AppendDevicePathNode (ParentDevicePath, &PciNode.Header);

  return PciIoDevice->DevicePath;
}

/**
  Check whether the PCI IOV VF bar is existed or not.

  @param PciIoDevice       A pointer to the PCI_IO_DEVICE.
  @param Offset            The offset.
  @param BarLengthValue    The bar length value returned.
  @param OriginalBarValue  The original bar value returned.

  @retval EFI_NOT_FOUND    The bar doesn't exist.
  @retval EFI_SUCCESS      The bar exist.

**/
EFI_STATUS
VfBarExisted (
  IN PCI_IO_DEVICE  *PciIoDevice,
  IN UINTN          Offset,
  OUT UINT32        *BarLengthValue,
  OUT UINT32        *OriginalBarValue
  )
{
  EFI_PCI_IO_PROTOCOL  *PciIo;
  UINT32               OriginalValue;
  UINT32               Value;
  EFI_TPL              OldTpl;

  //
  // Ensure it is called properly
  //
  ASSERT (PciIoDevice->SrIovCapabilityOffset != 0);
  if (PciIoDevice->SrIovCapabilityOffset == 0) {
    return EFI_NOT_FOUND;
  }

  PciIo = &PciIoDevice->PciIo;

  //
  // Preserve the original value
  //

  PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, (UINT32)Offset, 1, &OriginalValue);

  //
  // Raise TPL to high level to disable timer interrupt while the BAR is probed
  //
  OldTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);

  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, (UINT32)Offset, 1, &gAllOne);
  PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, (UINT32)Offset, 1, &Value);

  //
  // Write back the original value
  //
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, (UINT32)Offset, 1, &OriginalValue);

  //
  // Restore TPL to its original level
  //
  gBS->RestoreTPL (OldTpl);

  if (BarLengthValue != NULL) {
    *BarLengthValue = Value;
  }

  if (OriginalBarValue != NULL) {
    *OriginalBarValue = OriginalValue;
  }

  if (Value == 0) {
    return EFI_NOT_FOUND;
  } else {
    return EFI_SUCCESS;
  }
}

/**
  Check whether the bar is existed or not.

  @param PciIoDevice       A pointer to the PCI_IO_DEVICE.
  @param Offset            The offset.
  @param BarLengthValue    The bar length value returned.
  @param OriginalBarValue  The original bar value returned.

  @retval EFI_NOT_FOUND    The bar doesn't exist.
  @retval EFI_SUCCESS      The bar exist.

**/
EFI_STATUS
BarExisted (
  IN  PCI_IO_DEVICE  *PciIoDevice,
  IN  UINTN          Offset,
  OUT UINT32         *BarLengthValue,
  OUT UINT32         *OriginalBarValue
  )
{
  EFI_PCI_IO_PROTOCOL  *PciIo;
  UINT32               OriginalValue;
  UINT32               Value;
  EFI_TPL              OldTpl;

  PciIo = &PciIoDevice->PciIo;

  //
  // Preserve the original value
  //
  PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, (UINT8)Offset, 1, &OriginalValue);

  //
  // Raise TPL to high level to disable timer interrupt while the BAR is probed
  //
  OldTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);

  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, (UINT8)Offset, 1, &gAllOne);
  PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, (UINT8)Offset, 1, &Value);

  //
  // Write back the original value
  //
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, (UINT8)Offset, 1, &OriginalValue);

  //
  // Restore TPL to its original level
  //
  gBS->RestoreTPL (OldTpl);

  if (BarLengthValue != NULL) {
    *BarLengthValue = Value;
  }

  if (OriginalBarValue != NULL) {
    *OriginalBarValue = OriginalValue;
  }

  if (Value == 0) {
    return EFI_NOT_FOUND;
  } else {
    return EFI_SUCCESS;
  }
}

/**
  Test whether the device can support given attributes.

  @param PciIoDevice      Pci device instance.
  @param Command          Input command register value, and
                          returned supported register value.
  @param BridgeControl    Input bridge control value for PPB or P2C, and
                          returned supported bridge control value.
  @param OldCommand       Returned and stored old command register offset.
  @param OldBridgeControl Returned and stored old Bridge control value for PPB or P2C.

**/
VOID
PciTestSupportedAttribute (
  IN     PCI_IO_DEVICE  *PciIoDevice,
  IN OUT UINT16         *Command,
  IN OUT UINT16         *BridgeControl,
  OUT UINT16            *OldCommand,
  OUT UINT16            *OldBridgeControl
  )
{
  EFI_TPL  OldTpl;
  UINT16   CommandValue;

  //
  // Preserve the original value
  //
  PCI_READ_COMMAND_REGISTER (PciIoDevice, OldCommand);

  //
  // Raise TPL to high level to disable timer interrupt while the BAR is probed
  //
  OldTpl       = gBS->RaiseTPL (TPL_HIGH_LEVEL);
  CommandValue = *Command | *OldCommand;

  PCI_SET_COMMAND_REGISTER (PciIoDevice, CommandValue);
  PCI_READ_COMMAND_REGISTER (PciIoDevice, &CommandValue);

  *Command = *Command & CommandValue;
  //
  // Write back the original value
  //
  PCI_SET_COMMAND_REGISTER (PciIoDevice, *OldCommand);

  //
  // Restore TPL to its original level
  //
  gBS->RestoreTPL (OldTpl);

  if (IS_PCI_BRIDGE (&PciIoDevice->Pci) || IS_CARDBUS_BRIDGE (&PciIoDevice->Pci)) {
    //
    // Preserve the original value
    //
    PCI_READ_BRIDGE_CONTROL_REGISTER (PciIoDevice, OldBridgeControl);

    //
    // Raise TPL to high level to disable timer interrupt while the BAR is probed
    //
    OldTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL);

    PCI_SET_BRIDGE_CONTROL_REGISTER (PciIoDevice, *BridgeControl);
    PCI_READ_BRIDGE_CONTROL_REGISTER (PciIoDevice, BridgeControl);

    //
    // Write back the original value
    //
    PCI_SET_BRIDGE_CONTROL_REGISTER (PciIoDevice, *OldBridgeControl);

    //
    // Restore TPL to its original level
    //
    gBS->RestoreTPL (OldTpl);
  } else {
    *OldBridgeControl = 0;
    *BridgeControl    = 0;
  }
}

/**
  Set the supported or current attributes of a PCI device.

  @param PciIoDevice    Structure pointer for PCI device.
  @param Command        Command register value.
  @param BridgeControl  Bridge control value for PPB or P2C.
  @param Option         Make a choice of EFI_SET_SUPPORTS or EFI_SET_ATTRIBUTES.

**/
VOID
PciSetDeviceAttribute (
  IN PCI_IO_DEVICE  *PciIoDevice,
  IN UINT16         Command,
  IN UINT16         BridgeControl,
  IN UINTN          Option
  )
{
  UINT64  Attributes;

  Attributes = 0;

  if ((Command & EFI_PCI_COMMAND_IO_SPACE) != 0) {
    Attributes |= EFI_PCI_IO_ATTRIBUTE_IO;
  }

  if ((Command & EFI_PCI_COMMAND_MEMORY_SPACE) != 0) {
    Attributes |= EFI_PCI_IO_ATTRIBUTE_MEMORY;
  }

  if ((Command & EFI_PCI_COMMAND_BUS_MASTER) != 0) {
    Attributes |= EFI_PCI_IO_ATTRIBUTE_BUS_MASTER;
  }

  if ((Command & EFI_PCI_COMMAND_VGA_PALETTE_SNOOP) != 0) {
    Attributes |= EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO;
  }

  if ((BridgeControl & EFI_PCI_BRIDGE_CONTROL_ISA) != 0) {
    Attributes |= EFI_PCI_IO_ATTRIBUTE_ISA_IO;
  }

  if ((BridgeControl & EFI_PCI_BRIDGE_CONTROL_VGA) != 0) {
    Attributes |= EFI_PCI_IO_ATTRIBUTE_VGA_IO;
    Attributes |= EFI_PCI_IO_ATTRIBUTE_VGA_MEMORY;
    Attributes |= EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO;
  }

  if ((BridgeControl & EFI_PCI_BRIDGE_CONTROL_VGA_16) != 0) {
    Attributes |= EFI_PCI_IO_ATTRIBUTE_VGA_IO_16;
    Attributes |= EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO_16;
  }

  if (Option == EFI_SET_SUPPORTS) {
    Attributes |= (UINT64)(EFI_PCI_IO_ATTRIBUTE_MEMORY_WRITE_COMBINE |
                           EFI_PCI_IO_ATTRIBUTE_MEMORY_CACHED        |
                           EFI_PCI_IO_ATTRIBUTE_MEMORY_DISABLE       |
                           EFI_PCI_IO_ATTRIBUTE_EMBEDDED_DEVICE      |
                           EFI_PCI_IO_ATTRIBUTE_EMBEDDED_ROM         |
                           EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE);

    if (IS_PCI_LPC (&PciIoDevice->Pci)) {
      Attributes |= EFI_PCI_IO_ATTRIBUTE_ISA_MOTHERBOARD_IO;
      Attributes |= (mReserveIsaAliases ? (UINT64)EFI_PCI_IO_ATTRIBUTE_ISA_IO : \
                     (UINT64)EFI_PCI_IO_ATTRIBUTE_ISA_IO_16);
    }

    if (IS_PCI_BRIDGE (&PciIoDevice->Pci) || IS_CARDBUS_BRIDGE (&PciIoDevice->Pci)) {
      //
      // For bridge, it should support IDE attributes
      //
      Attributes |= EFI_PCI_IO_ATTRIBUTE_IDE_SECONDARY_IO;
      Attributes |= EFI_PCI_IO_ATTRIBUTE_IDE_PRIMARY_IO;

      if (mReserveVgaAliases) {
        Attributes &= ~(UINT64)(EFI_PCI_IO_ATTRIBUTE_VGA_IO_16 | \
                                EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO_16);
      } else {
        Attributes &= ~(UINT64)(EFI_PCI_IO_ATTRIBUTE_VGA_IO | \
                                EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO);
      }
    } else {
      if (IS_PCI_IDE (&PciIoDevice->Pci)) {
        Attributes |= EFI_PCI_IO_ATTRIBUTE_IDE_SECONDARY_IO;
        Attributes |= EFI_PCI_IO_ATTRIBUTE_IDE_PRIMARY_IO;
      }

      if (IS_PCI_VGA (&PciIoDevice->Pci)) {
        Attributes |= EFI_PCI_IO_ATTRIBUTE_VGA_MEMORY;
        Attributes |= (mReserveVgaAliases ? (UINT64)EFI_PCI_IO_ATTRIBUTE_VGA_IO : \
                       (UINT64)EFI_PCI_IO_ATTRIBUTE_VGA_IO_16);
      }
    }

    PciIoDevice->Supports  = Attributes;
    PciIoDevice->Supports &= ((PciIoDevice->Parent->Supports) | \
                              EFI_PCI_IO_ATTRIBUTE_IO | EFI_PCI_IO_ATTRIBUTE_MEMORY | \
                              EFI_PCI_IO_ATTRIBUTE_BUS_MASTER);
  } else {
    //
    // When this attribute is clear, the RomImage and RomSize fields in the PCI IO were
    // initialized based on the PCI option ROM found through the ROM BAR of the PCI controller.
    // When this attribute is set, the PCI option ROM described by the RomImage and RomSize
    // fields is not from the the ROM BAR of the PCI controller.
    //
    if (!PciIoDevice->EmbeddedRom) {
      Attributes |= EFI_PCI_IO_ATTRIBUTE_EMBEDDED_ROM;
    }

    PciIoDevice->Attributes = Attributes;
  }
}

/**
  Determine if the device can support Fast Back to Back attribute.

  @param PciIoDevice  Pci device instance.
  @param StatusIndex  Status register value.

  @retval EFI_SUCCESS       This device support Fast Back to Back attribute.
  @retval EFI_UNSUPPORTED   This device doesn't support Fast Back to Back attribute.

**/
EFI_STATUS
GetFastBackToBackSupport (
  IN PCI_IO_DEVICE  *PciIoDevice,
  IN UINT8          StatusIndex
  )
{
  EFI_PCI_IO_PROTOCOL  *PciIo;
  EFI_STATUS           Status;
  UINT32               StatusRegister;

  //
  // Read the status register
  //
  PciIo  = &PciIoDevice->PciIo;
  Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint16, StatusIndex, 1, &StatusRegister);
  if (EFI_ERROR (Status)) {
    return EFI_UNSUPPORTED;
  }

  //
  // Check the Fast B2B bit
  //
  if ((StatusRegister & EFI_PCI_FAST_BACK_TO_BACK_CAPABLE) != 0) {
    return EFI_SUCCESS;
  } else {
    return EFI_UNSUPPORTED;
  }
}

/**
  Process the option ROM for all the children of the specified parent PCI device.
  It can only be used after the first full Option ROM process.

  @param PciIoDevice Pci device instance.

**/
VOID
ProcessOptionRomLight (
  IN PCI_IO_DEVICE  *PciIoDevice
  )
{
  PCI_IO_DEVICE  *Temp;
  LIST_ENTRY     *CurrentLink;

  //
  // For RootBridge, PPB , P2C, go recursively to traverse all its children
  //
  CurrentLink = PciIoDevice->ChildList.ForwardLink;
  while (CurrentLink != NULL && CurrentLink != &PciIoDevice->ChildList) {
    Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink);

    if (!IsListEmpty (&Temp->ChildList)) {
      ProcessOptionRomLight (Temp);
    }

    Temp->AllOpRomProcessed = PciRomGetImageMapping (Temp);

    CurrentLink = CurrentLink->ForwardLink;
  }
}

/**
  Determine the related attributes of all devices under a Root Bridge.

  @param PciIoDevice   PCI device instance.

**/
EFI_STATUS
DetermineDeviceAttribute (
  IN PCI_IO_DEVICE  *PciIoDevice
  )
{
  UINT16         Command;
  UINT16         BridgeControl;
  UINT16         OldCommand;
  UINT16         OldBridgeControl;
  BOOLEAN        FastB2BSupport;
  PCI_IO_DEVICE  *Temp;
  LIST_ENTRY     *CurrentLink;
  EFI_STATUS     Status;

  //
  // For Root Bridge, just copy it by RootBridgeIo protocol
  // so as to keep consistent with the actual attribute
  //
  if (PciIoDevice->Parent == NULL) {
    Status = PciIoDevice->PciRootBridgeIo->GetAttributes (
                                             PciIoDevice->PciRootBridgeIo,
                                             &PciIoDevice->Supports,
                                             &PciIoDevice->Attributes
                                             );
    if (EFI_ERROR (Status)) {
      return Status;
    }

    //
    // Assume the PCI Root Bridge supports DAC
    //
    PciIoDevice->Supports |= (UINT64)(EFI_PCI_IO_ATTRIBUTE_EMBEDDED_DEVICE |
                                      EFI_PCI_IO_ATTRIBUTE_EMBEDDED_ROM |
                                      EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE);
  } else {
    //
    // Set the attributes to be checked for common PCI devices and PPB or P2C
    // Since some devices only support part of them, it is better to set the
    // attribute according to its command or bridge control register
    //
    Command = EFI_PCI_COMMAND_IO_SPACE     |
              EFI_PCI_COMMAND_MEMORY_SPACE |
              EFI_PCI_COMMAND_BUS_MASTER   |
              EFI_PCI_COMMAND_VGA_PALETTE_SNOOP;

    BridgeControl = EFI_PCI_BRIDGE_CONTROL_ISA | EFI_PCI_BRIDGE_CONTROL_VGA | EFI_PCI_BRIDGE_CONTROL_VGA_16;

    //
    // Test whether the device can support attributes above
    //
    PciTestSupportedAttribute (PciIoDevice, &Command, &BridgeControl, &OldCommand, &OldBridgeControl);

    //
    // Set the supported attributes for specified PCI device
    //
    PciSetDeviceAttribute (PciIoDevice, Command, BridgeControl, EFI_SET_SUPPORTS);

    //
    // Set the current attributes for specified PCI device
    //
    PciSetDeviceAttribute (PciIoDevice, OldCommand, OldBridgeControl, EFI_SET_ATTRIBUTES);

    //
    // Enable other PCI supported attributes but not defined in PCI_IO_PROTOCOL
    // For PCI Express devices, Memory Write and Invalidate is hardwired to 0b so only enable it for PCI devices.
    if (!PciIoDevice->IsPciExp) {
      PCI_ENABLE_COMMAND_REGISTER (PciIoDevice, EFI_PCI_COMMAND_MEMORY_WRITE_AND_INVALIDATE);
    }
  }

  FastB2BSupport = TRUE;

  //
  // P2C can not support FB2B on the secondary side
  //
  if (IS_CARDBUS_BRIDGE (&PciIoDevice->Pci)) {
    FastB2BSupport = FALSE;
  }

  //
  // For RootBridge, PPB , P2C, go recursively to traverse all its children
  //
  CurrentLink = PciIoDevice->ChildList.ForwardLink;
  while (CurrentLink != NULL && CurrentLink != &PciIoDevice->ChildList) {
    Temp   = PCI_IO_DEVICE_FROM_LINK (CurrentLink);
    Status = DetermineDeviceAttribute (Temp);
    if (EFI_ERROR (Status)) {
      return Status;
    }

    //
    // Detect Fast Back to Back support for the device under the bridge
    //
    Status = GetFastBackToBackSupport (Temp, PCI_PRIMARY_STATUS_OFFSET);
    if (FastB2BSupport && EFI_ERROR (Status)) {
      FastB2BSupport = FALSE;
    }

    CurrentLink = CurrentLink->ForwardLink;
  }

  //
  // Set or clear Fast Back to Back bit for the whole bridge
  //
  if (!IsListEmpty (&PciIoDevice->ChildList)) {
    if (IS_PCI_BRIDGE (&PciIoDevice->Pci)) {
      Status = GetFastBackToBackSupport (PciIoDevice, PCI_BRIDGE_STATUS_REGISTER_OFFSET);

      if (EFI_ERROR (Status) || (!FastB2BSupport)) {
        FastB2BSupport = FALSE;
        PCI_DISABLE_BRIDGE_CONTROL_REGISTER (PciIoDevice, EFI_PCI_BRIDGE_CONTROL_FAST_BACK_TO_BACK);
      } else {
        PCI_ENABLE_BRIDGE_CONTROL_REGISTER (PciIoDevice, EFI_PCI_BRIDGE_CONTROL_FAST_BACK_TO_BACK);
      }
    }

    CurrentLink = PciIoDevice->ChildList.ForwardLink;
    while (CurrentLink != NULL && CurrentLink != &PciIoDevice->ChildList) {
      Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink);
      if (FastB2BSupport) {
        PCI_ENABLE_COMMAND_REGISTER (Temp, EFI_PCI_COMMAND_FAST_BACK_TO_BACK);
      } else {
        PCI_DISABLE_COMMAND_REGISTER (Temp, EFI_PCI_COMMAND_FAST_BACK_TO_BACK);
      }

      CurrentLink = CurrentLink->ForwardLink;
    }
  }

  //
  // End for IsListEmpty
  //
  return EFI_SUCCESS;
}

/**
  This routine is used to update the bar information for those incompatible PCI device.

  @param PciIoDevice      Input Pci device instance. Output Pci device instance with updated
                          Bar information.

  @retval EFI_SUCCESS     Successfully updated bar information.
  @retval EFI_UNSUPPORTED Given PCI device doesn't belong to incompatible PCI device list.

**/
EFI_STATUS
UpdatePciInfo (
  IN OUT PCI_IO_DEVICE  *PciIoDevice
  )
{
  EFI_STATUS                         Status;
  UINTN                              BarIndex;
  BOOLEAN                            SetFlag;
  VOID                               *Configuration;
  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR  *Ptr;

  Configuration = NULL;
  Status        = EFI_SUCCESS;

  if (gIncompatiblePciDeviceSupport == NULL) {
    //
    // It can only be supported after the Incompatible PCI Device
    // Support Protocol has been installed
    //
    Status = gBS->LocateProtocol (
                    &gEfiIncompatiblePciDeviceSupportProtocolGuid,
                    NULL,
                    (VOID **)&gIncompatiblePciDeviceSupport
                    );
  }

  if (Status == EFI_SUCCESS) {
    //
    // Check whether the device belongs to incompatible devices from protocol or not
    // If it is , then get its special requirement in the ACPI table
    //
    Status = gIncompatiblePciDeviceSupport->CheckDevice (
                                              gIncompatiblePciDeviceSupport,
                                              PciIoDevice->Pci.Hdr.VendorId,
                                              PciIoDevice->Pci.Hdr.DeviceId,
                                              PciIoDevice->Pci.Hdr.RevisionID,
                                              PciIoDevice->Pci.Device.SubsystemVendorID,
                                              PciIoDevice->Pci.Device.SubsystemID,
                                              &Configuration
                                              );
  }

  if (EFI_ERROR (Status) || (Configuration == NULL)) {
    return EFI_UNSUPPORTED;
  }

  //
  // Update PCI device information from the ACPI table
  //
  Ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Configuration;

  while (Ptr->Desc != ACPI_END_TAG_DESCRIPTOR) {
    if (Ptr->Desc != ACPI_ADDRESS_SPACE_DESCRIPTOR) {
      //
      // The format is not support
      //
      break;
    }

    for (BarIndex = 0; BarIndex < PCI_MAX_BAR; BarIndex++) {
      if ((Ptr->AddrTranslationOffset != MAX_UINT64) &&
          (Ptr->AddrTranslationOffset != MAX_UINT8) &&
          (Ptr->AddrTranslationOffset != BarIndex)
          )
      {
        //
        // Skip updating when AddrTranslationOffset is not MAX_UINT64 or MAX_UINT8 (wide match).
        // Skip updating when current BarIndex doesn't equal to AddrTranslationOffset.
        // Comparing against MAX_UINT8 is to keep backward compatibility.
        //
        continue;
      }

      SetFlag = FALSE;
      switch (Ptr->ResType) {
        case ACPI_ADDRESS_SPACE_TYPE_MEM:

          //
          // Make sure the bar is memory type
          //
          if (CheckBarType (PciIoDevice, (UINT8)BarIndex, PciBarTypeMem)) {
            SetFlag = TRUE;

            //
            // Ignored if granularity is 0.
            // Ignored if PCI BAR is I/O or 32-bit memory.
            // If PCI BAR is 64-bit memory and granularity is 32, then
            // the PCI BAR resource is allocated below 4GB.
            // If PCI BAR is 64-bit memory and granularity is 64, then
            // the PCI BAR resource is allocated above 4GB.
            //
            if (PciIoDevice->PciBar[BarIndex].BarType == PciBarTypeMem64) {
              switch (Ptr->AddrSpaceGranularity) {
                case 32:
                  PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeMem32;
                case 64:
                  PciIoDevice->PciBar[BarIndex].BarTypeFixed = TRUE;
                  break;
                default:
                  break;
              }
            }

            if (PciIoDevice->PciBar[BarIndex].BarType == PciBarTypePMem64) {
              switch (Ptr->AddrSpaceGranularity) {
                case 32:
                  PciIoDevice->PciBar[BarIndex].BarType = PciBarTypePMem32;
                case 64:
                  PciIoDevice->PciBar[BarIndex].BarTypeFixed = TRUE;
                  break;
                default:
                  break;
              }
            }
          }

          break;

        case ACPI_ADDRESS_SPACE_TYPE_IO:

          //
          // Make sure the bar is IO type
          //
          if (CheckBarType (PciIoDevice, (UINT8)BarIndex, PciBarTypeIo)) {
            SetFlag = TRUE;
          }

          break;
      }

      if (SetFlag) {
        //
        // Update the new alignment for the device
        //
        SetNewAlign (&(PciIoDevice->PciBar[BarIndex].Alignment), Ptr->AddrRangeMax);

        //
        // Update the new length for the device
        //
        if (Ptr->AddrLen != 0) {
          PciIoDevice->PciBar[BarIndex].Length = Ptr->AddrLen;
        }
      }
    }

    Ptr++;
  }

  FreePool (Configuration);

  return EFI_SUCCESS;
}

/**
  This routine will update the alignment with the new alignment.
  Compare with OLD_ALIGN/EVEN_ALIGN/SQUAD_ALIGN/DQUAD_ALIGN is to keep
  backward compatibility.

  @param Alignment    Input Old alignment. Output updated alignment.
  @param NewAlignment New alignment.

**/
VOID
SetNewAlign (
  IN OUT UINT64  *Alignment,
  IN     UINT64  NewAlignment
  )
{
  UINT64  OldAlignment;
  UINTN   ShiftBit;

  //
  // The new alignment is the same as the original,
  // so skip it
  //
  if ((NewAlignment == 0) || (NewAlignment == OLD_ALIGN)) {
    return;
  }

  //
  // Check the validity of the parameter
  //
  if ((NewAlignment != EVEN_ALIGN) &&
      (NewAlignment != SQUAD_ALIGN) &&
      (NewAlignment != DQUAD_ALIGN))
  {
    *Alignment = NewAlignment;
    return;
  }

  OldAlignment = (*Alignment) + 1;
  ShiftBit     = 0;

  //
  // Get the first non-zero hex value of the length
  //
  while ((OldAlignment & 0x0F) == 0x00) {
    OldAlignment = RShiftU64 (OldAlignment, 4);
    ShiftBit    += 4;
  }

  //
  // Adjust the alignment to even, quad or double quad boundary
  //
  if (NewAlignment == EVEN_ALIGN) {
    if ((OldAlignment & 0x01) != 0) {
      OldAlignment = OldAlignment + 2 - (OldAlignment & 0x01);
    }
  } else if (NewAlignment == SQUAD_ALIGN) {
    if ((OldAlignment & 0x03) != 0) {
      OldAlignment = OldAlignment + 4 - (OldAlignment & 0x03);
    }
  } else if (NewAlignment == DQUAD_ALIGN) {
    if ((OldAlignment & 0x07) != 0) {
      OldAlignment = OldAlignment + 8 - (OldAlignment & 0x07);
    }
  }

  //
  // Update the old value
  //
  NewAlignment = LShiftU64 (OldAlignment, ShiftBit) - 1;
  *Alignment   = NewAlignment;

  return;
}

/**
  Parse PCI IOV VF bar information and fill them into PCI device instance.

  @param PciIoDevice  Pci device instance.
  @param Offset       Bar offset.
  @param BarIndex     Bar index.

  @return Next bar offset.

**/
UINTN
PciIovParseVfBar (
  IN PCI_IO_DEVICE  *PciIoDevice,
  IN UINTN          Offset,
  IN UINTN          BarIndex
  )
{
  UINT32      Value;
  UINT32      OriginalValue;
  UINT32      Mask;
  EFI_STATUS  Status;

  //
  // Ensure it is called properly
  //
  ASSERT (PciIoDevice->SrIovCapabilityOffset != 0);
  if (PciIoDevice->SrIovCapabilityOffset == 0) {
    return 0;
  }

  OriginalValue = 0;
  Value         = 0;

  Status = VfBarExisted (
             PciIoDevice,
             Offset,
             &Value,
             &OriginalValue
             );

  if (EFI_ERROR (Status)) {
    PciIoDevice->VfPciBar[BarIndex].BaseAddress = 0;
    PciIoDevice->VfPciBar[BarIndex].Length      = 0;
    PciIoDevice->VfPciBar[BarIndex].Alignment   = 0;

    //
    // Scan all the BARs anyway
    //
    PciIoDevice->VfPciBar[BarIndex].Offset = (UINT16)Offset;
    return Offset + 4;
  }

  PciIoDevice->VfPciBar[BarIndex].Offset = (UINT16)Offset;
  if ((Value & 0x01) != 0) {
    //
    // Device I/Os. Impossible
    //
    ASSERT (FALSE);
    return Offset + 4;
  } else {
    Mask = 0xfffffff0;

    PciIoDevice->VfPciBar[BarIndex].BaseAddress = OriginalValue & Mask;

    switch (Value & 0x07) {
      //
      // memory space; anywhere in 32 bit address space
      //
      case 0x00:
        if ((Value & 0x08) != 0) {
          PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypePMem32;
        } else {
          PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeMem32;
        }

        PciIoDevice->VfPciBar[BarIndex].Length    = (~(Value & Mask)) + 1;
        PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1;

        //
        // Adjust Length
        //
        PciIoDevice->VfPciBar[BarIndex].Length = MultU64x32 (PciIoDevice->VfPciBar[BarIndex].Length, PciIoDevice->InitialVFs);
        //
        // Adjust Alignment
        //
        if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) {
          PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1;
        }

        break;

      //
      // memory space; anywhere in 64 bit address space
      //
      case 0x04:
        if ((Value & 0x08) != 0) {
          PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypePMem64;
        } else {
          PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeMem64;
        }

        //
        // According to PCI 2.2,if the bar indicates a memory 64 decoding, next bar
        // is regarded as an extension for the first bar. As a result
        // the sizing will be conducted on combined 64 bit value
        // Here just store the masked first 32bit value for future size
        // calculation
        //
        PciIoDevice->VfPciBar[BarIndex].Length    = Value & Mask;
        PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1;

        if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) {
          PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1;
        }

        //
        // Increment the offset to point to next DWORD
        //
        Offset += 4;

        Status = VfBarExisted (
                   PciIoDevice,
                   Offset,
                   &Value,
                   &OriginalValue
                   );

        if (EFI_ERROR (Status)) {
          PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeUnknown;
          return Offset + 4;
        }

        //
        // Fix the length to support some special 64 bit BAR
        //
        Value |= ((UINT32)-1 << HighBitSet32 (Value));

        //
        // Calculate the size of 64bit bar
        //
        PciIoDevice->VfPciBar[BarIndex].BaseAddress |= LShiftU64 ((UINT64)OriginalValue, 32);

        PciIoDevice->VfPciBar[BarIndex].Length    = PciIoDevice->VfPciBar[BarIndex].Length | LShiftU64 ((UINT64)Value, 32);
        PciIoDevice->VfPciBar[BarIndex].Length    = (~(PciIoDevice->VfPciBar[BarIndex].Length)) + 1;
        PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1;

        //
        // Adjust Length
        //
        PciIoDevice->VfPciBar[BarIndex].Length = MultU64x32 (PciIoDevice->VfPciBar[BarIndex].Length, PciIoDevice->InitialVFs);
        //
        // Adjust Alignment
        //
        if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) {
          PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1;
        }

        break;

      //
      // reserved
      //
      default:
        PciIoDevice->VfPciBar[BarIndex].BarType   = PciBarTypeUnknown;
        PciIoDevice->VfPciBar[BarIndex].Length    = (~(Value & Mask)) + 1;
        PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1;

        if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) {
          PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1;
        }

        break;
    }
  }

  //
  // Check the length again so as to keep compatible with some special bars
  //
  if (PciIoDevice->VfPciBar[BarIndex].Length == 0) {
    PciIoDevice->VfPciBar[BarIndex].BarType     = PciBarTypeUnknown;
    PciIoDevice->VfPciBar[BarIndex].BaseAddress = 0;
    PciIoDevice->VfPciBar[BarIndex].Alignment   = 0;
  }

  //
  // Increment number of bar
  //
  return Offset + 4;
}

/**
  Parse PCI bar information and fill them into PCI device instance.

  @param PciIoDevice  Pci device instance.
  @param Offset       Bar offset.
  @param BarIndex     Bar index.

  @return Next bar offset.

**/
UINTN
PciParseBar (
  IN PCI_IO_DEVICE  *PciIoDevice,
  IN UINTN          Offset,
  IN UINTN          BarIndex
  )
{
  UINT32      Value;
  UINT32      OriginalValue;
  UINT32      Mask;
  EFI_STATUS  Status;

  OriginalValue = 0;
  Value         = 0;

  Status = BarExisted (
             PciIoDevice,
             Offset,
             &Value,
             &OriginalValue
             );

  if (EFI_ERROR (Status)) {
    PciIoDevice->PciBar[BarIndex].BaseAddress = 0;
    PciIoDevice->PciBar[BarIndex].Length      = 0;
    PciIoDevice->PciBar[BarIndex].Alignment   = 0;

    //
    // Some devices don't fully comply to PCI spec 2.2. So be to scan all the BARs anyway
    //
    PciIoDevice->PciBar[BarIndex].Offset = (UINT8)Offset;
    return Offset + 4;
  }

  PciIoDevice->PciBar[BarIndex].BarTypeFixed = FALSE;
  PciIoDevice->PciBar[BarIndex].Offset       = (UINT8)Offset;
  if ((Value & 0x01) != 0) {
    //
    // Device I/Os
    //
    Mask = 0xfffffffc;

    if ((Value & 0xFFFF0000) != 0) {
      //
      // It is a IO32 bar
      //
      PciIoDevice->PciBar[BarIndex].BarType   = PciBarTypeIo32;
      PciIoDevice->PciBar[BarIndex].Length    = ((~(Value & Mask)) + 1);
      PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1;
    } else {
      //
      // It is a IO16 bar
      //
      PciIoDevice->PciBar[BarIndex].BarType   = PciBarTypeIo16;
      PciIoDevice->PciBar[BarIndex].Length    = 0x0000FFFF & ((~(Value & Mask)) + 1);
      PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1;
    }

    //
    // Workaround. Some platforms implement IO bar with 0 length
    // Need to treat it as no-bar
    //
    if (PciIoDevice->PciBar[BarIndex].Length == 0) {
      PciIoDevice->PciBar[BarIndex].BarType = (PCI_BAR_TYPE)0;
    }

    PciIoDevice->PciBar[BarIndex].BaseAddress = OriginalValue & Mask;
  } else {
    Mask = 0xfffffff0;

    PciIoDevice->PciBar[BarIndex].BaseAddress = OriginalValue & Mask;

    switch (Value & 0x07) {
      //
      // memory space; anywhere in 32 bit address space
      //
      case 0x00:
        if ((Value & 0x08) != 0) {
          PciIoDevice->PciBar[BarIndex].BarType = PciBarTypePMem32;
        } else {
          PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeMem32;
        }

        PciIoDevice->PciBar[BarIndex].Length = (~(Value & Mask)) + 1;
        if (PciIoDevice->PciBar[BarIndex].Length < (SIZE_4KB)) {
          //
          // Force minimum 4KByte alignment for Virtualization technology for Directed I/O
          //
          PciIoDevice->PciBar[BarIndex].Alignment = (SIZE_4KB - 1);
        } else {
          PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1;
        }

        break;

      //
      // memory space; anywhere in 64 bit address space
      //
      case 0x04:
        if ((Value & 0x08) != 0) {
          PciIoDevice->PciBar[BarIndex].BarType = PciBarTypePMem64;
        } else {
          PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeMem64;
        }

        //
        // According to PCI 2.2,if the bar indicates a memory 64 decoding, next bar
        // is regarded as an extension for the first bar. As a result
        // the sizing will be conducted on combined 64 bit value
        // Here just store the masked first 32bit value for future size
        // calculation
        //
        PciIoDevice->PciBar[BarIndex].Length    = Value & Mask;
        PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1;

        //
        // Increment the offset to point to next DWORD
        //
        Offset += 4;

        Status = BarExisted (
                   PciIoDevice,
                   Offset,
                   &Value,
                   &OriginalValue
                   );

        if (EFI_ERROR (Status)) {
          //
          // the high 32 bit does not claim any BAR, we need to re-check the low 32 bit BAR again
          //
          if (PciIoDevice->PciBar[BarIndex].Length == 0) {
            //
            // some device implement MMIO bar with 0 length, need to treat it as no-bar
            //
            PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeUnknown;
            return Offset + 4;
          }
        }

        //
        // Fix the length to support some special 64 bit BAR
        //
        if (Value == 0) {
          DEBUG ((DEBUG_INFO, "[PciBus]BAR probing for upper 32bit of MEM64 BAR returns 0, change to 0xFFFFFFFF.\n"));
          Value = (UINT32)-1;
        } else {
          Value |= ((UINT32)(-1) << HighBitSet32 (Value));
        }

        //
        // Calculate the size of 64bit bar
        //
        PciIoDevice->PciBar[BarIndex].BaseAddress |= LShiftU64 ((UINT64)OriginalValue, 32);

        PciIoDevice->PciBar[BarIndex].Length = PciIoDevice->PciBar[BarIndex].Length | LShiftU64 ((UINT64)Value, 32);
        PciIoDevice->PciBar[BarIndex].Length = (~(PciIoDevice->PciBar[BarIndex].Length)) + 1;
        if (PciIoDevice->PciBar[BarIndex].Length < (SIZE_4KB)) {
          //
          // Force minimum 4KByte alignment for Virtualization technology for Directed I/O
          //
          PciIoDevice->PciBar[BarIndex].Alignment = (SIZE_4KB - 1);
        } else {
          PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1;
        }

        break;

      //
      // reserved
      //
      default:
        PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeUnknown;
        PciIoDevice->PciBar[BarIndex].Length  = (~(Value & Mask)) + 1;
        if (PciIoDevice->PciBar[BarIndex].Length < (SIZE_4KB)) {
          //
          // Force minimum 4KByte alignment for Virtualization technology for Directed I/O
          //
          PciIoDevice->PciBar[BarIndex].Alignment = (SIZE_4KB - 1);
        } else {
          PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1;
        }

        break;
    }
  }

  //
  // Check the length again so as to keep compatible with some special bars
  //
  if (PciIoDevice->PciBar[BarIndex].Length == 0) {
    PciIoDevice->PciBar[BarIndex].BarType     = PciBarTypeUnknown;
    PciIoDevice->PciBar[BarIndex].BaseAddress = 0;
    PciIoDevice->PciBar[BarIndex].Alignment   = 0;
  }

  //
  // Increment number of bar
  //
  return Offset + 4;
}

/**
  This routine is used to initialize the bar of a PCI device.

  @param PciIoDevice Pci device instance.

  @note It can be called typically when a device is going to be rejected.

**/
VOID
InitializePciDevice (
  IN PCI_IO_DEVICE  *PciIoDevice
  )
{
  EFI_PCI_IO_PROTOCOL  *PciIo;
  UINT8                Offset;

  PciIo = &(PciIoDevice->PciIo);

  //
  // Put all the resource apertures
  // Resource base is set to all ones so as to indicate its resource
  // has not been allocated
  //
  for (Offset = 0x10; Offset <= 0x24; Offset += sizeof (UINT32)) {
    PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, Offset, 1, &gAllOne);
  }
}

/**
  This routine is used to initialize the bar of a PCI-PCI Bridge device.

  @param  PciIoDevice PCI-PCI bridge device instance.

**/
VOID
InitializePpb (
  IN PCI_IO_DEVICE  *PciIoDevice
  )
{
  EFI_PCI_IO_PROTOCOL  *PciIo;

  PciIo = &(PciIoDevice->PciIo);

  //
  // Put all the resource apertures including IO16
  // Io32, pMem32, pMem64 to quiescent state
  // Resource base all ones, Resource limit all zeros
  //
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint8, 0x1C, 1, &gAllOne);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint8, 0x1D, 1, &gAllZero);

  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, 0x20, 1, &gAllOne);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, 0x22, 1, &gAllZero);

  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, 0x24, 1, &gAllOne);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, 0x26, 1, &gAllZero);

  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x28, 1, &gAllOne);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x2C, 1, &gAllZero);

  //
  // Don't support use io32 as for now
  //
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, 0x30, 1, &gAllOne);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, 0x32, 1, &gAllZero);

  //
  // Force Interrupt line to zero for cards that come up randomly
  //
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint8, 0x3C, 1, &gAllZero);
}

/**
  This routine is used to initialize the bar of a PCI Card Bridge device.

  @param PciIoDevice  PCI Card bridge device.

**/
VOID
InitializeP2C (
  IN PCI_IO_DEVICE  *PciIoDevice
  )
{
  EFI_PCI_IO_PROTOCOL  *PciIo;

  PciIo = &(PciIoDevice->PciIo);

  //
  // Put all the resource apertures including IO16
  // Io32, pMem32, pMem64 to quiescent state(
  // Resource base all ones, Resource limit all zeros
  //
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x1c, 1, &gAllOne);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x20, 1, &gAllZero);

  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x24, 1, &gAllOne);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x28, 1, &gAllZero);

  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x2c, 1, &gAllOne);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x30, 1, &gAllZero);

  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x34, 1, &gAllOne);
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, 0x38, 1, &gAllZero);

  //
  // Force Interrupt line to zero for cards that come up randomly
  //
  PciIo->Pci.Write (PciIo, EfiPciIoWidthUint8, 0x3C, 1, &gAllZero);
}

/**
  Authenticate the PCI device by using DeviceSecurityProtocol.

  @param PciIoDevice  PCI device.

  @retval EFI_SUCCESS     The device passes the authentication.
  @return not EFI_SUCCESS The device failes the authentication or
                          unexpected error happen during authentication.
**/
EFI_STATUS
AuthenticatePciDevice (
  IN PCI_IO_DEVICE  *PciIoDevice
  )
{
  EDKII_DEVICE_IDENTIFIER  DeviceIdentifier;
  EFI_STATUS               Status;

  if (mDeviceSecurityProtocol != NULL) {
    //
    // Prepare the parameter
    //
    DeviceIdentifier.Version = EDKII_DEVICE_IDENTIFIER_REVISION;
    CopyGuid (&DeviceIdentifier.DeviceType, &gEdkiiDeviceIdentifierTypePciGuid);
    DeviceIdentifier.DeviceHandle = NULL;
    Status                        = gBS->InstallMultipleProtocolInterfaces (
                                           &DeviceIdentifier.DeviceHandle,
                                           &gEfiDevicePathProtocolGuid,
                                           PciIoDevice->DevicePath,
                                           &gEdkiiDeviceIdentifierTypePciGuid,
                                           &PciIoDevice->PciIo,
                                           NULL
                                           );
    if (EFI_ERROR (Status)) {
      return Status;
    }

    //
    // Do DeviceAuthentication
    //
    Status = mDeviceSecurityProtocol->DeviceAuthenticate (mDeviceSecurityProtocol, &DeviceIdentifier);
    //
    // Always uninstall, because they are only for Authentication.
    // No need to check return Status.
    //
    gBS->UninstallMultipleProtocolInterfaces (
           DeviceIdentifier.DeviceHandle,
           &gEfiDevicePathProtocolGuid,
           PciIoDevice->DevicePath,
           &gEdkiiDeviceIdentifierTypePciGuid,
           &PciIoDevice->PciIo,
           NULL
           );
    return Status;
  }

  //
  // Device Security Protocol is not found, just return success
  //
  return EFI_SUCCESS;
}

/**
  Checks if PCI device is Root Bridge.

  @param PciIoDevice       Instance of PCI device

  @retval TRUE             Device is Root Bridge
  @retval FALSE            Device is not Root Bridge

**/
BOOLEAN
IsRootBridge (
  IN PCI_IO_DEVICE  *PciIoDevice
  )
{
  if (PciIoDevice->Parent == NULL) {
    return TRUE;
  } else {
    return FALSE;
  }
}

/**
  Create and initialize general PCI I/O device instance for
  PCI device/bridge device/hotplug bridge device.

  @param Bridge            Parent bridge instance.
  @param Pci               Input Pci information block.
  @param Bus               Device Bus NO.
  @param Device            Device device NO.
  @param Func              Device func NO.

  @return Instance of PCI device. NULL means no instance created.

**/
PCI_IO_DEVICE *
CreatePciIoDevice (
  IN PCI_IO_DEVICE  *Bridge,
  IN PCI_TYPE00     *Pci,
  IN UINT8          Bus,
  IN UINT8          Device,
  IN UINT8          Func
  )
{
  PCI_IO_DEVICE        *PciIoDevice;
  EFI_PCI_IO_PROTOCOL  *PciIo;
  EFI_STATUS           Status;

  PciIoDevice = AllocateZeroPool (sizeof (PCI_IO_DEVICE));
  if (PciIoDevice == NULL) {
    return NULL;
  }

  PciIoDevice->Signature       = PCI_IO_DEVICE_SIGNATURE;
  PciIoDevice->Handle          = NULL;
  PciIoDevice->PciRootBridgeIo = Bridge->PciRootBridgeIo;
  PciIoDevice->DevicePath      = NULL;
  PciIoDevice->BusNumber       = Bus;
  PciIoDevice->DeviceNumber    = Device;
  PciIoDevice->FunctionNumber  = Func;
  PciIoDevice->Decodes         = 0;

  if (gFullEnumeration) {
    PciIoDevice->Allocated = FALSE;
  } else {
    PciIoDevice->Allocated = TRUE;
  }

  PciIoDevice->Registered        = FALSE;
  PciIoDevice->Attributes        = 0;
  PciIoDevice->Supports          = 0;
  PciIoDevice->BusOverride       = FALSE;
  PciIoDevice->AllOpRomProcessed = FALSE;

  PciIoDevice->IsPciExp = FALSE;

  CopyMem (&(PciIoDevice->Pci), Pci, sizeof (PCI_TYPE01));

  //
  // Initialize the PCI I/O instance structure
  //
  InitializePciIoInstance (PciIoDevice);
  InitializePciDriverOverrideInstance (PciIoDevice);
  InitializePciLoadFile2 (PciIoDevice);
  PciIo = &PciIoDevice->PciIo;

  //
  // Create a device path for this PCI device and store it into its private data
  //
  CreatePciDevicePath (
    Bridge->DevicePath,
    PciIoDevice
    );

  //
  // Detect if PCI Express Device
  //
  PciIoDevice->PciExpressCapabilityOffset = 0;
  Status                                  = LocateCapabilityRegBlock (
                                              PciIoDevice,
                                              EFI_PCI_CAPABILITY_ID_PCIEXP,
                                              &PciIoDevice->PciExpressCapabilityOffset,
                                              NULL
                                              );
  if (!EFI_ERROR (Status)) {
    PciIoDevice->IsPciExp = TRUE;
  }

  //
  // Now we can do the authentication check for the device.
  //
  Status = AuthenticatePciDevice (PciIoDevice);
  //
  // If authentication fails, skip this device.
  //
  if (EFI_ERROR (Status)) {
    if (PciIoDevice->DevicePath != NULL) {
      FreePool (PciIoDevice->DevicePath);
    }

    FreePool (PciIoDevice);
    return NULL;
  }

  //
  // Check if device's parent is not Root Bridge
  //
  if (PcdGetBool (PcdAriSupport) && !IsRootBridge (Bridge)) {
    //
    // Check if the device is an ARI device.
    //
    Status = LocatePciExpressCapabilityRegBlock (
               PciIoDevice,
               EFI_PCIE_CAPABILITY_ID_ARI,
               &PciIoDevice->AriCapabilityOffset,
               NULL
               );
    if (!EFI_ERROR (Status)) {
      //
      // We need to enable ARI feature before calculate BusReservation,
      // because FirstVFOffset and VFStride may change after that.
      //
      EFI_PCI_IO_PROTOCOL  *ParentPciIo;
      UINT32               Data32;

      //
      // Check if its parent supports ARI forwarding.
      //
      ParentPciIo = &Bridge->PciIo;
      ParentPciIo->Pci.Read (
                         ParentPciIo,
                         EfiPciIoWidthUint32,
                         Bridge->PciExpressCapabilityOffset + EFI_PCIE_CAPABILITY_DEVICE_CAPABILITIES_2_OFFSET,
                         1,
                         &Data32
                         );
      if ((Data32 & EFI_PCIE_CAPABILITY_DEVICE_CAPABILITIES_2_ARI_FORWARDING) != 0) {
        //
        // ARI forward support in bridge, so enable it.
        //
        ParentPciIo->Pci.Read (
                           ParentPciIo,
                           EfiPciIoWidthUint32,
                           Bridge->PciExpressCapabilityOffset + EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET,
                           1,
                           &Data32
                           );
        if ((Data32 & EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_ARI_FORWARDING) == 0) {
          Data32 |= EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_ARI_FORWARDING;
          ParentPciIo->Pci.Write (
                             ParentPciIo,
                             EfiPciIoWidthUint32,
                             Bridge->PciExpressCapabilityOffset + EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET,
                             1,
                             &Data32
                             );
          DEBUG ((
            DEBUG_INFO,
            " ARI: forwarding enabled for PPB[%02x:%02x:%02x]\n",
            Bridge->BusNumber,
            Bridge->DeviceNumber,
            Bridge->FunctionNumber
            ));
        }
      }

      DEBUG ((DEBUG_INFO, " ARI: CapOffset = 0x%x\n", PciIoDevice->AriCapabilityOffset));
    }
  }

  //
  // Initialization for SR-IOV
  //

  if (PcdGetBool (PcdSrIovSupport)) {
    Status = LocatePciExpressCapabilityRegBlock (
               PciIoDevice,
               EFI_PCIE_CAPABILITY_ID_SRIOV,
               &PciIoDevice->SrIovCapabilityOffset,
               NULL
               );
    if (!EFI_ERROR (Status)) {
      UINT32  SupportedPageSize;
      UINT16  VFStride;
      UINT16  FirstVFOffset;
      UINT16  Data16;
      UINT32  PFRid;
      UINT32  LastVF;

      //
      // If the SR-IOV device is an ARI device, then Set ARI Capable Hierarchy for the device.
      //
      if (PcdGetBool (PcdAriSupport) && (PciIoDevice->AriCapabilityOffset != 0)) {
        PciIo->Pci.Read (
                     PciIo,
                     EfiPciIoWidthUint16,
                     PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_CONTROL,
                     1,
                     &Data16
                     );
        Data16 |= EFI_PCIE_CAPABILITY_ID_SRIOV_CONTROL_ARI_HIERARCHY;
        PciIo->Pci.Write (
                     PciIo,
                     EfiPciIoWidthUint16,
                     PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_CONTROL,
                     1,
                     &Data16
                     );
      }

      //
      // Calculate SystemPageSize
      //

      PciIo->Pci.Read (
                   PciIo,
                   EfiPciIoWidthUint32,
                   PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_SUPPORTED_PAGE_SIZE,
                   1,
                   &SupportedPageSize
                   );
      PciIoDevice->SystemPageSize = (PcdGet32 (PcdSrIovSystemPageSize) & SupportedPageSize);
      ASSERT (PciIoDevice->SystemPageSize != 0);

      PciIo->Pci.Write (
                   PciIo,
                   EfiPciIoWidthUint32,
                   PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_SYSTEM_PAGE_SIZE,
                   1,
                   &PciIoDevice->SystemPageSize
                   );
      //
      // Adjust SystemPageSize for Alignment usage later
      //
      PciIoDevice->SystemPageSize <<= 12;

      //
      // Calculate BusReservation for PCI IOV
      //

      //
      // Read First FirstVFOffset, InitialVFs, and VFStride
      //
      PciIo->Pci.Read (
                   PciIo,
                   EfiPciIoWidthUint16,
                   PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_FIRSTVF,
                   1,
                   &FirstVFOffset
                   );
      PciIo->Pci.Read (
                   PciIo,
                   EfiPciIoWidthUint16,
                   PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_INITIALVFS,
                   1,
                   &PciIoDevice->InitialVFs
                   );
      PciIo->Pci.Read (
                   PciIo,
                   EfiPciIoWidthUint16,
                   PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_VFSTRIDE,
                   1,
                   &VFStride
                   );
      //
      // Calculate LastVF
      //
      PFRid  = EFI_PCI_RID (Bus, Device, Func);
      LastVF = PFRid + FirstVFOffset + (PciIoDevice->InitialVFs - 1) * VFStride;

      //
      // Calculate ReservedBusNum for this PF
      //
      PciIoDevice->ReservedBusNum = (UINT16)(EFI_PCI_BUS_OF_RID (LastVF) - Bus + 1);

      DEBUG ((
        DEBUG_INFO,
        " SR-IOV: SupportedPageSize = 0x%x; SystemPageSize = 0x%x; FirstVFOffset = 0x%x;\n",
        SupportedPageSize,
        PciIoDevice->SystemPageSize >> 12,
        FirstVFOffset
        ));
      DEBUG ((
        DEBUG_INFO,
        "         InitialVFs = 0x%x; ReservedBusNum = 0x%x; CapOffset = 0x%x\n",
        PciIoDevice->InitialVFs,
        PciIoDevice->ReservedBusNum,
        PciIoDevice->SrIovCapabilityOffset
        ));
    }
  }

  if (PcdGetBool (PcdMrIovSupport)) {
    Status = LocatePciExpressCapabilityRegBlock (
               PciIoDevice,
               EFI_PCIE_CAPABILITY_ID_MRIOV,
               &PciIoDevice->MrIovCapabilityOffset,
               NULL
               );
    if (!EFI_ERROR (Status)) {
      DEBUG ((DEBUG_INFO, " MR-IOV: CapOffset = 0x%x\n", PciIoDevice->MrIovCapabilityOffset));
    }
  }

  PciIoDevice->ResizableBarOffset = 0;
  if (PcdGetBool (PcdPcieResizableBarSupport)) {
    Status = LocatePciExpressCapabilityRegBlock (
               PciIoDevice,
               PCI_EXPRESS_EXTENDED_CAPABILITY_RESIZABLE_BAR_ID,
               &PciIoDevice->ResizableBarOffset,
               NULL
               );
    if (!EFI_ERROR (Status)) {
      PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL  ResizableBarControl;
      UINT32                                                   Offset;
      Offset = PciIoDevice->ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER)
               + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CAPABILITY),
      PciIo->Pci.Read (
                   PciIo,
                   EfiPciIoWidthUint8,
                   Offset,
                   sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL),
                   &ResizableBarControl
                   );
      PciIoDevice->ResizableBarNumber = ResizableBarControl.Bits.ResizableBarNumber;
      PciProgramResizableBar (PciIoDevice, PciResizableBarMax);
    }
  }

  //
  // Initialize the reserved resource list
  //
  InitializeListHead (&PciIoDevice->ReservedResourceList);

  //
  // Initialize the driver list
  //
  InitializeListHead (&PciIoDevice->OptionRomDriverList);

  //
  // Initialize the child list
  //
  InitializeListHead (&PciIoDevice->ChildList);

  return PciIoDevice;
}

/**
  This routine is used to enumerate entire pci bus system
  in a given platform.

  It is only called on the second start on the same Root Bridge.

  @param  Controller     Parent bridge handler.

  @retval EFI_SUCCESS    PCI enumeration finished successfully.
  @retval other          Some error occurred when enumerating the pci bus system.

**/
EFI_STATUS
PciEnumeratorLight (
  IN EFI_HANDLE  Controller
  )
{
  EFI_STATUS                         Status;
  EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL    *PciRootBridgeIo;
  PCI_IO_DEVICE                      *RootBridgeDev;
  UINT16                             MinBus;
  UINT16                             MaxBus;
  EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR  *Descriptors;

  MinBus      = 0;
  MaxBus      = PCI_MAX_BUS;
  Descriptors = NULL;

  //
  // If this root bridge has been already enumerated, then return successfully
  //
  if (GetRootBridgeByHandle (Controller) != NULL) {
    return EFI_SUCCESS;
  }

  //
  // Open pci root bridge io protocol
  //
  Status = gBS->OpenProtocol (
                  Controller,
                  &gEfiPciRootBridgeIoProtocolGuid,
                  (VOID **)&PciRootBridgeIo,
                  gPciBusDriverBinding.DriverBindingHandle,
                  Controller,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );
  if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) {
    return Status;
  }

  Status = PciRootBridgeIo->Configuration (PciRootBridgeIo, (VOID **)&Descriptors);

  if (EFI_ERROR (Status)) {
    return Status;
  }

  while (PciGetBusRange (&Descriptors, &MinBus, &MaxBus, NULL) == EFI_SUCCESS) {
    //
    // Create a device node for root bridge device with a NULL host bridge controller handle
    //
    RootBridgeDev = CreateRootBridge (Controller);

    if (RootBridgeDev == NULL) {
      Descriptors++;
      continue;
    }

    //
    // Record the root bridge-io protocol
    //
    RootBridgeDev->PciRootBridgeIo = PciRootBridgeIo;

    Status = PciPciDeviceInfoCollector (
               RootBridgeDev,
               (UINT8)MinBus
               );

    if (!EFI_ERROR (Status)) {
      //
      // Remove those PCI devices which are rejected when full enumeration
      //
      RemoveRejectedPciDevices (RootBridgeDev->Handle, RootBridgeDev);

      //
      // Process option rom light
      //
      ProcessOptionRomLight (RootBridgeDev);

      //
      // Determine attributes for all devices under this root bridge
      //
      DetermineDeviceAttribute (RootBridgeDev);

      //
      // If successfully, insert the node into device pool
      //
      InsertRootBridge (RootBridgeDev);
    } else {
      //
      // If unsuccessfully, destroy the entire node
      //
      DestroyRootBridge (RootBridgeDev);
    }

    Descriptors++;
  }

  return EFI_SUCCESS;
}

/**
  Get bus range from PCI resource descriptor list.

  @param Descriptors  A pointer to the address space descriptor.
  @param MinBus       The min bus returned.
  @param MaxBus       The max bus returned.
  @param BusRange     The bus range returned.

  @retval EFI_SUCCESS    Successfully got bus range.
  @retval EFI_NOT_FOUND  Can not find the specific bus.

**/
EFI_STATUS
PciGetBusRange (
  IN     EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR  **Descriptors,
  OUT    UINT16                             *MinBus,
  OUT    UINT16                             *MaxBus,
  OUT    UINT16                             *BusRange
  )
{
  while ((*Descriptors)->Desc != ACPI_END_TAG_DESCRIPTOR) {
    if ((*Descriptors)->ResType == ACPI_ADDRESS_SPACE_TYPE_BUS) {
      if (MinBus != NULL) {
        *MinBus = (UINT16)(*Descriptors)->AddrRangeMin;
      }

      if (MaxBus != NULL) {
        *MaxBus = (UINT16)(*Descriptors)->AddrRangeMax;
      }

      if (BusRange != NULL) {
        *BusRange = (UINT16)(*Descriptors)->AddrLen;
      }

      return EFI_SUCCESS;
    }

    (*Descriptors)++;
  }

  return EFI_NOT_FOUND;
}

/**
  This routine can be used to start the root bridge.

  @param RootBridgeDev     Pci device instance.

  @retval EFI_SUCCESS      This device started.
  @retval other            Failed to get PCI Root Bridge I/O protocol.

**/
EFI_STATUS
StartManagingRootBridge (
  IN PCI_IO_DEVICE  *RootBridgeDev
  )
{
  EFI_HANDLE                       RootBridgeHandle;
  EFI_STATUS                       Status;
  EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL  *PciRootBridgeIo;

  //
  // Get the root bridge handle
  //
  RootBridgeHandle = RootBridgeDev->Handle;
  PciRootBridgeIo  = NULL;

  //
  // Get the pci root bridge io protocol
  //
  Status = gBS->OpenProtocol (
                  RootBridgeHandle,
                  &gEfiPciRootBridgeIoProtocolGuid,
                  (VOID **)&PciRootBridgeIo,
                  gPciBusDriverBinding.DriverBindingHandle,
                  RootBridgeHandle,
                  EFI_OPEN_PROTOCOL_BY_DRIVER
                  );

  if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) {
    return Status;
  }

  //
  // Store the PciRootBridgeIo protocol into root bridge private data
  //
  RootBridgeDev->PciRootBridgeIo = PciRootBridgeIo;

  return EFI_SUCCESS;
}

/**
  This routine can be used to check whether a PCI device should be rejected when light enumeration.

  @param PciIoDevice  Pci device instance.

  @retval TRUE      This device should be rejected.
  @retval FALSE     This device shouldn't be rejected.

**/
BOOLEAN
IsPciDeviceRejected (
  IN PCI_IO_DEVICE  *PciIoDevice
  )
{
  EFI_STATUS  Status;
  UINT32      TestValue;
  UINT32      OldValue;
  UINT32      Mask;
  UINT8       BarOffset;

  //
  // PPB should be skip!
  //
  if (IS_PCI_BRIDGE (&PciIoDevice->Pci)) {
    return FALSE;
  }

  if (IS_CARDBUS_BRIDGE (&PciIoDevice->Pci)) {
    //
    // Only test base registers for P2C
    //
    for (BarOffset = 0x1C; BarOffset <= 0x38; BarOffset += 2 * sizeof (UINT32)) {
      Mask   = (BarOffset < 0x2C) ? 0xFFFFF000 : 0xFFFFFFFC;
      Status = BarExisted (PciIoDevice, BarOffset, &TestValue, &OldValue);
      if (EFI_ERROR (Status)) {
        continue;
      }

      TestValue = TestValue & Mask;
      if ((TestValue != 0) && (TestValue == (OldValue & Mask))) {
        //
        // The bar isn't programed, so it should be rejected
        //
        return TRUE;
      }
    }

    return FALSE;
  }

  for (BarOffset = 0x14; BarOffset <= 0x24; BarOffset += sizeof (UINT32)) {
    //
    // Test PCI devices
    //
    Status = BarExisted (PciIoDevice, BarOffset, &TestValue, &OldValue);
    if (EFI_ERROR (Status)) {
      continue;
    }

    if ((TestValue & 0x01) != 0) {
      //
      // IO Bar
      //
      Mask      = 0xFFFFFFFC;
      TestValue = TestValue & Mask;
      if ((TestValue != 0) && (TestValue == (OldValue & Mask))) {
        return TRUE;
      }
    } else {
      //
      // Mem Bar
      //
      Mask      = 0xFFFFFFF0;
      TestValue = TestValue & Mask;

      if ((TestValue & 0x07) == 0x04) {
        //
        // Mem64 or PMem64
        //
        BarOffset += sizeof (UINT32);
        if ((TestValue != 0) && (TestValue == (OldValue & Mask))) {
          //
          // Test its high 32-Bit BAR
          //
          Status = BarExisted (PciIoDevice, BarOffset, &TestValue, &OldValue);
          if (TestValue == OldValue) {
            return TRUE;
          }
        }
      } else {
        //
        // Mem32 or PMem32
        //
        if ((TestValue != 0) && (TestValue == (OldValue & Mask))) {
          return TRUE;
        }
      }
    }
  }

  return FALSE;
}

/**
  Reset all bus number from specific bridge.

  @param Bridge           Parent specific bridge.
  @param StartBusNumber   Start bus number.

**/
VOID
ResetAllPpbBusNumber (
  IN PCI_IO_DEVICE  *Bridge,
  IN UINT8          StartBusNumber
  )
{
  EFI_STATUS                       Status;
  PCI_TYPE00                       Pci;
  UINT8                            Device;
  UINT32                           Register;
  UINT8                            Func;
  UINT64                           Address;
  UINT8                            SecondaryBus;
  EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL  *PciRootBridgeIo;

  PciRootBridgeIo = Bridge->PciRootBridgeIo;

  for (Device = 0; Device <= PCI_MAX_DEVICE; Device++) {
    for (Func = 0; Func <= PCI_MAX_FUNC; Func++) {
      //
      // Check to see whether a pci device is present
      //
      Status = PciDevicePresent (
                 PciRootBridgeIo,
                 &Pci,
                 StartBusNumber,
                 Device,
                 Func
                 );

      if (EFI_ERROR (Status) && (Func == 0)) {
        //
        // go to next device if there is no Function 0
        //
        break;
      }

      if (!EFI_ERROR (Status) && (IS_PCI_BRIDGE (&Pci))) {
        Register = 0;
        Address  = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, 0x18);
        Status   = PciRootBridgeIo->Pci.Read (
                                          PciRootBridgeIo,
                                          EfiPciWidthUint32,
                                          Address,
                                          1,
                                          &Register
                                          );
        SecondaryBus = (UINT8)(Register >> 8);

        if (SecondaryBus != 0) {
          ResetAllPpbBusNumber (Bridge, SecondaryBus);
        }

        //
        // Reset register 18h, 19h, 1Ah on PCI Bridge
        //
        Register &= 0xFF000000;
        Status    = PciRootBridgeIo->Pci.Write (
                                           PciRootBridgeIo,
                                           EfiPciWidthUint32,
                                           Address,
                                           1,
                                           &Register
                                           );
      }

      if ((Func == 0) && !IS_PCI_MULTI_FUNC (&Pci)) {
        //
        // Skip sub functions, this is not a multi function device
        //
        Func = PCI_MAX_FUNC;
      }
    }
  }
}