summaryrefslogtreecommitdiff
path: root/arch/arm/mach-tegra/nvddk/nvddk_aes.c
blob: 9e7008c0e464c8b1329d553aac25f94cc66a4aee (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
/*
 * Copyright (c) 2007-2009 NVIDIA Corporation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the NVIDIA Corporation nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "nvos.h"
#include "nvassert.h"
#include "nvrm_power.h"
#include "nvrm_hardware_access.h"
#include "nvrm_module.h"
#include "nvrm_xpc.h"
#if NV_OAL
#include "nvbl_virtual.h"
#endif
#include "nvddk_aes.h"
#include "nvddk_aes_priv.h"

#include <linux/interrupt.h>
#include <linux/proc_fs.h>

// RFC3394 key wrap block size is 64 bites which is equal to 8 bytes
#define AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES 8

// Number of RFC3394 key wrap blocks for 128 bit key
#define AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY 2

static void AesCoreRequestHwAccess(void);
static void AesCoreReleaseHwAccess(void);
static void AesCoreDeAllocateRmMemory(AesHwContext *const pAesHwCtxt);
static void AesCoreFreeUpEngine(AesCoreEngine *const pAesCoreEngine);
static void AesCorePowerUp(const AesCoreEngine *const pAesCoreEngine, const NvBool SetDfsBusyHints);
static void AesCorePowerDown(const AesCoreEngine *const pAesCoreEngine, const NvBool SetDfsBusyHints);
static void AesCoreDeInitializeEngineSpace(const AesHwContext *const pAesHwCtxt);

static NvError AesCoreAllocateRmMemory(AesHwContext *const pAesHwCtxt);
static NvError AesCoreLoadSskToSecureScratchAndLock(const AesHwContext *const pAesHwCtxt, const NvU8 *const pKey);
static NvError AesCoreDfsBusyHint(const NvRmDeviceHandle hRmDevice, const NvU32 PowerClientId, const NvBool IsDfsOn);
static NvError AesCoreInitializeEngineSpace(const NvRmDeviceHandle hRmDevice, AesHwContext *const pAesHwCtxt);
static NvError AesCoreInitEngine(const NvRmDeviceHandle hRmDevice);
static NvError AesCoreGetCapabilities(const NvRmDeviceHandle hRmDevice, AesHwCapabilities **const ppCaps);
static NvError AesCoreClearUserKey(const NvDdkAes *const pAesClient);
static NvError
AesCoreWrapKey(
    const AesCoreEngine *const pAesCoreEngine,
    const NvU8 *const pOrgKey,
    const NvU8 *const pOrgIv,
    NvU8 *const pWrappedKey,
    NvU8 *const pWrappedIv);
static NvError
AesCoreUnWrapKey(
    const AesCoreEngine *const pAesCoreEngine,
    const NvU8 *const pWrappedKey,
    const NvU8 *const pWrappedIv,
    NvU8 *const pOrgKey,
    NvU8 *const pOrgIv);
static NvError
AesCoreGetFreeSlot(
    const AesCoreEngine *const pAesCoreEngine,
    AesHwEngine *const pEngine,
    AesHwKeySlot *const pKeySlot);
static NvError
AesCoreSetKey(
    const NvDdkAesKeyType KeyType,
    const NvBool IsDedicatedSlot,
    const NvU8 *const pKeyData,
    NvDdkAes *const pAesClient);
static NvError
AesCoreProcessBuffer(
    const NvU32 SkipOffset,
    const NvU32 SrcBufferSize,
    const NvU32 DestBufferSize,
    NvDdkAes *const pAesClient,
    const NvU8 *pSrcBuffer,
    NvU8 *pDestBuffer);
static NvError
AesCoreEcbProcessBuffer(
    const AesCoreEngine *const pAesCoreEngine,
    const NvU8 *const pInputBuffer,
    const NvU32 BufSize,
    const NvBool IsEncrypt,
    NvU8 *const pOutputBuffer);

static NvBool
AesCoreIsUserKeyCleared(
    const AesHwEngine Engine,
    const AesHwKeySlot KeySlot,
    AesHwContext *const pAesHwCtxt);
static NvBool
AesCoreIsSbkCleared(
    const AesHwEngine Engine,
    const AesHwKeySlot EncryptSlot,
    const AesHwKeySlot DecryptSlot,
    AesHwContext *const pAesHwCtxt);
static NvBool
AesCoreIsSskLocked(
    const AesHwEngine Engine,
    const AesHwKeySlot EncryptSlot,
    const AesHwKeySlot DecryptSlot,
    AesHwContext *const pAesHwCtxt);

static AesCoreEngine *gs_pAesCoreEngine = NULL;
static NvOsMutexHandle gs_hAesCoreEngineMutex = {0};

// Original IV of size 8 byte which is used in RFC 3394 key wrap algorithm
static NvU8 gs_OriginalIV[AES_RFC_IV_LENGTH_BYTES] =
{
    0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6
};

extern NvRmDeviceHandle s_hRmGlobal;

#define NVDDK_AES_CHECK_INPUT_PARAMS(parm) \
    do \
    { \
        if ((!pAesClient) || (!parm)) \
            return NvError_BadParameter; \
    } while (0)

#define NVDDK_AES_CHECK_ROOT_PERMISSION \
    do \
    { \
        if ((0 != pAesClient->uid) || (0 != pAesClient->gid)) \
            return NvError_AesPermissionDenied; \
    } while (0)

#define NVDDK_AES_CHECK_USER_IDENTITY \
    do \
    { \
        if ((pAesClient->uid != current->cred->uid) || (pAesClient->gid != current->cred->gid)) \
            return NvError_AesPermissionDenied; \
    } while (0)

#define NVDDK_AES_CHECK_INTERFACE(ctxt, engine) \
    do \
    { \
        NV_ASSERT(ctxt); \
        NV_ASSERT(ctxt->ppEngineCaps); \
        NV_ASSERT(ctxt->ppEngineCaps[engine]); \
        NV_ASSERT(ctxt->ppEngineCaps[engine]->pAesInterf); \
    } while (0)

#define NVDDK_AES_CHECK_INTERFACE_FUNC(ctxt, engine, func) \
    do \
    { \
        NV_ASSERT(ctxt->ppEngineCaps[engine]->pAesInterf->func); \
    } while (0)

#ifdef CONFIG_PM
void NvDdkAesSuspend(void)
{
    if (gs_hAesCoreEngineMutex)
    {
        NvOsMutexLock(gs_hAesCoreEngineMutex);
        if (gs_pAesCoreEngine)
            AesCorePowerDown(gs_pAesCoreEngine, NV_FALSE);
        NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    }
}

void NvDdkAesResume(void)
{
    NvU8 UnWrappedRFCIv[AES_RFC_IV_LENGTH_BYTES];
    NvU8 Iv[NvDdkAesConst_IVLengthBytes];
    AesHwEngine Engine;
    AesHwKeySlot KeySlot;
    AesHwContext *pAesHwCtxt;
    NvError e;

    if ((!gs_hAesCoreEngineMutex) ||(!gs_pAesCoreEngine))
        return;

    NvOsMutexLock(gs_hAesCoreEngineMutex);
    AesCorePowerUp(gs_pAesCoreEngine, NV_FALSE);

    // Get the AES H/W context
    pAesHwCtxt = &gs_pAesCoreEngine->AesHwCtxt;
    NvOsMemset(Iv, 0, sizeof(Iv));

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, Engine);
        NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwDisableAllKeyRead);
        pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwDisableAllKeyRead(
            pAesHwCtxt,
            Engine,
            pAesHwCtxt->ppEngineCaps[Engine]->NumSlotsSupported);
    }

    // Get the dedicated slot
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        for (KeySlot = AesHwKeySlot_0;
            KeySlot < (pAesHwCtxt->ppEngineCaps[Engine]->NumSlotsSupported);
            KeySlot++)
        {
            if ((gs_pAesCoreEngine->IsKeySlotUsed[Engine][KeySlot]) &&
                (gs_pAesCoreEngine->SbkEncryptSlot != KeySlot) &&
                (gs_pAesCoreEngine->SbkDecryptSlot != KeySlot) &&
                (gs_pAesCoreEngine->SskEncryptSlot != KeySlot) &&
                (gs_pAesCoreEngine->SskDecryptSlot != KeySlot))
            {
                AesCoreRequestHwAccess();

                // This is dedicated slot. Load key in slot
                e = (AesCoreUnWrapKey(
                    gs_pAesCoreEngine,
                    gs_pAesCoreEngine->DedicatedSlotKeyInfo[Engine][KeySlot].WrappedKey,
                    gs_pAesCoreEngine->DedicatedSlotKeyInfo[Engine][KeySlot].WrappedIv,
                    pAesHwCtxt->pKeyTableVirAddr[Engine] + pAesHwCtxt->KeyTableSize[Engine],
                    UnWrappedRFCIv));
                if (e != NvSuccess)
                    goto fail;

                // Check whether the key unwrap is success or not by comparing
                // the unwrapped RFC IV with original RFC IV
                if (NvOsMemcmp(UnWrappedRFCIv, gs_OriginalIV, sizeof(gs_OriginalIV)))
                {
                    // Unwrap key failed
                    NV_ASSERT(!"fail to unwrap key");
                    goto fail;
                }

                // Setup Key table
                NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetKeyAndIv);
                pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetKeyAndIv(
                    Engine,
                    KeySlot,
                    (AesHwKey *)(pAesHwCtxt->pKeyTableVirAddr[Engine] + pAesHwCtxt->KeyTableSize[Engine]),
                    (AesHwIv *)Iv,
                    gs_pAesCoreEngine->DedicatedSlotKeyInfo[Engine][KeySlot].IsEncryption,
                    pAesHwCtxt);

                // Memset the local variable to zeros where the key is stored
                NvOsMemset(
                    (pAesHwCtxt->pKeyTableVirAddr[Engine] + pAesHwCtxt->KeyTableSize[Engine]),
                    0,
                    NvDdkAesKeySize_128Bit);
                AesCoreReleaseHwAccess();
            }
        }
    }
    AesCorePowerDown(gs_pAesCoreEngine, NV_FALSE);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return;
fail:
    AesCorePowerDown(gs_pAesCoreEngine, NV_FALSE);
    AesCoreReleaseHwAccess();
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
}
#endif

NvError NvDdkAesOpen(NvU32 InstanceId, NvDdkAesHandle *phAes)
{
    NvError e = NvSuccess;
    NvDdkAes *pAes = NULL;
    NvOsMutexHandle hMutex = NULL;

    if (!phAes)
       return NvError_BadParameter;

    // Create mutex (if not already done)
    if (NULL == gs_hAesCoreEngineMutex)
    {
        e = NvOsMutexCreate(&hMutex);
        if (NvSuccess != e)
            return e;
        if (0 != NvOsAtomicCompareExchange32((NvS32*)&gs_hAesCoreEngineMutex, 0, (NvS32)hMutex))
            NvOsMutexDestroy(hMutex);
    }

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    // Create client record
    pAes = NvOsAlloc(sizeof(NvDdkAes));
    if (!pAes)
    {
        e = NvError_InsufficientMemory;
        goto fail;
    }
    NvOsMemset(pAes, 0, sizeof(NvDdkAes));

    if (NULL == gs_pAesCoreEngine)
    {
        // Init engine
        NV_CHECK_ERROR_CLEANUP(AesCoreInitEngine(s_hRmGlobal));
    }

    // Add client
    gs_pAesCoreEngine->OpenCount++;

    pAes->pAesCoreEngine = gs_pAesCoreEngine;

    // Store uid & gid
    pAes->uid = current->cred->uid;
    pAes->gid = current->cred->gid;

    *phAes = pAes;
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NvSuccess;

fail:
    NvDdkAesClose(pAes);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

void NvDdkAesClose(NvDdkAesHandle hAes)
{
    NvDdkAes *pAesClient = (NvDdkAes *)hAes;

    if (!hAes)
        return;

    if ((pAesClient->uid != current->cred->uid) || (pAesClient->gid != current->cred->gid))
        return;

    if (pAesClient->pAesCoreEngine)
    {
        NvOsMutexLock(gs_hAesCoreEngineMutex);

        // Check if client is using USER key with dedicated slot then free the associated client slot
        if ((NV_TRUE == pAesClient->IsDedicatedSlot) &&
            (NvDdkAesKeyType_UserSpecified == pAesClient->KeyType))
        {
            AesCorePowerUp(gs_pAesCoreEngine, NV_TRUE);
            // Client is using USER key with dedicated slot. So
            // clear the key in hardware slot and free the associated client slot
            if (!AesCoreClearUserKey(pAesClient))
            {
                NV_ASSERT(!"Failed to clear User Key");
            }
            AesCorePowerDown(gs_pAesCoreEngine, NV_TRUE);
            pAesClient->pAesCoreEngine->IsKeySlotUsed[pAesClient->Engine][pAesClient->KeySlot] = NV_FALSE;
        }

        // Free up engine if no other clients
        if (pAesClient->pAesCoreEngine->OpenCount)
        {
            // Decrement the Open count
            pAesClient->pAesCoreEngine->OpenCount--;

            if (0 == pAesClient->pAesCoreEngine->OpenCount)
            {
                // Free up resources
                AesCoreFreeUpEngine(pAesClient->pAesCoreEngine);

                NvOsFree(gs_pAesCoreEngine);
                gs_pAesCoreEngine = NULL;
            }
        }
        NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    }

    NvOsMemset(pAesClient, 0, sizeof(NvDdkAes));
    NvOsFree(pAesClient);
}

NvError NvDdkAesSelectKey(NvDdkAesHandle hAes, const NvDdkAesKeyInfo *pKeyInfo)
{
    NvDdkAes *pAesClient = (NvDdkAes*)hAes;

    NVDDK_AES_CHECK_INPUT_PARAMS(pKeyInfo);

    NVDDK_AES_CHECK_USER_IDENTITY;

    switch (pKeyInfo->KeyLength)
    {
        case NvDdkAesKeySize_128Bit:
            return AesCoreSetKey(
                pKeyInfo->KeyType,
                pKeyInfo->IsDedicatedKeySlot,
                pKeyInfo->Key,
                pAesClient);
            break;
        case NvDdkAesKeySize_192Bit:
        case NvDdkAesKeySize_256Bit:
        default:
            return NvError_NotSupported;
    }
}

NvError NvDdkAesSelectOperation(NvDdkAesHandle hAes, const NvDdkAesOperation *pOperation)
{
    NvDdkAes *pAesClient = (NvDdkAes*)hAes;

    NVDDK_AES_CHECK_INPUT_PARAMS(pOperation);

    NVDDK_AES_CHECK_USER_IDENTITY;

    switch (pOperation->OpMode)
    {
        case NvDdkAesOperationalMode_Cbc:
        case NvDdkAesOperationalMode_Ecb:
            pAesClient->IsEncryption = pOperation->IsEncrypt;
            break;
        case NvDdkAesOperationalMode_AnsiX931:
            pAesClient->IsEncryption = NV_TRUE;
            break;
        default:
            return NvError_NotSupported;
    }

    pAesClient->OpMode = pOperation->OpMode;
    return NvSuccess;
}

NvError NvDdkAesSetInitialVector(NvDdkAesHandle hAes, const NvU8 *pInitialVector, NvU32 VectorSize)
{
    NvDdkAes *pAesClient = (NvDdkAes*)hAes;

    NVDDK_AES_CHECK_INPUT_PARAMS(pInitialVector);

    NVDDK_AES_CHECK_USER_IDENTITY;

    if (NvDdkAesOperationalMode_Ecb == pAesClient->OpMode)
        return NvError_NotSupported;

    if (VectorSize < NvDdkAesConst_IVLengthBytes)
        return NvError_BadParameter;

    // Set the IV and store it with client
    NvOsMemcpy(pAesClient->Iv, pInitialVector, NvDdkAesConst_IVLengthBytes);

    return NvSuccess;
}

NvError NvDdkAesGetInitialVector(NvDdkAesHandle hAes, NvU32 VectorSize, NvU8 *pInitialVector)
{
    NvDdkAes *pAesClient = (NvDdkAes*)hAes;

    NVDDK_AES_CHECK_INPUT_PARAMS(pInitialVector);

    NVDDK_AES_CHECK_USER_IDENTITY;

    if (VectorSize < NvDdkAesConst_IVLengthBytes)
        return NvError_BadParameter;

    NvOsMemcpy(pInitialVector, pAesClient->Iv, NvDdkAesConst_IVLengthBytes);

    return NvSuccess;
}

NvError
NvDdkAesProcessBuffer(
    NvDdkAesHandle hAes,
    NvU32 SrcBufferSize,
    NvU32 DestBufferSize,
    const NvU8 *pSrcBuffer,
    NvU8 *pDestBuffer)
{
    if ((!hAes) || (!pSrcBuffer) || (!pDestBuffer))
        return NvError_BadParameter;

    return AesCoreProcessBuffer(0, SrcBufferSize, DestBufferSize, (NvDdkAes*)hAes, pSrcBuffer, pDestBuffer);
}

NvError NvDdkAesClearSecureBootKey(NvDdkAesHandle hAes)
{
    NvError e = NvSuccess;
    NvDdkAes *pAesClient = (NvDdkAes*)hAes;
    AesHwContext *pAesHwCtxt = NULL;
    AesHwEngine Engine;

    if (!hAes)
        return NvError_BadParameter;

    NVDDK_AES_CHECK_USER_IDENTITY;

    NVDDK_AES_CHECK_ROOT_PERMISSION;

    NvOsMutexLock(gs_hAesCoreEngineMutex);
    AesCorePowerUp(gs_pAesCoreEngine, NV_TRUE);

    // Get the AES H/W context
    NV_ASSERT(pAesClient->pAesCoreEngine);
    pAesHwCtxt = &pAesClient->pAesCoreEngine->AesHwCtxt;

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        AesHwEngine SbkEngine = pAesClient->pAesCoreEngine->SbkEngine[Engine];
        AesHwKeySlot DecryptSlot = pAesClient->pAesCoreEngine->SbkDecryptSlot;
        AesHwKeySlot EncryptSlot = pAesClient->pAesCoreEngine->SbkEncryptSlot;

        if (SbkEngine < AesHwEngine_Num)
        {
            NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, SbkEngine);

            AesCoreRequestHwAccess();

            // Clear the SBK encrypt key
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, SbkEngine, AesHwClearKeyAndIv);
            pAesHwCtxt->ppEngineCaps[SbkEngine]->pAesInterf->AesHwClearKeyAndIv(SbkEngine, EncryptSlot, pAesHwCtxt);

            // Clear the SBK decrypt key
            pAesHwCtxt->ppEngineCaps[SbkEngine]->pAesInterf->AesHwClearKeyAndIv(SbkEngine, DecryptSlot, pAesHwCtxt);

            AesCoreReleaseHwAccess();

            if (!AesCoreIsSbkCleared(SbkEngine, EncryptSlot, DecryptSlot, pAesHwCtxt))
            {
                // Return error if SB clear check fails
                e = NvError_AesClearSbkFailed;
            }
        }
    }
    AesCorePowerDown(gs_pAesCoreEngine, NV_TRUE);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

NvError NvDdkAesLockSecureStorageKey(NvDdkAesHandle hAes)
{
    NvError e = NvSuccess;
    NvDdkAes *pAesClient = (NvDdkAes*)hAes;
    AesHwContext *pAesHwCtxt = NULL;
    AesHwEngine Engine;

    if (!hAes)
        return NvError_BadParameter;

    NVDDK_AES_CHECK_USER_IDENTITY;

    NVDDK_AES_CHECK_ROOT_PERMISSION;

    NvOsMutexLock(gs_hAesCoreEngineMutex);
    AesCorePowerUp(gs_pAesCoreEngine, NV_TRUE);

    // Get the AES H/W context
    NV_ASSERT(pAesClient->pAesCoreEngine);
    pAesHwCtxt = &pAesClient->pAesCoreEngine->AesHwCtxt;

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        AesHwEngine SskEngine = pAesClient->pAesCoreEngine->SskEngine[Engine];
        AesHwKeySlot DecryptSlot = pAesClient->pAesCoreEngine->SskDecryptSlot;
        AesHwKeySlot EncryptSlot = pAesClient->pAesCoreEngine->SskEncryptSlot;

        if (SskEngine < AesHwEngine_Num)
        {
            NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, SskEngine);

            AesCoreRequestHwAccess();

            // Disable permissions to the SSK key slot in the AES engine
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, SskEngine, AesHwLockSskReadWrites);
            pAesHwCtxt->ppEngineCaps[SskEngine]->pAesInterf->AesHwLockSskReadWrites(pAesHwCtxt, SskEngine);

            AesCoreReleaseHwAccess();

            if (!AesCoreIsSskLocked(SskEngine, EncryptSlot, DecryptSlot, pAesHwCtxt))
            {
                e = NvError_AesLockSskFailed;
                goto fail;
            }

            // Also, lock the Secure scratch registers
            NV_CHECK_ERROR_CLEANUP(AesCoreLoadSskToSecureScratchAndLock(pAesHwCtxt, NULL));
        }
    }

fail:
    AesCorePowerDown(gs_pAesCoreEngine, NV_TRUE);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

NvError
NvDdkAesSetAndLockSecureStorageKey(
    NvDdkAesHandle hAes,
    NvDdkAesKeySize KeyLength,
    const NvU8 *pSecureStorageKey)
{
    NvError e = NvSuccess;
    NvDdkAes *pAesClient = (NvDdkAes*)hAes;
    AesHwContext *pAesHwCtxt = NULL;
    AesHwIv Iv;
    AesHwEngine Engine;

    NVDDK_AES_CHECK_INPUT_PARAMS(pSecureStorageKey);

    NVDDK_AES_CHECK_USER_IDENTITY;

    NVDDK_AES_CHECK_ROOT_PERMISSION;

    switch (KeyLength)
    {
        case NvDdkAesKeySize_128Bit:
            break;
        case NvDdkAesKeySize_192Bit:
        case NvDdkAesKeySize_256Bit:
        default:
            return NvError_NotSupported;
    }

    NvOsMutexLock(gs_hAesCoreEngineMutex);
    AesCorePowerUp(gs_pAesCoreEngine, NV_TRUE);

    // Get the AES H/W context
    NV_ASSERT(pAesClient->pAesCoreEngine);
    pAesHwCtxt = &pAesClient->pAesCoreEngine->AesHwCtxt;

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        AesHwEngine SskEngine = pAesClient->pAesCoreEngine->SskEngine[Engine];
        AesHwKeySlot DecryptSlot = pAesClient->pAesCoreEngine->SskDecryptSlot;
        AesHwKeySlot EncryptSlot = pAesClient->pAesCoreEngine->SskEncryptSlot;

        if (SskEngine < AesHwEngine_Num)
        {
            // Setup the SSK with Zero IV
            NvOsMemset(&Iv, 0, NvDdkAesConst_IVLengthBytes);

            NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, SskEngine);

            AesCoreRequestHwAccess();

            // Setup SSK Key table for encryption
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, SskEngine, AesHwSetKeyAndIv);
            pAesHwCtxt->ppEngineCaps[SskEngine]->pAesInterf->AesHwSetKeyAndIv(
                SskEngine,
                EncryptSlot,
                (AesHwKey*)pSecureStorageKey,
                &Iv,
                NV_TRUE,
                pAesHwCtxt);

            // Setup SSK Key table for decryption
            pAesHwCtxt->ppEngineCaps[SskEngine]->pAesInterf->AesHwSetKeyAndIv(
                SskEngine,
                DecryptSlot,
                (AesHwKey*)pSecureStorageKey,
                &Iv,
                NV_FALSE,
                pAesHwCtxt);

            // Disable the read / write access
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, SskEngine, AesHwLockSskReadWrites);
            pAesHwCtxt->ppEngineCaps[SskEngine]->pAesInterf->AesHwLockSskReadWrites(pAesHwCtxt, SskEngine);

            AesCoreReleaseHwAccess();

            if (!AesCoreIsSskLocked(SskEngine, EncryptSlot, DecryptSlot, pAesHwCtxt))
            {
                e = NvError_AesLockSskFailed;
                goto fail;
            }

            // Store the SSK in the Secure scratch and lock
            NV_CHECK_ERROR_CLEANUP(AesCoreLoadSskToSecureScratchAndLock(pAesHwCtxt, pSecureStorageKey));
        }
    }

fail:
    AesCorePowerDown(gs_pAesCoreEngine, NV_TRUE);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

NvError NvDdkAesDisableCrypto(NvDdkAesHandle hAes)
{
    NvError e = NvSuccess;
    NvDdkAes *pAesClient = (NvDdkAes*)hAes;
    AesHwContext *pAesHwCtxt = NULL;
    AesHwEngine Engine;

    if (!hAes)
        return NvError_BadParameter;

    NVDDK_AES_CHECK_USER_IDENTITY;

    NVDDK_AES_CHECK_ROOT_PERMISSION;

    NvOsMutexLock(gs_hAesCoreEngineMutex);
    AesCorePowerUp(gs_pAesCoreEngine, NV_TRUE);

    // Get the AES H/W context
    NV_ASSERT(pAesClient->pAesCoreEngine);
    pAesHwCtxt = &pAesClient->pAesCoreEngine->AesHwCtxt;

    AesCoreRequestHwAccess();

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, Engine);
        NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwDisableEngine);

        if (NvSuccess != pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwDisableEngine(pAesHwCtxt, Engine))
            e = NvError_AesDisableCryptoFailed;
    }

    AesCoreReleaseHwAccess();

    if (NvSuccess == e)
    {
        // Mark engine as disabled
        pAesClient->pAesCoreEngine->IsEngineDisabled = NV_TRUE;
    }

    AesCorePowerDown(gs_pAesCoreEngine, NV_TRUE);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

NvError NvDdkAesGetCapabilities(NvDdkAesHandle hAes, NvDdkAesCapabilities *pCapabilities)
{
    NvDdkAes *pAesClient = (NvDdkAes*)hAes;

    NVDDK_AES_CHECK_INPUT_PARAMS(pCapabilities);

    NVDDK_AES_CHECK_USER_IDENTITY;

    pCapabilities->OptimalBufferAlignment = 1;

    return NvSuccess;
}

/**
 * Request access to HW.
 */
void AesCoreRequestHwAccess(void)
{
#if !NV_OAL
    NvRmXpcModuleAcquire(NvRmModuleID_Vde);
    NvRmXpcModuleAcquire(NvRmModuleID_BseA);
#endif
}

/**
 * Release access to HW.
 */
void AesCoreReleaseHwAccess(void)
{
#if !NV_OAL
    NvRmXpcModuleRelease(NvRmModuleID_BseA);
    NvRmXpcModuleRelease(NvRmModuleID_Vde);
#endif
}

#if NV_OAL

/**
 * Allocate the RM memory for key table and dma buffers.
 *
 * @param pAesHwCtxt Pointer to the AES H/W engine context.
 *
 * @retval NvError_Success if memory is allocated successfully.
 * @retval NvError_InsufficientMemory if memory is not allocated successfully.
 */
NvError AesCoreAllocateRmMemory(AesHwContext *const pAesHwCtxt)
{
    NvError e;
    NvU8 *pKeyTabVirtAddr = NULL;
    NvRmPhysAddr KeyTabPhyAddr = NVBL_AES_KEY_TABLE_ADDR;
    NvU8 *pDmaVirtAddr = NULL;
    NvRmPhysAddr DmaPhyAddr = 0;
    AesHwEngine Engine;
    NvU32 size = 0;

    NV_ASSERT(pAesHwCtxt);

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    // Calculate total size needed
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
        size += (pAesHwCtxt->KeyTableSize[Engine] + NvDdkAesKeySize_128Bit);

    // Get virtual address
    NV_ASSERT_SUCCESS(NvOsPhysicalMemMap(
        KeyTabPhyAddr,
        size,
        NvOsMemAttribute_Uncached,
        NVOS_MEM_READ_WRITE,
        (void*)&pKeyTabVirtAddr));

    size = 0;
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        pAesHwCtxt->KeyTablePhyAddr[Engine] = KeyTabPhyAddr + size;
        pAesHwCtxt->pKeyTableVirAddr[Engine] = pKeyTabVirtAddr + size;
        size = pAesHwCtxt->KeyTableSize[Engine] + NvDdkAesKeySize_128Bit;
    }

    // Allocate DMA buffer for both the engines
    size = AES_HW_DMA_BUFFER_SIZE_BYTES * AesHwEngine_Num;
    NV_CHECK_ERROR_CLEANUP(NvRmMemHandleCreate(pAesHwCtxt->hRmDevice, &pAesHwCtxt->hDmaMemBuf, size));

    NV_CHECK_ERROR_CLEANUP(NvRmMemAlloc(
        pAesHwCtxt->hDmaMemBuf,
        NULL,
        0,
        AES_HW_DMA_ADDR_ALIGNMENT,
        NvOsMemAttribute_Uncached));

    // Get the virtual address
    pDmaVirtAddr = (NvU8 *)NvRmMemPin((NvRmMemHandle)pAesHwCtxt->hDmaMemBuf);

    // Get the physical address
    DmaPhyAddr = NvBlVaToPa(pDmaVirtAddr);
    if (NVBL_INVALID_PA == DmaPhyAddr)
    {
        NV_ASSERT(0);
        e = NvError_InvalidAddress;
        goto fail;
    }

    // Get a uncached alias to the buffer
    if (NvOsPhysicalMemMap(DmaPhyAddr, size, NvOsMemAttribute_Uncached, NVOS_MEM_READ_WRITE, (void **)&pDmaVirtAddr) !=
        NvError_Success)
    {
        NV_ASSERT(0);
        e = NvError_InvalidAddress;
        goto fail;
    }

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        pAesHwCtxt->DmaPhyAddr[Engine] = DmaPhyAddr + (Engine * AES_HW_DMA_BUFFER_SIZE_BYTES);
        pAesHwCtxt->pDmaVirAddr[Engine] = pDmaVirtAddr + (Engine * AES_HW_DMA_BUFFER_SIZE_BYTES);
    }

    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NvError_Success;

