summaryrefslogtreecommitdiff
path: root/wolfcrypt/src/port/caam/caam_driver.c
blob: 5d44f2da8ecc6c9333101dc051f5530c783c18f5 (plain) (blame)
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
/* caam_driver.c
 *
 * Copyright (C) 2006-2020 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 2 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
 */

#if defined(__INTEGRITY) || defined(INTEGRITY)

/* build into Integrity kernel */
#include <bsp.h>
#include "wolfssl/wolfcrypt/port/caam/caam_driver.h"

#define CAAM_READ(reg) *(volatile unsigned int*)(reg)
#define CAAM_WRITE(reg, in) *(volatile unsigned int*)(reg) = (in);

#define DESC_COUNT 1
#define MAX_BUF 20
#define BUFFER_COUNT (MAX_BUF * DESC_COUNT)

/* CAAM descriptors can only be 64 unsigned ints */
#define MAX_DESC_SZ 64

/* 64 byte buffer for when data crosses a page boundary */
#define ALIGN_BUF 16

/* MAX_CTX is 64 bytes (sha512 digest) + 8 bytes (CAAM length value) */
#define MAX_CTX 18

#define MIN_READ_REG 0xF2100000
#define MAX_READ_REG 0XF2110000

struct JobRing {
    Address JobIn;
    Address JobOut;
    Address Desc;
    Value   page;    /* page allocation for descriptor to use */
};

struct buffer {
    Address data;
    Address dataSz;
};

/* CAAM descriptor */
struct DescStruct {
    struct IORequestStruct TheIORequest;
    struct CAAM_DEVICE*    caam;
    struct buffer          buf[MAX_BUF]; /* buffers holding data input address */
    UINT4                  desc[MAX_DESC_SZ]; /* max size of 64 word32 */
    UINT4                  aadSzBuf[4];       /* Formatted AAD size for CCM */
    UINT4                  alignBuf[ALIGN_BUF]; /* 64 byte buffer for non page
                                                   align */
    UINT4                  iv[MAX_CTX]; /* AES IV and also hash state */
    UINT4                  ctxBuf[MAX_CTX]; /* key */
    Address                output; /* address to output buffer */
    Address                ctxOut; /* address to update buffer holding state */
    Value                  alignIdx;/* index for align buffer */
    Value                  idx;     /* index for descriptor buffer */
    Value                  headIdx; /* for first portion of descriptor buffer */
    Value                  lastIdx; /* for last portion of descriptor buffer */
    Value                  outputIdx; /* idx to output buffer in "buf" */
    Value                  inputSz;   /* size of input buffer */
    Value                  ctxSz;     /* size of CTX/Key buffer */
    Value                  aadSz;     /* AAD size for CCM */
    Value                  lastFifo;
    Value                  type;
    Value                  state;
    Value                  DescriptorCount;
    Boolean                running; /* True if building/running descriptor is
                                       in process */
};

struct CAAM_DEVICE {
    struct IODeviceVectorStruct caamVector;
    struct IODescriptorStruct   IODescriptorArray[BUFFER_COUNT];
    struct DescStruct           DescArray[DESC_COUNT];
    volatile Value              InterruptStatus;
    CALL                        HandleInterruptCall;
    struct JobRing              ring;
};

#define DRIVER_NAME "wolfSSL_CAAM_Driver"

static struct CAAM_DEVICE caam;

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

/* 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_BASE | 0x1054, CAAM_READ(CAAM_BASE | 0x1054) | 1);

    /* flush and reset job rings using JRCR0 register */
    CAAM_WRITE(CAAM_BASE | 0x106C, 1);

    /* check register JRINTR for if halt is in progress */
    while (t > 0 && ((CAAM_READ(CAAM_BASE | 0x104C) & 0x4) == 0x4)) t--;
    if (t == 0) {
        /*unrecoverable failure, the job ring is locked, up hard reset needed*/
        return NotRestartable;
    }

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

    /* reset most registers and state machines in CAAM using MCFGR register
       also reset DMA */
    CAAM_WRITE(CAAM_BASE | 0x0004, 0x90000000);

    return Success;
}

/* returns MemoryMapMayNotBeEmpty if page/par is already owned
 * returns Success on success
 * all other returns is an error state
 */
static Error caamCreatePartition(unsigned char page, unsigned char par)
{
    /* check ownership of partition */
    if ((CAAM_READ(CAAM_BASE | 0x1FBC) & (0x3 << (par * 2))) > 0) {
        return MemoryMapMayNotBeEmpty;
    }

    /* set generic all access permissions, gets reset later */
    CAAM_WRITE(CAAM_BASE | (0x1108 + (par * 16)), 0xF);
    CAAM_WRITE(CAAM_BASE | (0x110C + (par * 16)), 0xF);
    CAAM_WRITE(CAAM_BASE | (0x1104 + (par * 16)), 0xFF);

    /* check ownership of page */
    CAAM_WRITE(CAAM_BASE | 0x10F4, (page << 16) | 0x5);
    /* wait for inquiry cmd to complete */
    while ((CAAM_READ(CAAM_BASE | 0x10FC) & 0x0000C000) > 0 &&
       (CAAM_READ(CAAM_BASE | 0x10FC) & 0x00003000)  == 0) {
    }
    if ((CAAM_READ(CAAM_BASE | 0x10FC) & 0x000000C0) == 0xC0) {
        /* owns the page can dealloc it */
        CAAM_WRITE(CAAM_BASE | 0x10F4, (page << 16) | 0x2);
        while ((CAAM_READ(CAAM_BASE | 0x10FC) & 0x0000C000) > 0 &&
               (CAAM_READ(CAAM_BASE | 0x10FC) & 0x00003000)  == 0) {}
        if ((CAAM_READ(CAAM_BASE | 0x10FC) & 0x00003000)  > 0) {
            /* error while deallocating page */
            return MemoryMapMayNotBeEmpty; /* PSP set on page or is unavailable */
        }
    }
    else {
        /* check if owned by someone else */
        if ((CAAM_READ(CAAM_BASE | 0x10FC) & 0x000000C0) != 0) {
            return MemoryMapMayNotBeEmpty;
        }
    }

    /* allocate page to partition */
    CAAM_WRITE(CAAM_BASE | 0x10F4, (page << 16) | (par << 8) | 0x1);
    /* wait for alloc cmd to complete */
    while ((CAAM_READ(CAAM_BASE | 0x10FC) & 0x0000C000) > 0 &&
       (CAAM_READ(CAAM_BASE | 0x10FC) & 0x00003000)  == 0) {
    }

    if ((CAAM_READ(CAAM_BASE | 0x10FC) & 0x00003000) > 0) {
        return MemoryOperationNotPerformed;
    }

    /* double check ownership now of page */
    CAAM_WRITE(CAAM_BASE | 0x10F4, (page << 16) | 0x5);
    /* wait for inquiry cmd to complete */
    while ((CAAM_READ(CAAM_BASE | 0x10FC) & 0x0000C000) > 0 &&
       (CAAM_READ(CAAM_BASE | 0x10FC) & 0x00003000)  == 0) {
    }
    if ((CAAM_READ(CAAM_BASE | 0x10FC) & 0x0000000F) == 0 ||
        (CAAM_READ(CAAM_BASE | 0x10FC) & 0x00003000) > 0) {
        /* page not owned */
        return MemoryOperationNotPerformed;
    }

    return Success;
}


