summaryrefslogtreecommitdiffstats
path: root/SecurityPkg/Tcg/Opal/OpalPassword/OpalNvmeMode.c
blob: 7657bb26e23c88df59bd3d4efe043e24946ffc60 (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
/** @file
  Provide functions to initialize NVME controller and perform NVME commands

Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution.  The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

**/

#include "OpalPasswordPei.h"


#define ALIGN(v, a)                         (UINTN)((((v) - 1) | ((a) - 1)) + 1)

///
/// NVME Host controller registers operation
///
#define NVME_GET_CAP(Nvme, Cap)             NvmeMmioRead  (Cap, Nvme->Nbar + NVME_CAP_OFFSET, sizeof (NVME_CAP))
#define NVME_GET_CC(Nvme, Cc)               NvmeMmioRead  (Cc, Nvme->Nbar + NVME_CC_OFFSET, sizeof (NVME_CC))
#define NVME_SET_CC(Nvme, Cc)               NvmeMmioWrite (Nvme->Nbar + NVME_CC_OFFSET, Cc, sizeof (NVME_CC))
#define NVME_GET_CSTS(Nvme, Csts)           NvmeMmioRead  (Csts, Nvme->Nbar + NVME_CSTS_OFFSET, sizeof (NVME_CSTS))
#define NVME_GET_AQA(Nvme, Aqa)             NvmeMmioRead  (Aqa, Nvme->Nbar + NVME_AQA_OFFSET, sizeof (NVME_AQA))
#define NVME_SET_AQA(Nvme, Aqa)             NvmeMmioWrite (Nvme->Nbar + NVME_AQA_OFFSET, Aqa, sizeof (NVME_AQA))
#define NVME_GET_ASQ(Nvme, Asq)             NvmeMmioRead  (Asq, Nvme->Nbar + NVME_ASQ_OFFSET, sizeof (NVME_ASQ))
#define NVME_SET_ASQ(Nvme, Asq)             NvmeMmioWrite (Nvme->Nbar + NVME_ASQ_OFFSET, Asq, sizeof (NVME_ASQ))
#define NVME_GET_ACQ(Nvme, Acq)             NvmeMmioRead  (Acq, Nvme->Nbar + NVME_ACQ_OFFSET, sizeof (NVME_ACQ))
#define NVME_SET_ACQ(Nvme, Acq)             NvmeMmioWrite (Nvme->Nbar + NVME_ACQ_OFFSET, Acq, sizeof (NVME_ACQ))
#define NVME_GET_VER(Nvme, Ver)             NvmeMmioRead  (Ver, Nvme->Nbar + NVME_VER_OFFSET, sizeof (NVME_VER))
#define NVME_SET_SQTDBL(Nvme, Qid, Sqtdbl)  NvmeMmioWrite (Nvme->Nbar + NVME_SQTDBL_OFFSET(Qid, Nvme->Cap.Dstrd), Sqtdbl, sizeof (NVME_SQTDBL))
#define NVME_SET_CQHDBL(Nvme, Qid, Cqhdbl)  NvmeMmioWrite (Nvme->Nbar + NVME_CQHDBL_OFFSET(Qid, Nvme->Cap.Dstrd), Cqhdbl, sizeof (NVME_CQHDBL))

///
/// Base memory address
///
enum {
  BASEMEM_CONTROLLER_DATA,
  BASEMEM_IDENTIFY_DATA,
  BASEMEM_ASQ,
  BASEMEM_ACQ,
  BASEMEM_SQ,
  BASEMEM_CQ,
  BASEMEM_PRP,
  BASEMEM_SECURITY,
  MAX_BASEMEM_COUNT
};

///
/// All of base memories are 4K(0x1000) alignment
///
#define NVME_MEM_BASE(Nvme)                 ((UINTN)(Nvme->BaseMem))
#define NVME_CONTROL_DATA_BASE(Nvme)        (ALIGN (NVME_MEM_BASE(Nvme) + ((NvmeGetBaseMemPages (BASEMEM_CONTROLLER_DATA))                        * EFI_PAGE_SIZE), EFI_PAGE_SIZE))
#define NVME_NAMESPACE_DATA_BASE(Nvme)      (ALIGN (NVME_MEM_BASE(Nvme) + ((NvmeGetBaseMemPages (BASEMEM_IDENTIFY_DATA))                          * EFI_PAGE_SIZE), EFI_PAGE_SIZE))
#define NVME_ASQ_BASE(Nvme)                 (ALIGN (NVME_MEM_BASE(Nvme) + ((NvmeGetBaseMemPages (BASEMEM_ASQ))                                    * EFI_PAGE_SIZE), EFI_PAGE_SIZE))
#define NVME_ACQ_BASE(Nvme)                 (ALIGN (NVME_MEM_BASE(Nvme) + ((NvmeGetBaseMemPages (BASEMEM_ACQ))                                    * EFI_PAGE_SIZE), EFI_PAGE_SIZE))
#define NVME_SQ_BASE(Nvme, index)           (ALIGN (NVME_MEM_BASE(Nvme) + ((NvmeGetBaseMemPages (BASEMEM_SQ) + ((index)*(NVME_MAX_IO_QUEUES-1)))  * EFI_PAGE_SIZE), EFI_PAGE_SIZE))
#define NVME_CQ_BASE(Nvme, index)           (ALIGN (NVME_MEM_BASE(Nvme) + ((NvmeGetBaseMemPages (BASEMEM_CQ) + ((index)*(NVME_MAX_IO_QUEUES-1)))  * EFI_PAGE_SIZE), EFI_PAGE_SIZE))
#define NVME_PRP_BASE(Nvme, index)          (ALIGN (NVME_MEM_BASE(Nvme) + ((NvmeGetBaseMemPages (BASEMEM_PRP) + ((index)*NVME_PRP_SIZE))          * EFI_PAGE_SIZE), EFI_PAGE_SIZE))
#define NVME_SEC_BASE(Nvme)                 (ALIGN (NVME_MEM_BASE(Nvme) + ((NvmeGetBaseMemPages (BASEMEM_SECURITY))                               * EFI_PAGE_SIZE), EFI_PAGE_SIZE))

/**
  Transfer MMIO Data to memory.

  @param[in,out] MemBuffer - Destination: Memory address
  @param[in] MmioAddr      - Source: MMIO address
  @param[in] Size          - Size for read

  @retval EFI_SUCCESS - MMIO read sucessfully
**/
EFI_STATUS
NvmeMmioRead (
  IN OUT VOID *MemBuffer,
  IN     UINTN MmioAddr,
  IN     UINTN Size
  )
{
  UINTN  Offset;
  UINT8  Data;
  UINT8  *Ptr;

  // priority has adjusted
  switch (Size) {
    case 4:
      *((UINT32 *)MemBuffer) = MmioRead32 (MmioAddr);
      break;

    case 8:
      *((UINT64 *)MemBuffer) = MmioRead64 (MmioAddr);
      break;

    case 2:
      *((UINT16 *)MemBuffer) = MmioRead16 (MmioAddr);
      break;

    case 1:
      *((UINT8 *)MemBuffer) = MmioRead8 (MmioAddr);
      break;

    default:
      Ptr = (UINT8 *)MemBuffer;
      for (Offset = 0; Offset < Size; Offset += 1) {
        Data = MmioRead8 (MmioAddr + Offset);
        Ptr[Offset] = Data;
      }
      break;
  }

  return EFI_SUCCESS;
}

/**
  Transfer memory data to MMIO.

  @param[in,out] MmioAddr - Destination: MMIO address
  @param[in] MemBuffer    - Source: Memory address
  @param[in] Size         - Size for write

  @retval EFI_SUCCESS - MMIO write sucessfully
**/
EFI_STATUS
NvmeMmioWrite (
  IN OUT UINTN MmioAddr,
  IN     VOID *MemBuffer,
  IN     UINTN Size
  )
{
  UINTN  Offset;
  UINT8  Data;
  UINT8  *Ptr;

  // priority has adjusted
  switch (Size) {
    case 4:
      MmioWrite32 (MmioAddr, *((UINT32 *)MemBuffer));
      break;

    case 8:
      MmioWrite64 (MmioAddr, *((UINT64 *)MemBuffer));
      break;

    case 2:
      MmioWrite16 (MmioAddr, *((UINT16 *)MemBuffer));
      break;

    case 1:
      MmioWrite8 (MmioAddr, *((UINT8 *)MemBuffer));
      break;

    default:
      Ptr = (UINT8 *)MemBuffer;
      for (Offset = 0; Offset < Size; Offset += 1) {
        Data = Ptr[Offset];
        MmioWrite8 (MmioAddr + Offset, Data);
      }
      break;
  }

  return EFI_SUCCESS;
}

/**
  Transfer MMIO data to memory.

  @param[in,out] MemBuffer - Destination: Memory address
  @param[in] MmioAddr      - Source: MMIO address
  @param[in] Size          - Size for read

  @retval EFI_SUCCESS - MMIO read sucessfully
**/
EFI_STATUS
OpalPciRead (
  IN OUT VOID *MemBuffer,
  IN     UINTN MmioAddr,
  IN     UINTN Size
  )
{
  UINTN  Offset;
  UINT8  Data;
  UINT8  *Ptr;

  // priority has adjusted
  switch (Size) {
    case 4:
      *((UINT32 *)MemBuffer) = PciRead32 (MmioAddr);
      break;

    case 2:
      *((UINT16 *)MemBuffer) = PciRead16 (MmioAddr);
      break;

    case 1:
      *((UINT8 *)MemBuffer) = PciRead8 (MmioAddr);
      break;

    default:
      Ptr = (UINT8 *)MemBuffer;
      for (Offset = 0; Offset < Size; Offset += 1) {
        Data = PciRead8 (MmioAddr + Offset);
        Ptr[Offset] = Data;
      }
      break;
  }

  return EFI_SUCCESS;
}

/**
  Transfer memory data to MMIO.

  @param[in,out] MmioAddr - Destination: MMIO address
  @param[in] MemBuffer    - Source: Memory address
  @param[in] Size         - Size for write

  @retval EFI_SUCCESS - MMIO write sucessfully
**/
EFI_STATUS
OpalPciWrite (
  IN OUT UINTN MmioAddr,
  IN     VOID *MemBuffer,
  IN     UINTN Size
  )
{
  UINTN  Offset;
  UINT8  Data;
  UINT8  *Ptr;

  // priority has adjusted
  switch (Size) {
    case 4:
      PciWrite32 (MmioAddr, *((UINT32 *)MemBuffer));
      break;

    case 2:
      PciWrite16 (MmioAddr, *((UINT16 *)MemBuffer));
      break;

    case 1:
      PciWrite8 (MmioAddr, *((UINT8 *)MemBuffer));
      break;

    default:
      Ptr = (UINT8 *)MemBuffer;
      for (Offset = 0; Offset < Size; Offset += 1) {
        Data = Ptr[Offset];
        PciWrite8 (MmioAddr + Offset, Data);
      }
      break;
  }

  return EFI_SUCCESS;
}

/**
  Get total pages for specific NVME based memory.

  @param[in] BaseMemIndex           - The Index of BaseMem (0-based).

  @retval - The page count for specific BaseMem Index

**/
UINT32
NvmeGetBaseMemPages (
  IN UINTN              BaseMemIndex
  )
{
  UINT32                Pages;
  UINTN                 Index;
  UINT32                PageSizeList[8];

  PageSizeList[0] = 1;  /* Controller Data */
  PageSizeList[1] = 1;  /* Identify Data */
  PageSizeList[2] = 1;  /* ASQ */
  PageSizeList[3] = 1;  /* ACQ */
  PageSizeList[4] = 1;  /* SQs */
  PageSizeList[5] = 1;  /* CQs */
  PageSizeList[6] = NVME_PRP_SIZE * NVME_CSQ_DEPTH;  /* PRPs */
  PageSizeList[7] = 1;  /* Security Commands */

  if (BaseMemIndex > MAX_BASEMEM_COUNT) {
    ASSERT (FALSE);
    return 0;
  }

  Pages = 0;
  for (Index = 0; Index < BaseMemIndex; Index++) {
    Pages += PageSizeList[Index];
  }

  return Pages;
}

/**
  Wait for NVME controller status to be ready or not.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] WaitReady              - Flag for waitting status ready or not

  @return EFI_SUCCESS               - Successfully to wait specific status.
  @return others                    - Fail to wait for specific controller status.

**/
STATIC
EFI_STATUS
NvmeWaitController (
  IN NVME_CONTEXT       *Nvme,
  IN BOOLEAN            WaitReady
  )
{
  NVME_CSTS              Csts;
  EFI_STATUS             Status;
  UINT32                 Index;
  UINT8                  Timeout;

  //
  // Cap.To specifies max delay time in 500ms increments for Csts.Rdy to set after
  // Cc.Enable. Loop produces a 1 millisecond delay per itteration, up to 500 * Cap.To.
  //
  if (Nvme->Cap.To == 0) {
    Timeout = 1;
  } else {
    Timeout = Nvme->Cap.To;
  }

  Status = EFI_SUCCESS;
  for(Index = (Timeout * 500); Index != 0; --Index) {
    MicroSecondDelay (1000);

    //
    // Check if the controller is initialized
    //
    Status = NVME_GET_CSTS (Nvme, &Csts);
    if (EFI_ERROR(Status)) {
      DEBUG ((DEBUG_ERROR, "NVME_GET_CSTS fail, Status = %r\n", Status));
      return Status;
    }

    if ((BOOLEAN) Csts.Rdy == WaitReady) {
      break;
    }
  }

  if (Index == 0) {
    Status = EFI_TIMEOUT;
  }

  return Status;
}

/**
  Disable the Nvm Express controller.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @return EFI_SUCCESS               - Successfully disable the controller.
  @return others                    - Fail to disable the controller.

**/
STATIC
EFI_STATUS
NvmeDisableController (
  IN NVME_CONTEXT       *Nvme
  )
{
  NVME_CC                Cc;
  NVME_CSTS              Csts;
  EFI_STATUS             Status;

  Status = NVME_GET_CSTS (Nvme, &Csts);

  ///
  /// Read Controller Configuration Register.
  ///
  Status = NVME_GET_CC (Nvme, &Cc);
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "NVME_GET_CC fail, Status = %r\n", Status));
    goto Done;
  }

  if (Cc.En == 1) {
    Cc.En = 0;
    ///
    /// Disable the controller.
    ///
    Status = NVME_SET_CC (Nvme, &Cc);
    if (EFI_ERROR(Status)) {
      DEBUG ((DEBUG_ERROR, "NVME_SET_CC fail, Status = %r\n", Status));
      goto Done;
    }
  }

  Status = NvmeWaitController (Nvme, FALSE);
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "NvmeWaitController fail, Status = %r\n", Status));
    goto Done;
  }

  return EFI_SUCCESS;