fail:
    AesCoreDeAllocateRmMemory(pAesHwCtxt);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

/**
 * De-allocate the RM memory allocated with .AesAllocateRmMemory().
 *
 * @param pAesHwCtxt Pointer to the AES Hw engine context.
 *
 * @retval None.
 */
void AesCoreDeAllocateRmMemory(AesHwContext *const pAesHwCtxt)
{
    NV_ASSERT(pAesHwCtxt);

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    if (pAesHwCtxt->hKeyTableMemBuf)
    {
        NvRmMemUnpin(pAesHwCtxt->hKeyTableMemBuf);
        NvRmMemHandleFree(pAesHwCtxt->hKeyTableMemBuf);
        pAesHwCtxt->hKeyTableMemBuf = NULL;
    }

    if (pAesHwCtxt->hDmaMemBuf)
    {
        NvRmMemUnpin(pAesHwCtxt->hDmaMemBuf);
        NvRmMemHandleFree(pAesHwCtxt->hDmaMemBuf);
        pAesHwCtxt->hDmaMemBuf = NULL;
    }

    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
}

#else

/**
 * Allocate the RM memory for key table and dma buffers.
 *
 * @param pAesHwCtxt Pointer to the AES H/W engine context.
 *
 * @retval NvError_Success if memory is allocated successfully.
 * @retval NvError_InsufficientMemory if memory is not allocated successfully.
 */