/* Gets the status of a job. Returns Waiting if no output jobs ready to be
 * read.
 * If no jobs are done then return 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, UINT4* status)
{
    UINT4 reg = CAAM_READ(CAAM_BASE | 0x1044); /* JRSTAR0 status */
    if (status) {
        *status = 0;
    }

    /* check for DECO, CCB, and Job Ring error state JRSTAR0 register */
    if (((reg & 0xF0000000) == 0x20000000) ||         /* CCB error */
        ((reg & 0xF0000000) == 0x40000000)||  /* DECO error */
        ((reg & 0xF0000000) == 0x60000000)) { /* Job Ring error */

        if ((reg & 0x0000000F) > 0) {
            *status = reg;
            return Failure;
        }
    }

    /* Check number of done jobs in output list */
    reg = CAAM_READ(CAAM_BASE | 0x103C);
    if ((reg & 0x000003FF) > 0) {
        UINT4* out = (UINT4*)(dev->ring.JobOut);
        if (status) {
            *status = out[1];
        }

        if ((dev->ring.Desc ^ 0xF0000000) != out[0]) {
            db_printf("CAAM job completed vs expected mismatch");
            return NoActivityReady;
        }

        if (out[1] > 0) {
            return Failure;
        }

        /* increment jobs removed */
        CAAM_WRITE(CAAM_BASE | 0x1034, 1);
    }
    else {
        /* check if the CAAM is idle and not processing any descriptors */
        if ((CAAM_READ(CAAM_BASE | 0x0FD4) & 0x00000002) == 2 /* idle */
        && (CAAM_READ(CAAM_BASE | 0x0FD4) & 0x00000001) == 0) {
            return NoActivityReady;
        }

        return Waiting;
    }

    return Success;
}


/* Initialize CAAM RNG
 * returns 0 on success */
static int caamInitRng(struct CAAM_DEVICE* dev)
{
    UINT4 reg, status;
    int ret = 0;

    /* Set up use of the TRNG for seeding wolfSSL HASH-DRBG */
    CAAM_WRITE(CAAM_RTMCTL, CAAM_PRGM);
    CAAM_WRITE(CAAM_RTMCTL, CAAM_READ(CAAM_RTMCTL) | 0x40); /* reset */

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

    /* Set up delay for TRNG @TODO Optimizations?
     * Shift left with RTSDCTL because 0-15 is for sample number
     * Also setting the max and min frequencies */
    CAAM_WRITE(CAAM_RTSDCTL, (CAAM_ENT_DLY << 16) | 0x09C4);
    CAAM_WRITE(CAAM_RTFRQMIN, CAAM_ENT_DLY >> 1); /* 1/2      */
    CAAM_WRITE(CAAM_RTFRQMAX, CAAM_ENT_DLY << 3); /* up to 8x */

    /* Set back to run mode and clear RTMCL error bit */
    reg = CAAM_READ(CAAM_RTMCTL) ^ CAAM_PRGM;

    CAAM_WRITE(CAAM_RTMCTL, reg);
    reg = CAAM_READ(CAAM_RTMCTL);
    reg |= CAAM_CTLERR;
    CAAM_WRITE(CAAM_RTMCTL, reg);

    /* check input slot is available and then add */
    if (CAAM_READ(CAAM_BASE | 0x1014) > 0) {
        UINT4* in = (UINT4*)dev->ring.JobIn;

        memcpy((unsigned char*)dev->ring.Desc, (unsigned char*)wc_rng_start,
        sizeof(wc_rng_start));

        in[0] = dev->ring.Desc ^ 0xF0000000; /* physical address */
        CAAM_WRITE(CAAM_IRJAR0, 0x00000001);
    }
    else {
        return Waiting;
    }

    do {
        ret = caamGetJob(dev, &status);
        /* @TODO use a better way to chill out CPU. */
    } while (ret == Waiting);

    return ret;
}


static Error caamDoJob(struct DescStruct* desc)
{
    Error ret;
    UINT4 status;

    /* clear and set desc size */
    desc->desc[0] &= 0xFFFFFF80;
    desc->desc[0] += desc->idx;

    /* check input slot is available and then add */
    if (CAAM_READ(CAAM_BASE | 0x1014) > 0) {
        UINT4* in = (UINT4*)desc->caam->ring.JobIn;

        memcpy((unsigned char*)desc->caam->ring.Desc, (unsigned char*)desc->desc,
        (desc->idx + 1) * sizeof(UINT4));

        in[0] = desc->caam->ring.Desc ^ 0xF0000000; /* physical address */
        CAAM_WRITE(CAAM_IRJAR0, 0x00000001);
    }
    else {
        return Waiting;
    }

    do {
        ret = caamGetJob(desc->caam, &status);
    /* @TODO use a better way to chill out CPU. */
    } while (ret == Waiting);

    if (status != 0 || ret != Success) {
        #if 0
        /* Used during testing to print out descriptor */
        {
        char msg[2048];
        char* pt = msg;
        int z;

        memset(msg, 0, sizeof(msg));
        for (z = 0; z < desc->idx; z++) {
                    snprintf(pt, sizeof(msg) - (z * 21), "desc[%d] = 0x%8.8x, ",
                z, desc->desc[z]);
            pt += 21;
        }
        snprintf(pt, sizeof(msg) - (z * 21), "status = 0x%8.8x\n", status);
        if (desc->buf[0].data != 0) { /* for testing */
            memcpy((char*)desc->buf[0].data, msg, sizeof(msg));
        }
        }
        #endif


        /* try to reset after error */
        caamReset();
        return ret;
    }

    return Success;
}


/* handle input or output buffers
 * NOTES: if sz == 0 then read all the rest of the buffers available
 * when align == 1 then there is no alignment constraints
 *
 * returns the data size in bytes on success. With failure a negative value is
 * returned.
 */