Done:
  DEBUG ((DEBUG_INFO, "NvmeDisableController fail, Status: %r\n", Status));
  return Status;
}

/**
  Enable the Nvm Express controller.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @return EFI_SUCCESS               - Successfully enable the controller.
  @return EFI_DEVICE_ERROR          - Fail to enable the controller.
  @return EFI_TIMEOUT               - Fail to enable the controller in given time slot.

**/
STATIC
EFI_STATUS
NvmeEnableController (
  IN NVME_CONTEXT       *Nvme
  )
{
  NVME_CC                Cc;
  EFI_STATUS             Status;

  //
  // Enable the controller
  //
  ZeroMem (&Cc, sizeof (NVME_CC));
  Cc.En     = 1;
  Cc.Iosqes = 6;
  Cc.Iocqes = 4;
  Status    = NVME_SET_CC (Nvme, &Cc);
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "NVME_SET_CC fail, Status = %r\n", Status));
    goto Done;
  }

  Status = NvmeWaitController (Nvme, TRUE);
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "NvmeWaitController fail, Status = %r\n", Status));
    goto Done;
  }

  return EFI_SUCCESS;

Done:
  DEBUG ((DEBUG_INFO, "NvmeEnableController fail, Status: %r\n", Status));
  return Status;
}

/**
  Shutdown the Nvm Express controller.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @return EFI_SUCCESS               - Successfully shutdown the controller.
  @return EFI_DEVICE_ERROR          - Fail to shutdown the controller.
  @return EFI_TIMEOUT               - Fail to shutdown the controller in given time slot.

**/
STATIC
EFI_STATUS
NvmeShutdownController (
  IN NVME_CONTEXT       *Nvme
  )
{
  NVME_CC                Cc;
  NVME_CSTS              Csts;
  EFI_STATUS             Status;
  UINT32                 Index;
  UINTN                  Timeout;

  Status    = NVME_GET_CC (Nvme, &Cc);
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "NVME_GET_CC fail, Status = %r\n", Status));
    return Status;
  }

  Cc.Shn     = 1; // Normal shutdown

  Status    = NVME_SET_CC (Nvme, &Cc);
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "NVME_SET_CC fail, Status = %r\n", Status));
    return Status;
  }

  Timeout = NVME_GENERIC_TIMEOUT/1000; // ms
  for(Index = (UINT32)(Timeout); Index != 0; --Index) {
    MicroSecondDelay (1000);

    Status = NVME_GET_CSTS (Nvme, &Csts);
    if (EFI_ERROR(Status)) {
      DEBUG ((DEBUG_ERROR, "NVME_GET_CSTS fail, Status = %r\n", Status));
      return Status;
    }

    if (Csts.Shst == 2) { // Shutdown processing complete
      break;
    }
  }

  if (Index == 0) {
    Status = EFI_TIMEOUT;
  }

  return Status;
}