NvError AesCoreAllocateRmMemory(AesHwContext *const pAesHwCtxt)
{
    NvError e;
    static const NvRmHeap s_Heaps[] = {NvRmHeap_IRam};
    NvU8 *pKeyTabVirtAddr = NULL;
    NvRmPhysAddr KeyTabPhyAddr = 0;
    NvU8 * pDmaVirtAddr = NULL;
    NvRmPhysAddr DmaPhyAddr = 0;
    // Allocate key table memory for both the engines
    NvU32 size = NVBL_AES_KEY_TABLE_OFFSET;
    AesHwEngine Engine;

    NV_ASSERT(pAesHwCtxt);

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    // Calculate total size needed
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
        size += (pAesHwCtxt->KeyTableSize[Engine] + NvDdkAesKeySize_128Bit);

    NV_CHECK_ERROR(NvRmMemHandleCreate(pAesHwCtxt->hRmDevice, &pAesHwCtxt->hKeyTableMemBuf, size));

    if (!pAesHwCtxt->hKeyTableMemBuf)
    {
        e = NvError_InsufficientMemory;
        goto fail;
    }

    NV_CHECK_ERROR_CLEANUP(NvRmMemAlloc(
        pAesHwCtxt->hKeyTableMemBuf,
        s_Heaps,
        NV_ARRAY_SIZE(s_Heaps),
        AES_HW_KEY_TABLE_ADDR_ALIGNMENT,
        NvOsMemAttribute_Uncached));

    KeyTabPhyAddr = NvRmMemPin(pAesHwCtxt->hKeyTableMemBuf) + NVBL_AES_KEY_TABLE_OFFSET;

    NV_CHECK_ERROR_CLEANUP(NvRmPhysicalMemMap(
        KeyTabPhyAddr,
        (size - NVBL_AES_KEY_TABLE_OFFSET),
        NVOS_MEM_READ_WRITE,
        NvOsMemAttribute_Uncached,
        (void **)&pKeyTabVirtAddr));

    size = 0;
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        pAesHwCtxt->KeyTablePhyAddr[Engine] = KeyTabPhyAddr + size;
        pAesHwCtxt->pKeyTableVirAddr[Engine] = pKeyTabVirtAddr + size;
        size = pAesHwCtxt->KeyTableSize[Engine] + NvDdkAesKeySize_128Bit;
    }

    // Allocate DMA buffer for both the engines
    size = AES_HW_DMA_BUFFER_SIZE_BYTES * AesHwEngine_Num;

    NV_CHECK_ERROR_CLEANUP(NvRmMemHandleCreate(pAesHwCtxt->hRmDevice, &pAesHwCtxt->hDmaMemBuf, size));

    NV_CHECK_ERROR_CLEANUP(NvRmMemAlloc(
        pAesHwCtxt->hDmaMemBuf,
        NULL,
        0,
        AES_HW_DMA_ADDR_ALIGNMENT,
        NvOsMemAttribute_Uncached));

    DmaPhyAddr = NvRmMemPin(pAesHwCtxt->hDmaMemBuf);

    NV_CHECK_ERROR_CLEANUP(NvRmMemMap(pAesHwCtxt->hDmaMemBuf, 0, size, NVOS_MEM_READ_WRITE, (void **)&pDmaVirtAddr));

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        pAesHwCtxt->DmaPhyAddr[Engine] = DmaPhyAddr + (Engine * AES_HW_DMA_BUFFER_SIZE_BYTES);
        pAesHwCtxt->pDmaVirAddr[Engine] = pDmaVirtAddr + (Engine * AES_HW_DMA_BUFFER_SIZE_BYTES);
    }

    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NvSuccess;

fail:
    AesCoreDeAllocateRmMemory(pAesHwCtxt);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

/**
 * De-allocate the RM memory allocated with .AesAllocateRmMemory().
 *
 * @param pAesHwCtxt Pointer to the AES Hw engine context.
 *
 * @retval None.
 */
void AesCoreDeAllocateRmMemory(AesHwContext *const pAesHwCtxt)
{
    NV_ASSERT(pAesHwCtxt);

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    if (pAesHwCtxt->hKeyTableMemBuf)
    {
        AesHwEngine Engine;
        NvU32 size = 0;

        for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
            size += (pAesHwCtxt->KeyTableSize[Engine] + NvDdkAesKeySize_128Bit);

        NvRmPhysicalMemUnmap(pAesHwCtxt->pKeyTableVirAddr[0], size);
        NvRmMemUnpin(pAesHwCtxt->hKeyTableMemBuf);
        NvRmMemHandleFree(pAesHwCtxt->hKeyTableMemBuf);
        pAesHwCtxt->hKeyTableMemBuf = NULL;
    }

    if (pAesHwCtxt->hDmaMemBuf)
    {
        NvRmMemUnmap(
            pAesHwCtxt->hDmaMemBuf,
            pAesHwCtxt->pDmaVirAddr[0],
            AES_HW_DMA_BUFFER_SIZE_BYTES * AesHwEngine_Num);
        NvRmMemUnpin(pAesHwCtxt->hDmaMemBuf);
        NvRmMemHandleFree(pAesHwCtxt->hDmaMemBuf);
        pAesHwCtxt->hDmaMemBuf = NULL;
    }

    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
}

#endif // NV_OAL

/**
 * Select the key specified by the client in the AES engine.
 *

 * @param KeyType Key type.
 * @param IsDedicatedSlot NV_TRUE if slot is dedicated, NV_FALSE if not.
 * @param pKeyData Pointer to the key data.
 * @param pAesClient Pointer to AES client.
 *
 * @retval NvSuccess if successfully completed.
 * @retval NvError_NotSupported if operation is not supported.
 */
