wolfssl-sys 4.0.0

System bindings for WolfSSL
Documentation
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
/* caam_driver.c
 *
 * Copyright (C) 2006-2026 wolfSSL Inc.
 *
 * This file is part of wolfSSL.
 *
 * wolfSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * wolfSSL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
 */

#ifdef HAVE_CONFIG_H
    #include <config.h>
#endif

#if (defined(__INTEGRITY) || defined(INTEGRITY)) || \
    (defined(__QNX__) || defined(__QNXNTO__))

#if defined(__QNX__) || defined(__QNXNTO__)
    #include <sys/mman.h>
    #ifdef __aarch64__
        #include <aarch64/inout.h>
    #else
        #include <hw/inout.h>
    #endif
    #include <sys/iofunc.h>
    #include <sys/neutrino.h>

    #include <wolfssl/wolfcrypt/port/caam/caam_qnx.h>
#endif

#include <wolfssl/wolfcrypt/port/caam/caam_driver.h>
#include <wolfssl/wolfcrypt/port/caam/caam_error.h>

#include <string.h> /* for memcpy / memset */

struct JobRing {
    /* base address for job ring */
    CAAM_ADDRESS BaseAddr;

    /* physical address */
    CAAM_ADDRESS JobIn;
    CAAM_ADDRESS JobOut;
    CAAM_ADDRESS Desc;

    /* virtual address */
    void* VirtualIn;
    void* VirtualOut;
    void* VirtualDesc;
    Value   page;    /* page allocation for descriptor to use */
    CAAM_MUTEX jr_lock;
};

struct CAAM_DEVICE {
#if defined(__INTEGRITY) || defined(INTEGRITY)
    struct IODeviceVectorStruct caamVector;
    struct IODescriptorStruct   IODescriptorArray[BUFFER_COUNT];
    struct DescStruct           DescArray[DESC_COUNT];
    volatile Value              InterruptStatus;
    CALL                        HandleInterruptCall;
#endif
    struct JobRing ring;
    CAAM_ADDRESS   baseAddr;     /* base address for CAAM */
    unsigned short vrs;          /* era version number of CAAM */
};

#define DRIVER_NAME "wolfSSL_CAAM_Driver"

static struct CAAM_DEVICE caam;

/* function declarations */
Error caamAddJob(DESCSTRUCT* desc);
Error caamDoJob(DESCSTRUCT* desc);



/******************************************************************************
  Internal CAAM Job Ring and partition functions
  ****************************************************************************/

#ifdef CAAM_DEBUG_MODE
/* runs a descriptor in debug mode */
static Error caamDebugDesc(struct DescStruct* desc)
{
    int z;
    int sz;
    unsigned int flag = 0x20000000;

    /* clear and set desc size */
    sz = desc->desc[0] & 0x0000007F;
    CAAM_WRITE(CAAM_DECORR, 1); /* ask for DECO permissions */
    printf("CAAM_DECORR = 0x%08X\n", CAAM_READ(CAAM_DECORR));
    printf("STATUS : 0x%08X\n", CAAM_READ(CAAM_DOOPSTA_MS));
    printf("CAAM STATUS : 0x%08X\n", CAAM_READ(0x0FD4));
    printf("DECO DRG (bit 32 is valid -- running) : 0x%08X\n", CAAM_READ(0x8E04));

    printf("Descriptor input :\n");
    /* write descriptor into descriptor buffer */
    for (z = 0; z < sz; z = z + 1) {
        CAAM_WRITE(CAAM_DODESB + (z*4), desc->desc[z]);
        printf("\t0x%08X\n", desc->desc[z]);
    }
    printf("\n");

    printf("command size = %d\n", sz);
    if (sz > 4) {
        flag |= 0x10000000;
    }

    CAAM_WRITE(CAAM_DODAR+4, desc->caam->ring.Desc);
    /* set WHL bit since we loaded the entire descriptor */
    CAAM_WRITE(CAAM_DOJQCR_MS, flag);

    printf("CAAM STATUS : 0x%08X\n", CAAM_READ(0x0FD4));
    printf("DECO DRG (bit 32 is valid -- running) : 0x%08X\n", CAAM_READ(0x8E04));

    /* DECO buffer */
    printf("DECO BUFFER [0x%08X]:\n", CAAM_READ(CAAM_DODAR+4));
    printf("\tSTATUS : 0x%08X\n", CAAM_READ(CAAM_DOOPSTA_MS));
    printf("\tJRSTAR_JR0 : 0x%08X\n", CAAM_READ(0x1044));
    for (z = 0; z < sz; z = z + 1) {
        printf("\t0x%08X\n", CAAM_READ(CAAM_DODESB + (z*4)));
    }


    /* D0JQCR_LS */
    printf("Next command to be executed = 0x%08X\n", CAAM_READ(0x8804));
    printf("Desc          = 0x%08X\n", desc->caam->ring.Desc);


    /* DECO buffer */
    printf("DECO BUFFER [0x%08X]:\n", CAAM_READ(CAAM_DODAR+4));
    printf("\tSTATUS : 0x%08X\n", CAAM_READ(CAAM_DOOPSTA_MS));
    printf("\tJRSTAR_JR0 : 0x%08X\n", CAAM_READ(0x1044));
    for (z = 0; z < sz; z = z + 1) {
        printf("\t0x%08X\n", CAAM_READ(CAAM_DODESB + (z*4)));
    }

    printf("Next command to be executed = 0x%08X\n", CAAM_READ(0x8804));
    printf("CAAM STATUS : 0x%08X\n", CAAM_READ(0x0FD4));
    while ((CAAM_READ(0x8E04) & 0x80000000U) != 0U) {
        printf("DECO DRG (bit 32 is valid -- running) : 0x%08X\n",
                CAAM_READ(0x8E04));
        sleep(1);
    }
    CAAM_WRITE(CAAM_DECORR, 0); /* free DECO */
    printf("done with debug job\n");
    return Success;
}
#endif /* CAAM_DEBUG_MODE */


#if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
static void printSecureMemoryInfo()
{
    unsigned int SMVID_MS, SMVID_LS;

    printf("SMSTA = 0x%08X\n", CAAM_READ(caam.ring.BaseAddr + 0x0FB4));
    printf("SMPO  = 0x%08X\n", CAAM_READ(caam.ring.BaseAddr + CAAM_SM_SMPO));
    SMVID_MS = CAAM_READ(caam.ring.BaseAddr + CAAM_SM_SMVID_MS);
    SMVID_LS = CAAM_READ(caam.ring.BaseAddr + CAAM_SM_SMVID_LS);
    printf("\tNumber Partitions : %d\n", ((SMVID_MS >> 12) & 0xFU));
    printf("\tNumber Pages : %d\n", (SMVID_MS & 0x3FFU));
    printf("\tPage Size : 2^%d\n", ((SMVID_LS >> 16) & 0x7U));
}
#endif

/* flush job ring and reset */
static Error caamReset(void)
{
    int t = 100000; /* time out counter for flushing job ring */

    /* make sure interrupts are masked in JRCFGR0_LS register */
    CAAM_WRITE(caam.ring.BaseAddr + JRCFGR_JR,
        CAAM_READ(caam.ring.BaseAddr + JRCFGR_JR) | 1);

    /* flush and reset job rings using JRCR0 register */
    CAAM_WRITE(caam.ring.BaseAddr + JRCR_JR, 1);

    /* check register JRINTR for if halt is in progress */
    while (t > 0 && ((CAAM_READ(caam.ring.BaseAddr + JRINTR_JR) & 0x4)
        == 0x4)) {
        t = t - 1;
    }
    if (t == 0) {
        /*unrecoverable failure, the job ring is locked, up hard reset needed*/
        return -1;
    }

    /* now that flush has been done restart the job ring */
    t = 100000;
    CAAM_WRITE(caam.ring.BaseAddr + JRCR_JR, 1);
    while (t > 0 && ((CAAM_READ(caam.ring.BaseAddr + JRCR_JR) & 1) == 1)) {
        t = t - 1;
    }
    if (t == 0) {
        /*unrecoverable failure, reset bit did not return to 0 */
        return -1;
    }

    if (caam.vrs < 9) {
        /* reset most registers and state machines in CAAM using MCFGR register
           also reset DMA */
        CAAM_WRITE(caam.baseAddr + CAAM_RSTA, 0x90000000);

        /* DDR */
        CAAM_WRITE(caam.baseAddr + CAAM_DRR, 1);
    }

    return Success;
}