/**
  Check the execution status from a given completion queue entry.

  @param[in]     Cq                 - A pointer to the NVME_CQ item.

**/
EFI_STATUS
NvmeCheckCqStatus (
  IN NVME_CQ             *Cq
  )
{
  if (Cq->Sct == 0x0 && Cq->Sc == 0x0) {
    return EFI_SUCCESS;
  }

  DEBUG ((DEBUG_INFO, "Dump NVMe Completion Entry Status from [0x%x]:\n", (UINTN)Cq));
  DEBUG ((DEBUG_INFO, "  SQ Identifier : [0x%x], Phase Tag : [%d], Cmd Identifier : [0x%x]\n", Cq->Sqid, Cq->Pt, Cq->Cid));
  DEBUG ((DEBUG_INFO, "  NVMe Cmd Execution Result - "));

  switch (Cq->Sct) {
    case 0x0:
      switch (Cq->Sc) {
        case 0x0:
          DEBUG ((DEBUG_INFO, "Successful Completion\n"));
          return EFI_SUCCESS;
        case 0x1:
          DEBUG ((DEBUG_INFO, "Invalid Command Opcode\n"));
          break;
        case 0x2:
          DEBUG ((DEBUG_INFO, "Invalid Field in Command\n"));
          break;
        case 0x3:
          DEBUG ((DEBUG_INFO, "Command ID Conflict\n"));
          break;
        case 0x4:
          DEBUG ((DEBUG_INFO, "Data Transfer Error\n"));
          break;
        case 0x5:
          DEBUG ((DEBUG_INFO, "Commands Aborted due to Power Loss Notification\n"));
          break;
        case 0x6:
          DEBUG ((DEBUG_INFO, "Internal Device Error\n"));
          break;
        case 0x7:
          DEBUG ((DEBUG_INFO, "Command Abort Requested\n"));
          break;
        case 0x8:
          DEBUG ((DEBUG_INFO, "Command Aborted due to SQ Deletion\n"));
          break;
        case 0x9:
          DEBUG ((DEBUG_INFO, "Command Aborted due to Failed Fused Command\n"));
          break;
        case 0xA:
          DEBUG ((DEBUG_INFO, "Command Aborted due to Missing Fused Command\n"));
          break;
        case 0xB:
          DEBUG ((DEBUG_INFO, "Invalid Namespace or Format\n"));
          break;
        case 0xC:
          DEBUG ((DEBUG_INFO, "Command Sequence Error\n"));
          break;
        case 0xD:
          DEBUG ((DEBUG_INFO, "Invalid SGL Last Segment Descriptor\n"));
          break;
        case 0xE:
          DEBUG ((DEBUG_INFO, "Invalid Number of SGL Descriptors\n"));
          break;
        case 0xF:
          DEBUG ((DEBUG_INFO, "Data SGL Length Invalid\n"));
          break;
        case 0x10:
          DEBUG ((DEBUG_INFO, "Metadata SGL Length Invalid\n"));
          break;
        case 0x11:
          DEBUG ((DEBUG_INFO, "SGL Descriptor Type Invalid\n"));
          break;
        case 0x80:
          DEBUG ((DEBUG_INFO, "LBA Out of Range\n"));
          break;
        case 0x81:
          DEBUG ((DEBUG_INFO, "Capacity Exceeded\n"));
          break;
        case 0x82:
          DEBUG ((DEBUG_INFO, "Namespace Not Ready\n"));
          break;
        case 0x83:
          DEBUG ((DEBUG_INFO, "Reservation Conflict\n"));
          break;
      }
      break;

    case 0x1:
      switch (Cq->Sc) {
        case 0x0:
          DEBUG ((DEBUG_INFO, "Completion Queue Invalid\n"));
          break;
        case 0x1:
          DEBUG ((DEBUG_INFO, "Invalid Queue Identifier\n"));
          break;
        case 0x2:
          DEBUG ((DEBUG_INFO, "Maximum Queue Size Exceeded\n"));
          break;
        case 0x3:
          DEBUG ((DEBUG_INFO, "Abort Command Limit Exceeded\n"));
          break;
        case 0x5:
          DEBUG ((DEBUG_INFO, "Asynchronous Event Request Limit Exceeded\n"));
          break;
        case 0x6:
          DEBUG ((DEBUG_INFO, "Invalid Firmware Slot\n"));
          break;
        case 0x7:
          DEBUG ((DEBUG_INFO, "Invalid Firmware Image\n"));
          break;
        case 0x8:
          DEBUG ((DEBUG_INFO, "Invalid Interrupt Vector\n"));
          break;
        case 0x9:
          DEBUG ((DEBUG_INFO, "Invalid Log Page\n"));
          break;
        case 0xA:
          DEBUG ((DEBUG_INFO, "Invalid Format\n"));
          break;
        case 0xB:
          DEBUG ((DEBUG_INFO, "Firmware Application Requires Conventional Reset\n"));
          break;
        case 0xC:
          DEBUG ((DEBUG_INFO, "Invalid Queue Deletion\n"));
          break;
        case 0xD:
          DEBUG ((DEBUG_INFO, "Feature Identifier Not Saveable\n"));
          break;
        case 0xE:
          DEBUG ((DEBUG_INFO, "Feature Not Changeable\n"));
          break;
        case 0xF:
          DEBUG ((DEBUG_INFO, "Feature Not Namespace Specific\n"));
          break;
        case 0x10:
          DEBUG ((DEBUG_INFO, "Firmware Application Requires NVM Subsystem Reset\n"));
          break;
        case 0x80:
          DEBUG ((DEBUG_INFO, "Conflicting Attributes\n"));
          break;
        case 0x81:
          DEBUG ((DEBUG_INFO, "Invalid Protection Information\n"));
          break;
        case 0x82:
          DEBUG ((DEBUG_INFO, "Attempted Write to Read Only Range\n"));
          break;
      }
      break;

    case 0x2:
      switch (Cq->Sc) {
        case 0x80:
          DEBUG ((DEBUG_INFO, "Write Fault\n"));
          break;
        case 0x81:
          DEBUG ((DEBUG_INFO, "Unrecovered Read Error\n"));
          break;
        case 0x82:
          DEBUG ((DEBUG_INFO, "End-to-end Guard Check Error\n"));
          break;
        case 0x83:
          DEBUG ((DEBUG_INFO, "End-to-end Application Tag Check Error\n"));
          break;
        case 0x84:
          DEBUG ((DEBUG_INFO, "End-to-end Reference Tag Check Error\n"));
          break;
        case 0x85:
          DEBUG ((DEBUG_INFO, "Compare Failure\n"));
          break;
        case 0x86:
          DEBUG ((DEBUG_INFO, "Access Denied\n"));
          break;
      }
      break;

    default:
      DEBUG ((DEBUG_INFO, "Unknown error\n"));
      break;
  }

  return EFI_DEVICE_ERROR;
}

/**
  Create PRP lists for Data transfer which is larger than 2 memory pages.
  Note here we calcuate the number of required PRP lists and allocate them at one time.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] SqId                   - The SQ index for this PRP
  @param[in] PhysicalAddr           - The physical base address of Data Buffer.
  @param[in] Pages                  - The number of pages to be transfered.
  @param[out] PrpListHost           - The host base address of PRP lists.
  @param[in,out] PrpListNo          - The number of PRP List.

  @retval The pointer Value to the first PRP List of the PRP lists.

**/
STATIC
UINT64
NvmeCreatePrpList (
  IN     NVME_CONTEXT                 *Nvme,
  IN     UINT16                       SqId,
  IN     EFI_PHYSICAL_ADDRESS         PhysicalAddr,
  IN     UINTN                        Pages,
     OUT VOID                         **PrpListHost,
  IN OUT UINTN                        *PrpListNo
  )
{
  UINTN                       PrpEntryNo;
  UINT64                      PrpListBase;
  UINTN                       PrpListIndex;
  UINTN                       PrpEntryIndex;
  UINT64                      Remainder;
  EFI_PHYSICAL_ADDRESS        PrpListPhyAddr;
  UINTN                       Bytes;
  UINT8                       *PrpEntry;
  EFI_PHYSICAL_ADDRESS        NewPhyAddr;

  ///
  /// The number of Prp Entry in a memory page.
  ///
  PrpEntryNo = EFI_PAGE_SIZE / sizeof (UINT64);

  ///
  /// Calculate total PrpList number.
  ///
  *PrpListNo = (UINTN) DivU64x64Remainder ((UINT64)Pages, (UINT64)PrpEntryNo, &Remainder);
  if (Remainder != 0) {
    *PrpListNo += 1;
  }

  if (*PrpListNo > NVME_PRP_SIZE) {
    DEBUG ((DEBUG_INFO, "NvmeCreatePrpList (PhysicalAddr: %lx, Pages: %x) PrpEntryNo: %x\n",
      PhysicalAddr, Pages, PrpEntryNo));
    DEBUG ((DEBUG_INFO, "*PrpListNo: %x, Remainder: %lx", *PrpListNo, Remainder));
    ASSERT (FALSE);
  }
  *PrpListHost = (VOID *)(UINTN) NVME_PRP_BASE (Nvme, SqId);

  Bytes = EFI_PAGES_TO_SIZE (*PrpListNo);
  PrpListPhyAddr = (UINT64)(UINTN)(*PrpListHost);

  ///
  /// Fill all PRP lists except of last one.
  ///
  ZeroMem (*PrpListHost, Bytes);
  for (PrpListIndex = 0; PrpListIndex < *PrpListNo - 1; ++PrpListIndex) {
    PrpListBase = *(UINT64*)PrpListHost + PrpListIndex * EFI_PAGE_SIZE;

    for (PrpEntryIndex = 0; PrpEntryIndex < PrpEntryNo; ++PrpEntryIndex) {
      PrpEntry = (UINT8 *)(UINTN) (PrpListBase + PrpEntryIndex * sizeof(UINT64));
      if (PrpEntryIndex != PrpEntryNo - 1) {
        ///
        /// Fill all PRP entries except of last one.
        ///
        CopyMem (PrpEntry, (VOID *)(UINTN) (&PhysicalAddr), sizeof (UINT64));
        PhysicalAddr += EFI_PAGE_SIZE;
      } else {
        ///
        /// Fill last PRP entries with next PRP List pointer.
        ///
        NewPhyAddr = (PrpListPhyAddr + (PrpListIndex + 1) * EFI_PAGE_SIZE);
        CopyMem (PrpEntry, (VOID *)(UINTN) (&NewPhyAddr), sizeof (UINT64));
      }
    }
  }

  ///
  /// Fill last PRP list.
  ///
  PrpListBase = *(UINT64*)PrpListHost + PrpListIndex * EFI_PAGE_SIZE;
  for (PrpEntryIndex = 0; PrpEntryIndex < ((Remainder != 0) ? Remainder : PrpEntryNo); ++PrpEntryIndex) {
    PrpEntry = (UINT8 *)(UINTN) (PrpListBase + PrpEntryIndex * sizeof(UINT64));
    CopyMem (PrpEntry, (VOID *)(UINTN) (&PhysicalAddr), sizeof (UINT64));

    PhysicalAddr += EFI_PAGE_SIZE;
  }

  return PrpListPhyAddr;
}