NvError
AesCoreSetKey(
    const NvDdkAesKeyType KeyType,
    const NvBool IsDedicatedSlot,
    const NvU8 *const pKeyData,
    NvDdkAes *const pAesClient)
{
    NvError e = NvSuccess;
    AesHwContext *pAesHwCtxt = NULL;
    AesHwEngine Engine;
    AesHwKeySlot KeySlot;

    NV_ASSERT(pAesClient);

    if ((NvDdkAesKeyType_SecureBootKey == KeyType) || (NvDdkAesKeyType_SecureStorageKey == KeyType))
    {
        NVDDK_AES_CHECK_ROOT_PERMISSION;
    }

    pAesClient->IsDedicatedSlot = NV_FALSE;

    NvOsMutexLock(gs_hAesCoreEngineMutex);
    AesCorePowerUp(gs_pAesCoreEngine, NV_TRUE);

    // Get the AES H/W context
    NV_ASSERT(pAesClient->pAesCoreEngine);
    pAesHwCtxt = &pAesClient->pAesCoreEngine->AesHwCtxt;

    switch (KeyType)
    {
        case NvDdkAesKeyType_SecureBootKey:
            pAesClient->Engine = pAesClient->pAesCoreEngine->SbkEngine[0];
            pAesClient->KeySlot = pAesClient->IsEncryption ?
                pAesClient->pAesCoreEngine->SbkEncryptSlot : pAesClient->pAesCoreEngine->SbkDecryptSlot;
            break;
        case NvDdkAesKeyType_SecureStorageKey:
            pAesClient->Engine = pAesClient->pAesCoreEngine->SskEngine[0];
            pAesClient->KeySlot = pAesClient->IsEncryption ?
                pAesClient->pAesCoreEngine->SskEncryptSlot : pAesClient->pAesCoreEngine->SskDecryptSlot;
            break;
        case NvDdkAesKeyType_UserSpecified:
            pAesClient->IsDedicatedSlot = IsDedicatedSlot;
            // Wrap the key using RFC3394 key wrapping algorithm
            // The wrapped key and RFCwrapped IV will be stored in client handle
            AesCoreRequestHwAccess();
            e = AesCoreWrapKey(
                pAesClient->pAesCoreEngine,
                pKeyData,
                gs_OriginalIV,
                pAesClient->Key,
                pAesClient->WrappedIv);
            AesCoreReleaseHwAccess();
            if (NvSuccess != e)
                goto fail;
            if (!IsDedicatedSlot)
               break;
            // It is dedicated slot
            NV_CHECK_ERROR_CLEANUP(AesCoreGetFreeSlot(pAesClient->pAesCoreEngine, &Engine, &KeySlot));
            pAesClient->pAesCoreEngine->IsKeySlotUsed[Engine][KeySlot] = NV_TRUE;
            pAesClient->Engine = Engine;
            pAesClient->KeySlot = KeySlot;
            // Store the dedicated slot key info in wrapped form to use in LP0 resume
            gs_pAesCoreEngine->DedicatedSlotKeyInfo[Engine][KeySlot].IsEncryption = pAesClient->IsEncryption;
            NvOsMemcpy(gs_pAesCoreEngine->DedicatedSlotKeyInfo[Engine][KeySlot].WrappedKey,
                pAesClient->Key,
                NvDdkAesConst_MaxKeyLengthBytes);
            NvOsMemcpy(gs_pAesCoreEngine->DedicatedSlotKeyInfo[Engine][KeySlot].WrappedIv,
                pAesClient->WrappedIv,
                AES_RFC_IV_LENGTH_BYTES);
            // Initialize IV to zeros
            NvOsMemset(pAesClient->Iv, 0, NvDdkAesConst_IVLengthBytes);
            NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, Engine);

            AesCoreRequestHwAccess();

            // Setup Key table
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetKeyAndIv);
            pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwSetKeyAndIv(
                pAesClient->Engine,
                pAesClient->KeySlot,
                (AesHwKey *)pKeyData,
                (AesHwIv *)pAesClient->Iv,
                pAesClient->IsEncryption,
                pAesHwCtxt);

            AesCoreReleaseHwAccess();
            break;
        default:
            goto fail;
    }

    if ((KeyType == NvDdkAesKeyType_UserSpecified) && (!IsDedicatedSlot))
        goto done;
    NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, pAesClient->Engine);

    AesCoreRequestHwAccess();

    // Select Key slot
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwSelectKeyIvSlot);
    pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwSelectKeyIvSlot(
        pAesClient->Engine,
        pAesClient->KeySlot,
        pAesHwCtxt);

    // Get the IV and store it with client
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwGetIv);
    pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwGetIv(
        pAesHwCtxt,
        pAesClient->Engine,
        pAesClient->KeySlot,
        (AesHwIv *)pAesClient->Iv);

    AesCoreReleaseHwAccess();

done:
    // Store the Key Type for this client
    pAesClient->KeyType = KeyType;

fail:
    AesCorePowerDown(gs_pAesCoreEngine, NV_TRUE);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

/**
 * Load the SSK into the secure scratch and disables the write permissions.
 * Note: If Key is not specified then this API locks the Secure Scratch registers.
 *
 * @param pAesHwCtxt Pointer to AES H/W context.
 * @param pKey Pointer to the key. If pKey == NULL then key will not be set to the
 *             secure scratch registers, but locks the Secure scratch register.
 *
 * @retval NvSuccess if successfully completed.
 */
NvError AesCoreLoadSskToSecureScratchAndLock(const AesHwContext *const pAesHwCtxt, const NvU8 *const pKey)
{
    NvError e = NvSuccess;
    NvRmPhysAddr PhysAdr;
    NvU32 BankSize;
    NvU32 RmPwrClientId = 0;

    NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, 0);

    // Get the secure scratch base address
    NvRmModuleGetBaseAddress(pAesHwCtxt->hRmDevice, NVRM_MODULE_ID(NvRmModuleID_Pmif, 0), &PhysAdr, &BankSize);

    // Register with Power Manager
    RmPwrClientId = NVRM_POWER_CLIENT_TAG('A','E','S','2');

    NV_CHECK_ERROR_CLEANUP(NvRmPowerRegister(pAesHwCtxt->hRmDevice, NULL, &RmPwrClientId));

    // Enable the Voltage
    NV_CHECK_ERROR_CLEANUP(NvRmPowerVoltageControl(
        pAesHwCtxt->hRmDevice,
        NvRmModuleID_Pmif,
        RmPwrClientId,
        NvRmVoltsUnspecified,
        NvRmVoltsUnspecified,
        NULL,
        0,
        NULL));

    // Emable the clock to the PMIC
    NV_CHECK_ERROR_CLEANUP(NvRmPowerModuleClockControl(pAesHwCtxt->hRmDevice, NvRmModuleID_Pmif, RmPwrClientId, NV_TRUE));

    // Store SSK and lock the secure scratch -- engine doesn't matter here
    // since the key is being provided and not really read from the key table of an engine .here
    // If pKey == NULL this call will disable the write permissions to the scratch registers.
    AesCoreRequestHwAccess();

    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, 0, AesHwLoadSskToSecureScratchAndLock);
    pAesHwCtxt->ppEngineCaps[0]->pAesInterf->AesHwLoadSskToSecureScratchAndLock(PhysAdr, (AesHwKey *)pKey, BankSize);

    AesCoreReleaseHwAccess();

fail:
    // Disable the clock to the PMIC
    NV_ASSERT_SUCCESS(NvRmPowerModuleClockControl(pAesHwCtxt->hRmDevice, NvRmModuleID_Pmif, RmPwrClientId, NV_FALSE));

    // Disable the Voltage
    NV_ASSERT_SUCCESS(NvRmPowerVoltageControl(
        pAesHwCtxt->hRmDevice,
        NvRmModuleID_Pmif,
        RmPwrClientId,
        NvRmVoltsOff,
        NvRmVoltsOff,
        NULL,
        0,
        NULL));

    // Unregister driver from Power Manager
    NvRmPowerUnRegister(pAesHwCtxt->hRmDevice, RmPwrClientId);
    return e;
}

/**
 * Check the SBK clear by encrypting / decrypting the known data.
 *
 * @param Engine Engine on which encryption and decryption need to be performed
 * @param EncryptSlot Key slot where encrypt key is located.
 * @param DecryptSlot Key slot where decrypt key is located.
 * @param pAesHwCtxt Pointer to AES H/W context.
 *
 * @retval NV_TRUE if successfully encryption and decryption is done else NV_FALSE.
 */
NvBool AesCoreIsSbkCleared(
    const AesHwEngine Engine,
    const AesHwKeySlot EncryptSlot,
    const AesHwKeySlot DecryptSlot,
    AesHwContext *const pAesHwCtxt)
{
    NvError e = NvSuccess;
    AesHwIv ZeroIv;
    NvU32 i;

    // Known Good data
    static NvU8 s_GoldData[NvDdkAesConst_BlockLengthBytes] =
    {
        0x00, 0x01, 0x02, 0x03,
        0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0A, 0x0B,
        0x0C, 0x0D, 0x0E, 0x0F
    };

    // Encrypted data for above known data with Zero key and Zero IV
    static NvU8 s_EncryptDataWithZeroKeyTable[NvDdkAesConst_BlockLengthBytes] =
    {
        0x7A, 0xCA, 0x0F, 0xD9,
        0xBC, 0xD6, 0xEC, 0x7C,
        0x9F, 0x97, 0x46, 0x66,
        0x16, 0xE6, 0xA2, 0x82
    };

    // Encrypted data for above known data with Zero key and Zero IV
    static NvU8 s_EncryptDataWithZeroKeySchedule[NvDdkAesConst_BlockLengthBytes] =
    {
        0x18, 0x9D, 0x19, 0xEA,
        0xDB, 0xA7, 0xE3, 0x0E,
        0xD9, 0x72, 0x80, 0x8F,
        0x3F, 0x2B, 0xA0, 0x30
    };

    NvU8 *pEncryptData = NULL;
    NvU8 EncryptBuffer[NvDdkAesConst_BlockLengthBytes];
    NvU8 DecryptBuffer[NvDdkAesConst_BlockLengthBytes];

    NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, Engine);

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    if (pAesHwCtxt->ppEngineCaps[Engine]->IsHwKeySchedGenSupported)
        pEncryptData = s_EncryptDataWithZeroKeyTable;
    else
        pEncryptData = s_EncryptDataWithZeroKeySchedule;

    NvOsMemset(EncryptBuffer, 0, NvDdkAesConst_BlockLengthBytes);
    NvOsMemset(DecryptBuffer, 0, NvDdkAesConst_BlockLengthBytes);
    NvOsMemset(&ZeroIv, 0, sizeof(AesHwIv));

    AesCoreRequestHwAccess();

    // Select Encrypt Key slot
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSelectKeyIvSlot);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSelectKeyIvSlot(Engine, EncryptSlot, pAesHwCtxt);

    // Set the Zero IV for test data
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetIv);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetIv(
        Engine,
        EncryptSlot,
        &ZeroIv,
        pAesHwCtxt));

    // Process the buffer for encryption
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwStartEngine);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwStartEngine(
        Engine,
        NvDdkAesConst_BlockLengthBytes,
        s_GoldData,
        NV_TRUE,
        NvDdkAesOperationalMode_Cbc,
        EncryptBuffer,
        pAesHwCtxt));

    // Select Decrypt Key slot
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSelectKeyIvSlot);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSelectKeyIvSlot(Engine, DecryptSlot, pAesHwCtxt);

    // Set the Zero IV for test data
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetIv);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetIv(
        Engine,
        DecryptSlot,
        &ZeroIv,
        pAesHwCtxt));

    // Process the buffer for encryption
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwStartEngine);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwStartEngine(
        Engine,
        NvDdkAesConst_BlockLengthBytes,
        EncryptBuffer,
        NV_FALSE,
        NvDdkAesOperationalMode_Cbc,
        DecryptBuffer,
        pAesHwCtxt));

    // Clear the IV in the engine before we leave
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwClearIv);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwClearIv(Engine, EncryptSlot, pAesHwCtxt);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwClearIv(Engine, DecryptSlot, pAesHwCtxt);

    // Clear the DMA buffer before we leave from this operation.
    NV_ASSERT(pAesHwCtxt->pDmaVirAddr[Engine]);
    NvOsMemset(pAesHwCtxt->pDmaVirAddr[Engine], 0, AES_HW_DMA_BUFFER_SIZE_BYTES);

    for (i = 0; i < NvDdkAesConst_BlockLengthBytes; i++)
    {
        if ((pEncryptData[i] != EncryptBuffer[i]) || (s_GoldData[i] != DecryptBuffer[i]))
            goto fail;
    }

    AesCoreReleaseHwAccess();
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NV_TRUE;

fail:
    // Clear the DMA buffer before we leave from this operation
    NV_ASSERT(pAesHwCtxt->pDmaVirAddr[Engine]);
    NvOsMemset(pAesHwCtxt->pDmaVirAddr[Engine], 0, AES_HW_DMA_BUFFER_SIZE_BYTES);
    AesCoreReleaseHwAccess();
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NV_FALSE;
}

/**
 * Check the SSK lock is successfully done or not by writing zero key into SSK.
 *
 * @param Engine Engine where SSK is set.
 * @param EncryptSlot Key slot where encrypt key is located.
 * @param DecryptSlot Key slot where decrypt key is located.
 * @param pAesHwCtxt Pointer to AES H/W context.
 *
 * @retval NV_TRUE if successfully SSK is locked else NV_FALSE.
 */