/* free the page and dealloc */
static Error caamFreePage(unsigned int page)
{
    /* owns the page can dealloc it */
    CAAM_WRITE(caam.ring.BaseAddr + CAAM_SM_CMD, (page << 16U) | 0x2U);
    while ((CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS) & 0x00004000) > 0 &&
        (CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS) & 0x00003000)  == 0) {
        CAAM_CPU_CHILL();
    }
    if ((CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS) & 0x00003000)  > 0) {
        /* error while deallocating page */
        WOLFSSL_MSG("error while deallocating page");
        return MemoryMapMayNotBeEmpty; /* PSP set on page or is unavailable */
    }
    WOLFSSL_MSG("free'd page");
    return Success;
}

/* free the partition and dealloc */
Error caamFreePart(unsigned int part)
{
    unsigned int status;

    #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
    printf("freeing partition %d\n", part);
    #endif
    CAAM_WRITE(caam.ring.BaseAddr + CAAM_SM_CMD, (part << 8U) | 0x3U);

    status = CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS);
    while (((status & 0x00004000U) > 0U) && ((status & 0x00003000U) == 0U)) {
        CAAM_CPU_CHILL();
        status = CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS);
    }

    if (((status & 0x00003000U) > 0U) || ((status & 0x0000C000U) > 0U)) {
        /* error while deallocating page */
        WOLFSSL_MSG("error while deallocating partition");
        return MemoryMapMayNotBeEmpty; /* PSP set on page or is unavailable */
    }
    WOLFSSL_MSG("free'd partition");
    return Success;
}


/* find all partitions we own and free them */
static Error caamFreeAllPart()
{
    unsigned int SMPO;
    unsigned int i;

    WOLFSSL_MSG("Free all partitions");
    SMPO = CAAM_READ(caam.ring.BaseAddr + CAAM_SM_SMPO);
    for (i = 0; i < 15U; i = i + 1U) {
        if ((SMPO & (0x3U << (i * 2U))) == (0x3U << (i * 2U))) {
            caamFreePart(i);
        }
    }

    return 0;
}


/* search through the partitions to find an unused one
 * returns negative value on failure, on success returns 0 or greater
 */
int caamFindUnusedPartition()
{
    unsigned int SMPO;
    unsigned int i;
    int ret = -1;

    SMPO = CAAM_READ(caam.ring.BaseAddr + CAAM_SM_SMPO);
    for (i = 0; i < 15U; i = i + 1) {
        if ((SMPO & (0x3U << (i * 2U))) == 0U) {
            ret = (int)i;
            break;
        }
    }

    return ret;
}


/* flag contains how the partition is set i.e CSP flag and read/write access
 *      it also contains if locked
 */
static Error caamCreatePartition(unsigned int* page, unsigned int par,
        unsigned int flag)
{
    int testPage;
    unsigned int status;

    /* check ownership of partition */
    status = CAAM_READ(caam.ring.BaseAddr + CAAM_SM_SMPO);
    if ((status & (0x3U << (par * 2))) > 0) {
        if ((status & (0x3U << (par * 2))) == (0x3U << (par * 2))) {
            WOLFSSL_MSG("we own this partition!");
        }
        else {
            return MemoryMapMayNotBeEmpty;
        }
    }
    CAAM_WRITE(caam.ring.BaseAddr + CAAM_SMAPR + (par * 16), flag);

    /* dealloc page if we own it */
    for (testPage = 0; testPage < 16; testPage++) {
        CAAM_WRITE(caam.ring.BaseAddr + CAAM_SM_CMD, (testPage << 16) | 0x5);
        while ((CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS) & 0x00004000) > 0
            && (CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS) & 0x00003000)
            == 0) {
            CAAM_CPU_CHILL();
        }
        if ((CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS) & 0x000000C0) ==
            0xC0) {
            if (caamFreePage(testPage) != Success) {
                continue;
            }
        }
        else if ((CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS) & 0x000000C0)
            == 0x00) {
            WOLFSSL_MSG("testPage available and un-owned");
        }
        else {
            WOLFSSL_MSG("we don't own the testPage...");
            continue;
        }

        CAAM_WRITE(caam.ring.BaseAddr + CAAM_SM_CMD, (testPage << 16) |
            (par << 8) | 0x1);
        /* wait for alloc cmd to complete */
        while ((CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS) & 0x00004000) > 0 &&
           (CAAM_READ(caam.ring.BaseAddr + CAAM_SM_STATUS) & 0x00003000)  == 0) {
            CAAM_CPU_CHILL();
        }
        break;
    }
    if (testPage == 16)
        return -1;
    *page=testPage;

    return Success;
}


/* return a partitions physical address on success, returns 0 on fail */
CAAM_ADDRESS caamGetPartition(unsigned int part, int partSz, unsigned int flag)
{
    int err;

    (void)flag; /* flag is for future changes to flag passed when creating */

    /* create and claim the partition */
    err = caamCreatePartition(&part, part, CAAM_SM_CSP | CAAM_SM_SMAP_LOCK |
                CAAM_SM_CSP | CAAM_SM_ALL_RW);
    if (err != Success) {
        WOLFSSL_MSG("Error creating partitions for secure ecc key");
        return 0;
    }

    return (CAAM_ADDRESS)(CAAM_PAGE + (part << 12));
}


/* Gets the status of a job. Returns CAAM_WAITING if no output jobs ready to be
 * read.
 * If no jobs are done then return CAAM_WAITING
 * If jobs are done but does not match desc then return NoActivityReady
 * Status holds the error values if any */
static Error caamGetJob(struct CAAM_DEVICE* dev, unsigned int* status)
{
    CAAM_ADDRESS baseAddr;
    unsigned int reg;
    if (status) {
        *status = 0;
    }

    baseAddr = caam.ring.BaseAddr;

#ifdef CAAM_DEBUG_MODE
    (void)dev;
    return Success;
#endif

    /* Check number of done jobs in output list */
    reg = CAAM_READ(baseAddr + CAAM_ORJAR);
#if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
    printf("number of jobs in output list = 0x%08X\n", reg);
#endif
    if ((reg & 0x000003FF) > 0) {
        unsigned int *pt;

        if (CAAM_ADR_SYNC(caam.ring.VirtualOut, (2 * CAAM_JOBRING_SIZE *
                        sizeof(unsigned int))) != 0) {
            return -1;
        }

        /* sanity check on job out */
        pt = (unsigned int*)caam.ring.VirtualOut;
        if (pt[0] != (unsigned int)caam.ring.Desc) {
        #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
            printf("Job found %08X does not match expected job %08X\n",
                    pt[0], (unsigned int)caam.ring.Desc);
        #endif
            return -1;
        }
        *status = pt[1];

        /* increment jobs removed */
    #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
        printf("\tjob 0x%08X done - result 0x%08X\n", pt[0], pt[1]);
        printf("removing job from list\n");
        fflush(stdout);
    #endif
        CAAM_WRITE(baseAddr + CAAM_ORJRR, 1);
    }
    else {
        /* check if the CAAM is idle and not processing any descriptors */
        if ((CAAM_READ(baseAddr + 0x0FD4) & 0x00000002) == 2 /* idle */
        && (CAAM_READ(baseAddr + 0x0FD4) & 0x00000001) == 0) {
            WOLFSSL_MSG("caam is idle.....");
            return NoActivityReady;
        }
        return CAAM_WAITING;
    }
    (void)dev;

    CAAM_WRITE(baseAddr + JRCFGR_JR, 0);
    if (*status == 0) {
        return Success;
    }
    return Failure;
}


/* instantiate RNG and create JDKEK, TDKEK, and TDSK key */
#define WC_RNG_START_SIZE 6
static unsigned int wc_rng_start[WC_RNG_START_SIZE] = {
    CAAM_HEAD | 0x00000006,
    CAAM_OP | CAAM_CLASS1 | CAAM_RNG | 0x00000004, /* Instantiate RNG handle 0
                                                      with TRNG */
    CAAM_JUMP | 0x02000001,  /* wait for Class1 RNG and jump to next cmd */
    CAAM_LOAD | 0x00880004,  /* Load to clear written register */
    0x00000001, /* reset done interrupt */
    CAAM_OP | CAAM_CLASS1 | CAAM_RNG | 0x00001000   /* Generate secure keys */
};


/* Initialize CAAM RNG
 * returns 0 on success */