/**
  Check whether there are available command slots.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] Qid                    - Queue index

  @retval EFI_SUCCESS               - Available command slot is found
  @retval EFI_NOT_READY             - No available command slot is found
  @retval EFI_DEVICE_ERROR          - Error occurred on device side.

**/
EFI_STATUS
NvmeHasFreeCmdSlot (
  IN NVME_CONTEXT       *Nvme,
  IN UINT8              Qid
  )
{
  return TRUE;
}

/**
  Check whether all command slots are clean.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] Qid                    - Queue index

  @retval EFI_SUCCESS               - All command slots are clean
  @retval EFI_NOT_READY             - Not all command slots are clean
  @retval EFI_DEVICE_ERROR          - Error occurred on device side.

**/
EFI_STATUS
NvmeIsAllCmdSlotClean (
  IN NVME_CONTEXT       *Nvme,
  IN UINT8              Qid
  )
{
  return EFI_SUCCESS;
}

/**
  Waits until all NVME commands completed.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] Qid                    - Queue index

  @retval EFI_SUCCESS               - All NVME commands have completed
  @retval EFI_TIMEOUT               - Timeout occured
  @retval EFI_NOT_READY             - Not all NVME commands have completed
  @retval others                    - Error occurred on device side.
**/
EFI_STATUS
NvmeWaitAllComplete (
  IN NVME_CONTEXT       *Nvme,
  IN UINT8              Qid
  )
{
  return EFI_SUCCESS;
}

/**
  Sends an NVM Express Command Packet to an NVM Express controller or namespace. This function supports
  both blocking I/O and nonblocking I/O. The blocking I/O functionality is required, and the nonblocking
  I/O functionality is optional.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] NamespaceId            - Is a 32 bit Namespace ID to which the Express HCI command packet will be sent.
                                      A Value of 0 denotes the NVM Express controller, a Value of all 0FFh in the namespace
                                      ID specifies that the command packet should be sent to all valid namespaces.
  @param[in] NamespaceUuid          - Is a 64 bit Namespace UUID to which the Express HCI command packet will be sent.
                                      A Value of 0 denotes the NVM Express controller, a Value of all 0FFh in the namespace
                                      UUID specifies that the command packet should be sent to all valid namespaces.
  @param[in,out] Packet             - A pointer to the NVM Express HCI Command Packet to send to the NVMe namespace specified
                                      by NamespaceId.

  @retval EFI_SUCCESS               - The NVM Express Command Packet was sent by the host. TransferLength bytes were transferred
                                      to, or from DataBuffer.
  @retval EFI_NOT_READY             - The NVM Express Command Packet could not be sent because the controller is not ready. The caller
                                      may retry again later.
  @retval EFI_DEVICE_ERROR          - A device error occurred while attempting to send the NVM Express Command Packet.
  @retval EFI_INVALID_PARAMETER     - Namespace, or the contents of NVM_EXPRESS_PASS_THRU_COMMAND_PACKET are invalid. The NVM
                                      Express Command Packet was not sent, so no additional status information is available.
  @retval EFI_UNSUPPORTED           - The command described by the NVM Express Command Packet is not supported by the host adapter.
                                      The NVM Express Command Packet was not sent, so no additional status information is available.
  @retval EFI_TIMEOUT               - A timeout occurred while waiting for the NVM Express Command Packet to execute.

**/
EFI_STATUS
NvmePassThru (
  IN     NVME_CONTEXT                         *Nvme,
  IN     UINT32                               NamespaceId,
  IN     UINT64                               NamespaceUuid,
  IN OUT NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet
  )
{
  EFI_STATUS                    Status;
  NVME_SQ                       *Sq;
  NVME_CQ                       *Cq;
  UINT8                         Qid;
  UINT32                        Bytes;
  UINT32                        Offset;
  EFI_PHYSICAL_ADDRESS          PhyAddr;
  VOID                          *PrpListHost;
  UINTN                         PrpListNo;
  UINT32                        Timer;
  UINTN SqSize;
  UINTN CqSize;

  ///
  /// check the Data fields in Packet parameter.
  ///
  if ((Nvme == NULL) || (Packet == NULL)) {
    DEBUG ((DEBUG_ERROR, "NvmePassThru, invalid parameter: Nvme(%x)/Packet(%x)\n",
      (UINTN)Nvme, (UINTN)Packet));
    return EFI_INVALID_PARAMETER;
  }

  if ((Packet->NvmeCmd == NULL) || (Packet->NvmeResponse == NULL)) {
    DEBUG ((DEBUG_ERROR, "NvmePassThru, invalid parameter: NvmeCmd(%x)/NvmeResponse(%x)\n",
      (UINTN)Packet->NvmeCmd, (UINTN)Packet->NvmeResponse));
    return EFI_INVALID_PARAMETER;
  }

  if (Packet->QueueId != NVME_ADMIN_QUEUE && Packet->QueueId != NVME_IO_QUEUE) {
    DEBUG ((DEBUG_ERROR, "NvmePassThru, invalid parameter: QueueId(%x)\n",
      Packet->QueueId));
    return EFI_INVALID_PARAMETER;
  }

  PrpListHost = NULL;
  PrpListNo   = 0;
  Status      = EFI_SUCCESS;

  Qid = Packet->QueueId;
  Sq  = Nvme->SqBuffer[Qid] + Nvme->SqTdbl[Qid].Sqt;
  Cq  = Nvme->CqBuffer[Qid] + Nvme->CqHdbl[Qid].Cqh;
  if (Qid == NVME_ADMIN_QUEUE) {
    SqSize = NVME_ASQ_SIZE + 1;
    CqSize = NVME_ACQ_SIZE + 1;
  } else {
    SqSize = NVME_CSQ_DEPTH;
    CqSize = NVME_CCQ_DEPTH;
  }

  if (Packet->NvmeCmd->Nsid != NamespaceId) {
    DEBUG ((DEBUG_ERROR, "NvmePassThru: Nsid mismatch (%x, %x)\n",
      Packet->NvmeCmd->Nsid, NamespaceId));
    return EFI_INVALID_PARAMETER;
  }

  ZeroMem (Sq, sizeof (NVME_SQ));
  Sq->Opc  = Packet->NvmeCmd->Cdw0.Opcode;
  Sq->Fuse = Packet->NvmeCmd->Cdw0.FusedOperation;
  Sq->Cid  = Packet->NvmeCmd->Cdw0.Cid;
  Sq->Nsid = Packet->NvmeCmd->Nsid;

  ///
  /// Currently we only support PRP for Data transfer, SGL is NOT supported.
  ///
  ASSERT (Sq->Psdt == 0);
  if (Sq->Psdt != 0) {
    DEBUG ((DEBUG_ERROR, "NvmePassThru: doesn't support SGL mechanism\n"));
    return EFI_UNSUPPORTED;
  }

  Sq->Prp[0] = Packet->TransferBuffer;
  Sq->Prp[1] = 0;

  if(Packet->MetadataBuffer != (UINT64)(UINTN)NULL) {
    Sq->Mptr = Packet->MetadataBuffer;
  }

  ///
  /// If the Buffer Size spans more than two memory pages (page Size as defined in CC.Mps),
  /// then build a PRP list in the second PRP submission queue entry.
  ///
  Offset = ((UINT32)Sq->Prp[0]) & (EFI_PAGE_SIZE - 1);
  Bytes  = Packet->TransferLength;

  if ((Offset + Bytes) > (EFI_PAGE_SIZE * 2)) {
    ///
    /// Create PrpList for remaining Data Buffer.
    ///
    PhyAddr = (Sq->Prp[0] + EFI_PAGE_SIZE) & ~(EFI_PAGE_SIZE - 1);
    Sq->Prp[1] = NvmeCreatePrpList (Nvme, Nvme->SqTdbl[Qid].Sqt, PhyAddr, EFI_SIZE_TO_PAGES(Offset + Bytes) - 1, &PrpListHost, &PrpListNo);
    if (Sq->Prp[1] == 0) {
      Status = EFI_OUT_OF_RESOURCES;
      DEBUG ((DEBUG_ERROR, "NvmeCreatePrpList fail, Status: %r\n", Status));
      goto EXIT;
    }

  } else if ((Offset + Bytes) > EFI_PAGE_SIZE) {
    Sq->Prp[1] = (Sq->Prp[0] + EFI_PAGE_SIZE) & ~(EFI_PAGE_SIZE - 1);
  }

  if(Packet->NvmeCmd->Flags & CDW10_VALID) {
    Sq->Payload.Raw.Cdw10 = Packet->NvmeCmd->Cdw10;
  }
  if(Packet->NvmeCmd->Flags & CDW11_VALID) {
    Sq->Payload.Raw.Cdw11 = Packet->NvmeCmd->Cdw11;
  }
  if(Packet->NvmeCmd->Flags & CDW12_VALID) {
    Sq->Payload.Raw.Cdw12 = Packet->NvmeCmd->Cdw12;
  }
  if(Packet->NvmeCmd->Flags & CDW13_VALID) {
    Sq->Payload.Raw.Cdw13 = Packet->NvmeCmd->Cdw13;
  }
  if(Packet->NvmeCmd->Flags & CDW14_VALID) {
    Sq->Payload.Raw.Cdw14 = Packet->NvmeCmd->Cdw14;
  }
  if(Packet->NvmeCmd->Flags & CDW15_VALID) {
    Sq->Payload.Raw.Cdw15 = Packet->NvmeCmd->Cdw15;
  }

  ///
  /// Ring the submission queue doorbell.
  ///
  Nvme->SqTdbl[Qid].Sqt++;
  if(Nvme->SqTdbl[Qid].Sqt == SqSize) {
    Nvme->SqTdbl[Qid].Sqt = 0;
  }
  Status = NVME_SET_SQTDBL (Nvme, Qid, &Nvme->SqTdbl[Qid]);
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "NVME_SET_SQTDBL fail, Status: %r\n", Status));
    goto EXIT;
  }

  ///
  /// Wait for completion queue to get filled in.
  ///
  Status = EFI_TIMEOUT;
  Timer   = 0;
  while (Timer < NVME_CMD_TIMEOUT) {
    //DEBUG ((DEBUG_VERBOSE, "Timer: %x, Cq:\n", Timer));
    //DumpMem (Cq, sizeof (NVME_CQ));
    if (Cq->Pt != Nvme->Pt[Qid]) {
      Status = EFI_SUCCESS;
      break;
    }

    MicroSecondDelay (NVME_CMD_WAIT);
    Timer += NVME_CMD_WAIT;
  }

  Nvme->CqHdbl[Qid].Cqh++;
  if (Nvme->CqHdbl[Qid].Cqh == CqSize) {
    Nvme->CqHdbl[Qid].Cqh = 0;
    Nvme->Pt[Qid] ^= 1;
  }

  ///
  /// Copy the Respose Queue entry for this command to the callers response Buffer
  ///
  CopyMem (Packet->NvmeResponse, Cq, sizeof(NVM_EXPRESS_RESPONSE));

  if (!EFI_ERROR(Status)) { // We still need to check CQ status if no timeout error occured
    Status = NvmeCheckCqStatus (Cq);
  }
  NVME_SET_CQHDBL (Nvme, Qid, &Nvme->CqHdbl[Qid]);