static int caamAddIO(struct DescStruct* desc, UINT4 options, UINT4 sz,
    UINT4 align, UINT4* idx)
{
    int i, outSz = 0;

    if (align == 0) {
        return -1; /* programming error */
    }

    for (i = *idx; i < desc->DescriptorCount; i++) {
        /* input must be a multiple of "align" bytes */
        struct buffer* buf = &desc->buf[i];
        int blocks = buf->dataSz / align;
        Address data   = buf->data;
        Address dataSz = buf->dataSz;

        if (outSz >= sz && sz != 0) {
            break;
        }

        if (dataSz % align > 0) {
            /* store potential overlap */
            int tmpSz  = dataSz % align;
            int add = (tmpSz < (align - desc->alignIdx)) ? tmpSz :
                align - desc->alignIdx;
            unsigned char* local = (unsigned char*)desc->alignBuf;

            /* if already something in the buffer then add from front */
            if (desc->alignIdx > 0) {
                memcpy((unsigned char*)&local[desc->alignIdx],
                (unsigned char*)data, add);
                data += add;
            }
            else {
                memcpy((unsigned char*)&local[desc->alignIdx],
                (unsigned char*)data + (blocks * align), add);
            }
            dataSz -= add;
            desc->alignIdx += add;
        }

        if (desc->alignIdx == align) {
            desc->lastFifo = desc->idx;
            if (desc->idx + 2 > MAX_DESC_SZ) {
                return -1;
            }
            desc->desc[desc->idx++] = options + desc->alignIdx;
            desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->alignBuf);
            ASP_FlushCaches((Address)desc->alignBuf, desc->alignIdx);
            outSz += desc->alignIdx;
        }

        if (blocks > 0) {
            desc->lastFifo = desc->idx;
            if (desc->idx + 2 > MAX_DESC_SZ) {
                return -1;
            }
            desc->desc[desc->idx++] = options + (blocks * align);
            desc->desc[desc->idx++] = BSP_VirtualToPhysical(data);
            outSz += (blocks * align);

            /* only one buffer available for align cases so exit here and make
            a new descriptor after running current one */
            if (desc->alignIdx == align) {
                desc->alignIdx = 0;
                i++; /* start at next buffer */
                break;
            }
        }
    }

    *idx = i;
    return outSz;
}


/******************************************************************************
  IODevice Register Read and Write
  ****************************************************************************/

static Error caamReadRegister(IODeviceVector ioCaam, Value reg, Value *out)
{
    if (reg < MIN_READ_REG || reg > MAX_READ_REG) {
         return IllegalRegisterNumber;
    }

    switch (reg) {
    case CAAM_STATUS:
    case CAAM_VERSION_MS:
    case CAAM_VERSION_LS:
    case CAMM_SUPPORT_MS:
    case CAMM_SUPPORT_LS:
    case CAAM_RTMCTL:
        *out = CAAM_READ(reg);
        break;

    default:
        return IllegalRegisterNumber;
    }

    (void)ioCaam;
    return Success;
}


static Error caamWriteRegister(IODeviceVector ioCaam, Value reg, Value in)
{
    /* Should be no need for writes */
    return OperationNotAllowedOnTheUniversalIODevice;
}


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

/* limit on size due to size of job ring being 64 word32's */
static Error caamBlob(struct DescStruct* desc)
{
    Error err;
    UINT4 keyType = 0x00000C08; /* default red */
    UINT4 i = 0;
    int sz = 0, ret;

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

    /*default to Red Key type, with offset of 12 and 8 byte load to context 2*/
    desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS2 | CAAM_IMM | keyType);

    /* add key modifier */
    if (i < desc->DescriptorCount) {
        UINT4* pt;
        Address data   = desc->buf[i].data;
        Address dataSz = desc->buf[i].dataSz;

        pt = (UINT4*)data;
        if (dataSz < 8) { /* expecting 8 bytes for key modifier*/
            return TooManyBuffers;
        }
        desc->desc[desc->idx++] = pt[0];
        desc->desc[desc->idx++] = pt[1];
    }

    /* add input */
    while (sz < desc->inputSz && i < desc->DescriptorCount) {
        ret = caamAddIO(desc, CAAM_SEQI, desc->inputSz - sz, 1, &i);
        if (ret < 0) { /* handle error case */
            return TooManyBuffers;
        }
        sz += ret;
    }
    desc->outputIdx = i;

    /* add output */
    if (caamAddIO(desc, CAAM_SEQO, 0, 1, &i) < 0) {
        return TooManyBuffers;
    }

    if (desc->idx + 1 > MAX_DESC_SZ) {
        return Failure;
    }
    desc->desc[desc->idx++] = CAAM_OP |  CAAM_OPID_BLOB | desc->type;

    if ((err = caamDoJob(desc)) != Success) {
        return err;
    }

    /* flush output buffers */
    for (i = desc->outputIdx; i < desc->DescriptorCount; i++) {
        ASP_FlushCaches(desc->buf[i].data, desc->buf[i].dataSz);
    }

    return Success;
}


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

/* returns amount written on success and negative value in error case.
 * Is different from caamAddIO in that it only adds a single input buffer
 * rather than multiple ones.
 */
static int caamAesInput(struct DescStruct* desc, UINT4* idx, int align,
    UINT4 totalSz)
{
    int sz;
    UINT4 i = *idx;

    /* handle alignment constraints on input */
    if (desc->alignIdx > 0) {
        sz = desc->alignIdx;

        /* if there is more input buffers then add part of it */
        if (i < desc->outputIdx && i < desc->DescriptorCount) {
            sz = align - desc->alignIdx;
            sz = (sz <= desc->buf[i].dataSz) ? sz : desc->buf[i].dataSz;
            memcpy((unsigned char*)(desc->alignBuf) + desc->alignIdx,
                   (unsigned char*)(desc->buf[i].data), sz);

            desc->buf[i].dataSz -= sz;
            desc->buf[i].data   += sz;
            sz += desc->alignIdx;
        }

        if (desc->idx + 2 > MAX_DESC_SZ) {
            return -1;
        }
        ASP_FlushCaches((Address)desc->alignBuf, sz);
        desc->desc[desc->idx++] = (CAAM_FIFO_L | FIFOL_TYPE_LC1 |
                                   CAAM_CLASS1 | FIFOL_TYPE_MSG) + sz;
        desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->alignBuf);
        desc->alignIdx = 0;
    }
    else {
        sz = desc->buf[i].dataSz;
        if ((totalSz + sz) == desc->inputSz) { /* not an issue on final */
            align = 1;
        }

        desc->alignIdx = sz % align;
        if (desc->alignIdx != 0) {
            sz -= desc->alignIdx;
            memcpy((unsigned char*)desc->alignBuf,
                   (unsigned char*)(desc->buf[i].data) + sz,
                   desc->alignIdx);
        }

        if (desc->idx + 2 > MAX_DESC_SZ) {
            return -1;
        }
        desc->desc[desc->idx++] = (CAAM_FIFO_L | FIFOL_TYPE_LC1 |
                                   CAAM_CLASS1 | FIFOL_TYPE_MSG) + sz;
        desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->buf[i].data);
        i++;
    }

    *idx = i;
    return sz;
}