int caamInitRng(struct CAAM_DEVICE* dev);
int caamInitRng(struct CAAM_DEVICE* dev)
{
    DESCSTRUCT desc;
    unsigned int reg, entropy_delay;
    int ret = 0, i;

    /* set up the job description for RNG initialization */
    memset(&desc, 0, sizeof(DESCSTRUCT));
    desc.desc[desc.idx++] = CAAM_HEAD; /* later will put size to header*/
    for (i = 1; i < WC_RNG_START_SIZE; i++) {
        desc.desc[desc.idx++] = wc_rng_start[i];
    }
    desc.caam = dev;

    /* Attempt to start the RNG, first trying the fastest entropy delay value
     * and increasing it after each failed attempt until either a success is hit
     * or the max delay value is.
     */
    for (entropy_delay = CAAM_ENT_DLY; entropy_delay <= CAAM_ENT_DLY_MAX;
            entropy_delay = entropy_delay + CAAM_ENT_DLY_INCREMENT) {

        /* Set up use of the TRNG for seeding wolfSSL HASH-DRBG */
        /* check out the status and see if already setup */
        CAAM_WRITE(caam.baseAddr + CAAM_RTMCTL, CAAM_PRGM);
        CAAM_WRITE(caam.baseAddr + CAAM_RTMCTL,
                CAAM_READ(caam.baseAddr + CAAM_RTMCTL) | CAAM_RTMCTL_RESET);

        /* Set up reading from TRNG */
        CAAM_WRITE(caam.baseAddr + CAAM_RTMCTL,
                CAAM_READ(caam.baseAddr + CAAM_RTMCTL) | CAAM_TRNG);

        /* Set up delay for TRNG
         * Shift left with RTSDCTL because 0-15 is for sample number
         * Also setting the max and min frequencies */
        CAAM_WRITE(caam.baseAddr + CAAM_RTSDCTL,
                (entropy_delay << 16) | CAAM_ENT_SAMPLE);
        CAAM_WRITE(caam.baseAddr + CAAM_RTFRQMIN,
                entropy_delay >> CAAM_ENT_MINSHIFT);
        CAAM_WRITE(caam.baseAddr + CAAM_RTFRQMAX,
                entropy_delay << CAAM_ENT_MAXSHIFT);

    #ifdef WOLFSSL_CAAM_PRINT
        printf("Attempt with entropy delay set to %d\n", entropy_delay);
        printf("Min delay of %d and max of %d\n",
                entropy_delay >> CAAM_ENT_MINSHIFT,
                entropy_delay << CAAM_ENT_MAXSHIFT);
    #endif

        /* Set back to run mode and clear RTMCL error bit */
        reg = CAAM_READ(caam.baseAddr + CAAM_RTMCTL) & (~CAAM_PRGM);
        CAAM_WRITE(caam.baseAddr + CAAM_RTMCTL, reg);
        reg = CAAM_READ(caam.baseAddr + CAAM_RTMCTL);
        reg |= CAAM_CTLERR;
        CAAM_WRITE(caam.baseAddr + CAAM_RTMCTL, reg);

        /* check out the status and see if already setup */
        reg = CAAM_READ(caam.baseAddr + CAAM_RDSTA);
        if (((reg >> 16) & 0xF) > 0) {
            WOLFSSL_MSG("RNG is in error state, resetting");
            caamReset();
        }

        if (reg & (1U << 30)) {
            WOLFSSL_MSG("JKDKEK rng was setup using a non deterministic key");
            return 0;
        }

        do {
            ret = caamDoJob(&desc);
        } while (ret == CAAM_WAITING);

        /* if this entropy delay frequency succeeded then break out, otherwise
         * try again with increasing the delay value */
        if (ret == Success) {
            WOLFSSL_MSG("Init RNG success");
            break;
        }
        WOLFSSL_MSG("Increasing entropy delay");
    }

    if (ret == Success)
        return 0;
    return -1;
}


/* Take in a descriptor and add it to the job list */
Error caamAddJob(DESCSTRUCT* desc)
{
    CAAM_ADDRESS baseAddr;

    /* clear and set desc size */
    desc->desc[0] &= 0xFFFFFF80;
    desc->desc[0] += desc->idx + (desc->startIdx << 16);

    CAAM_LOCK_MUTEX(&caam.ring.jr_lock);
    baseAddr = caam.ring.BaseAddr;

    /* check input slot is available and then add */
    if (CAAM_READ(baseAddr + CAAM_IRSAR_JR) > 0) {
        int i;
        unsigned int *pt;

        pt = (unsigned int*)caam.ring.VirtualDesc;
    #if defined(WOLFSSL_CAAM_PRINT)
        printf("Number of input ring slots available is %d\n",
            CAAM_READ(baseAddr + CAAM_IRSAR_JR));
        printf("Doing Job :\n");
    #endif
        for (i = 0; i < desc->idx; i = i + 1) {
            pt[i] = desc->desc[i];
    #if defined(WOLFSSL_CAAM_PRINT)
            printf("\tCMD %02d [%p] = 0x%08X\n", i+1, pt + i,
                  desc->desc[i]);
    #endif
        }

        pt    = (unsigned int*)caam.ring.VirtualIn;
        pt[0] = (unsigned int)caam.ring.Desc;

        /* Sync both the virtual in and the descriptor */
        if (CAAM_ADR_SYNC(caam.ring.VirtualIn,
                    (CAAM_JOBRING_SIZE * sizeof(unsigned int)) +
                    (desc->idx * sizeof(unsigned int))) != 0) {
            CAAM_UNLOCK_MUTEX(&caam.ring.jr_lock);
            return -1;
        }

    #ifdef CAAM_DEBUG_MODE
        caamDebugDesc(desc);
    #else
        #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
        printf("started job 0x%08X done\n", (unsigned int)caam.ring.Desc);
        #endif
        CAAM_WRITE(baseAddr + CAAM_IRJAR0, 0x00000001);
    #endif
    }
    else {
        CAAM_UNLOCK_MUTEX(&caam.ring.jr_lock);
        return CAAM_WAITING;
    }
    CAAM_UNLOCK_MUTEX(&caam.ring.jr_lock);
    return Success;
}


/* Synchronous job completion, add it to job queue and wait till finished */
Error caamDoJob(DESCSTRUCT* desc)
{
    Error ret;
    unsigned int status;

    ret = caamAddJob(desc);
    if (ret != Success) {
        return ret;
    }

    do {
        ret = caamGetJob(desc->caam, &status);
        CAAM_CPU_CHILL();
    } while (ret == CAAM_WAITING);

    #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
    printf("job status = 0x%08X, ret = %d\n", status, ret);
    #endif

    /* try to reset after error */
    if (status != 0 || ret != Success) {
        /* consider any job ring errors as fatal, and try reset */
        if (caamParseJRError(CAAM_READ(caam.ring.BaseAddr + JRINTR_JR)) != 0) {
            caamReset();
        }
        caamParseError(status);
        return ret;
    }

    return Success;
}


/******************************************************************************
  CAAM Blob Operations
  ****************************************************************************/

/* limit on size due to size of job ring being 64 unsigned int's */
int caamBlob(DESCSTRUCT* desc)
{
    void *vaddrOut, *vaddr, *keymod;
    Error err;
    unsigned int keyType = 0x00000C08; /* default red */
    unsigned int i = 0;
    int inputSz;
    int outputSz;

    if (desc->idx + 3 > MAX_DESC_SZ) {
        return Failure;
    }

    /* doing black blobs */
    if (desc->state) {
        WOLFSSL_MSG("making a black blob");
        keyType = 0x00000010;
    }

    desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS2 | keyType);

    /* add key modifier */
    keymod = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(keymod, desc->buf[i].dataSz);
    i++;

    inputSz = desc->buf[i].dataSz;
    if (desc->state && (desc->type == CAAM_BLOB_ENCAP)) {
        /* black keys with CCM have mac at the end */
        inputSz += BLACK_KEY_MAC_SZ;
    }

    vaddr = CAAM_ADR_MAP(desc->buf[i].data, inputSz, 1);

    /* add input */
    desc->desc[desc->idx++] = CAAM_SEQI + desc->buf[i].dataSz;
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr, inputSz);
    i++;
    desc->outputIdx = i;

    outputSz = desc->buf[i].dataSz;
    if (desc->state && (desc->type == CAAM_BLOB_DECAP)) {
        /* black keys with CCM have mac at the end */
        outputSz += BLACK_KEY_MAC_SZ;
    }
    vaddrOut = CAAM_ADR_MAP(desc->buf[i].data, outputSz, 0);

    /* add output */
    desc->desc[desc->idx++] = CAAM_SEQO + desc->buf[i].dataSz;
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddrOut, outputSz);
    if (desc->idx + 1 > MAX_DESC_SZ) {
        return Failure;
    }
    desc->desc[desc->idx] = CAAM_OP |  CAAM_OPID_BLOB | desc->type;

    if (desc->state) {
        desc->desc[desc->idx] |= 0x104; /* EKT and Black_key (key is covered) */
    }
    desc->idx++;
    do {
        err = caamDoJob(desc);
    } while (err == CAAM_WAITING);

    CAAM_ADR_UNMAP(keymod, desc->buf[0].data, desc->buf[0].dataSz, 0);
    CAAM_ADR_UNMAP(vaddr, desc->buf[1].data, inputSz, 0);
    CAAM_ADR_UNMAP(vaddrOut, desc->buf[2].data, outputSz, 1);

    return err;
}