EXIT:
  return Status;
}

/**
  Get identify controller Data.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] Buffer                 - The Buffer used to store the identify controller Data.

  @return EFI_SUCCESS               - Successfully get the identify controller Data.
  @return others                    - Fail to get the identify controller Data.

**/
STATIC
EFI_STATUS
NvmeIdentifyController (
  IN NVME_CONTEXT                          *Nvme,
  IN VOID                                  *Buffer
  )
{
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));

  Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_OPC;
  Command.Cdw0.Cid    = Nvme->Cid[NVME_ADMIN_QUEUE]++;
  //
  // According to Nvm Express 1.1 spec Figure 38, When not used, the field shall be cleared to 0h.
  // For the Identify command, the Namespace Identifier is only used for the Namespace Data structure.
  //
  Command.Nsid        = 0;

  CommandPacket.NvmeCmd        = &Command;
  CommandPacket.NvmeResponse   = &Response;
  CommandPacket.TransferBuffer = (UINT64)(UINTN)Buffer;
  CommandPacket.TransferLength = sizeof (NVME_ADMIN_CONTROLLER_DATA);
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_ADMIN_QUEUE;
  //
  // Set bit 0 (Cns bit) to 1 to identify a controller
  //
  Command.Cdw10                = 1;
  Command.Flags                = CDW10_VALID;

  Status = NvmePassThru (
              Nvme,
              NVME_CONTROLLER_ID,
              0,
              &CommandPacket
              );
  if (!EFI_ERROR (Status)) {
    Status = NvmeWaitAllComplete (Nvme, CommandPacket.QueueId);
  }

  return Status;
}

/**
  Get specified identify namespace Data.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] NamespaceId            - The specified namespace identifier.
  @param[in] Buffer                 - The Buffer used to store the identify namespace Data.

  @return EFI_SUCCESS               - Successfully get the identify namespace Data.
  @return others                    - Fail to get the identify namespace Data.

**/
STATIC
EFI_STATUS
NvmeIdentifyNamespace (
  IN NVME_CONTEXT                          *Nvme,
  IN UINT32                                NamespaceId,
  IN VOID                                  *Buffer
  )
{
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));

  CommandPacket.NvmeCmd      = &Command;
  CommandPacket.NvmeResponse = &Response;

  Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_OPC;
  Command.Cdw0.Cid    = Nvme->Cid[NVME_ADMIN_QUEUE]++;
  Command.Nsid        = NamespaceId;
  CommandPacket.TransferBuffer = (UINT64)(UINTN)Buffer;
  CommandPacket.TransferLength = sizeof (NVME_ADMIN_NAMESPACE_DATA);
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_ADMIN_QUEUE;
  //
  // Set bit 0 (Cns bit) to 1 to identify a namespace
  //
  CommandPacket.NvmeCmd->Cdw10 = 0;
  CommandPacket.NvmeCmd->Flags = CDW10_VALID;

  Status = NvmePassThru (
              Nvme,
              NamespaceId,
              0,
              &CommandPacket
              );
  if (!EFI_ERROR (Status)) {
    Status = NvmeWaitAllComplete (Nvme, CommandPacket.QueueId);
  }

  return Status;
}

/**
  Get Block Size for specific namespace of NVME.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @return                           - Block Size in bytes

**/
STATIC
UINT32
NvmeGetBlockSize (
  IN NVME_CONTEXT       *Nvme
  )
{
  UINT32                BlockSize;
  UINT32                Lbads;
  UINT32                Flbas;
  UINT32                LbaFmtIdx;

  Flbas     = Nvme->NamespaceData->Flbas;
  LbaFmtIdx = Flbas & 3;
  Lbads     = Nvme->NamespaceData->LbaFormat[LbaFmtIdx].Lbads;

  BlockSize = (UINT32)1 << Lbads;
  return BlockSize;
}

/**
  Get last LBA for specific namespace of NVME.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @return                           - Last LBA address

**/
STATIC
EFI_LBA
NvmeGetLastLba (
  IN NVME_CONTEXT       *Nvme
  )
{
  EFI_LBA               LastBlock;
  LastBlock = Nvme->NamespaceData->Nsze - 1;
  return LastBlock;
}

/**
  Create io completion queue.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @return EFI_SUCCESS               - Successfully create io completion queue.
  @return others                    - Fail to create io completion queue.

**/
STATIC
EFI_STATUS
NvmeCreateIoCompletionQueue (
  IN     NVME_CONTEXT                      *Nvme
  )
{
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;
  NVME_ADMIN_CRIOCQ                        CrIoCq;

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));
  ZeroMem (&CrIoCq, sizeof(NVME_ADMIN_CRIOCQ));

  CommandPacket.NvmeCmd      = &Command;
  CommandPacket.NvmeResponse = &Response;

  Command.Cdw0.Opcode = NVME_ADMIN_CRIOCQ_OPC;
  Command.Cdw0.Cid    = Nvme->Cid[NVME_ADMIN_QUEUE]++;
  CommandPacket.TransferBuffer = (UINT64)(UINTN)Nvme->CqBuffer[NVME_IO_QUEUE];
  CommandPacket.TransferLength = EFI_PAGE_SIZE;
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_ADMIN_QUEUE;

  CrIoCq.Qid   = NVME_IO_QUEUE;
  CrIoCq.Qsize = NVME_CCQ_SIZE;
  CrIoCq.Pc    = 1;
  CopyMem (&CommandPacket.NvmeCmd->Cdw10, &CrIoCq, sizeof (NVME_ADMIN_CRIOCQ));
  CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID;

  Status = NvmePassThru (
              Nvme,
              NVME_CONTROLLER_ID,
              0,
              &CommandPacket
              );
  if (!EFI_ERROR (Status)) {
    Status = NvmeWaitAllComplete (Nvme, CommandPacket.QueueId);
  }

  return Status;
}

/**
  Create io submission queue.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @return EFI_SUCCESS               - Successfully create io submission queue.
  @return others                    - Fail to create io submission queue.

**/
STATIC
EFI_STATUS
NvmeCreateIoSubmissionQueue (
  IN NVME_CONTEXT                          *Nvme
  )
{
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;
  NVME_ADMIN_CRIOSQ                        CrIoSq;

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));
  ZeroMem (&CrIoSq, sizeof(NVME_ADMIN_CRIOSQ));

  CommandPacket.NvmeCmd      = &Command;
  CommandPacket.NvmeResponse = &Response;

  Command.Cdw0.Opcode = NVME_ADMIN_CRIOSQ_OPC;
  Command.Cdw0.Cid    = Nvme->Cid[NVME_ADMIN_QUEUE]++;
  CommandPacket.TransferBuffer = (UINT64)(UINTN)Nvme->SqBuffer[NVME_IO_QUEUE];
  CommandPacket.TransferLength = EFI_PAGE_SIZE;
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_ADMIN_QUEUE;

  CrIoSq.Qid   = NVME_IO_QUEUE;
  CrIoSq.Qsize = NVME_CSQ_SIZE;
  CrIoSq.Pc    = 1;
  CrIoSq.Cqid  = NVME_IO_QUEUE;
  CrIoSq.Qprio = 0;
  CopyMem (&CommandPacket.NvmeCmd->Cdw10, &CrIoSq, sizeof (NVME_ADMIN_CRIOSQ));
  CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID;

  Status = NvmePassThru (
              Nvme,
              NVME_CONTROLLER_ID,
              0,
              &CommandPacket
              );
  if (!EFI_ERROR (Status)) {
    Status = NvmeWaitAllComplete (Nvme, CommandPacket.QueueId);
  }

  return Status;
}