/* returns enum Success on success, all other return values should be
 * considered an error.
 *
 * ofst    is the amount of leftover buffer from previous calls
 * inputSz is the amount of input in bytes that is being matched to output
 */
static Error caamAesOutput(struct DescStruct* desc, int* ofst, UINT4 inputSz)
{
    int offset = *ofst;

    if (desc->output != 0 && offset > 0 && inputSz > 0) {
        UINT4 addSz;

        /* handle potential leftovers */
        addSz = (inputSz >= offset) ? offset : inputSz;

        inputSz -= addSz;
        desc->desc[desc->idx++] = CAAM_FIFO_S | FIFOS_TYPE_MSG + addSz;
        if (inputSz > 0) { /* check if expecting more output */
            desc->desc[desc->idx - 1] |= CAAM_FIFOS_CONT;
        }
        desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->output);

        if (addSz == offset) {
            /* reset */
            desc->output = 0;
            offset       = 0;
        }
        else {
            offset -= addSz;
            desc->output += addSz;

            if (offset < 0) {
                return TransferFailed;
            }
        }
    }

    for (; desc->lastIdx < desc->DescriptorCount; desc->lastIdx++) {
        struct buffer* buf = &desc->buf[desc->lastIdx];

        if (inputSz > 0) {
            int tmp;

            if (buf->dataSz <= inputSz) {
                tmp = buf->dataSz;
            }
            else {
                offset = buf->dataSz - inputSz;
                tmp    = inputSz;
                desc->output = buf->data + tmp;
            }
            inputSz -= tmp;
            if (desc->idx + 2 > MAX_DESC_SZ) {
                return TransferFailed;
            }
            desc->desc[desc->idx++] = CAAM_FIFO_S | FIFOS_TYPE_MSG + tmp;
            if (inputSz > 0) { /* check if expecting more output */
                desc->desc[desc->idx - 1] |= CAAM_FIFOS_CONT;
            }
            desc->desc[desc->idx++] = BSP_VirtualToPhysical(buf->data);
        }
        else {
            break;
        }
    }

    *ofst = offset;
    return Success;
}


/* check size of output and get starting buffer for it */
static Error caamAesOutSz(struct DescStruct* desc, UINT4 i)
{
    int sz = 0;

    for (desc->outputIdx = i; desc->outputIdx < desc->DescriptorCount &&
    sz < desc->inputSz; desc->outputIdx++) {
        sz += desc->buf[desc->outputIdx].dataSz;
    }
    desc->lastIdx = desc->outputIdx;

    /* make certain that output size is same as input */
    sz = 0;
    for (; desc->lastIdx < desc->DescriptorCount; desc->lastIdx++) {
        sz += desc->buf[desc->lastIdx].dataSz;
    }
    if (sz != desc->inputSz) {
        return SizeIsTooLarge;
    }
    desc->lastIdx = desc->outputIdx;

    return Success;
}


/* AES operations follow the buffer sequence of KEY -> (IV) -> Input -> Output
 */
static Error caamAes(struct DescStruct* desc)
{
    struct buffer* ctx[3];
    struct buffer* iv[3];
    Value ofst = 0;
    Error err;
    UINT4 i, totalSz = 0;
    int ctxIdx = 0;
    int ivIdx  = 0;
    int offset = 0;
    int align  = 1;
    int sz     = 0;

    int ctxSz = desc->ctxSz;

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

    if (ctxSz != 16 && ctxSz != 24 && ctxSz != 32) {
        return ArgumentError;
    }

    /* get key */
    for (i = 0; i < desc->DescriptorCount; i++) {
        struct buffer* buf = &desc->buf[i];
        unsigned char* local = (unsigned char*)desc->ctxBuf;

        if (sz < ctxSz && sz < (MAX_CTX * sizeof(UINT4))) {
            ctx[ctxIdx] = buf;
            sz += buf->dataSz;

            memcpy((unsigned char*)&local[offset],
                   (unsigned char*)ctx[ctxIdx]->data, ctx[ctxIdx]->dataSz);
            offset += ctx[ctxIdx]->dataSz;
            ctxIdx++;
        }
        else {
            break;
        }
    }

    /* sanity checks on size of key */
    if (sz > ctxSz) {
        return SizeIsTooLarge;
    }
    if (ctxSz > (MAX_CTX * sizeof(UINT4)) - 16) {
        return ArgumentError;
    }

    /* Flush cache of ctx buffer then :
       Add KEY Load command          0x0220000X
       Add address to read key from  0xXXXXXXXX */
    ASP_FlushCaches((Address)desc->ctxBuf, ctxSz);
    if (desc->idx + 2 > MAX_DESC_SZ) {
        return TransferFailed;
    }
    desc->desc[desc->idx++] = (CAAM_KEY | CAAM_CLASS1 | CAAM_NWB) + ctxSz;
    desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->ctxBuf);

    /* 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 */

            sz = 0;
            offset = 0;
            for (; i < desc->DescriptorCount; i++) {
                struct buffer* buf = &desc->buf[i];
                unsigned char* local = (unsigned char*)desc->iv;

                if (sz < maxSz) {
                    iv[ivIdx] = buf;

                    if (buf->dataSz + sz > maxSz) {
                        return SizeIsTooLarge;
                    }

                    sz += buf->dataSz;
                    memcpy((unsigned char*)&local[offset],
                        (unsigned char*)iv[ivIdx]->data, iv[ivIdx]->dataSz);
                    offset += iv[ivIdx]->dataSz;
                    ivIdx++;
                }
                else {
                    break;
                }
            }

            if (sz != maxSz) {
                /* invalid IV size */
                return SizeIsTooLarge;
            }

            ASP_FlushCaches((Address)desc->iv, maxSz);
            if (desc->idx + 2 > MAX_DESC_SZ) {
                return TransferFailed;
            }
            desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS1 | ofst) + maxSz;
            desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->iv);
         }
         break;

        default:
            return OperationNotImplemented;
    }

    /* write operation */
    if (desc->idx + 1 > MAX_DESC_SZ) {
        return TransferFailed;
    }
    desc->desc[desc->idx++] = CAAM_OP | CAAM_CLASS1 | desc->type |
             CAAM_ALG_UPDATE | desc->state;

    /* find output buffers */
    if (caamAesOutSz(desc, i) != Success) {
        return SizeIsTooLarge;
    }

    /* set alignment constraints */
    if (desc->type == CAAM_AESCBC || desc->type == CAAM_AESECB) {
        align = 16;
    }

    /* indefinite loop for input/output buffers */
    desc->headIdx = desc->idx;
    desc->output  = 0;
    offset = 0; /* store left over amount for output buffer */
    do {
        desc->idx = desc->headIdx; /* reset for each loop */

        /* add a single input buffer (multiple ones was giving deco watch dog
         * time out errors on the FIFO load of 1c.
         * @TODO this could be a place for optimization if more data could be
         * loaded in at one time */
        if ((sz = caamAesInput(desc, &i, align, totalSz)) < 0) {
            return TransferFailed;
        }
        totalSz += sz;

        if (caamAesOutput(desc, &offset, sz) != Success) {
            return TransferFailed;
        }

        /* store updated IV */
        if (ivIdx > 0) {
            if (desc->idx + 2 > MAX_DESC_SZ) {
                return TransferFailed;
            }
            desc->desc[desc->idx++] = CAAM_STORE_CTX | CAAM_CLASS1 | ofst | 16;
            desc->desc[desc->idx++] = BSP_VirtualToPhysical((Address)desc->iv);
        }

        if ((err = caamDoJob(desc)) != Success) {
            return err;
        }
        ASP_FlushCaches((Address)desc->iv, 16);
    } while (desc->lastIdx < desc->DescriptorCount || offset > 0);

    /* flush output buffers */
    for (i = desc->outputIdx; i < desc->lastIdx; i++) {
        ASP_FlushCaches(desc->buf[i].data, desc->buf[i].dataSz);
    }

    /* handle case with IV */
    if (ivIdx > 0) {
        unsigned char* pt = (unsigned char*)desc->iv;
        ASP_FlushCaches((Address)pt, 16);
        for (i = 0; i < ivIdx; i++) {
            memcpy((unsigned char*)iv[i]->data, pt, iv[i]->dataSz);
            pt += iv[i]->dataSz;
            ASP_FlushCaches(iv[i]->data, iv[i]->dataSz);
        }
    }

    return Success;
}