NvBool
AesCoreIsSskLocked(
    const AesHwEngine Engine,
    const AesHwKeySlot EncryptSlot,
    const AesHwKeySlot DecryptSlot,
    AesHwContext *const pAesHwCtxt)
{
    NvError e = NvSuccess;
    AesHwIv ZeroIv;
    AesHwKey ZeroKey;
    NvU32 i;

    static NvU8 s_GoldData[NvDdkAesConst_BlockLengthBytes] =
    {
        0x00, 0x11, 0x22, 0x33,
        0x44, 0x55, 0x66, 0x77,
        0x88, 0x99, 0xAA, 0xBB,
        0xCC, 0xDD, 0xEE, 0xFF
    };

    NvU8 EncryptBuffer1[NvDdkAesConst_BlockLengthBytes];
    NvU8 DecryptBuffer1[NvDdkAesConst_BlockLengthBytes];
    NvU8 EncryptBuffer2[NvDdkAesConst_BlockLengthBytes];
    NvU8 DecryptBuffer2[NvDdkAesConst_BlockLengthBytes];

    NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, Engine);

    NvOsMemset(EncryptBuffer1, 0, NvDdkAesConst_BlockLengthBytes);
    NvOsMemset(DecryptBuffer1, 0, NvDdkAesConst_BlockLengthBytes);
    NvOsMemset(EncryptBuffer2, 0, NvDdkAesConst_BlockLengthBytes);
    NvOsMemset(DecryptBuffer2, 0, NvDdkAesConst_BlockLengthBytes);
    NvOsMemset(&ZeroIv, 0, sizeof(AesHwIv));
    NvOsMemset(&ZeroKey, 0, sizeof(AesHwKey));

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    AesCoreRequestHwAccess();

    // Select Encrypt Key slot
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSelectKeyIvSlot);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSelectKeyIvSlot(Engine, EncryptSlot, pAesHwCtxt);

    // Set the Zero IV for test data
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetIv);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetIv(
        Engine,
        EncryptSlot,
        &ZeroIv,
        pAesHwCtxt));

    // Process the buffer for encryption
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwStartEngine);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwStartEngine(
        Engine,
        NvDdkAesConst_BlockLengthBytes,
        s_GoldData,
        NV_TRUE,
        NvDdkAesOperationalMode_Cbc,
        EncryptBuffer1,
        pAesHwCtxt));

    // Select Decrypt Key slot
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSelectKeyIvSlot);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSelectKeyIvSlot(Engine, DecryptSlot, pAesHwCtxt);

    // Set the Zero IV for test data
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetIv);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetIv(
        Engine,
        DecryptSlot,
        &ZeroIv,
        pAesHwCtxt));

    // Process the buffer for encryption
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwStartEngine);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwStartEngine(
        Engine,
        NvDdkAesConst_BlockLengthBytes,
        s_GoldData,
        NV_FALSE,
        NvDdkAesOperationalMode_Cbc,
        DecryptBuffer1,
        pAesHwCtxt));

    // Set Zero key to the SSK slot and try encryption / decryption with
    // known data and check data after encryption and decryption are same with SSK

    // Setup SSK Key table for encryption
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetKeyAndIv);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetKeyAndIv(
        Engine,
        EncryptSlot,
        &ZeroKey,
        &ZeroIv,
        NV_TRUE,
        pAesHwCtxt);

    // Setup SSK Key table for encryption
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetKeyAndIv);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetKeyAndIv(
        Engine,
        DecryptSlot,
        &ZeroKey,
        &ZeroIv,
        NV_FALSE,
        pAesHwCtxt);

    // Select Encrypt Key slot
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSelectKeyIvSlot);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSelectKeyIvSlot(Engine, EncryptSlot, pAesHwCtxt);

    // Set the Zero IV for test data
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetIv);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetIv(
        Engine,
        EncryptSlot,
        &ZeroIv,
        pAesHwCtxt));

    // Process the buffer for encryption
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwStartEngine);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwStartEngine(
        Engine,
        NvDdkAesConst_BlockLengthBytes,
        s_GoldData,
        NV_TRUE,
        NvDdkAesOperationalMode_Cbc,
        EncryptBuffer2,
        pAesHwCtxt));

    // Select Decrypt Key slot
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSelectKeyIvSlot);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSelectKeyIvSlot(Engine, DecryptSlot, pAesHwCtxt);

    // Set the Zero IV for test data
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetIv);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetIv(
        Engine,
        DecryptSlot,
        &ZeroIv,
        pAesHwCtxt));

    // Process the buffer for encryption
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwStartEngine);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwStartEngine(
        Engine,
        NvDdkAesConst_BlockLengthBytes,
        s_GoldData,
        NV_FALSE,
        NvDdkAesOperationalMode_Cbc,
        DecryptBuffer2,
        pAesHwCtxt));

    // Clear the IV in the engine before we leave
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwClearIv);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwClearIv(Engine, EncryptSlot, pAesHwCtxt);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwClearIv(Engine, DecryptSlot, pAesHwCtxt);

    // Clear the DMA buffer before we leave from this operation.
    NV_ASSERT(pAesHwCtxt->pDmaVirAddr[Engine]);
    NvOsMemset(pAesHwCtxt->pDmaVirAddr[Engine], 0, AES_HW_DMA_BUFFER_SIZE_BYTES);

    // Check encrypt and decrypt output is same before and after zero key set to SSK
    // If both encrypt and decrypt data match then SSK lock is OK
    for (i = 0; i < NvDdkAesConst_BlockLengthBytes; i++)
    {
        if ((EncryptBuffer1[i] != EncryptBuffer2[i]) || (DecryptBuffer1[i] != DecryptBuffer2[i]))
            goto fail;
    }

    AesCoreReleaseHwAccess();
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NV_TRUE;

fail:
    // Clear the DMA buffer before we leave from this operation.
    NV_ASSERT(pAesHwCtxt->pDmaVirAddr[Engine]);
    NvOsMemset(pAesHwCtxt->pDmaVirAddr[Engine], 0, AES_HW_DMA_BUFFER_SIZE_BYTES);
    AesCoreReleaseHwAccess();
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NV_FALSE;
}

/**
 * Add the Busy hints to boost or reduce the CPU, System and EMC frequencies.
 *
 * @param hRmDevice RM device handle.
 * @param PowerClientId The client ID obtained during Power registration.
 * @param IsDfsOn Indicator to boost the frequency, if set to NV_TRUE. Cancel the
 *        DFS busy hint if set to NV_FALSE.
 *
 * @retval NvSuccess if busy hint request completed successfully.
 * @retval NvError_NotSupported if DFS is disabled.
 * @retval NvError_BadValue if specified client ID is not registered.
 * @retval NvError_InsufficientMemory if failed to allocate memory for busy hints.
 */
NvError AesCoreDfsBusyHint(const NvRmDeviceHandle hRmDevice, const NvU32 PowerClientId, const NvBool IsDfsOn)
{
    #define AES_EMC_BOOST_FREQ_KHZ 100000
    #define AES_SYS_BOOST_FREQ_KHZ 100000

    NvRmDfsBusyHint AesBusyHintOn[] =
    {
        {NvRmDfsClockId_Emc, NV_WAIT_INFINITE, AES_EMC_BOOST_FREQ_KHZ, NV_TRUE},
        {NvRmDfsClockId_System, NV_WAIT_INFINITE, AES_SYS_BOOST_FREQ_KHZ, NV_TRUE}
    };

    NvRmDfsBusyHint AesBusyHintOff[] =
    {
        {NvRmDfsClockId_Emc, 0, 0, NV_TRUE},
        {NvRmDfsClockId_System, 0, 0, NV_TRUE}
    };

    NV_ASSERT(hRmDevice);

    if (IsDfsOn)
    {
        return NvRmPowerBusyHintMulti(
            hRmDevice,
            PowerClientId,
            AesBusyHintOn,
            NV_ARRAY_SIZE(AesBusyHintOn),
            NvRmDfsBusyHintSyncMode_Async);
    }
    else
    {
        return NvRmPowerBusyHintMulti(
            hRmDevice,
            PowerClientId,
            AesBusyHintOff,
            NV_ARRAY_SIZE(AesBusyHintOff),
            NvRmDfsBusyHintSyncMode_Async);
    }
}

/**
 * Populate the structure for AES context with the engine base address.
 *
 * @param hRmDevice Rm device handle.
 * @param pAesHwCtxt Pointer to AES H/W context.
 *
 * @retval NvSuccess if successfully completed.
 *
 */
NvError AesCoreInitializeEngineSpace(const NvRmDeviceHandle hRmDevice, AesHwContext *const pAesHwCtxt)
{
    NvError e = NvSuccess;
    AesHwEngine Engine;

    NV_ASSERT(hRmDevice);
    NV_ASSERT(pAesHwCtxt);

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        switch (Engine)
        {
            case AesHwEngine_A:
                // Get the controller base address
                NvRmModuleGetBaseAddress(
                    hRmDevice,
                    NVRM_MODULE_ID(NvRmModuleID_Vde, 0),
                    &pAesHwCtxt->PhysAdr[Engine],
                    &pAesHwCtxt->BankSize[Engine]);
                break;
            case AesHwEngine_B:
                // Get the controller base address
                NvRmModuleGetBaseAddress(
                    hRmDevice,
                    NVRM_MODULE_ID(NvRmModuleID_BseA, 0),
                    &pAesHwCtxt->PhysAdr[Engine],
                    &pAesHwCtxt->BankSize[Engine]);
                break;
            default:
                break;
        }

        // Map the physical memory to virtual memory
        NV_CHECK_ERROR_CLEANUP(NvRmPhysicalMemMap(
            pAesHwCtxt->PhysAdr[Engine],
            pAesHwCtxt->BankSize[Engine],
            NVOS_MEM_READ_WRITE,
            NvOsMemAttribute_Uncached,
            (void **)&pAesHwCtxt->pVirAdr[Engine]));
    }

    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NvSuccess;

fail:
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

/**
 * Unmap all engine space.
 *
 * @param pAesHwCtxt Pointer to AES H/W context.
 *
 * @retval None.
 *
 */
void AesCoreDeInitializeEngineSpace(const AesHwContext *const pAesHwCtxt)
{
    AesHwEngine Engine;

    NV_ASSERT(pAesHwCtxt);

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    // Clean up resources
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        // UnMap the virtual Address
        NvRmPhysicalMemUnmap(pAesHwCtxt->pVirAdr[Engine], pAesHwCtxt->BankSize[Engine]);
    }

    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
}

/**
 * Find the unused key slot.
 *
 * @param pAesCoreEngine Pointer to AES core engine.
 * @param pEngine Pointer to the engine.
 * @param pKeySlot Pointer to the key slot.
 *
 * @retval NvSuccess if successfully completed.
 * @retval NvError_AlreadyAllocated if all slots are allocated.
 */
NvError
AesCoreGetFreeSlot(
    const AesCoreEngine *const pAesCoreEngine,
    AesHwEngine *const pEngine,
    AesHwKeySlot *const pKeySlot)
{
    AesHwEngine Engine;
    AesHwKeySlot KeySlot;
    const AesHwContext *pAesHwCtxt;

    NV_ASSERT(pAesCoreEngine);
    NV_ASSERT(pEngine);
    NV_ASSERT(pKeySlot);

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    // Get the AES H/W context
    pAesHwCtxt = &pAesCoreEngine->AesHwCtxt;

    // Get the free slot
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        NV_ASSERT(pAesHwCtxt->ppEngineCaps);
        NV_ASSERT(pAesHwCtxt->ppEngineCaps[Engine]);
        for (KeySlot = AesHwKeySlot_0;
            KeySlot < (NvU32)(pAesHwCtxt->ppEngineCaps[Engine]->NumSlotsSupported);
            KeySlot++)
        {
            if (!pAesCoreEngine->IsKeySlotUsed[Engine][KeySlot])
            {
                *pEngine = Engine;
                *pKeySlot = KeySlot;

                NvOsMutexUnlock(gs_hAesCoreEngineMutex);
                return NvSuccess;
            }
        }
    }

    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NvError_AlreadyAllocated;
}

/**
 * Init AES engine.
 *
 * @param hRmDevice Resource Manager Handle.
 *
 * @retval NvSuccess if successful.
 */