/******************************************************************************
  CAAM AES Operations
  ****************************************************************************/

static void caamAddFIFOLPhy(DESCSTRUCT* desc, unsigned int in, int inSz,
    unsigned int flush)
{
    /* if size is larger than short type then use extended length option */
    if (inSz > 0xFFFF) {
        desc->desc[desc->idx++] = (CAAM_FIFO_L | flush | FIFOS_EXT |
                                   CAAM_CLASS1 | FIFOL_TYPE_MSG);
        desc->desc[desc->idx++] = in;
        desc->desc[desc->idx++] = inSz;
    }
    else {
        desc->desc[desc->idx++] = (CAAM_FIFO_L | flush |
                                   CAAM_CLASS1 | FIFOL_TYPE_MSG) + inSz;
        desc->desc[desc->idx++] = in;
    }
}


static void caamAddFIFOL(DESCSTRUCT* desc, void* in, int inSz,
    unsigned int flush)
{
    caamAddFIFOLPhy(desc, CAAM_ADR_TO_PHYSICAL(in, inSz), inSz, flush);
}


static void caamAddFIFOSPhy(DESCSTRUCT* desc, unsigned int out, int outSz)
{
    /* if size is larger than short type then use extended length option */
    if (outSz > 0xFFFF) {
        desc->desc[desc->idx++] = CAAM_FIFO_S | FIFOS_TYPE_MSG | FIFOS_EXT;
        desc->desc[desc->idx++] = out;
        desc->desc[desc->idx++] = outSz;
    }
    else {
        desc->desc[desc->idx++] = (CAAM_FIFO_S | FIFOS_TYPE_MSG) + outSz;
        desc->desc[desc->idx++] = out;
    }
}


static void caamAddFIFOS(DESCSTRUCT* desc, void* out, int outSz)
{
    caamAddFIFOSPhy(desc, CAAM_ADR_TO_PHYSICAL(out, outSz), outSz);
}


int caamAesCmac(DESCSTRUCT* desc, int sz, unsigned int args[4])
{
    Error err;
    unsigned int keySz;
    unsigned int macSz = 0;
    void *vaddr[4] = {0};
    unsigned int vidx = 0;
    unsigned int ctx;
    unsigned int isBlackKey;
    int i;

    isBlackKey = args[2];
    keySz = args[1];

    /* Get CTX physical address */
    vaddr[vidx] = CAAM_ADR_MAP(desc->buf[1].data, desc->buf[1].dataSz, 1);
    ctx = CAAM_ADR_TO_PHYSICAL(vaddr[vidx], desc->buf[1].dataSz);
    vidx++;

    /* LOAD KEY */
    desc->desc[desc->idx] = (CAAM_KEY | CAAM_CLASS1 | CAAM_NWB) + keySz;
    if (isBlackKey) {
        desc->desc[desc->idx] |= CAAM_LOAD_BLACK_KEY;
        macSz = BLACK_KEY_MAC_SZ;
    }
    desc->idx++;
    vaddr[vidx] = CAAM_ADR_MAP(desc->buf[0].data, desc->buf[0].dataSz + macSz, 1);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
            desc->buf[0].dataSz + macSz);
    DEBUG_PRINT_ARRAY(vaddr[vidx], keySz, "AES CMAC Key");
    vidx++;

    /* Load in CTX only when not initialization */
    if ((desc->state & CAAM_ALG_INIT) == 0) {
        int ofst = 0;
        desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS1 | ofst) +
            desc->buf[1].dataSz;
        desc->desc[desc->idx++] = ctx;
        DEBUG_PRINT_ARRAY(vaddr[0], 32, "AES CMAC CTX");
    }

    /* add protinfo to operation command */
    desc->desc[desc->idx++] = CAAM_OP | CAAM_CLASS1 | desc->type | desc->state;

    /* add in all input buffers */
    for (i = 2; i < sz; i = i + 1) {
        desc->desc[desc->idx] = (CAAM_FIFO_L | CAAM_CLASS1 | FIFOL_TYPE_MSG)
            + desc->buf[i].dataSz;
        if (i+1 == sz) {
            /* this is the last input buffer, signal the HW with LC1 bit */
            desc->desc[desc->idx] |= FIFOL_TYPE_LC1;
        }
        desc->idx++;

        vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
        desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
        DEBUG_PRINT_ARRAY(vaddr[vidx], desc->buf[i].dataSz, "AES CMAC Input");
        vidx++;
    }

    /* if there is no input buffers than add in a single FIFO LOAD to kick off
     * the operation */
    if (sz == 2) { /* only key and ctx buffer */
        desc->desc[desc->idx++] = CAAM_FIFO_L | FIFOL_TYPE_LC1 | CAAM_CLASS1 |
            FIFOL_TYPE_MSG;
        vaddr[vidx] = CAAM_ADR_MAP(0, 0, 0);
        desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx], 0);
        vidx++;
    }

    desc->desc[desc->idx++] = CAAM_STORE_CTX | CAAM_CLASS1 | 32;
    desc->desc[desc->idx++] = ctx;

    do {
        err = caamDoJob(desc);
    } while (err == CAAM_WAITING);
    DEBUG_PRINT_ARRAY(vaddr[0], 32, "AES CMAC CTX");

    vidx = 0;
    CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[1].data, desc->buf[1].dataSz, 1);
    CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[0].data, desc->buf[0].dataSz + macSz, 0);
    if (sz == 2) {
        CAAM_ADR_UNMAP(vaddr[vidx], 0, 0, 0);
    }
    else {
        for (i = 2; i < sz; i = i + 1) { /* unmap the input buffers */
            CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[i].data,
                    desc->buf[i].dataSz, 0);
        }
    }

    return err;
}