/******************************************************************************
  CAAM AEAD Operations
  ****************************************************************************/

/* AEAD operations follow the buffer sequence of KEY -> (IV or B0 | CTR0) -> (AD)
 * -> Input -> Output
 *
 */
static Error caamAead(struct DescStruct* desc)
{
    struct buffer* ctx[3];
    struct buffer* iv[3];
    Value ofst    = 0;
    UINT4 state   = CAAM_ALG_INIT;
    UINT4 totalSz = 0;
    Error err;
    UINT4 i;
    int ctxIdx = 0;
    int ivIdx  = 0;
    int offset = 0;
    int sz     = 0;
    int ivSz   = 32; /* size of B0 | CTR0 for CCM mode */
    int ctxSz  = desc->ctxSz;
    int align  = 16; /* input should be multiples of 16 bytes unless is final */
    int opIdx;

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

    /* sanity check is valid AES key size */
    if (ctxSz != 16 && ctxSz != 24 && ctxSz != 32) {
        return ArgumentError;
    }

    /* get key */
    for (i = 0; i < desc->DescriptorCount; i++) {
        struct buffer* buf = &desc->buf[i];
        unsigned char* local = (unsigned char*)desc->ctxBuf;

        if (sz < ctxSz && sz < (MAX_CTX * sizeof(UINT4))) {
            ctx[ctxIdx] = buf;
            sz += buf->dataSz;

            memcpy((unsigned char*)&local[offset],
                   (unsigned char*)ctx[ctxIdx]->data, ctx[ctxIdx]->dataSz);
            offset += ctx[ctxIdx]->dataSz;
            ctxIdx++;
        }
        else {
            break;
        }
    }

    /* sanity checks on size of key */
    if (sz > ctxSz) {
        return SizeIsTooLarge;
    }

    /* Flush cache of ctx buffer then :
       Add KEY Load command          0x0220000X
       Add address to read key from  0xXXXXXXXX */
    ASP_FlushCaches((Address)desc->ctxBuf, ctxSz);
    if (desc->idx + 2 > MAX_DESC_SZ) {
        return TransferFailed;
    }
    desc->desc[desc->idx++] = (CAAM_KEY | CAAM_CLASS1 | CAAM_NWB) + ctxSz;
    desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->ctxBuf);

    desc->headIdx = desc->idx;
    desc->output  = 0;
    offset = 0; /* store left over amount for output buffer */
    do {
        desc->idx = desc->headIdx; /* reset for each loop */

        /* write operation */
        if (desc->idx + 1 > MAX_DESC_SZ) {
            return TransferFailed;
        }
        opIdx = desc->idx;
        desc->desc[desc->idx++] = CAAM_OP | CAAM_CLASS1 | state | desc->type |
                                  desc->state;

        /* get IV if needed by algorithm */
        switch (desc->type) {
            case CAAM_AESCCM:
                if ((state & CAAM_ALG_INIT) == CAAM_ALG_INIT) {
                    sz = 0;
                    offset = 0;
                    for (; i < desc->DescriptorCount; i++) {
                        struct buffer* buf = &desc->buf[i];
                        unsigned char* local = (unsigned char*)desc->iv;

                        if (sz < ivSz) {
                            iv[ivIdx] = buf;

                            if (buf->dataSz + sz > ivSz) {
                                return SizeIsTooLarge;
                            }

                            sz += buf->dataSz;
                            memcpy((unsigned char*)&local[offset],
                            (unsigned char*)iv[ivIdx]->data, iv[ivIdx]->dataSz);
                            offset += iv[ivIdx]->dataSz;
                            ivIdx++;
                        }
                        else {
                            break;
                        }
                    }

                    if (sz != ivSz) {
                        /* invalid IV size */
                        return SizeIsTooLarge;
                    }
                    offset = 0;
                }

                ASP_FlushCaches((Address)desc->iv, ivSz);
                if (desc->idx + 2 > MAX_DESC_SZ) {
                    return TransferFailed;
                }
                desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS1 | ofst)
                                           + ivSz;
                desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->iv);
                break;

            default:
                return OperationNotImplemented;
        }


        /********* handle AAD -- is only done with Init **********************/
        if ((state & CAAM_ALG_INIT) == CAAM_ALG_INIT) {
            if ((desc->type == CAAM_AESCCM) && (desc->aadSz > 0)) {
                /* set formatted AAD buffer size for CCM */
                ASP_FlushCaches((Address)desc->aadSzBuf, sizeof(desc->aadSzBuf));
                desc->desc[desc->idx++] = CAAM_FIFO_L | CAAM_CLASS1 |
                    FIFOL_TYPE_AAD + desc->aadSz;
                desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->aadSzBuf);

                /* now set aadSz to unformatted version for getting buffers */
                if (desc->aadSz == 2) {
                    unsigned char* pt = (unsigned char*)desc->aadSzBuf;
                    desc->aadSz = (((UINT4)pt[0] & 0xFF) << 8) |
                           ((UINT4)pt[1] & 0xFF);
                }
                else {
                    unsigned char* pt = (unsigned char*)desc->aadSzBuf;
                    desc->aadSz = (((UINT4)pt[2] & 0xFF) << 24) |
                                  (((UINT4)pt[3] & 0xFF) << 16) |
                                  (((UINT4)pt[4] & 0xFF) <<  8) |
                                   ((UINT4)pt[5] & 0xFF);
                }
            }

            /* get additional data buffers */
            if (desc->aadSz > 0) {
                sz = 0;
                for (; i < desc->DescriptorCount; i++) {
                    struct buffer* buf = &desc->buf[i];
                    if (sz < desc->aadSz) {
                        if (desc->idx + 2 > MAX_DESC_SZ) {
                            return TransferFailed;
                        }
                        desc->lastFifo = desc->idx;
                        desc->desc[desc->idx++] = CAAM_FIFO_L | CAAM_CLASS1 |
                                                  FIFOL_TYPE_AAD + buf->dataSz;
                        desc->desc[desc->idx++] = BSP_VirtualToPhysical(buf->data);
                        sz += buf->dataSz;
                    }
                    else {
                        break;
                    }
                }

                /* flush AAD from FIFO and pad it to 16 byte block */
                desc->desc[desc->lastFifo] |= FIFOL_TYPE_FC1;
            }

            /* find output buffers */
            if (caamAesOutSz(desc, i) != Success) {
                return SizeIsTooLarge;
            }
        }

        /* handle alignment constraints on input */
        if ((sz = caamAesInput(desc, &i, align, totalSz)) < 0) {
            return TransferFailed;
        }
        totalSz += sz;

        /* handle output buffers  */
        if (caamAesOutput(desc, &offset, sz) != Success) {
            return TransferFailed;
        }

        /* store updated IV, if is last then set offset and final for MAC */
        if ((desc->lastIdx == desc->DescriptorCount) && (offset == 0)) {
            ivSz = 16;
            if (desc->state == CAAM_ENC) {
                ofst = 32 << 8; /* offset is in 15-8 bits */
            }
            else {
                ofst = 0;
            }
            desc->desc[opIdx] |= CAAM_ALG_FINAL;
        }
        else {
            /* if not final then store and use ctr and encrypted ctr from
                context dword 2,3 and 4,5. Also store MAC and AAD info from
                context dword 6. */
            ivSz = 56;
            ofst = 0;
        }

        if (desc->idx + 2 > MAX_DESC_SZ) {
            return TransferFailed;
        }
        desc->desc[desc->idx++] = CAAM_STORE_CTX | CAAM_CLASS1 | ofst | ivSz;
        desc->desc[desc->idx++] = BSP_VirtualToPhysical((Address)desc->iv);

        if ((err = caamDoJob(desc)) != Success) {
            return err;
        }
        state = CAAM_ALG_UPDATE;
    } while (desc->lastIdx < desc->DescriptorCount || offset > 0);

    /* flush output buffers */
    for (i = desc->outputIdx; i < desc->lastIdx; i++) {
        ASP_FlushCaches(desc->buf[i].data, desc->buf[i].dataSz);
    }

    /* handle case with IV (This is also the output of MAC with AES-CCM) */
    if (ivIdx > 0) {
        unsigned char* pt = (unsigned char*)desc->iv;
        ASP_FlushCaches((Address)pt, ivSz);
        for (i = 0; i < ivIdx; i++) {
            memcpy((unsigned char*)iv[i]->data, pt, iv[i]->dataSz);
            pt += iv[i]->dataSz;
            ASP_FlushCaches(iv[i]->data, iv[i]->dataSz);
        }
    }

    return Success;
}