/**
  Security send and receive commands.

  @param[in]     Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in]     SendCommand            - The flag to indicate the command type, TRUE for Send command and FALSE for receive command
  @param[in]     SecurityProtocol       - Security Protocol
  @param[in]     SpSpecific             - Security Protocol Specific
  @param[in]     TransferLength         - Transfer Length of Buffer (in bytes) - always a multiple of 512
  @param[in,out] TransferBuffer         - Address of Data to transfer

  @return EFI_SUCCESS               - Successfully create io submission queue.
  @return others                    - Fail to send/receive commands.

**/
EFI_STATUS
NvmeSecuritySendReceive (
  IN NVME_CONTEXT                          *Nvme,
  IN BOOLEAN                               SendCommand,
  IN UINT8                                 SecurityProtocol,
  IN UINT16                                SpSpecific,
  IN UINTN                                 TransferLength,
  IN OUT VOID                              *TransferBuffer
  )
{
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;
  NVME_ADMIN_SECSEND                       SecSend;
  OACS                                     *Oacs;
  UINT8                                    Opcode;
  VOID*                                    *SecBuff;

  Oacs = (OACS *)&Nvme->ControllerData->Oacs;

  //
  // Verify security bit for Security Send/Receive commands
  //
  if (Oacs->Security == 0) {
    DEBUG ((DEBUG_ERROR, "Security command doesn't support.\n"));
    return EFI_NOT_READY;
  }

  SecBuff = (VOID *)(UINTN) NVME_SEC_BASE (Nvme);

  //
  // Actions for sending security command
  //
  if (SendCommand) {
    CopyMem (SecBuff, TransferBuffer, TransferLength);
  }

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));
  ZeroMem (&SecSend, sizeof(NVME_ADMIN_SECSEND));

  CommandPacket.NvmeCmd      = &Command;
  CommandPacket.NvmeResponse = &Response;

  Opcode = (UINT8)(SendCommand ? NVME_ADMIN_SECURITY_SEND_OPC : NVME_ADMIN_SECURITY_RECV_OPC);
  Command.Cdw0.Opcode = Opcode;
  Command.Cdw0.Cid    = Nvme->Cid[NVME_ADMIN_QUEUE]++;
  CommandPacket.TransferBuffer = (UINT64)(UINTN)SecBuff;
  CommandPacket.TransferLength = (UINT32)TransferLength;
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_ADMIN_QUEUE;

  SecSend.Spsp = SpSpecific;
  SecSend.Secp = SecurityProtocol;
  SecSend.Tl   = (UINT32)TransferLength;

  CopyMem (&CommandPacket.NvmeCmd->Cdw10, &SecSend, sizeof (NVME_ADMIN_SECSEND));
  CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID;

  Status = NvmePassThru (
              Nvme,
              NVME_CONTROLLER_ID,
              0,
              &CommandPacket
              );
  if (!EFI_ERROR (Status)) {
    Status = NvmeWaitAllComplete (Nvme, CommandPacket.QueueId);
  }

  //
  // Actions for receiving security command
  //
  if (!SendCommand) {
    CopyMem (TransferBuffer, SecBuff, TransferLength);
  }

  return Status;
}

/**
  Destroy io completion queue.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @return EFI_SUCCESS               - Successfully destroy io completion queue.
  @return others                    - Fail to destroy io completion queue.

**/
STATIC
EFI_STATUS
NvmeDestroyIoCompletionQueue (
  IN     NVME_CONTEXT                      *Nvme
  )
{
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;
  NVME_ADMIN_DEIOCQ                        DelIoCq;

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));
  ZeroMem (&DelIoCq, sizeof(NVME_ADMIN_DEIOCQ));

  CommandPacket.NvmeCmd      = &Command;
  CommandPacket.NvmeResponse = &Response;

  Command.Cdw0.Opcode = NVME_ADMIN_DELIOCQ_OPC;
  Command.Cdw0.Cid    = Nvme->Cid[NVME_ADMIN_QUEUE]++;
  CommandPacket.TransferBuffer = (UINT64)(UINTN)Nvme->CqBuffer[NVME_IO_QUEUE];
  CommandPacket.TransferLength = EFI_PAGE_SIZE;
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_ADMIN_QUEUE;

  DelIoCq.Qid   = NVME_IO_QUEUE;
  CopyMem (&CommandPacket.NvmeCmd->Cdw10, &DelIoCq, sizeof (NVME_ADMIN_DEIOCQ));
  CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID;

  Status = NvmePassThru (
              Nvme,
              NVME_CONTROLLER_ID,
              0,
              &CommandPacket
              );
  if (!EFI_ERROR (Status)) {
    Status = NvmeWaitAllComplete (Nvme, CommandPacket.QueueId);
  }

  return Status;
}

/**
  Destroy io submission queue.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @return EFI_SUCCESS               - Successfully destroy io submission queue.
  @return others                    - Fail to destroy io submission queue.

**/
STATIC
EFI_STATUS
NvmeDestroyIoSubmissionQueue (
  IN NVME_CONTEXT                          *Nvme
  )
{
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;
  NVME_ADMIN_DEIOSQ                        DelIoSq;

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));
  ZeroMem (&DelIoSq, sizeof(NVME_ADMIN_DEIOSQ));

  CommandPacket.NvmeCmd      = &Command;
  CommandPacket.NvmeResponse = &Response;

  Command.Cdw0.Opcode = NVME_ADMIN_DELIOSQ_OPC;
  Command.Cdw0.Cid    = Nvme->Cid[NVME_ADMIN_QUEUE]++;
  CommandPacket.TransferBuffer = (UINT64)(UINTN)Nvme->SqBuffer[NVME_IO_QUEUE];
  CommandPacket.TransferLength = EFI_PAGE_SIZE;
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_ADMIN_QUEUE;

  DelIoSq.Qid   = NVME_IO_QUEUE;
  CopyMem (&CommandPacket.NvmeCmd->Cdw10, &DelIoSq, sizeof (NVME_ADMIN_DEIOSQ));
  CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID;

  Status = NvmePassThru (
              Nvme,
              NVME_CONTROLLER_ID,
              0,
              &CommandPacket
              );
  if (!EFI_ERROR (Status)) {
    Status = NvmeWaitAllComplete (Nvme, CommandPacket.QueueId);
  }

  return Status;
}

/**
  Allocate transfer-related Data struct which is used at Nvme.

  @param[in, out] Nvme          The pointer to the NVME_CONTEXT Data structure.

  @retval EFI_OUT_OF_RESOURCE   No enough resource.
  @retval EFI_SUCCESS           Successful to allocate resource.

**/
EFI_STATUS
EFIAPI
NvmeAllocateResource (
  IN OUT NVME_CONTEXT       *Nvme
  )
{
  EFI_STATUS                Status;
  EFI_PHYSICAL_ADDRESS      DeviceAddress;
  VOID                      *Base;
  VOID                      *Mapping;

  //
  // Allocate resources for DMA.
  //
  Status = IoMmuAllocateBuffer (
             EFI_SIZE_TO_PAGES (NVME_MEM_MAX_SIZE),
             &Base,
             &DeviceAddress,
             &Mapping
             );
  if (EFI_ERROR (Status)) {
    return EFI_OUT_OF_RESOURCES;
  }
  ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS) (UINTN) Base));
  Nvme->BaseMemMapping = Mapping;
  Nvme->BaseMem = Base;
  ZeroMem (Nvme->BaseMem, EFI_PAGE_SIZE * EFI_SIZE_TO_PAGES (NVME_MEM_MAX_SIZE));

  DEBUG ((
    DEBUG_INFO,
    "%a() NvmeContext 0x%x\n",
    __FUNCTION__,
    Nvme->BaseMem
    ));

  return EFI_SUCCESS;
}

/**
  Free allocated transfer-related Data struct which is used at NVMe.

  @param[in, out] Nvme          The pointer to the NVME_CONTEXT Data structure.

**/
VOID
EFIAPI
NvmeFreeResource (
  IN OUT NVME_CONTEXT       *Nvme
  )
{
  if (Nvme->BaseMem != NULL) {
    IoMmuFreeBuffer (
       EFI_SIZE_TO_PAGES (NVME_MEM_MAX_SIZE),
       Nvme->BaseMem,
       Nvme->BaseMemMapping
       );
    Nvme->BaseMem = NULL;
  }
}