NvError AesCoreInitEngine(const NvRmDeviceHandle hRmDevice)
{
    NvError e = NvSuccess;
    AesHwContext *pAesHwCtxt = NULL;
    AesHwEngine Engine;

    NV_ASSERT(hRmDevice);

    gs_pAesCoreEngine = NvOsAlloc(sizeof(AesCoreEngine));
    if (NULL == gs_pAesCoreEngine)
        return NvError_InsufficientMemory;

    // Clear the memory initially
    NvOsMemset(gs_pAesCoreEngine, 0, sizeof(AesCoreEngine));

    // Get the AES H/W context
    pAesHwCtxt = &gs_pAesCoreEngine->AesHwCtxt;

    // Store the RM handle for future use
    pAesHwCtxt->hRmDevice = hRmDevice;

    pAesHwCtxt->ppEngineCaps = (AesHwCapabilities **)NvOsAlloc(sizeof(AesHwCapabilities) * AesHwEngine_Num);
    if (NULL == pAesHwCtxt->ppEngineCaps)
    {
        NvOsFree(gs_pAesCoreEngine);
        gs_pAesCoreEngine = NULL;
        return NvError_InsufficientMemory;
    }
    AesCoreGetCapabilities(hRmDevice, pAesHwCtxt->ppEngineCaps);

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        NV_ASSERT(pAesHwCtxt->ppEngineCaps[Engine]);
        pAesHwCtxt->KeyTableSize[Engine] = pAesHwCtxt->ppEngineCaps[Engine]->HwKeySchedLengthBytes;
    }

    NV_CHECK_ERROR(AesCoreInitializeEngineSpace(hRmDevice, pAesHwCtxt));

    // Allocate memories required for H/W operation
    NV_CHECK_ERROR(AesCoreAllocateRmMemory(pAesHwCtxt));

    // Create mutex to guard the H/W engine
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        NV_CHECK_ERROR(NvOsMutexCreate(&pAesHwCtxt->Mutex[Engine]));

        // Register with Power Manager
        gs_pAesCoreEngine->RmPwrClientId[Engine] = NVRM_POWER_CLIENT_TAG('A','E','S','1');

        NV_CHECK_ERROR(NvRmPowerRegister(hRmDevice, NULL, &gs_pAesCoreEngine->RmPwrClientId[Engine]));

        // Enable the voltage
        NV_CHECK_ERROR(NvRmPowerVoltageControl(
            hRmDevice,
            (AesHwEngine_A == Engine) ?
            NvRmModuleID_Vde : NvRmModuleID_BseA,
            gs_pAesCoreEngine->RmPwrClientId[Engine],
            NvRmVoltsUnspecified,
            NvRmVoltsUnspecified,
            NULL,
            0,
            NULL));

        // Enable clock
        NV_CHECK_ERROR(NvRmPowerModuleClockControl(
            hRmDevice,
            (AesHwEngine_A == Engine) ?
            NvRmModuleID_Vde : NvRmModuleID_BseA,
            gs_pAesCoreEngine->RmPwrClientId[Engine],
            NV_TRUE));
    }

    // Request the H/W semaphore before accessing the AES H/W
    AesCoreRequestHwAccess();

    // Reset the BSEV and BSEA engines
    NvRmModuleReset(hRmDevice, NvRmModuleID_Vde);
    NvRmModuleReset(hRmDevice, NvRmModuleID_BseA);

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, Engine);
        NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwIsEngineDisabled);

        gs_pAesCoreEngine->IsEngineDisabled =
            pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwIsEngineDisabled(pAesHwCtxt, Engine);
    }

    // If engine is not disabled then set the SBK & SSK
    if (!gs_pAesCoreEngine->IsEngineDisabled)
    {
        // The slots already dedicated don't depend on which engine is being used but
        // on the capabilities the engines can provide. Basic assumption: both engines have
        // same capabilities.
        NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, 0, AesHwGetUsedSlots);
        pAesHwCtxt->ppEngineCaps[0]->pAesInterf->AesHwGetUsedSlots(gs_pAesCoreEngine);
    }

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, Engine);
        NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwDisableAllKeyRead);
        pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwDisableAllKeyRead(
            pAesHwCtxt,
            Engine,
            pAesHwCtxt->ppEngineCaps[Engine]->NumSlotsSupported);
    }

    // Release the H/W semaphore
    AesCoreReleaseHwAccess();

    // Disable clocks after AES init
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        // Disable clock
        NV_CHECK_ERROR(NvRmPowerModuleClockControl(
            pAesHwCtxt->hRmDevice,
            (AesHwEngine_A == Engine) ?
            NvRmModuleID_Vde : NvRmModuleID_BseA,
            gs_pAesCoreEngine->RmPwrClientId[Engine],
            NV_FALSE));

        // Disable the voltage
        NV_CHECK_ERROR(NvRmPowerVoltageControl(
            pAesHwCtxt->hRmDevice,
            (AesHwEngine_A == Engine) ?
            NvRmModuleID_Vde : NvRmModuleID_BseA,
            gs_pAesCoreEngine->RmPwrClientId[Engine],
            NvRmVoltsOff,
            NvRmVoltsOff,
            NULL,
            0,
            NULL));
    }
    return e;
}

/**
  * Free up resources.
  *
  * @retval None.
  */
void AesCoreFreeUpEngine(AesCoreEngine *const pAesCoreEngine)
{
    AesHwEngine Engine;
    AesHwContext *pAesHwCtxt;

    NV_ASSERT(pAesCoreEngine);

    // Get the AES H/W context
    pAesHwCtxt = &pAesCoreEngine->AesHwCtxt;

    AesCoreDeInitializeEngineSpace(pAesHwCtxt);

    // Deallocate the memory
    AesCoreDeAllocateRmMemory(pAesHwCtxt);

    // Destroy mutex
    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        NvOsMutexDestroy(pAesHwCtxt->Mutex[Engine]);
        // Unregister driver from Power Manager
        NvRmPowerUnRegister(pAesHwCtxt->hRmDevice, pAesCoreEngine->RmPwrClientId[Engine]);
        if (pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf)
        {
            NvOsFree(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf);
            pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf = NULL;
        }
    }
    if (pAesHwCtxt->ppEngineCaps)
    {
        NvOsFree(pAesHwCtxt->ppEngineCaps);
        pAesHwCtxt->ppEngineCaps = NULL;
    }
}

/**
 * Power up the AES core engine.
 *
 * @param pAesCoreEngine Pointer to the AesCoreEngine argument.
 * @param SetDfsBusyHints If set to NV_TRUE, DFS busy hints will be set to ON
 *
 * @retval None.
 */
void AesCorePowerUp(const AesCoreEngine *const pAesCoreEngine, const NvBool SetDfsBusyHints)
{
    AesHwEngine Engine;
    const AesHwContext *pAesHwCtxt;

    NV_ASSERT(pAesCoreEngine);

    // Get the Aes Hw context
    pAesHwCtxt = &pAesCoreEngine->AesHwCtxt;

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        if (SetDfsBusyHints)
        {
            // DFS busy hints On
            NV_ASSERT_SUCCESS(AesCoreDfsBusyHint(pAesHwCtxt->hRmDevice, pAesCoreEngine->RmPwrClientId[Engine], NV_TRUE));
        }

        // Enable the voltage
        NV_ASSERT_SUCCESS(NvRmPowerVoltageControl(
            pAesHwCtxt->hRmDevice,
            (AesHwEngine_A == Engine) ? NvRmModuleID_Vde : NvRmModuleID_BseA,
            pAesCoreEngine->RmPwrClientId[Engine],
            NvRmVoltsUnspecified,
            NvRmVoltsUnspecified,
            NULL,
            0,
            NULL));

        // Enable clock
        NV_ASSERT_SUCCESS(NvRmPowerModuleClockControl(
            pAesHwCtxt->hRmDevice,
            (AesHwEngine_A == Engine) ? NvRmModuleID_Vde : NvRmModuleID_BseA,
            pAesCoreEngine->RmPwrClientId[Engine],
            NV_TRUE));
    }
}

/**
 * Power down the AES core engine.
 *
 * @param pAesCoreEngine Pointer to the AesCoreEngine argument.
 * @param SetDfsBusyHints If set to NV_TRUE, DFS busy hints will be set to OFF
 *
 * @retval None.
 */
void AesCorePowerDown(const AesCoreEngine *const pAesCoreEngine, const NvBool SetDfsBusyHints)
{
    AesHwEngine Engine;
    const AesHwContext *pAesHwCtxt;

    NV_ASSERT(pAesCoreEngine);

    // Get the AES H/W context
    pAesHwCtxt = &pAesCoreEngine->AesHwCtxt;

    for (Engine = AesHwEngine_A; Engine < AesHwEngine_Num; Engine++)
    {
        // Disable clock
        NV_ASSERT_SUCCESS(NvRmPowerModuleClockControl(
            pAesHwCtxt->hRmDevice,
            (AesHwEngine_A == Engine) ? NvRmModuleID_Vde : NvRmModuleID_BseA,
            pAesCoreEngine->RmPwrClientId[Engine],
            NV_FALSE));

        // Disable the voltage
        NV_ASSERT_SUCCESS(NvRmPowerVoltageControl(
            pAesHwCtxt->hRmDevice,
            (AesHwEngine_A == Engine) ? NvRmModuleID_Vde : NvRmModuleID_BseA,
            pAesCoreEngine->RmPwrClientId[Engine],
            NvRmVoltsOff,
            NvRmVoltsOff,
            NULL,
            0,
            NULL));
        if (SetDfsBusyHints)
        {
            // DFS busy hints Off
            NV_ASSERT_SUCCESS(AesCoreDfsBusyHint(pAesHwCtxt->hRmDevice, pAesCoreEngine->RmPwrClientId[Engine], NV_FALSE));
        }
    }
}

/**
 * Process the buffers for encryption or decryption.
 *
 * @param SkipOffset Skip initial SkipOffset bytes of SrcBuffer before beginning cipher.
 * @param SrcBufferSize Size of src buffer in bytes.
 * @param DestBufferSize Size of dest buffer in bytes.
 * @param pAesClient Pointer to AES client.
 * @param pSrcBuffer Pointer to src buffer.
 * @param pDestBuffer Pointer to dest buffer.
 *
 * @retval NvSuccess if successfully completed.
 */