/******************************************************************************
  CAAM SHA Operations
  ****************************************************************************/
static int shaSize(struct DescStruct* desc)
{
    /* sanity check on dataSz for context */
    switch (desc->type) {
        case CAAM_MD5:
            return CAAM_MD5_CTXSZ;

        case CAAM_SHA:
            return CAAM_SHA_CTXSZ;

        case CAAM_SHA224:
            return CAAM_SHA224_CTXSZ;

        case CAAM_SHA256:
            return CAAM_SHA256_CTXSZ;

        case CAAM_SHA384:
            return CAAM_SHA384_CTXSZ;

        case CAAM_SHA512:
            return CAAM_SHA512_CTXSZ;

        default:
            return 0;
    }
}

/* SHA operations
 * start: the index to start traversing through buffers. It's needed to allow
 *       for HMAC to reuse this code.
 *
 * return Success on success. All other return values are considered a fail
 *         case.
 */
static Error caamSha(struct DescStruct* desc, int start)
{
    struct buffer* ctx[3];
    Error err;
    UINT4 i;
    int sz     = 0;
    int ctxIdx = 0;
    int offset = 0;

    int ctxSz = shaSize(desc);

    /* get context */
    for (i = start; i < desc->DescriptorCount; i++) {
        struct buffer* buf = &desc->buf[i];
        unsigned char* local = (unsigned char*)desc->iv;

        if (sz < ctxSz && sz < (MAX_CTX * sizeof(UINT4))) {
            ctx[ctxIdx] = buf;
            sz += buf->dataSz;

            if (ctx[ctxIdx]->dataSz + offset > (MAX_CTX * sizeof(UINT4))) {
                return SizeIsTooLarge;
            }
            memcpy((unsigned char*)&local[offset], (unsigned char*)ctx[ctxIdx]->data,
            ctx[ctxIdx]->dataSz);
            offset += ctx[ctxIdx]->dataSz;
            ctxIdx++;
        }
        else {
            break;
        }
    }
    if (sz > ctxSz || ctxSz > (MAX_CTX * sizeof(UINT4))) {
        return SizeIsTooLarge;
    }

    ASP_FlushCaches((Address)desc->iv, ctxSz);
    /*Manage Context (current digest + 8 byte running message length)*/
    if ((desc->state & CAAM_ALG_INIT) != CAAM_ALG_INIT) {
        /* don't load into the class 2 context register on inti.
           Found that loading in caused context to not get set. */
        if (desc->idx + 2 > MAX_DESC_SZ) {
            return TransferFailed;
        }
        desc->desc[desc->idx++] = (CAAM_LOAD_CTX | CAAM_CLASS2) + ctxSz;
        desc->desc[desc->idx++] = BSP_VirtualToPhysical((Address)desc->iv);
    }

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

    /* Check case where there is no input.
       In all cases the FIFO Load should be flushed. */
    if (i == desc->DescriptorCount) {
        desc->lastFifo = desc->idx;
        if (desc->idx + 1 > MAX_DESC_SZ) {
            return TransferFailed;
        }
        desc->desc[desc->idx++] = CAAM_FIFO_L | CAAM_CLASS2 |
        FIFOL_TYPE_MSG | CAAM_IMM;
    }

    /* save index for looping over input */
    desc->headIdx = desc->idx;
    do {
        desc->idx = desc->headIdx; /* reset for each loop */
        if (i < desc->DescriptorCount) {
            /* input must be a multiple of 64 bytes unless in final call */
            if (((desc->state & CAAM_ALG_FINAL) == CAAM_ALG_FINAL)) {
                if (caamAddIO(desc, (CAAM_FIFO_L | CAAM_CLASS2 |
                    FIFOL_TYPE_MSG), 0, 1, &i) < 0) {
                    return TooManyBuffers;
                }
            }
            else {
                if (caamAddIO(desc, (CAAM_FIFO_L | CAAM_CLASS2 |
                    FIFOL_TYPE_MSG), 0, 64, &i) < 0) {
                    return TooManyBuffers;
                }
            }
        }

        desc->desc[desc->lastFifo] |= FIFOL_TYPE_LC2;

        /* set context out */
        if (desc->idx + 2 > MAX_DESC_SZ) {
            return TransferFailed;
        }
        desc->desc[desc->idx++] = CAAM_STORE_CTX | CAAM_CLASS2 + ctxSz;
        desc->desc[desc->idx++] = BSP_VirtualToPhysical(desc->iv);

        if ((err = caamDoJob(desc)) != Success) {
            return err;
        }
        /* flush context output for each loop */
        ASP_FlushCaches((Address)desc->iv, ctxSz);
    } while (i < desc->DescriptorCount);

    /* store context to buffers */
    {
        unsigned char* pt = (unsigned char*)desc->iv;
        for (i = 0; i < ctxIdx; i++) {
            memcpy((unsigned char*)ctx[i]->data, pt, ctx[i]->dataSz);
            pt += ctx[i]->dataSz;
            ASP_FlushCaches(ctx[i]->data, ctx[i]->dataSz);
        }
    }

    return Success;
}