/**
  Initialize the Nvm Express controller.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @retval EFI_SUCCESS               - The NVM Express Controller is initialized successfully.
  @retval Others                    - A device error occurred while initializing the controller.

**/
EFI_STATUS
NvmeControllerInit (
  IN NVME_CONTEXT       *Nvme
  )
{
  EFI_STATUS            Status;
  NVME_AQA              Aqa;
  NVME_ASQ              Asq;
  NVME_ACQ              Acq;
  NVME_VER              Ver;

  UINT32                MlBAR;
  UINT32                MuBAR;

  ///
  /// Update PCIE BAR0/1 for NVME device
  ///
  MlBAR = Nvme->Nbar;
  MuBAR = 0;
  PciWrite32 (Nvme->PciBase + 0x10, MlBAR); // MLBAR (BAR0)
  PciWrite32 (Nvme->PciBase + 0x14, MuBAR); // MUBAR (BAR1)

  ///
  /// Enable PCIE decode
  ///
  PciWrite8 (Nvme->PciBase + NVME_PCIE_PCICMD, 0x6);

  // Version
  NVME_GET_VER (Nvme, &Ver);
  if (!(Ver.Mjr == 0x0001) && (Ver.Mnr == 0x0000)) {
    DEBUG ((DEBUG_INFO, "\n!!!\n!!! NVME Version mismatch for the implementation !!!\n!!!\n"));
  }

  ///
  /// Read the Controller Capabilities register and verify that the NVM command set is supported
  ///
  Status = NVME_GET_CAP (Nvme, &Nvme->Cap);
  if (EFI_ERROR (Status)) {
    DEBUG ((DEBUG_ERROR, "NVME_GET_CAP fail, Status: %r\n", Status));
    goto Done;
  }

  if (Nvme->Cap.Css != 0x01) {
    DEBUG ((DEBUG_ERROR, "NvmeControllerInit fail: the controller doesn't support NVMe command set\n"));
    Status = EFI_UNSUPPORTED;
    goto Done;
  }

  ///
  /// Currently the driver only supports 4k page Size.
  ///
  if ((Nvme->Cap.Mpsmin + 12) > EFI_PAGE_SHIFT) {
    DEBUG ((DEBUG_ERROR, "NvmeControllerInit fail: only supports 4k page Size\n"));
    ASSERT (FALSE);
    Status = EFI_UNSUPPORTED;
    goto Done;
  }

  Nvme->Cid[0] = 0;
  Nvme->Cid[1] = 0;

  Nvme->Pt[0]  = 0;
  Nvme->Pt[1]  = 0;

  ZeroMem ((VOID *)(UINTN)(&(Nvme->SqTdbl[0])), sizeof (NVME_SQTDBL) * NVME_MAX_IO_QUEUES);
  ZeroMem ((VOID *)(UINTN)(&(Nvme->CqHdbl[0])), sizeof (NVME_CQHDBL) * NVME_MAX_IO_QUEUES);

  ZeroMem (Nvme->BaseMem, NVME_MEM_MAX_SIZE);

  Status = NvmeDisableController (Nvme);
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "NvmeDisableController fail, Status: %r\n", Status));
    goto Done;
  }

  ///
  /// set number of entries admin submission & completion queues.
  ///
  Aqa.Asqs  = NVME_ASQ_SIZE;
  Aqa.Rsvd1 = 0;
  Aqa.Acqs  = NVME_ACQ_SIZE;
  Aqa.Rsvd2 = 0;

  ///
  /// Address of admin submission queue.
  ///
  Asq = (UINT64)(UINTN)(NVME_ASQ_BASE (Nvme) & ~0xFFF);

  ///
  /// Address of admin completion queue.
  ///
  Acq = (UINT64)(UINTN)(NVME_ACQ_BASE (Nvme) & ~0xFFF);

  ///
  /// Address of I/O submission & completion queue.
  ///
  Nvme->SqBuffer[0] = (NVME_SQ *)(UINTN)NVME_ASQ_BASE (Nvme);   // NVME_ADMIN_QUEUE
  Nvme->CqBuffer[0] = (NVME_CQ *)(UINTN)NVME_ACQ_BASE (Nvme);   // NVME_ADMIN_QUEUE
  Nvme->SqBuffer[1] = (NVME_SQ *)(UINTN)NVME_SQ_BASE (Nvme, 0); // NVME_IO_QUEUE
  Nvme->CqBuffer[1] = (NVME_CQ *)(UINTN)NVME_CQ_BASE (Nvme, 0); // NVME_IO_QUEUE

  DEBUG ((DEBUG_INFO, "Admin Submission Queue Size (Aqa.Asqs) = [%08X]\n", Aqa.Asqs));
  DEBUG ((DEBUG_INFO, "Admin Completion Queue Size (Aqa.Acqs) = [%08X]\n", Aqa.Acqs));
  DEBUG ((DEBUG_INFO, "Admin Submission Queue (SqBuffer[0]) =   [%08X]\n", Nvme->SqBuffer[0]));
  DEBUG ((DEBUG_INFO, "Admin Completion Queue (CqBuffer[0]) =   [%08X]\n", Nvme->CqBuffer[0]));
  DEBUG ((DEBUG_INFO, "I/O   Submission Queue (SqBuffer[1]) =   [%08X]\n", Nvme->SqBuffer[1]));
  DEBUG ((DEBUG_INFO, "I/O   Completion Queue (CqBuffer[1]) =   [%08X]\n", Nvme->CqBuffer[1]));

  ///
  /// Program admin queue attributes.
  ///
  Status = NVME_SET_AQA (Nvme, &Aqa);
  if (EFI_ERROR(Status)) {
    goto Done;
  }

  ///
  /// Program admin submission queue address.
  ///
  Status = NVME_SET_ASQ (Nvme, &Asq);
  if (EFI_ERROR(Status)) {
    goto Done;
  }

  ///
  /// Program admin completion queue address.
  ///
  Status = NVME_SET_ACQ (Nvme, &Acq);
  if (EFI_ERROR(Status)) {
    goto Done;
  }

  Status = NvmeEnableController (Nvme);
  if (EFI_ERROR(Status)) {
    goto Done;
  }

  ///
  /// Create one I/O completion queue.
  ///
  Status = NvmeCreateIoCompletionQueue (Nvme);
  if (EFI_ERROR(Status)) {
    goto Done;
  }

  ///
  /// Create one I/O Submission queue.
  ///
  Status = NvmeCreateIoSubmissionQueue (Nvme);
  if (EFI_ERROR(Status)) {
    goto Done;
  }

  ///
  /// Get current Identify Controller Data
  ///
  Nvme->ControllerData = (NVME_ADMIN_CONTROLLER_DATA *)(UINTN) NVME_CONTROL_DATA_BASE (Nvme);
  Status = NvmeIdentifyController (Nvme, Nvme->ControllerData);
  if (EFI_ERROR(Status)) {
    goto Done;
  }

  ///
  /// Dump NvmExpress Identify Controller Data
  ///
  Nvme->ControllerData->Sn[19] = 0;
  Nvme->ControllerData->Mn[39] = 0;
  //NvmeDumpIdentifyController (Nvme->ControllerData);

  ///
  /// Get current Identify Namespace Data
  ///
  Nvme->NamespaceData = (NVME_ADMIN_NAMESPACE_DATA *)NVME_NAMESPACE_DATA_BASE (Nvme);
  Status = NvmeIdentifyNamespace (Nvme, Nvme->Nsid, Nvme->NamespaceData);
  if (EFI_ERROR(Status)) {
    DEBUG ((DEBUG_ERROR, "NvmeIdentifyNamespace fail, Status = %r\n", Status));
    goto Done;
  }

  ///
  /// Dump NvmExpress Identify Namespace Data
  ///
  if (Nvme->NamespaceData->Ncap == 0) {
    DEBUG ((DEBUG_ERROR, "Invalid Namespace, Ncap: %lx\n", Nvme->NamespaceData->Ncap));
    Status = EFI_DEVICE_ERROR;
    goto Done;
  }

  Nvme->BlockSize = NvmeGetBlockSize (Nvme);
  Nvme->LastBlock = NvmeGetLastLba (Nvme);

  Nvme->State    = NvmeStatusInit;

  return EFI_SUCCESS;

Done:
  return Status;
}

/**
  Un-initialize the Nvm Express controller.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @retval EFI_SUCCESS               - The NVM Express Controller is un-initialized successfully.
  @retval Others                    - A device error occurred while un-initializing the controller.

**/
EFI_STATUS
NvmeControllerExit (
  IN NVME_CONTEXT       *Nvme
  )
{
  EFI_STATUS            Status;

  Status = EFI_SUCCESS;
  if (Nvme->State == NvmeStatusInit || Nvme->State == NvmeStatusMax) {
    ///
    /// Destroy I/O Submission queue.
    ///
    Status = NvmeDestroyIoSubmissionQueue (Nvme);
    if (EFI_ERROR(Status)) {
      DEBUG ((DEBUG_ERROR, "NvmeDestroyIoSubmissionQueue fail, Status = %r\n", Status));
      return Status;
    }

    ///
    /// Destroy I/O completion queue.
    ///
    Status = NvmeDestroyIoCompletionQueue (Nvme);
    if (EFI_ERROR(Status)) {
      DEBUG ((DEBUG_ERROR, "NvmeDestroyIoCompletionQueue fail, Status = %r\n", Status));
      return Status;
    }

    Status = NvmeShutdownController (Nvme);
    if (EFI_ERROR(Status)) {
      DEBUG ((DEBUG_ERROR, "NvmeShutdownController fail, Status: %r\n", Status));
    }
  }

  ///
  /// Disable PCIE decode
  ///
  PciWrite8  (Nvme->PciBase + NVME_PCIE_PCICMD, 0x0);
  PciWrite32 (Nvme->PciBase + 0x10, 0); // MLBAR (BAR0)
  PciWrite32 (Nvme->PciBase + 0x14, 0); // MUBAR (BAR1)

  Nvme->State = NvmeStatusUnknown;
  return Status;
}