int caamAead(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4])
{
    int fifol = 0; /* last index for FIFO */
    Value ofst = 0;
    Error err;
    int ivSz = 0;
    void *iv, *key, *in, *out, *tag;
    int keySz;
    int tagSz;
    int inSz;
    int outSz;
    int idx = 0;
    void* aadCtxBuf = NULL;
    int state = CAAM_ALG_INITF; /* single shot mode */
    unsigned int aadSz;

    if (desc->state != CAAM_ENC && desc->state != CAAM_DEC) {
        return CAAM_ARGS_E;
    }

    keySz = buf[idx].Length;
    if (keySz != 16 && keySz != 24 && keySz != 32) {
        WOLFSSL_MSG("Bad AES key size found");
        return CAAM_ARGS_E;
    }
    aadSz = (args[0] >> 16) & 0xFFFF;

    /* map and copy over key */
    key = (void*)buf[idx].TheAddress;
    desc->desc[desc->idx++] = (CAAM_KEY | CAAM_CLASS1 | CAAM_NWB) + keySz;
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(key, keySz);
    DEBUG_PRINT_ARRAY(key, keySz, "AES AEAD Key");
    idx++;

    /* write operation, in the case of decryption add IVC to check tag */
    desc->desc[desc->idx] = CAAM_OP | CAAM_CLASS1 | desc->type |
             state | desc->state;
    if (desc->state == CAAM_DEC) {
        desc->desc[desc->idx] |= CAAM_ALG_IVC;
    }
    desc->idx++;

    /* get IV if needed by algorithm */
    switch (desc->type) {
        case CAAM_AESGCM:
        {
            ivSz = buf[idx].Length;
            iv   = (void*)buf[idx].TheAddress;
            fifol = desc->idx;
            desc->desc[desc->idx++] = (CAAM_FIFO_L | CAAM_CLASS1 |
                FIFOL_TYPE_FC1 | FIFOL_TYPE_IV) + ivSz;
            desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(iv, ivSz);
            idx++;
         }
        break;

        case CAAM_AESCCM:
        {
            ivSz = buf[idx].Length;
            iv   = (void*)buf[idx].TheAddress;
            desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS1 | ofst) +
                ivSz;
            desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(iv, ivSz);
            idx++;
         }
         break;

        default:
            WOLFSSL_MSG("Mode of AES not implemented");
            return CAAM_ARGS_E;
    }
    DEBUG_PRINT_ARRAY(iv, ivSz, "AES AEAD IV");

    /* get input */
    inSz = buf[idx].Length;
    in   = (void*)buf[idx].TheAddress;
    DEBUG_PRINT_ARRAY(in, inSz, "AES AEAD Input");
    idx++;

    /* set output */
    outSz = buf[idx].Length;
    out   = (void*)buf[idx].TheAddress;
    idx++;

    /* TAG in/out */
    tagSz = buf[idx].Length;
    tag   = (void*)buf[idx].TheAddress;
    idx++;

    /* set aad if present */
    if (aadSz > 0) {
        /* special AAD size setup of context register for CCM mode */
        if (desc->type == CAAM_AESCCM) {
            unsigned char* pt;

            aadCtxBuf = CAAM_ADR_MAP(0, 4, 0);
            pt = (unsigned char*)aadCtxBuf;
            memset(pt, 0, 4);
            if (aadSz <= 0xFEFF) {
                pt[0] = (aadSz & 0xFF00) >> 8;
                pt[1] = (aadSz & 0x00FF);
                desc->desc[desc->idx++] = (CAAM_FIFO_L | CAAM_CLASS1 |
                    FIFOL_TYPE_AAD) + 2;
            }
            else {
                pt[0] = (aadSz >> 24) & 0xFF;
                pt[1] = (aadSz >> 16) & 0xFF;
                pt[2] = (aadSz >> 8 ) & 0xFF;
                pt[3] = aadSz & 0xFF;
                fifol = desc->idx;
                desc->desc[desc->idx++] = (CAAM_FIFO_L | CAAM_CLASS1 |
                    FIFOL_TYPE_AAD) + 4;
            }
            desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(aadCtxBuf, 4);
            CAAM_ADR_SYNC(aadCtxBuf, 4);
        }

        /* Load in AAD */
        fifol = desc->idx;
        desc->desc[desc->idx++] = (CAAM_FIFO_L | CAAM_CLASS1 | FIFOL_TYPE_FC1 |
            FIFOL_TYPE_AAD) + aadSz;
        desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL((void*)buf[idx].TheAddress,
            buf[idx].Length);
        DEBUG_PRINT_ARRAY((void*)buf[idx].TheAddress, aadSz, "AES AEAD AAD");
        idx++;
    }

    /* set input/output in descriptor */
    if (outSz > 0) {
        caamAddFIFOS(desc, out, outSz);
    }

    if (inSz > 0) {
        fifol = desc->idx;
        caamAddFIFOL(desc, in, inSz, FIFOL_TYPE_FC1);
    }

    if (desc->state == CAAM_DEC) {
        fifol = desc->idx;
        desc->desc[desc->idx++] = (CAAM_FIFO_L | FIFOL_TYPE_FC1 |
                                   CAAM_CLASS1 | FIFOL_TYPE_IVC) + tagSz;
        desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(tag, tagSz);
    }

    /* remove FC1 and set LC1 for last FIFO load */
    desc->desc[fifol] &= ~FIFOL_TYPE_FC1;
    desc->desc[fifol] |= FIFOL_TYPE_LC1;

    /* store updated IV / MAC */
    if (desc->state == CAAM_ENC) {
    switch (desc->type) {
        case CAAM_AESGCM:
            desc->desc[desc->idx++] = CAAM_STORE_CTX | CAAM_CLASS1 | tagSz;
            desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(tag, tagSz);
            break;

        case CAAM_AESCCM:
            desc->desc[desc->idx++] = CAAM_STORE_CTX | CAAM_CLASS1 |
                (32 << 8) | tagSz;
            desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(tag, tagSz);
            break;
    }
    }

    do {
        err = caamDoJob(desc);
    } while (err == CAAM_WAITING);

    if (aadCtxBuf != NULL)
        CAAM_ADR_UNMAP(aadCtxBuf, 0, 4, 0);

    DEBUG_PRINT_ARRAY(tag, tagSz, "AES AEAD Tag Out");
    DEBUG_PRINT_ARRAY(out, outSz, "AES AEAD Output");
    return err;
}


static int caamAesInternal(DESCSTRUCT* desc,
    unsigned int keyPhy, int keySz,
    unsigned int ivPhy,  int ivSz,
    unsigned int inPhy,  int inSz,
    unsigned int outPhy, int outSz)
{
    Value ofst = 0;
    Error err;
    int state = CAAM_ALG_UPDATE;

    if (desc->state != CAAM_ENC && desc->state != CAAM_DEC) {
        return CAAM_ARGS_E;
    }

    if (keySz != 16 && keySz != 24 && keySz != 32) {
        WOLFSSL_MSG("Bad AES key size found");
        return CAAM_ARGS_E;
    }

    /* map and copy over key */
    desc->desc[desc->idx++] = (CAAM_KEY | CAAM_CLASS1 | CAAM_NWB) + keySz;
    desc->desc[desc->idx++] = keyPhy;

    /* get IV if needed by algorithm */
    switch (desc->type) {
        case CAAM_AESECB:
            break;

        case CAAM_AESCTR:
            ofst = 0x00001000;
            /* fall through because states are the same only the offset changes */

        case CAAM_AESCBC:
        {
            int maxSz = 16; /* default to CBC/CTR max size */

            if (ivSz != maxSz) {
                WOLFSSL_MSG("Invalid AES-CBC IV size\n");
                return CAAM_ARGS_E;
            }

            desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS1 | ofst) +
                    maxSz;
            desc->desc[desc->idx++] = ivPhy;
         }
         break;

        default:
            WOLFSSL_MSG("Mode of AES not implemented");
            return CAAM_ARGS_E;
    }

    /* write operation */
    desc->desc[desc->idx++] = CAAM_OP | CAAM_CLASS1 | desc->type |
             state | desc->state;

    /* set input/output in descriptor */
    caamAddFIFOLPhy(desc, inPhy, inSz, FIFOL_TYPE_LC1);
    caamAddFIFOSPhy(desc, outPhy, outSz);

    /* store updated IV */
    switch (desc->type) {
        case CAAM_AESCBC:
        case CAAM_AESCTR:
        if (ivSz > 0) {
            desc->desc[desc->idx++] = CAAM_STORE_CTX | CAAM_CLASS1 | ofst | 16;
            desc->desc[desc->idx++] = ivPhy;
        }
        break;
    }

    do {
        err = caamDoJob(desc);
    } while (err == CAAM_WAITING);

    return err;
}


/* Scattered memory, does a mapping for each variable. Less performant than
 * caamAesCombined.
 * AES operations follow the buffer sequence of KEY -> (IV) -> Input -> Output
 */
int caamAes(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4])
{
    void *iv = NULL, *key, *in, *out;
    int ivSz = 0, keySz, inSz, outSz;
    int idx = 0;

    unsigned int keyPhy = 0, inPhy = 0, outPhy = 0, ivPhy = 0;

    /* map and copy over key */
    key    = (void*)buf[idx].TheAddress;
    keySz  = buf[idx].Length;
    keyPhy = CAAM_ADR_TO_PHYSICAL(key, keySz);
    idx++;

    /* get IV if needed by algorithm */
    switch (desc->type) {
        case CAAM_AESECB:
            break;

        case CAAM_AESCTR:
        case CAAM_AESCBC:
        {
            ivSz  = buf[idx].Length;
            iv    = (void*)buf[idx].TheAddress;
            ivPhy = CAAM_ADR_TO_PHYSICAL(iv, ivSz);
            idx++;
         }
         break;

        default:
            WOLFSSL_MSG("Mode of AES not implemented");
            return CAAM_ARGS_E;
    }

    /* get input */
    inSz  = buf[idx].Length;
    in    = (void*)buf[idx].TheAddress;
    inPhy = CAAM_ADR_TO_PHYSICAL(in, inSz);
    idx++;

    /* set output */
    outSz  = buf[idx].Length;
    out    = (void*)buf[idx].TheAddress;
    outPhy = CAAM_ADR_TO_PHYSICAL(out, outSz);
    idx++;

    return caamAesInternal(desc, keyPhy, keySz, ivPhy, ivSz, inPhy, inSz,
            outPhy, outSz);
}


/* When a single buffer is used [key] [in] [iv] [out] for optimization
 * phyMem is non 0 when the physical memory location is already known
 */
int caamAesCombined(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4],
    unsigned int phyMem)
{
    int idx = 0;
    unsigned int keyPhy;
    int keySz, inSz, ivSz = 0, outSz;
    void* pt;

    keySz = buf[idx].Length;
    pt    = (void*)buf[idx].TheAddress;
    idx++;

    /* get IV if needed by algorithm */
    switch (desc->type) {
        case CAAM_AESECB:
            break;

        case CAAM_AESCTR:
        case CAAM_AESCBC:
        {
            ivSz = buf[idx].Length;
            idx++;
         }
         break;

        default:
            WOLFSSL_MSG("Mode of AES not implemented");
            return CAAM_ARGS_E;
    }

    /* get input */
    inSz = buf[idx].Length;
    idx++;

    /* set output */
    outSz = buf[idx].Length;
    idx++;

    if (phyMem != 0) {
        keyPhy = phyMem;
    }
    else {
        keyPhy = CAAM_ADR_TO_PHYSICAL(pt, keySz + inSz + ivSz + outSz);
    }

    return caamAesInternal(desc, keyPhy, keySz,
            keyPhy + keySz + inSz,ivSz,            /* IV */
            keyPhy + keySz, inSz,                  /* IN buffer */
            keyPhy + keySz + inSz + ivSz, outSz);  /* OUT buffer */
}