/******************************************************************************
  CAAM TRNG Operations
  ****************************************************************************/

/* If Entropy is not ready then return Waiting */
static Error caamRng(struct DescStruct* desc)
{
    int sz = 0;
    int i;

    Address  reg; /* RTENT reg to read */
    int ofst = sizeof(UINT4);


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

    /* check state of TRNG */
    if ((CAAM_READ(CAAM_RTSTATUS) & 0x0000FFFF) > 0) {
        return Failure;
    }

    /* read entropy from RTENT registers */
    reg = CAAM_RTENT0;

    for (i = 0; i < desc->DescriptorCount; i++) {
        struct buffer* buf = &desc->buf[i];
        unsigned char* local = (unsigned char*)buf->data;
        sz = buf->dataSz;

        while (sz > 3 && reg <= CAAM_RTENT11) {
            *((UINT4*)local) = CAAM_READ(reg);
            reg    += ofst;
            local  += ofst;
            sz     -= ofst;
        }

        if (reg > CAAM_RTENT11 && sz > 0) {
            return SizeIsTooLarge;
        }

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

        ASP_FlushCaches(buf->data, buf->dataSz);
    }


    /* read RTENT11 to trigger new entropy generation */
    if (reg != CAAM_RTENT11) {
        CAAM_READ(CAAM_RTENT11);
    }

    return Success;
}


/******************************************************************************
  IODevice Start, Transfer and Finish Buffer
  ****************************************************************************/
/* args[0] holds the state such as encrypt/decrypt or init/update/final
 * args[1] holds the ctx/key size
 * args[2] holds the input size
 * args[3] dependent on algo (such as AAD size with AES-CCM) */
static Error caamTransferStart(IODeviceVector ioCaam,
    Value type, const volatile Value args[4])
{
    struct CAAM_DEVICE* local = (struct CAAM_DEVICE*)ioCaam;
    struct DescStruct*  desc;

    /* currently only one desc is available for use */
    desc = &local->DescArray[0];

    /* check if the desc is idle before using */
    if (GetIORequestStatus((IORequest)desc) != IdleIORequest) {
         return ResourceNotAvailable;
    }

    desc->idx    = 0;
    desc->output = 0;
    desc->ctxOut = 0;
    desc->outputIdx = 0;
    desc->alignIdx = 0;
    desc->lastFifo = 0;
    desc->state    = args[0];
    desc->ctxSz    = args[1];
    desc->inputSz  = args[2];
    desc->aadSz    = 0;
    desc->desc[desc->idx++] = CAAM_HEAD; /* later will put size to header*/

    switch (type) {
        case CAAM_AESECB:
        case CAAM_AESCBC:
            if (desc->inputSz % 16 != 0) {
                return ArgumentError;
            }
            /* fall through to break */
        case CAAM_AESCTR:
            break;

        case CAAM_AESCCM:
            memset((unsigned char*)desc->aadSzBuf, 0, sizeof(desc->aadSzBuf));
            if (args[3] > 0) {
                /* encode the length in */
                if (args[3] <= 0xFEFF) {
                    unsigned char* pt = (unsigned char*)desc->aadSzBuf;
                    desc->aadSz = 2;
                    pt[0] = ((args[3] & 0xFF00) >> 8);
                    pt[1] =  (args[3] & 0x00FF);
                }
                else if (args[3] <= 0xFFFFFFFF) {
                    unsigned char* pt = (unsigned char*)desc->aadSzBuf;
                    desc->aadSz = 6;
                    pt[0] = 0xFF; pt[1] = 0xFE;
                    pt[2] = ((args[3] & 0xFF000000) >> 24);
                    pt[3] = ((args[3] & 0x00FF0000) >> 16);
                    pt[4] = ((args[3] & 0x0000FF00) >>  8);
                    pt[5] =  (args[3] & 0x000000FF);
                }
            }
            break;

        case CAAM_MD5:
        case CAAM_SHA:
        case CAAM_SHA224:
        case CAAM_SHA256:
        case CAAM_SHA384:
        case CAAM_SHA512:
            break;

        case CAAM_BLOB_ENCAP:
        case CAAM_BLOB_DECAP:
            break;

        case CAAM_ENTROPY:
            break;

        default:
            /* unknown type */
            return UsageNotSupported;
    }

    desc->DescriptorCount = 0;
    desc->type    = type;
    desc->running = true;
    StartIORequest((IORequest)desc);

    /* For now only require READ permissions */
    SetIORequestBufferPermissions((IORequest)desc, MEMORY_READ);
    return Success;
}