NvError
AesCoreProcessBuffer(
    const NvU32 SkipOffset,
    const NvU32 SrcBufferSize,
    const NvU32 DestBufferSize,
    NvDdkAes *const pAesClient,
    const NvU8 *pSrcBuffer,
    NvU8 *pDestBuffer)
{
    NvError e = NvSuccess;
    AesHwContext *pAesHwCtxt = NULL;
    AesHwEngine Engine;
    AesHwKeySlot KeySlot;
    NvU32 TotalBytesToProcess = 0;
    NvU32 BytesToProcess = 0;

    NV_ASSERT(pAesClient);
    NV_ASSERT(pSrcBuffer);
    NV_ASSERT(pDestBuffer);

    NVDDK_AES_CHECK_USER_IDENTITY;

    // Check type of operation supported for the process buffer
    switch (pAesClient->OpMode)
    {
        case NvDdkAesOperationalMode_Cbc:
        case NvDdkAesOperationalMode_Ecb:
        case NvDdkAesOperationalMode_AnsiX931:
            break;
        default:
            return NvError_InvalidState;
    }

    if (DestBufferSize % NvDdkAesConst_BlockLengthBytes)
        return NvError_InvalidSize;

    // Check if client has already assigned key for this process if not return
    if ((NvDdkAesKeyType_Invalid == pAesClient->KeyType) || (pAesClient->KeyType >= NvDdkAesKeyType_Num))
        return NvError_InvalidState;

    // Get the AES H/W context
    NV_ASSERT(pAesClient->pAesCoreEngine);
    pAesHwCtxt = &pAesClient->pAesCoreEngine->AesHwCtxt;

    TotalBytesToProcess = DestBufferSize;

    NvOsMutexLock(gs_hAesCoreEngineMutex);
    AesCorePowerUp(gs_pAesCoreEngine, NV_TRUE);

    NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, pAesClient->Engine);

    while (TotalBytesToProcess)
    {
        // Request the H/W semaphore before accesing the AES H/W
        AesCoreRequestHwAccess();

        // In the bootloader version entire buffer is processed for AES operation
#if NV_OAL
        BytesToProcess = TotalBytesToProcess;
        TotalBytesToProcess = 0;
#else
        // At OS level only AES_HW_MAX_PROCESS_SIZE_BYTES will be processed.
        // Once the AES H/W lock is acquired again then remaining bytes or maximum of
        // AES_HW_MAX_PROCESS_SIZE_BYTES will be processed.
        if (TotalBytesToProcess > AES_HW_MAX_PROCESS_SIZE_BYTES)
            BytesToProcess = AES_HW_MAX_PROCESS_SIZE_BYTES;
        else
            BytesToProcess = TotalBytesToProcess;
#endif

        if ((!pAesClient->IsDedicatedSlot) && (NvDdkAesKeyType_UserSpecified == pAesClient->KeyType))
        {
            // If it is not dedicated slot, unwrap the key
            NvU8 UnWrappedRFCIv[AES_RFC_IV_LENGTH_BYTES];

            NV_CHECK_ERROR_CLEANUP(AesCoreGetFreeSlot(pAesClient->pAesCoreEngine, &Engine, &KeySlot));
            pAesClient->Engine = Engine;
            pAesClient->KeySlot = KeySlot;

            // Unwrap the key
            NV_CHECK_ERROR_CLEANUP(AesCoreUnWrapKey(
                pAesClient->pAesCoreEngine,
                pAesClient->Key,
                pAesClient->WrappedIv,
                pAesHwCtxt->pKeyTableVirAddr[Engine] + pAesHwCtxt->KeyTableSize[Engine],
                UnWrappedRFCIv));
            // Check whether the key unwrap is success or not by comparing the unwrapped RFC IV with original RFC IV
            if (NvOsMemcmp(UnWrappedRFCIv, gs_OriginalIV, sizeof(gs_OriginalIV)))
            {
                // Unwrap key failed
                e = NvError_AesKeyUnWrapFailed;
                goto fail;
            }

            // Setup Key table
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwSetKeyAndIv);
            pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwSetKeyAndIv(
                pAesClient->Engine,
                pAesClient->KeySlot,
                (AesHwKey *)(pAesHwCtxt->pKeyTableVirAddr[Engine] + pAesHwCtxt->KeyTableSize[Engine]),
                (AesHwIv *)pAesClient->Iv,
                pAesClient->IsEncryption,
                pAesHwCtxt);

            // Memset the local variable to zeros where the key is stored
            NvOsMemset(
                (pAesHwCtxt->pKeyTableVirAddr[Engine] + pAesHwCtxt->KeyTableSize[Engine]),
                0,
                NvDdkAesKeySize_128Bit);
        }
        else
        {
            // Select Key slot
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwSelectKeyIvSlot);
            pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwSelectKeyIvSlot(
                pAesClient->Engine,
                pAesClient->KeySlot,
                pAesHwCtxt);

            // Set the last IV operated with this client
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwSetIv);
            NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwSetIv(
                pAesClient->Engine,
                pAesClient->KeySlot,
                (AesHwIv *)pAesClient->Iv,
                pAesHwCtxt));
        }

        // Process the buffer for encryption/decryption
        NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwStartEngine);
        e = pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwStartEngine(
            pAesClient->Engine,
            BytesToProcess,
            pSrcBuffer,
            pAesClient->IsEncryption,
            pAesClient->OpMode,
            pDestBuffer,
            pAesHwCtxt);
        if (NvSuccess != e)
        {
            // If the key is user specified and not in dedicated slot, clear it
            if ((!pAesClient->IsDedicatedSlot) && (NvDdkAesKeyType_UserSpecified == pAesClient->KeyType))
            {
                // Clear key
                NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwClearKeyAndIv);
                pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwClearKeyAndIv(
                    pAesClient->Engine,
                    pAesClient->KeySlot,
                    pAesHwCtxt);
            }
            goto fail;
        }

        // Store the last IV operated with this client
        NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwGetIv);
        pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwGetIv(
            pAesHwCtxt,
            pAesClient->Engine,
            pAesClient->KeySlot,
            (AesHwIv *)pAesClient->Iv);

        // If the key is user specified and not in dedicated slot, clear it
        if ((!pAesClient->IsDedicatedSlot) && (NvDdkAesKeyType_UserSpecified == pAesClient->KeyType))
        {
            // Clear key
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwClearKeyAndIv);
            pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwClearKeyAndIv(
                pAesClient->Engine,
                pAesClient->KeySlot,
                pAesHwCtxt);
        }
        else
        {
            // Clear the IV in the engine
            NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwClearIv);
            pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwClearIv(
                pAesClient->Engine,
                pAesClient->KeySlot,
                pAesHwCtxt);
        }

#if !NV_OAL
        pSrcBuffer += BytesToProcess;
        pDestBuffer += BytesToProcess;
        TotalBytesToProcess -= BytesToProcess;
#endif

        // Release the H/W semaphore
        AesCoreReleaseHwAccess();
    }

    // Clear the DMA buffer before we leave from this operation
    NV_ASSERT(pAesHwCtxt->pDmaVirAddr[pAesClient->Engine]);
    NvOsMemset(pAesHwCtxt->pDmaVirAddr[pAesClient->Engine], 0, AES_HW_DMA_BUFFER_SIZE_BYTES);
    AesCorePowerDown(gs_pAesCoreEngine, NV_TRUE);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NvSuccess;

fail:
    // Release the H/W semaphore
    AesCoreReleaseHwAccess();
    // Clear the DMA buffer before we leave from this operation
    NV_ASSERT(pAesHwCtxt->pDmaVirAddr[pAesClient->Engine]);
    NvOsMemset(pAesHwCtxt->pDmaVirAddr[pAesClient->Engine], 0, AES_HW_DMA_BUFFER_SIZE_BYTES);
    AesCorePowerDown(gs_pAesCoreEngine, NV_TRUE);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return e;
}

/**
 * Clear the User Key.
 *
 * @param pAesClient Pointer to AES client.
 *
 * @retval NvSuccess if User key is cleared, NV_FALSE otherwise.
 */
NvError AesCoreClearUserKey(const NvDdkAes *const pAesClient)
{
    AesHwContext *pAesHwCtxt = NULL;
    NvBool IsSuccess = NV_TRUE;

    NV_ASSERT(pAesClient);

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    // Get the AES H/W context
    NV_ASSERT(pAesClient->pAesCoreEngine);
    pAesHwCtxt = &pAesClient->pAesCoreEngine->AesHwCtxt;

    NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, pAesClient->Engine);

    AesCoreRequestHwAccess();

    // Clear the key and IV
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, pAesClient->Engine, AesHwClearKeyAndIv);
    pAesHwCtxt->ppEngineCaps[pAesClient->Engine]->pAesInterf->AesHwClearKeyAndIv(
        pAesClient->Engine,
        pAesClient->KeySlot,
        pAesHwCtxt);

    AesCoreReleaseHwAccess();

    IsSuccess = AesCoreIsUserKeyCleared(pAesClient->Engine, pAesClient->KeySlot, pAesHwCtxt);
    // Clear dedicated slot wrapped key info in local buffer
    NvOsMemset(gs_pAesCoreEngine->DedicatedSlotKeyInfo[pAesClient->Engine][pAesClient->KeySlot].WrappedKey,
        0,
        NvDdkAesConst_MaxKeyLengthBytes);
    NvOsMemset(gs_pAesCoreEngine->DedicatedSlotKeyInfo[pAesClient->Engine][pAesClient->KeySlot].WrappedIv,
        0,
        AES_RFC_IV_LENGTH_BYTES);

    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return IsSuccess;
}

/**
 * Check the user key clear by encrypting the known data.
 *
 * @param Engine Engine on which encryption need to be performed.
 * @param KeySlot Key slot where encrypt key is located.
 * @param pAesHw Pointer to AES H/W context.
 *
 * @retval NV_TRUE if encryption and decryption is successfully done else NV_FALSE
 */
NvBool
AesCoreIsUserKeyCleared(
    const AesHwEngine Engine,
    const AesHwKeySlot KeySlot,
    AesHwContext *const pAesHwCtxt)
{
    NvError e = NvSuccess;
    AesHwIv ZeroIv;
    NvU32 i;

    // Known Good data
    static NvU8 s_GoldData[NvDdkAesConst_BlockLengthBytes] =
    {
        0x00, 0x01, 0x02, 0x03,
        0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0A, 0x0B,
        0x0C, 0x0D, 0x0E, 0x0F
    };

    // Encrypted data for above known data with Zero key and Zero IV
    static NvU8 s_EncryptDataWithZeroKeyTable[NvDdkAesConst_BlockLengthBytes] =
    {
        0x7A, 0xCA, 0x0F, 0xD9,
        0xBC, 0xD6, 0xEC, 0x7C,
        0x9F, 0x97, 0x46, 0x66,
        0x16, 0xE6, 0xA2, 0x82
    };

    // Encrypted data for above known data with Zero key and Zero IV
    static NvU8 s_EncryptDataWithZeroKeySchedule[NvDdkAesConst_BlockLengthBytes] =
    {
        0x18, 0x9D, 0x19, 0xEA,
        0xDB, 0xA7, 0xE3, 0x0E,
        0xD9, 0x72, 0x80, 0x8F,
        0x3F, 0x2B, 0xA0, 0x30
    };

    NvU8 *pEncryptData;
    NvU8 EncryptBuffer[NvDdkAesConst_BlockLengthBytes];

    NvOsMutexLock(gs_hAesCoreEngineMutex);

    NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, Engine);

    if (pAesHwCtxt->ppEngineCaps[Engine]->IsHwKeySchedGenSupported)
        pEncryptData = s_EncryptDataWithZeroKeyTable;
    else
        pEncryptData = s_EncryptDataWithZeroKeySchedule;

    NvOsMemset(EncryptBuffer, 0, NvDdkAesConst_BlockLengthBytes);
    NvOsMemset(&ZeroIv, 0, sizeof(AesHwIv));

    AesCoreRequestHwAccess();

    // Select Encrypt Key slot
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSelectKeyIvSlot);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSelectKeyIvSlot(Engine, KeySlot, pAesHwCtxt);

    // Set the Zero IV for test data
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwSetIv);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwSetIv(
        Engine,
        KeySlot,
        &ZeroIv,
        pAesHwCtxt));

    // Process the buffer for encryption
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwStartEngine);
    NV_CHECK_ERROR_CLEANUP(pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwStartEngine(
        Engine,
        NvDdkAesConst_BlockLengthBytes,
        s_GoldData,
        NV_TRUE,
        NvDdkAesOperationalMode_Cbc,
        EncryptBuffer,
        pAesHwCtxt));

    // Clear the IV in the engine before we leave
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, Engine, AesHwClearIv);
    pAesHwCtxt->ppEngineCaps[Engine]->pAesInterf->AesHwClearIv(Engine, KeySlot, pAesHwCtxt);

    AesCoreReleaseHwAccess();

    // Clear the DMA buffer before we leave from this operation
    NV_ASSERT(pAesHwCtxt->pDmaVirAddr[Engine]);
    NvOsMemset(pAesHwCtxt->pDmaVirAddr[Engine], 0, AES_HW_DMA_BUFFER_SIZE_BYTES);

    for (i = 0; i < NvDdkAesConst_BlockLengthBytes; i++)
    {
        if (pEncryptData[i] != EncryptBuffer[i])
            goto fail;
    }

    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NV_TRUE;

fail:
    // Clear the DMA buffer before we leave from this operation
    NV_ASSERT(pAesHwCtxt->pDmaVirAddr[Engine]);
    NvOsMemset(pAesHwCtxt->pDmaVirAddr[Engine], 0, AES_HW_DMA_BUFFER_SIZE_BYTES);
    NvOsMutexUnlock(gs_hAesCoreEngineMutex);
    return NV_FALSE;
}

/**
 * Return the AES module capabilities.
 *
 * @param hRmDevice Rm Device handle.
 * @param ppCaps Pointer to pointer to capbilities structure.
 *
 * @retval NvSuccess if capabilities could be returned successfully.
 *
 */
NvError AesCoreGetCapabilities(const NvRmDeviceHandle hRmDevice, AesHwCapabilities **const ppCaps)
{
    NvError e = NvSuccess;

    static AesHwCapabilities s_Caps1;
    static AesHwCapabilities s_Caps2;

    static NvRmModuleCapability s_EngineA_Caps[] =
    {
        {1, 0, 0, &s_Caps1},
        {1, 1, 0, &s_Caps1},
        {1, 2, 0, &s_Caps2},
        {1, 3, 0, &s_Caps2}
    };

    static NvRmModuleCapability s_engineB_caps[] =
    {
        {1, 0, 0, &s_Caps1},
        {1, 1, 0, &s_Caps2},
        {1, 2, 0, &s_Caps2}
    };

    NV_ASSERT(hRmDevice);
    NV_ASSERT(ppCaps);

    NvOsMemset(&s_Caps1, 0, sizeof(s_Caps1));
    NvOsMemset(&s_Caps2, 0, sizeof(s_Caps2));

    s_Caps1.IsHashSupported = NV_FALSE;
    s_Caps1.IsHwKeySchedGenSupported = NV_FALSE;
    s_Caps1.MinBufferAlignment = 16;
    s_Caps1.MinKeyTableAlignment = 256;
    s_Caps1.NumSlotsSupported = AesHwKeySlot_Num;
    s_Caps1.pAesInterf = NULL;

    s_Caps2.IsHashSupported = NV_FALSE;
    s_Caps2.IsHwKeySchedGenSupported = NV_TRUE;
    s_Caps2.HwKeySchedLengthBytes = 80;
    s_Caps2.MinBufferAlignment = 16;
    s_Caps2.MinKeyTableAlignment = 4;
    s_Caps2.NumSlotsSupported = AesHwKeySlot_NumExt;
    s_Caps2.pAesInterf = NULL;

    NV_CHECK_ERROR_CLEANUP(NvRmModuleGetCapabilities(
        hRmDevice,
        NvRmModuleID_Vde,
        s_EngineA_Caps,
        NV_ARRAY_SIZE(s_EngineA_Caps),
        (void **)&(ppCaps[AesHwEngine_A])));

    if (ppCaps[AesHwEngine_A] == &s_Caps2)
    {
        if (NULL == s_Caps2.pAesInterf)
        {
            s_Caps2.pAesInterf = NvOsAlloc(sizeof(AesHwInterface));
            if (NULL == s_Caps2.pAesInterf)
                goto fail;
            NvAesIntfAp20GetHwInterface(s_Caps2.pAesInterf);
        }
    }

    NV_CHECK_ERROR_CLEANUP(NvRmModuleGetCapabilities(
        hRmDevice,
        NvRmModuleID_BseA,
        s_engineB_caps,
        NV_ARRAY_SIZE(s_engineB_caps),
        (void **)&(ppCaps[AesHwEngine_B])));

    if (ppCaps[AesHwEngine_B] == &s_Caps2)
    {
        if (NULL == s_Caps2.pAesInterf)
        {
            s_Caps2.pAesInterf = NvOsAlloc(sizeof(AesHwInterface));
            if (NULL == s_Caps2.pAesInterf)
                goto fail;
            NvAesIntfAp20GetHwInterface(s_Caps2.pAesInterf);
        }
    }

fail:
    return e;
}