/* ECDSA generate black key
 *
 * return Success on success. All other return values are considered a fail
 *         case.
 */
int caamECDSAMake(DESCSTRUCT* desc, CAAM_BUFFER* buf, unsigned int args[4])
{
    Error err;
    unsigned int part = 0;
    unsigned int isBlackKey = 0;
    unsigned int pdECDSEL   = 0;
    unsigned int phys;
    void *vaddr[2];

    if (args != NULL) {
        isBlackKey = args[0];
        pdECDSEL   = args[1];
    }
    vaddr[0] = NULL;
    vaddr[1] = NULL;

    desc->desc[desc->idx++] = pdECDSEL;
    if (isBlackKey == CAAM_BLACK_KEY_SM) {
        unsigned char* pt;

        /* create secure partition for private key out */
        part = caamFindUnusedPartition();
        if ((int)part < 0) {
            WOLFSSL_MSG("error finding an unused partition for new key");
            return -1;
        }

        /* create and claim the partition */
        err = caamCreatePartition(&part, part, CAAM_SM_CSP | CAAM_SM_SMAP_LOCK |
                CAAM_SM_CSP | CAAM_SM_ALL_RW);
        if (err != Success) {
            WOLFSSL_MSG("error creating partition for secure ecc key");
            return -1;
        }

        /* map secure partition to virtual address */
        phys = (CAAM_PAGE + (part << 12));
        pt = (unsigned char*)buf[0].TheAddress;
        pt[0] = (phys >> 24) & 0xFF;
        pt[1] = (phys >> 16) & 0xFF;
        pt[2] = (phys >> 8) & 0xFF;
        pt[3] = (phys) & 0xFF;
        desc->desc[desc->idx++] = phys;
    }
    else {
        vaddr[0] = CAAM_ADR_MAP(0, buf[0].Length, 0);
        desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[0], buf[0].Length);

    }
    vaddr[1] = CAAM_ADR_MAP(0, buf[1].Length, 0);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[1], buf[1].Length);

    /* add protinfo to operation command */
    desc->startIdx = desc->idx;

    /* add operation command               OPTYPE        PROTOID */
    desc->desc[desc->idx] = CAAM_OP | CAAM_PROT_UNIDI | desc->type;
    if (isBlackKey == CAAM_BLACK_KEY_SM || isBlackKey == CAAM_BLACK_KEY_CCM) {
        desc->desc[desc->idx] |= CAAM_PKHA_ENC_PRI_AESCCM;
    }
    if (isBlackKey == CAAM_BLACK_KEY_ECB) {
        desc->desc[desc->idx] |= CAAM_PKHA_ENC_PRI_AESECB;
    }
    desc->desc[desc->idx++] |= CAAM_PKHA_ECC;

    do {
        err = caamDoJob(desc);
    } while (err == CAAM_WAITING);

    if (isBlackKey == CAAM_BLACK_KEY_SM) {
        /* store partition number holding black keys */
        if (err != Success)
            caamFreePart(part);
        else
            args[2] = part;
    }
    else {
        /* copy non black keys out to buffers */
        CAAM_ADR_UNMAP(vaddr[0], buf[0].TheAddress, buf[0].Length, 1);
    }
    CAAM_ADR_UNMAP(vaddr[1], buf[1].TheAddress, buf[1].Length, 1);

    return err;
}



/* ECDSA verify signature
 *
 * return Success on success. All other return values are considered a fail
 *         case.
 */
int caamECDSAVerify(DESCSTRUCT* desc, CAAM_BUFFER* buf, int sz,
        unsigned int args[4])
{
    unsigned int isBlackKey = 0;
    unsigned int pdECDSEL   = 0;
    unsigned int msgSz = 0;
    unsigned int vidx = 0;
    unsigned int L;
    int i = 0;
    Error err;
    void *vaddr[MAX_ECDSA_VERIFY_ADDR];

    if (args != NULL) {
        isBlackKey = args[0];
        pdECDSEL   = args[1];
        msgSz      = args[2];
    }

    if (sz > MAX_ECDSA_VERIFY_ADDR) {
       return -1;
    }

    if (pdECDSEL == 0) {
        return -1;
    }
    else {
        L = args[3]; /* keysize */
        desc->desc[desc->idx++] = pdECDSEL;
    }

    /* public key */
    if (isBlackKey != CAAM_BLACK_KEY_SM) {
        vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
        desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
        vidx = vidx + 1;
    }
    else {
        desc->desc[desc->idx++] = desc->buf[i].data;
    }
    i = i + 1;

    /* message */
    vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
    vidx = vidx + 1; i = i + 1;

    /* r */
    vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
    vidx = vidx + 1; i = i + 1;

    /* s */
    vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
    vidx = vidx + 1; i = i + 1;

    /* tmp buffer */
    vaddr[vidx] = CAAM_ADR_MAP(0, 2*L, 0);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx], 2*L);
    if (msgSz > 0) {
        desc->desc[desc->idx++] = msgSz;
    }

    /* add protinfo to operation command */
    desc->startIdx = desc->idx;

    /* add operation command               OPTYPE        PROTOID */
    desc->desc[desc->idx] = CAAM_OP | CAAM_PROT_UNIDI | desc->type;
    if (msgSz > 0) {
        desc->desc[desc->idx] |= CAAM_ECDSA_MESREP_HASHED;
    }
    desc->desc[desc->idx++] |= CAAM_PKHA_ECC;

    do {
        err = caamDoJob(desc);
    } while (err == CAAM_WAITING);

    vidx = 0; i = 0;
    if (!isBlackKey) {
        CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[i].data, desc->buf[i].dataSz, 0);
    }
    i = i + 1;

    /* msg , r, s, tmp */
    CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[i].data, desc->buf[i].dataSz, 0);
    i = i + 1;
    CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[i].data, desc->buf[i].dataSz, 0);
    i = i + 1;
    CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[i].data, desc->buf[i].dataSz, 0);
    i = i + 1;
    CAAM_ADR_UNMAP(vaddr[vidx++], 0, 2*L, 0);

    return err;
}


/* ECDSA generate signature
 *
 * return Success on success. All other return values are considered a fail
 *         case.
 */
int caamECDSASign(DESCSTRUCT* desc, int sz, unsigned int args[4])
{
    Error err;
    unsigned int isBlackKey = 0;
    unsigned int pdECDSEL   = 0;
    unsigned int msgSz = 0;
    unsigned int vidx = 0;
    int i = 0;
    void *vaddr[MAX_ECDSA_SIGN_ADDR];

    if ((args == NULL) || (sz > MAX_ECDSA_SIGN_ADDR)) {
        return -1;
    }

    isBlackKey = args[0];
    pdECDSEL   = args[1];
    msgSz      = args[2];
    if (pdECDSEL == 0) {
        return -1;
    }

    /* using parameters already in hardware */
    desc->desc[desc->idx++] = pdECDSEL;

    /* private key */
    if (isBlackKey != CAAM_BLACK_KEY_SM) {
        vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
        desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
    #if 0
        {
            unsigned int z; unsigned char* pt;
            printf("private :");
            pt = (unsigned char*)desc->buf[i].data;
            for (z = 0; z < desc->buf[i].dataSz; z++)
                printf("%02X", pt[z]);
            printf("\n");
        }
    #endif
        vidx++;
    }
    else {
        desc->desc[desc->idx++] = desc->buf[i].data;
    }
    i++;

    for (; i < sz; i = i + 1) {
        vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
    #if 0
        {
            unsigned int z;
            unsigned char *pt = (unsigned char*)vaddr[vidx];
            printf("input index %d/%d\n", i, sz);
            for (z = 0; z < desc->buf[i].dataSz; z++)
                printf("%02X", pt[z]);
            printf("\n");
        }
    #endif
        desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
        vidx++;
    }

    desc->desc[desc->idx++] = msgSz;

    /* add protinfo to operation command */
    desc->startIdx = desc->idx;

    /* add operation command               OPTYPE        PROTOID */
    desc->desc[desc->idx] = CAAM_OP | CAAM_PROT_UNIDI | desc->type;
    if (isBlackKey == CAAM_BLACK_KEY_SM || isBlackKey == CAAM_BLACK_KEY_CCM) {
        /* set flag to use AES-CCM with black key */
        desc->desc[desc->idx] |= CAAM_PKHA_ENC_PRI_AESCCM;
    }
    if (isBlackKey == CAAM_BLACK_KEY_ECB) {
        /* set flag to use AES-ECB with black key */
        desc->desc[desc->idx] |= CAAM_PKHA_ENC_PRI_AESECB;
    }

    /* add protinfo to operation command */
    desc->desc[desc->idx++] |= CAAM_ECDSA_MESREP_HASHED | CAAM_PKHA_ECC;

    do {
        err = caamDoJob(desc);
    } while (err == CAAM_WAITING);

    vidx = 0; i = 0;
    if (isBlackKey != CAAM_BLACK_KEY_SM) {
        CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[i].data, desc->buf[i].dataSz, 0);
    }
    i++;

    /* msg */
    CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[i].data, desc->buf[i].dataSz, 0); i++;

    /* copy out the r and s values */
    CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[i].data, desc->buf[i].dataSz, 1); i++;
    CAAM_ADR_UNMAP(vaddr[vidx++], desc->buf[i].data, desc->buf[i].dataSz, 1); i++;

    return err;
}