static Error caamTransferBuffer(IODeviceVector TheIODeviceVector,
    IORequest req, IODescriptor NewIODescriptor,
    Address data, Address dataSz)
{
    struct DescStruct* desc = (struct DescStruct*)req;
    Error  err;

    switch (desc->type) {
        case CAAM_AESECB:
        case CAAM_AESCTR:
        case CAAM_AESCBC:
        case CAAM_AESCCM:

        case CAAM_MD5:
        case CAAM_SHA:
        case CAAM_SHA224:
        case CAAM_SHA256:
        case CAAM_SHA384:
        case CAAM_SHA512:

        case CAAM_BLOB_ENCAP:
        case CAAM_BLOB_DECAP:
        case CAAM_ENTROPY:
            { /* set buffer for transfer finish */
                struct buffer* buf;
                if (desc->DescriptorCount >= MAX_BUF) {
                    return TooManyBuffers;
                }
                buf = &desc->buf[desc->DescriptorCount];
                buf->data = data;
                buf->dataSz = dataSz;
            }
                err = Success;
            break;

        default:
            err = UsageNotSupported;
    }

    if (err != Success) {
        desc->running = false;
        DismissIORequest(req);
        return err;
    }

    desc->DescriptorCount++;
    return Success;
}


static Error caamTransferFinish(IODeviceVector ioCaam, IORequest req)
{
    struct DescStruct* desc = (struct DescStruct*)req;
    Error ret;

    /* construct desc */
    switch (desc->type) {
        case CAAM_AESECB:
        case CAAM_AESCTR:
        case CAAM_AESCBC:
            ret = caamAes(desc);
            break;

        case CAAM_AESCCM:
            ret = caamAead(desc);
            break;

        case CAAM_MD5:
        case CAAM_SHA:
        case CAAM_SHA224:
        case CAAM_SHA256:
        case CAAM_SHA384:
        case CAAM_SHA512:
            ret = caamSha(desc, 0);
            break;

        case CAAM_ENTROPY:
            ret = caamRng(desc);
            break;

        case CAAM_BLOB_ENCAP:
        case CAAM_BLOB_DECAP:
            ret = caamBlob(desc);
            break;

        default:
            ret = UsageNotSupported;
    }

    desc->running = false;
    DismissIORequest(req);
    return ret;
}


/******************************************************************************
  IODevice Interrupt and Init
  ****************************************************************************/

static Error caamTransferWrite(IODeviceVector ioCaam,
    IORequest req, Value dataSz, const volatile Value *data)
{
    DismissIORequest(req);
    return UsageNotSupported;
}


static void caamTransferAbort(IODeviceVector ioCaam, IORequest req)
{
    DismissIORequest(req);
}


static void caamTransferRecall(IODeviceVector ioCaam, IODescriptor req)
{

}


static void HandleInterrupt(Address id)
{
    struct CAAM_DEVICE* local = (struct CAAM_DEVICE*)id;
    Value InterruptStatus = INTERRUPT_AtomicWrite(&local->InterruptStatus, 0);
    int i;

    /* Loop through descriptors and try to dismiss them */
    for (i = 0; i < DESC_COUNT; i++) {
        struct DescStruct* desc = &local->DescArray[i];
        if (InterruptStatus & (1 << i)) {
            desc->running = false;
            if (GetIORequestStatus((IORequest)desc) == IORequestSuspended) {
                ContinueIORequest((IORequest)desc);
            }
            else {
                DismissIORequest((IORequest)desc);
            }
        }
    }
}


static Error caamCreate(IODeviceVector ioCaam)
{
    return Success;
}


void  InitCAAM(void)
{
    /* get IO vector and set it up */
    IODeviceVector ioCaam = &caam.caamVector;
    unsigned int reg;
    int   i;
    Error ret;


    ioCaam->Create         = &caamCreate;
    ioCaam->ReadRegister   = &caamReadRegister;
    ioCaam->WriteRegister  = &caamWriteRegister;

    ioCaam->TransferStart  = &caamTransferStart;
    ioCaam->TransferBuffer = &caamTransferBuffer;
    ioCaam->TransferWrite  = &caamTransferWrite;
    ioCaam->TransferFinish = &caamTransferFinish;
    ioCaam->TransferAbort  = &caamTransferAbort;
    ioCaam->TransferRecall = &caamTransferRecall;
#ifdef HARDWARE_CACHE_COHERENCY
    ioCaam->IOSynchronizationNotRequired = 1;
#endif

    RegisterIODeviceVector(ioCaam, DRIVER_NAME);
    RequestIOTerminationTask(ioCaam, 10);

    /* Initialize descriptors */
    for (i = 0; i < BUFFER_COUNT; i++) {
        InitializeIODescriptor(ioCaam, &caam.IODescriptorArray[i]);
    }

    /* Initialize Descriptors */
    for (i = 0; i < DESC_COUNT; i++) {
         InitializeIORequest(ioCaam, &caam.DescArray[i].TheIORequest,
                             IOREQUEST_STANDARD);
         caam.DescArray[i].running = false;
         caam.DescArray[i].caam    = &caam;
    }


    /* call interrupt to make IORequests available */
    caam.InterruptStatus = 0;
    INTERRUPT_InitCall(&caam.HandleInterruptCall,
        &HandleInterrupt, "Start up CAAM IORequest");

    /* set clock speed for CAAM. Setting it here to allow for restricting
       access */
    #define REGS_CCM_BASE     (0xf20c4000)
    #define HW_CCM_CCGR0_ADDR (0xf20c4068)
    #define CG(x) (3 << (x*2))

    reg = CG(6) | CG(5) | CG(4);
    *(volatile unsigned int*)HW_CCM_CCGR0_ADDR =
    *(volatile unsigned int*)HW_CCM_CCGR0_ADDR | reg;

    /* set up job ring */

    /* @TODO create partition in physical memory for job rings
       current partition security is set to the default */
    for (i = 1; i < CAAM_PAGE_MAX; i++) {
        ret = caamCreatePartition(i, i);
        if (ret == 0) {
            break;
        }

        if (ret != MemoryMapMayNotBeEmpty) {
            INTERRUPT_Panic();
        }
    }

    if (ret != 0) {
        INTERRUPT_Panic();
    }

    caam.ring.page = i;
    caam.ring.JobIn  =  (CAAM_PAGE + (i << 12));
    caam.ring.JobOut  = caam.ring.JobIn  + 16;
    caam.ring.Desc    = caam.ring.JobOut + 16;

    /* set physical address of job rings */
    CAAM_WRITE(CAAM_IRBAR0, caam.ring.JobIn  ^ 0xF0000000);
    CAAM_WRITE(CAAM_ORBAR0, caam.ring.JobOut ^ 0xF0000000);

    /* Initialize job ring sizes to 1 */
    CAAM_WRITE(CAAM_IRSR0, 1);
    CAAM_WRITE(CAAM_ORSR0, 1);

    /* set DECO watchdog to time out and flush jobs that cause the DECO to hang */
    CAAM_WRITE((CAAM_BASE | 0x0004), CAAM_READ(CAAM_BASE | 0x0004) | 0x40000000);

    /* start up RNG if not already started */
    if (caamInitRng(&caam) != 0) {
        INTERRUPT_Panic();
    }
}

void (*__ghsentry_bspuserinit_InitCAAM)(void) = &InitCAAM;

#endif /* INTEGRITY */