/**
 * Encrypt/Decrypt the given input buffer using Electronic CodeBook (ECB) mode.
 * Prerequisite:It is caller responsibility to acquire hardware lock before using this function.
 *
 * @param pAesCoreEngine Pointer to AES core engine.
 * @param pInputBuffer Pointer to input bufffer.
 * @param BufSize Buffer size.
 * @param IsEncrypt If set to NV_TRUE, encrypt the input buffer else decrypt it.
 * @param pOutputBuffer Pointer to output buffer.
 *
 * @retval NvSuccess if successfully completed.
 */
NvError
AesCoreEcbProcessBuffer(
    const AesCoreEngine *const pAesCoreEngine,
    const NvU8 *const pInputBuffer,
    const NvU32 BufSize,
    const NvBool IsEncrypt,
    NvU8 *const pOutputBuffer)
{
    NvError e = NvSuccess;
    AesHwEngine SskEngine;
    AesHwKeySlot SskKeySlot;
    AesHwContext *pAesHwCtxt;

    NV_ASSERT(pAesCoreEngine);
    NV_ASSERT(pInputBuffer);
    NV_ASSERT(pOutputBuffer);

    // Get the AES H/W context
    pAesHwCtxt = (AesHwContext *)&pAesCoreEngine->AesHwCtxt;

    SskEngine = pAesCoreEngine->SskEngine[0];
    SskKeySlot = (IsEncrypt ? pAesCoreEngine->SskEncryptSlot : pAesCoreEngine->SskDecryptSlot);

    NVDDK_AES_CHECK_INTERFACE(pAesHwCtxt, SskEngine);

    // Select SSK key for processing
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, SskEngine, AesHwSelectKeyIvSlot);
    pAesHwCtxt->ppEngineCaps[SskEngine]->pAesInterf->AesHwSelectKeyIvSlot(SskEngine, SskKeySlot, pAesHwCtxt);

    // Process the buffer
    NVDDK_AES_CHECK_INTERFACE_FUNC(pAesHwCtxt, SskEngine, AesHwStartEngine);
    e = pAesHwCtxt->ppEngineCaps[SskEngine]->pAesInterf->AesHwStartEngine(
        SskEngine,
        BufSize,
        pInputBuffer,
        IsEncrypt,
        NvDdkAesOperationalMode_Ecb,
        pOutputBuffer,
        pAesHwCtxt);

    // Clear the DMA buffer
    NV_ASSERT(pAesHwCtxt->pDmaVirAddr[SskEngine]);
    NvOsMemset(pAesHwCtxt->pDmaVirAddr[SskEngine], 0, AES_HW_DMA_BUFFER_SIZE_BYTES);

    return e;
}

/**
 * Wrap the given key data using RFC 3394 algoritham.
 *
 * Follwing is RFC3394 key wrap algoritham.
 *     Inputs:  Plaintext, n 64-bit values {P1, P2, ..., Pn}, and
 *             Key, K (the KEK).
 *    Outputs: Ciphertext, (n+1) 64-bit values {C0, C1, ..., Cn}.

 *    1) Initialize variables.
 *        Set A = IV, an initial value (see 2.2.3)
 *        For i = 1 to n
 *            R[i] = P[i]
 *    2) Calculate intermediate values.
 *        For j = 0 to 5
 *            For i=1 to n
 *                B = AES(K, A | R[i])
 *                A = MSB(64, B) ^ t where t = (n*j)+i
 *                R[i] = LSB(64, B)
 *    3) Output the results.
 *        Set C[0] = A
 *        For i = 1 to n
 *            C[i] = R[i]
 *
 * @param pAesCoreEngine Pointer to AES core engine.
 * @param pOrgKey Pointer to Original Key.
 * @param pOrgIv Pointer to Original Iv which is used in RFC3394 algorithm.
 * @param pWrappedKey Pointer to wrapped key.
 * @param pWrappedIv Pointer to wrapped Iv.
 *
 */
NvError
AesCoreWrapKey(
    const AesCoreEngine *const pAesCoreEngine,
    const NvU8 *const pOrgKey,
    const NvU8 *const pOrgIv,
    NvU8 *const pWrappedKey,
    NvU8 *const pWrappedIv)
{
    NvError e = NvSuccess;
    NvU8 n = AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY, i, j, k, t;
    NvU8 *A, *B;
    NvU8 **R;
    const AesHwContext *pAesHwCtxt;

    NV_ASSERT(pAesCoreEngine);
    NV_ASSERT(pOrgKey);
    NV_ASSERT(pOrgIv);
    NV_ASSERT(pWrappedKey);
    NV_ASSERT(pWrappedIv);

    // Get the AES H/W context
    pAesHwCtxt = &pAesCoreEngine->AesHwCtxt;

    // Local buffers which are used for processing should be in IRAM.
    // Use KeyTable buffer which is in IRAM.
    // The local variables should be of following format and sizes.
    // NvU8 A[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES];
    // NvU8 B[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES * AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY];
    // NvU8 R[AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY][AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES];

    A = pAesHwCtxt->pKeyTableVirAddr[0];
    B = A + AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES;

    R = (NvU8 **)(B + (AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY * AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES));
    for(i = 0; i < AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY; i++)
    {
        R[i] = ((B + (AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY * AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES)) +
            (AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES * sizeof(NvU8 *)) +
            (i * AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES));
    }

    // Set A = IV
    for (i = 0; i < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; i++)
        A[i] =  pOrgIv[i];

    //For i = 1 to n 	R[i] = P[i]
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; j++)
            R[i][j] = pOrgKey[j + (i *AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES)];
    }

    // Calculate intermediate values.
    //  For j = 0 to 5
    //      For i=1 to n
    //          B = AES(K, A | R[i])
    //          A = MSB(64, B) ^ t where t = (n*j)+i
    //          R[i] = LSB(64, B)
    for (j = 0; j <= 5; j++)
    {
        for (i = 0; i < n; i++)
        {
            for (k = 0; k < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; k++)
            {
                B[k] = A[k];
                B[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES+k] = R[i][k];
            }
            NV_CHECK_ERROR(AesCoreEcbProcessBuffer(pAesCoreEngine, B, NvDdkAesKeySize_128Bit, NV_TRUE, B));
            for (k = 0; k < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; k++)
            {
                A[k] =  B[k];
                R[i][k] = B[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES + k];
            }
            t = (n * j) + (i+1);
            A[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES-1] ^=  t;
        }
    }

    // Output the results.
    // Set C[0] = A
    // For i = 1 to n
    //    C[i] = R[i]
    for (k = 0; k < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; k++) {
        pWrappedIv[k] = A[k];
    }
    for (i = 0; i < n; i++)
    {
        for (k = 0; k < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; k++)
        {
            pWrappedKey[(AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES*i) + k] = R[i][k];
        }
    }

    // Clear the buffers.
    NvOsMemset(pAesHwCtxt->pKeyTableVirAddr[0], 0, pAesHwCtxt->KeyTableSize[0]);
    return e;
}

/**
 * UnWrapKey the given key data using RFC 3394 algorithm.
 *
 * Follwing is RFC3394 key unwrap algoritham.
 *  Inputs:  Ciphertext, (n+1) 64-bit values {C0, C1, ..., Cn}, and
 *             Key, K (the KEK).
 *    Outputs: Plaintext, n 64-bit values {P0, P1, K, Pn}.
 *
 *    1) Initialize variables.
 *        Set A = C[0]
 *        For i = 1 to n
 *            R[i] = C[i]
 *    2) Compute intermediate values.
 *        For j = 5 to 0
 *            For i = n to 1
 *                B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i
 *                A = MSB(64, B)
 *                R[i] = LSB(64, B)
 *    3) Output results.
 *    If A is an appropriate initial value (see 2.2.3),
 *    Then
 *        For i = 1 to n
 *            P[i] = R[i]
 *    Else
 *        Return an error
 *
 * @param pAesCoreEngine Pointer to AES core engine.
 * @param pWrappedKey Pointer to wrapped key
 * @param pWrappedIv Pointer to wrapped Iv
 * @param pOrgKey Pointer to Original Key.
 * @param pOrgIv Pointer to Original Iv which is used in RFC3394 algorithm.
 *
 */
NvError
AesCoreUnWrapKey(
    const AesCoreEngine *const pAesCoreEngine,
    const NvU8 *const pWrappedKey,
    const NvU8 *const pWrappedIv,
    NvU8 *const pOrgKey,
    NvU8 *const pOrgIv)
{
    NvError e = NvSuccess;
    NvS32 n = AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY, i, j, k, t;
    NvU8 *A, *B;
    NvU8 **R;
    const AesHwContext *pAesHwCtxt;

    NV_ASSERT(pAesCoreEngine);
    NV_ASSERT(pWrappedKey);
    NV_ASSERT(pWrappedIv);
    NV_ASSERT(pOrgKey);
    NV_ASSERT(pOrgIv);

    // Get the AES H/W context
    pAesHwCtxt = &pAesCoreEngine->AesHwCtxt;

    // Local buffers which are used for processing should in IRAM.
    // Use KeyTable buffer which is in IRAM.
    // The local variables should be of following format and sizes.
    // NvU8 A[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES];
    // NvU8 B[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES * AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY];
    // NvU8 R[AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY][AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES];

    A = pAesHwCtxt->pKeyTableVirAddr[0];
    B = A + AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES;
    R = (NvU8 **)(B + (AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY * AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES));
    for(i = 0; i < AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY; i++)
    {
        R[i] = ((B + (AES_RFC_3394_NUM_OF_BLOCKS_FOR_128BIT_KEY * AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES)) +
            (AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES * sizeof(NvU8 *)) +
            (i * AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES));
    }

    // Set A = C[0]
    for (i = 0; i < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; i++)
        A[i] = pWrappedIv[i];

    // For i = 1 to n R[i] = C[i]
    for (i = 0; i < n; i++) {
        for (j = 0; j < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; j++)
            R[i][j] = pWrappedKey[j + (i *AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES)];
    }

    // Compute intermediate values.
    //   For j = 5 to 0
    //       For i = n to 1
    //           B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i
    //           A = MSB(64, B)
    //           R[i] = LSB(64, B)
    for (j = 5; j >= 0; j--)
    {
        for (i = n; i > 0; i--)
        {
            t = (n * j) + (i);
            A[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES-1] ^=  t;
            for (k = 0; k < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; k++)
            {
                B[k] = A[k];
                B[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES+k] = R[i-1][k];
            }
            NV_CHECK_ERROR(AesCoreEcbProcessBuffer(pAesCoreEngine, B, NvDdkAesKeySize_128Bit, NV_FALSE, B));
            for (k = 0; k < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; k++)
            {
                A[k] =  B[k];
                R[i-1][k] = B[AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES + k];
            }
        }
    }

    // Output results.
    // For i = 1 to n
    // P[i] = R[i]
    for (k = 0; k < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; k++)
    {
        pOrgIv[k] = A[k];
    }

    for (i = 0; i < n; i++)
    {
        for (k = 0; k < AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES; k++)
        {
            pOrgKey[(AES_RFC_3394_KEY_WRAP_BLOCK_SIZE_BYTES*i) + k] = R[i][k];
        }
    }

    // Clear the buffers.
    NvOsMemset(pAesHwCtxt->pKeyTableVirAddr[0], 0, pAesHwCtxt->KeyTableSize[0]);
    return e;
}