/* ECDH generate shared secret
 *
 * return Success on success. All other return values are considered a fail
 *         case.
 */
int caamECDSA_ECDH(DESCSTRUCT* desc, int sz, unsigned int args[4])
{
    Error err;
    unsigned int isBlackKey = 0;
    unsigned int peerBlackKey = 0;
    unsigned int pdECDSEL   = 0;
    unsigned int vidx = 0;
    int i = 0;
    void* vaddr[sz];

    if (args != NULL) {
        isBlackKey   = args[0];
        peerBlackKey = args[1];
        pdECDSEL     = args[2];
    }

    if (pdECDSEL == 0) {
        return -1;
    }
    else {
        /* using parameters already in hardware */
        desc->desc[desc->idx++] = pdECDSEL;
    }

    /* public key */
    if (peerBlackKey != CAAM_BLACK_KEY_SM) {
        vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
        desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
        DEBUG_PRINT_ARRAY((void*)desc->buf[i].data, desc->buf[i].dataSz,
                "ECDH Public Key");
        vidx++;
    }
    else {
        desc->desc[desc->idx++] = desc->buf[i].data;
    }
    i++;

    /* private key */
    if (isBlackKey != CAAM_BLACK_KEY_SM) {
        if (isBlackKey == CAAM_BLACK_KEY_CCM) {
            vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz +
                BLACK_KEY_MAC_SZ, 1);
            desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz + BLACK_KEY_MAC_SZ);
            DEBUG_PRINT_ARRAY((void*)desc->buf[i].data, desc->buf[i].dataSz +
                BLACK_KEY_MAC_SZ, "ECDH Private Key w/CCM ");
        }
        else {
            vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
            desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
            DEBUG_PRINT_ARRAY((void*)desc->buf[i].data, desc->buf[i].dataSz,
                    "ECDH Private Key");
        }
        vidx++;
    }
    else {
        desc->desc[desc->idx++] = desc->buf[i].data;
    }
    i++;

    /* shared output */
    vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
            desc->buf[i].dataSz);
    i++; vidx++;

    /* add protinfo to operation command */
    desc->startIdx = desc->idx;

    /* add operation command               OPTYPE        PROTOID */
    desc->desc[desc->idx] = CAAM_OP | CAAM_PROT_UNIDI | desc->type;
    if (isBlackKey == CAAM_BLACK_KEY_SM || isBlackKey == CAAM_BLACK_KEY_CCM) {
        desc->desc[desc->idx] |= CAAM_PKHA_ENC_PRI_AESCCM;
    }
    if (isBlackKey == CAAM_BLACK_KEY_ECB) {
        desc->desc[desc->idx] |= CAAM_PKHA_ENC_PRI_AESECB;
    }

    /* add protinfo to operation command */
    desc->desc[desc->idx++] |= CAAM_PKHA_ECC;

    do {
        err = caamDoJob(desc);
    } while (err == CAAM_WAITING);

    vidx = 0; i = 0;
    if (pdECDSEL == 0) {
        /* unmap prime key */
        CAAM_ADR_UNMAP(vaddr[vidx], desc->buf[i].data, desc->buf[i].dataSz, 0);
        vidx++; i++;
    }

    if (peerBlackKey != 1) {
        CAAM_ADR_UNMAP(vaddr[vidx], desc->buf[i].data, desc->buf[i].dataSz, 0);
        vidx++;
    }
    i++;

    if (isBlackKey != CAAM_BLACK_KEY_SM) {
        CAAM_ADR_UNMAP(vaddr[vidx], desc->buf[i].data, desc->buf[i].dataSz, 0);
        vidx++;
    }
    i++;
    CAAM_ADR_UNMAP(vaddr[vidx], desc->buf[i].data, desc->buf[i].dataSz, 1);
    vidx++; i++;

    if (pdECDSEL == 0) {
        /* unmap A , B*/
        CAAM_ADR_UNMAP(vaddr[vidx], desc->buf[i].data, desc->buf[i].dataSz, 0);
        vidx++; i++;
    }
    return err;
}


/******************************************************************************
  IODevice Start, Transfer and Finish Buffer
  ****************************************************************************/
/* If Entropy is not ready then return CAAM_WAITING */
static int caamTRNG(unsigned char *out, int outSz)
{
    int sz = 0;

    CAAM_ADDRESS  reg; /* RTENT reg to read */
    unsigned char* local;
    int ofst = sizeof(unsigned int);

    /* Check ENT_VAL bit to make sure entropy is ready */
    if ((CAAM_READ(caam.baseAddr + CAAM_RTMCTL) & CAAM_ENTVAL) != CAAM_ENTVAL) {
        return CAAM_WAITING;
    }

    /* check state of TRNG */
    if ((CAAM_READ(caam.baseAddr + CAAM_RTSTATUS) & 0x0000FFFF) > 0) {
        WOLFSSL_MSG("RNG in a bad state");
        return Failure;
    }

    /* read entropy from RTENT registers */
    reg   = caam.baseAddr + CAAM_RTENT0;
    sz    = outSz;
    local = out;

    while (sz > 3 && reg <= caam.baseAddr + CAAM_RTENT_MAX) {
        unsigned int data = CAAM_READ(reg);
        *((unsigned int*)local) = data;
        reg    += ofst;
        local  += ofst;
        sz     -= ofst;
    }

    if (reg > CAAM_RTENT_MAX && sz > 0) {
        return -1;
    }

    /* handle non unsigned int size amount left over */
    if (sz > 0) {
        unsigned int tmp = CAAM_READ(reg);
        memcpy(local, (unsigned char*)&tmp, sz);
    }

    /* read the max RTENT to trigger new entropy generation */
    if (reg != CAAM_RTENT_MAX) {
        CAAM_READ(caam.baseAddr + CAAM_RTENT_MAX);
    }

    return Success;
}


/* out is the virtual address to store resulting RNG data in */
static int caamRNG(unsigned char *out, int outSz)
{
    DESCSTRUCT desc;
    int ret;

    /* set up the job description for RNG initialization */
    caamDescInit(&desc, 0, NULL, NULL, 0);
    desc.desc[desc.idx++] = CAAM_OP | CAAM_CLASS1 | CAAM_RNG;
    desc.desc[desc.idx++] = (CAAM_FIFO_S | FIFOS_TYPE_RNG) + outSz;
    desc.desc[desc.idx++] = CAAM_ADR_TO_PHYSICAL(out, outSz);

    do {
        ret = caamDoJob(&desc);
    } while (ret == CAAM_WAITING);

    return ret;
}


int caamEntropy(unsigned char *out, int outSz)
{
    if (caam.vrs < 9) {
        /* can access TRNG directly */
        return caamTRNG(out, outSz);
    }
    else {
        /* use CAAM RNG as source of entropy */
        return caamRNG(out, outSz);
    }
}


/* cover a plain text key and make it a black key */
int caamKeyCover(DESCSTRUCT* desc, int sz, unsigned int args[4])
{
    Error err;
    unsigned int vidx = 0;
    int i = 0;
    void* vaddr[2];

    (void)args;

    if (sz > 2) {
        return -1;
    }

    /* add input key */
    desc->desc[desc->idx++] = (CAAM_KEY | CAAM_CLASS1) +
        desc->buf[i].dataSz;
    vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz, 1);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
                desc->buf[i].dataSz);
    vidx++;
    i++;

    /* add output */
    desc->desc[desc->idx++] = (CAAM_FIFO_S | CAAM_CLASS1 | args[0] |
        desc->state) + desc->buf[i].dataSz;
    vaddr[vidx] = CAAM_ADR_MAP(desc->buf[i].data, desc->buf[i].dataSz +
            BLACK_KEY_MAC_SZ, 0);
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[vidx],
            desc->buf[i].dataSz + BLACK_KEY_MAC_SZ);