/**
  Read sector Data from the NVMe device.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in,out] Buffer             - The Buffer used to store the Data read from the device.
  @param[in] Lba                    - The start block number.
  @param[in] Blocks                 - Total block number to be read.

  @retval EFI_SUCCESS               - Datum are read from the device.
  @retval Others                    - Fail to read all the datum.

**/
EFI_STATUS
NvmeReadSectors (
  IN NVME_CONTEXT                          *Nvme,
  IN OUT UINT64                            Buffer,
  IN UINT64                                Lba,
  IN UINT32                                Blocks
  )
{
  UINT32                                   Bytes;
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;
  UINT32                                   BlockSize;

  BlockSize  = Nvme->BlockSize;
  Bytes      = Blocks * BlockSize;

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));

  CommandPacket.NvmeCmd      = &Command;
  CommandPacket.NvmeResponse = &Response;

  CommandPacket.NvmeCmd->Cdw0.Opcode = NVME_IO_READ_OPC;
  CommandPacket.NvmeCmd->Cdw0.Cid    = Nvme->Cid[NVME_IO_QUEUE]++;
  CommandPacket.NvmeCmd->Nsid        = Nvme->Nsid;
  CommandPacket.TransferBuffer       = Buffer;

  CommandPacket.TransferLength = Bytes;
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_IO_QUEUE;

  CommandPacket.NvmeCmd->Cdw10 = (UINT32)Lba;
  CommandPacket.NvmeCmd->Cdw11 = (UINT32)(RShiftU64 (Lba, 32));
  CommandPacket.NvmeCmd->Cdw12 = (Blocks - 1) & 0xFFFF;

  CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID | CDW12_VALID;

  Status = NvmePassThru (
              Nvme,
              Nvme->Nsid,
              0,
              &CommandPacket
              );

  return Status;
}

/**
  Write sector Data to the NVMe device.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] Buffer                 - The Buffer to be written into the device.
  @param[in] Lba                    - The start block number.
  @param[in] Blocks                 - Total block number to be written.

  @retval EFI_SUCCESS               - Datum are written into the Buffer.
  @retval Others                    - Fail to write all the datum.

**/
EFI_STATUS
NvmeWriteSectors (
  IN NVME_CONTEXT                          *Nvme,
  IN UINT64                                Buffer,
  IN UINT64                                Lba,
  IN UINT32                                Blocks
  )
{
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;
  UINT32                                   Bytes;
  UINT32                                   BlockSize;

  BlockSize  = Nvme->BlockSize;
  Bytes      = Blocks * BlockSize;

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));

  CommandPacket.NvmeCmd      = &Command;
  CommandPacket.NvmeResponse = &Response;

  CommandPacket.NvmeCmd->Cdw0.Opcode = NVME_IO_WRITE_OPC;
  CommandPacket.NvmeCmd->Cdw0.Cid    = Nvme->Cid[NVME_IO_QUEUE]++;
  CommandPacket.NvmeCmd->Nsid  = Nvme->Nsid;
  CommandPacket.TransferBuffer = Buffer;

  CommandPacket.TransferLength = Bytes;
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_IO_QUEUE;

  CommandPacket.NvmeCmd->Cdw10 = (UINT32)Lba;
  CommandPacket.NvmeCmd->Cdw11 = (UINT32)(RShiftU64 (Lba, 32));
  CommandPacket.NvmeCmd->Cdw12 = (Blocks - 1) & 0xFFFF;

  CommandPacket.MetadataBuffer = (UINT64)(UINTN)NULL;
  CommandPacket.MetadataLength = 0;

  CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID | CDW12_VALID;

  Status = NvmePassThru (
              Nvme,
              Nvme->Nsid,
              0,
              &CommandPacket
              );

  return Status;
}

/**
  Flushes all modified Data to the device.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.

  @retval EFI_SUCCESS               - Datum are written into the Buffer.
  @retval Others                    - Fail to write all the datum.

**/
EFI_STATUS
NvmeFlush (
  IN NVME_CONTEXT                          *Nvme
  )
{
  NVM_EXPRESS_PASS_THRU_COMMAND_PACKET     CommandPacket;
  NVM_EXPRESS_COMMAND                      Command;
  NVM_EXPRESS_RESPONSE                     Response;
  EFI_STATUS                               Status;

  ZeroMem (&CommandPacket, sizeof(NVM_EXPRESS_PASS_THRU_COMMAND_PACKET));
  ZeroMem (&Command, sizeof(NVM_EXPRESS_COMMAND));
  ZeroMem (&Response, sizeof(NVM_EXPRESS_RESPONSE));

  CommandPacket.NvmeCmd      = &Command;
  CommandPacket.NvmeResponse = &Response;

  CommandPacket.NvmeCmd->Cdw0.Opcode = NVME_IO_FLUSH_OPC;
  CommandPacket.NvmeCmd->Cdw0.Cid    = Nvme->Cid[NVME_IO_QUEUE]++;
  CommandPacket.NvmeCmd->Nsid  = Nvme->Nsid;
  CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT;
  CommandPacket.QueueId        = NVME_IO_QUEUE;

  Status = NvmePassThru (
              Nvme,
              Nvme->Nsid,
              0,
              &CommandPacket
              );
  if (!EFI_ERROR (Status)) {
    Status = NvmeWaitAllComplete (Nvme, CommandPacket.QueueId);
  }

  return Status;
}

/**
  Read some blocks from the device.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[out] Buffer                - The Buffer used to store the Data read from the device.
  @param[in] Lba                    - The start block number.
  @param[in] Blocks                 - Total block number to be read.

  @retval EFI_SUCCESS               - Datum are read from the device.
  @retval Others                    - Fail to read all the datum.

**/
EFI_STATUS
NvmeRead (
  IN NVME_CONTEXT                  *Nvme,
  OUT UINT64                       Buffer,
  IN UINT64                        Lba,
  IN UINTN                         Blocks
  )
{
  EFI_STATUS                       Status;
  UINT32                           BlockSize;
  UINT32                           MaxTransferBlocks;

  ASSERT (Blocks <= NVME_MAX_SECTORS);
  Status        = EFI_SUCCESS;
  BlockSize     = Nvme->BlockSize;
  if (Nvme->ControllerData->Mdts != 0) {
    MaxTransferBlocks = (1 << (Nvme->ControllerData->Mdts)) * (1 << (Nvme->Cap.Mpsmin + 12)) / BlockSize;
  } else {
    MaxTransferBlocks = 1024;
  }

  while (Blocks > 0) {
    if (Blocks > MaxTransferBlocks) {
      Status = NvmeReadSectors (Nvme, Buffer, Lba, MaxTransferBlocks);

      Blocks -= MaxTransferBlocks;
      Buffer += (MaxTransferBlocks * BlockSize);
      Lba    += MaxTransferBlocks;
    } else {
      Status = NvmeReadSectors (Nvme, Buffer, Lba, (UINT32) Blocks);
      Blocks = 0;
    }

    if (EFI_ERROR(Status)) {
      DEBUG ((DEBUG_ERROR, "NvmeRead fail, Status = %r\n", Status));
      break;
    }
  }

  return Status;
}

/**
  Write some blocks to the device.

  @param[in] Nvme                   - The pointer to the NVME_CONTEXT Data structure.
  @param[in] Buffer                 - The Buffer to be written into the device.
  @param[in] Lba                    - The start block number.
  @param[in] Blocks                 - Total block number to be written.

  @retval EFI_SUCCESS               - Datum are written into the Buffer.
  @retval Others                    - Fail to write all the datum.

**/
EFI_STATUS
NvmeWrite (
  IN NVME_CONTEXT                  *Nvme,
  IN UINT64                        Buffer,
  IN UINT64                        Lba,
  IN UINTN                         Blocks
  )
{
  EFI_STATUS                       Status;
  UINT32                           BlockSize;
  UINT32                           MaxTransferBlocks;

  ASSERT (Blocks <= NVME_MAX_SECTORS);
  Status        = EFI_SUCCESS;
  BlockSize     = Nvme->BlockSize;

  if (Nvme->ControllerData->Mdts != 0) {
    MaxTransferBlocks = (1 << (Nvme->ControllerData->Mdts)) * (1 << (Nvme->Cap.Mpsmin + 12)) / BlockSize;
  } else {
    MaxTransferBlocks = 1024;
  }

  while (Blocks > 0) {
    if (Blocks > MaxTransferBlocks) {
      Status = NvmeWriteSectors (Nvme, Buffer, Lba, MaxTransferBlocks);

      Blocks -= MaxTransferBlocks;
      Buffer += (MaxTransferBlocks * BlockSize);
      Lba    += MaxTransferBlocks;
    } else {
      Status = NvmeWriteSectors (Nvme, Buffer, Lba, (UINT32) Blocks);
      Blocks = 0;
    }

    if (EFI_ERROR(Status)) {
      DEBUG ((DEBUG_ERROR, "NvmeWrite fail, Status = %r\n", Status));
      break;
    }
  }

  return Status;
}