#if 0
    /* sanity check can we load it? used for debugging and testing */
    desc->desc[desc->idx++] = (CAAM_KEY | CAAM_CLASS1 | 0x500000) +
        desc->buf[i].dataSz;
    desc->desc[desc->idx++] = CAAM_ADR_TO_PHYSICAL(vaddr[1], desc->buf[1].dataSz);
#endif

    do {
        err = caamDoJob(desc);
    } while (err == CAAM_WAITING);

    CAAM_ADR_UNMAP(vaddr[0], desc->buf[0].data, desc->buf[0].dataSz, 0);
    CAAM_ADR_UNMAP(vaddr[1], desc->buf[1].data, desc->buf[1].dataSz +
            BLACK_KEY_MAC_SZ, 1);
    return err;
}


/******************************************************************************
  Init
  ****************************************************************************/

/* initialize a DESCSTRUCT for an operation */
void caamDescInit(DESCSTRUCT* desc, int type, unsigned int args[4],
        CAAM_BUFFER* buf, int sz)
{
    int i;

    desc->type   = type;
    desc->idx    = 0;
    desc->output = 0;
    desc->ctxOut = 0;
    desc->outputIdx = 0;
    desc->alignIdx = 0;
    desc->lastFifo = 0;
    if (args == NULL) {
        desc->state    = 0;
        desc->ctxSz    = 0;
        desc->inputSz  = 0;
    }
    else {
        desc->state    = args[0] & 0xFFFF;
        desc->ctxSz    = args[1] & 0xFFFF;
        desc->inputSz  = args[2];
    }
    desc->aadSz    = 0;
    desc->DescriptorCount = sz;
    desc->startIdx = 0;
    desc->desc[desc->idx++] = CAAM_HEAD; /* later will put size to header*/

    for (i = 0; i < sz; i = i + 1) {
        desc->buf[i].data   = buf[i].TheAddress;
        desc->buf[i].dataSz = buf[i].Length;
    }
}


static int SetupJobRing(struct JobRing* r)
{
    /* get environment specific addresses to use for job rings */
    CAAM_SET_JOBRING_ADDR(&r->BaseAddr, &r->JobIn, &r->VirtualIn);

    /* register the in/out and sizes of job ring */
    r->Desc     = r->JobIn + (CAAM_JOBRING_SIZE * sizeof(unsigned int));
    r->JobOut   = r->Desc + (CAAM_DESC_MAX * CAAM_JOBRING_SIZE);

    CAAM_INIT_MUTEX(&caam.ring.jr_lock);

    r->VirtualDesc = r->VirtualIn  + (CAAM_JOBRING_SIZE * sizeof(unsigned int));
    r->VirtualOut  = r->VirtualDesc + (CAAM_DESC_MAX * CAAM_JOBRING_SIZE);

    memset(r->VirtualIn,   0, CAAM_JOBRING_SIZE * sizeof(unsigned int));
    memset(r->VirtualDesc, 0, CAAM_DESC_MAX * CAAM_JOBRING_SIZE);
    memset(r->VirtualOut,  0, 2 * CAAM_JOBRING_SIZE * sizeof(unsigned int));

    #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
    printf("Setting JOB IN  address 0x%08X, size %d\n",
        (unsigned int)caam.ring.JobIn, CAAM_JOBRING_SIZE);
    printf("Setting JOB OUT address 0x%08X, size %d\n",
        (unsigned int)caam.ring.JobOut, CAAM_JOBRING_SIZE);
    printf("Setting DESC 0x%08X\n", (unsigned int)caam.ring.Desc);
    #endif

    /* set the job ring in/out address's */
    CAAM_WRITE(r->BaseAddr + CAAM_IRBAR0, r->JobIn);
    CAAM_WRITE(r->BaseAddr + CAAM_ORBAR, r->JobOut);

    /* Initialize job ring sizes */
    CAAM_WRITE(r->BaseAddr + CAAM_IRSR0, CAAM_JOBRING_SIZE);
    CAAM_WRITE(r->BaseAddr + CAAM_ORSR0, CAAM_JOBRING_SIZE);

    /* if the job ring is busy, park it, flush it, and reset it */
    if (((CAAM_READ(r->BaseAddr + CAAM_STATUS) & 0x00000001) != 0) &&
        (CAAM_READ(r->BaseAddr + JRINTR_JR) != 0)) {
        unsigned int reg;

    #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
        printf("Job ring is busy, trying to flush it\n");
    #endif

        /* JRCR job ring command register */
        CAAM_WRITE(r->BaseAddr + JRCR_JR, 0x2); /* park it  */
        CAAM_WRITE(r->BaseAddr + JRCR_JR, 0x1); /* flush it */
        do {
            reg = CAAM_READ(r->BaseAddr + JRINTR_JR);
        } while (!(reg & 0x8) && (reg != 0)); /* bit 3 hot signals is halted */

        if (reg != 0) {
            CAAM_WRITE(r->BaseAddr + JRCR_JR, 0x1); /* reset it */
        }
    }
    return 0;
}


int InitCAAM(void)
{
    Error ret;

    /* map to memory addresses needed for accessing CAAM */
#if defined(WOLFSSL_CAAM_PRINT)
    printf("Using CAAM_BASE 0x%04X\n", CAAM_BASE);
#endif
    ret = CAAM_SET_BASEADDR(&caam.baseAddr);
    if (ret != 0) {
        return ret;
    }

#if defined(WOLFSSL_CAAM_PRINT)
    printf("Using base address : 0x%04X\n", caam.baseAddr);
#endif
    ret = SetupJobRing(&caam.ring);
    if (ret != 0) {
        WOLFSSL_MSG("Error initializing job ring");
        INTERRUPT_Panic();
        return ret;
    }
#if defined(WOLFSSL_CAAM_PRINT)
    printf("Using base ring address : 0x%04X\n", caam.ring.BaseAddr);
#endif

    /* get CHA era */
    caam.vrs = CAAM_READ(caam.ring.BaseAddr + CAAM_CHA_CCBVID) >> 24;
#if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
    printf("CAAM version = %04X\n",
        CAAM_READ(caam.ring.BaseAddr + CAAM_VERSION_MS) & 0xFFFF);
    printf("CAAM era = %d\n", caam.vrs);
    printf("RNG revision number = %08X\n",
        CAAM_READ(caam.ring.BaseAddr + CAAM_CRNR_LS));
    printSecureMemoryInfo();

    /* Check if CAAM supports AES-GCM */
    {
        unsigned int chaVerLS =
            CAAM_READ(caam.ring.BaseAddr + CAAM_CHA_VERSION_LS);
        printf("\nCHA support\n");
        printf("CHA Version LS = %04X\n", chaVerLS);
        if (!(chaVerLS & CAAM_AES_HIGH_PERFORMANCE)) {
            printf("High Performance AES module not supported, NO AES-GCM/XTS\n");
        }
        if (chaVerLS & CAAM_AES_LOW_POWER) {
            printf("Low Power AES module found\n");
        }
        printf("\n");
    }
#endif

    /* when on i.MX8 with SECO the SECO has control of this */
    if (caam.vrs < 9) {
        /* set DECO watchdog to time out and flush jobs that cause the DECO to
           hang */
        CAAM_WRITE(caam.baseAddr + CAAM_RSTA,
                   CAAM_READ(caam.baseAddr + CAAM_RSTA) | 0x40000000);

        /* start up RNG if not already started */
        if (caamInitRng(&caam) != 0) {
            WOLFSSL_MSG("Error initializing RNG");
            INTERRUPT_Panic();
            return -1;
        }
    }

    WOLFSSL_MSG("Successfully initialized CAAM driver");
    #if defined(WOLFSSL_CAAM_DEBUG) || defined(WOLFSSL_CAAM_PRINT)
    fflush(stdout);
    #endif
    return 0;
}


int CleanupCAAM()
{
    caamFreeAllPart();
    CAAM_UNSET_JOBRING_ADDR(caam.ring.BaseAddr, caam.ring.JobIn,
        caam.ring.VirtualIn);
    CAAM_FREE_MUTEX(&caam.ring.jr_lock);
    CAAM_UNSET_BASEADDR(caam.baseAddr);
    return 0;
}

#endif /* __INTEGRITY || INTEGRITY || __QNX__ || __QNXNTO__ */