summaryrefslogtreecommitdiffstats
path: root/src/usr/secureboot/trusted/trustedboot.C
blob: d0ec760306234a578a75a0a19b107721986b0d96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/secureboot/trusted/trustedboot.C $                    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 * @file trustedboot.C
 *
 * @brief Trusted boot interfaces
 */

// ----------------------------------------------
// Includes
// ----------------------------------------------
#include <string.h>
#include <sys/time.h>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <errl/errludtarget.H>
#include <errl/errludstring.H>
#include <targeting/attrsync.H>
#include <targeting/attrrp.H>
#include <targeting/targplatutil.H>
#include <targeting/common/targetservice.H>
#include <targeting/common/commontargeting.H>
#include <secureboot/service.H>
#include <secureboot/trustedbootif.H>
#include <secureboot/trustedboot_reasoncodes.H>
#include <sys/mmio.h>
#include <sys/task.h>
#include <sys/sync.h>
#include <initservice/initserviceif.H>
#ifdef CONFIG_BMC_IPMI
#include <ipmi/ipmisensor.H>
#endif
#include <devicefw/driverif.H>
#include <i2c/tpmddif.H>
#include "trustedboot.H"
#include "trustedTypes.H"
#include "trustedbootCmds.H"
#include "trustedbootUtils.H"
#include "tpmLogMgr.H"
#include "base/trustedbootMsg.H"
#include <secureboot/settings.H>
#ifdef CONFIG_DRTM
#include <secureboot/drtm.H>
#endif
#include <fapi2.H>
#include <plat_hwp_invoker.H>
#include <p9_update_security_ctrl.H>
#include <algorithm>
#include <util/misc.H>
#include <hwas/common/hwasCommon.H>


namespace TRUSTEDBOOT
{

extern SystemData systemData;

errlHndl_t getTpmLogDevtreeInfo(
    const TpmTarget* const i_pTpm,
          uint64_t &       io_logAddr,
          size_t &         o_allocationSize,
          uint64_t &       o_xscomAddr,
          uint32_t &       o_i2cMasterOffset)
{
    assert(i_pTpm != nullptr,"getTpmLogDevtreeInfo: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "getTpmLogDevtreeInfo: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;
    auto * const pTpmLogMgr = getTpmLogMgr(i_pTpm);
    TRACUCOMP( g_trac_trustedboot,
               ENTER_MRK"getTpmLogDevtreeInfo() tgt=0x%08X Addr:0x%016lX "
               "0x%016lX",
               TARGETING::get_huid(i_pTpm),
               io_logAddr ,reinterpret_cast<uint64_t>(pTpmLogMgr));

    o_allocationSize = 0;

    auto hwasState = i_pTpm->getAttr<TARGETING::ATTR_HWAS_STATE>();

    if (nullptr != pTpmLogMgr &&
        hwasState.present)
    {
        err = TpmLogMgr_getDevtreeInfo(pTpmLogMgr,
                                       io_logAddr,
                                       o_allocationSize,
                                       o_xscomAddr,
                                       o_i2cMasterOffset);
    }
    TRACUCOMP( g_trac_trustedboot,
               EXIT_MRK"getTpmLogDevtreeInfo() Addr:0x%016lX",io_logAddr);
    return err;
}

void setTpmDevtreeInfo(
    const TpmTarget* const i_pTpm,
    const uint64_t         i_xscomAddr,
    const uint32_t         i_i2cMasterOffset)
{
    assert(i_pTpm != nullptr,"setTpmLogDevtreeInfo: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "setTpmLogDevtreeInfo: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    TRACUCOMP( g_trac_trustedboot,
               ENTER_MRK"setTpmLogDevtreeOffset() tgt=0x%08X "
               "Xscom:0x%016lX Master:0x%08X",
               TARGETING::get_huid(i_pTpm),
               i_xscomAddr, i_i2cMasterOffset);

    auto * const pTpmLogMgr = getTpmLogMgr(i_pTpm);
    if (nullptr != pTpmLogMgr)
    {
        TpmLogMgr_setTpmDevtreeInfo(pTpmLogMgr,
                                    i_xscomAddr, i_i2cMasterOffset);
    }
}

void getTpmWithRoleOf(
    TARGETING::TPM_ROLE const i_tpmRole,
    TARGETING::Target*&       o_pTpm)
{
    o_pTpm = nullptr;
    TARGETING::TargetHandleList tpmList;
    getTPMs(tpmList,TPM_FILTER::ALL_IN_BLUEPRINT);

    TARGETING::PredicateAttrVal<TARGETING::ATTR_TPM_ROLE>
        hasMatchingTpmRole(i_tpmRole);
    auto itr = std::find_if(tpmList.begin(),tpmList.end(),
        [&hasMatchingTpmRole](const TARGETING::Target* const i_pTpm)
        {
            return hasMatchingTpmRole(i_pTpm);
        });
    if(itr!=tpmList.end())
    {
        o_pTpm=*itr;
    }
}

void getPrimaryTpm(TARGETING::Target*& o_pPrimaryTpm)
{
    getTpmWithRoleOf(TARGETING::TPM_ROLE_TPM_PRIMARY,
        o_pPrimaryTpm);
}

void getBackupTpm(TARGETING::Target*& o_pBackupTpm)
{
    getTpmWithRoleOf(TARGETING::TPM_ROLE_TPM_BACKUP,
        o_pBackupTpm);
}

bool functionalPrimaryTpmExists()
{
    bool exists = false;
#ifdef CONFIG_TPMDD
    TARGETING::TargetHandleList tpmList;
    getTPMs(tpmList,TPM_FILTER::ALL_IN_BLUEPRINT);

    TARGETING::PredicateHwas present;
    present.present(true);

    TARGETING::PredicateHwas functional;
    functional.functional(true);

    TARGETING::PredicateAttrVal<TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>
        initialized(true);

    // Only look for primary TPM
    TARGETING::PredicateAttrVal<TARGETING::ATTR_TPM_ROLE>
                    isPrimaryTpm(TARGETING::TPM_ROLE_TPM_PRIMARY);

    auto itr = std::find_if(tpmList.begin(),tpmList.end(),
        [&present,&functional, &initialized, &isPrimaryTpm](
            const TARGETING::Target* const i_pTpm)
        {
            const auto isPresent = present(i_pTpm);
            const auto isFunctional = functional(i_pTpm);
            const auto isInitialized = initialized(i_pTpm);
            const auto isPrimary = isPrimaryTpm(i_pTpm);

            TRACFCOMP(g_trac_trustedboot,INFO_MRK
                "functionalPrimaryTpmExists(): TPM HUID 0x%08X's state = "
                "{present=%d,functional=%d,initialized=%d,primary=%d}",
                TARGETING::get_huid(i_pTpm),
                isPresent,isFunctional,isInitialized,isPrimary);

            return (   isPrimaryTpm(i_pTpm)
                    && (   (present(i_pTpm) && functional(i_pTpm))
                        || !initialized(i_pTpm)));
        });

    exists = (itr!=tpmList.end()) ? true : false;
#endif
    return exists;
}

void* host_update_master_tpm( void *io_pArgs )
{
    errlHndl_t err = nullptr;
    bool unlock = false;

    TRACFCOMP(g_trac_trustedboot,ENTER_MRK
        "host_update_master_tpm()");

    // Get all TPMs to setup our array
    TARGETING::TargetHandleList tpmList;
    getTPMs(tpmList,TPM_FILTER::ALL_IN_BLUEPRINT);

    // Currently we only support a MAX of two TPMS per node
    assert(tpmList.size() <= MAX_TPMS_PER_NODE, "Too many TPMs found");

    TRACFCOMP(g_trac_trustedboot,INFO_MRK
        "host_update_master_tpm: Found %d TPM(s) in blueprint",
        tpmList.size());

    do
    {
        if (tpmList.empty())
        {
            TRACFCOMP(g_trac_trustedboot,INFO_MRK
                "No TPM targets found");
            break;
        }

        TARGETING::TargetService& tS = TARGETING::targetService();

        TARGETING::Target* procTarget = nullptr;
        err = tS.queryMasterProcChipTargetHandle( procTarget );
        if (nullptr != err)
        {
            TRACFCOMP(g_trac_trustedboot,ERR_MRK
                "Failed to find master processor target");
            break;
        }

        for(auto tpm : tpmList)
        {
            mutex_lock(tpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>());
        }
        unlock = true;

        // Loop through the TPMs and figure out if they are attached
        //  to the master or alternate master processor
        TPMDD::tpm_info_t tpmData;
        for (auto tpm : tpmList)
        {
            memset(&tpmData, 0, sizeof(tpmData));
            errlHndl_t readErr = tpmReadAttributes(tpm,
                                                   tpmData,
                                                   TPM_LOCALITY_0);
            if (nullptr != readErr)
            {
                // We are just looking for configured TPMs here
                //  so we ignore any errors
                delete readErr;
                readErr = nullptr;
            }
            else
            {
                const auto originalTpmRole =
                    tpm->getAttr<TARGETING::ATTR_TPM_ROLE>();

                // If TPM connected to acting master processor, it is
                // primary; otherwise it is backup
                TARGETING::TPM_ROLE tpmRole =
                    (tpmData.i2cTarget == procTarget) ?
                          TARGETING::TPM_ROLE_TPM_PRIMARY
                        : TARGETING::TPM_ROLE_TPM_BACKUP;
                tpm->setAttr<TARGETING::ATTR_TPM_ROLE>(tpmRole);

                TRACFCOMP(g_trac_trustedboot,INFO_MRK
                    "TPM HUID 0x%08X's original role: %d, new role: %d",
                    TARGETING::get_huid(tpm),
                    originalTpmRole,tpmRole);
            }
        }

        // Initialize primary TPM
        TARGETING::Target* pPrimaryTpm = nullptr;
        (void)getPrimaryTpm(pPrimaryTpm);
        if(pPrimaryTpm)
        {
            auto hwasState = pPrimaryTpm->getAttr<TARGETING::ATTR_HWAS_STATE>();
            TRACFCOMP(g_trac_trustedboot,INFO_MRK
                "Prior to init, TPM HUID 0x%08X has state of {present=%d, "
                "functional=%d}",
                TARGETING::get_huid(pPrimaryTpm),
                hwasState.present,hwasState.functional);

            if(   hwasState.present
               && hwasState.functional)
            {
                // API call will set TPM init attempted appropriately
                tpmInitialize(pPrimaryTpm);
            }
            else
            {
                pPrimaryTpm->setAttr<
                    TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>(true);
            }

            // Allocate TPM log if it hasn't been already; note that
            // during MPIPL, the targeting init will attempt to re-use old
            // values, but then has logic to set the log manager pointer back to
            // 0.
            auto pTpmLogMgr = getTpmLogMgr(pPrimaryTpm);
            // Need to grab state again, as it could have changed
            hwasState = pPrimaryTpm->getAttr<
                TARGETING::ATTR_HWAS_STATE>();
            TRACFCOMP(g_trac_trustedboot,INFO_MRK
                "Prior to log init, TPM HUID 0x%08X has state of {present=%d, "
                "functional=%d}.  Log pointer is %p",
                TARGETING::get_huid(pPrimaryTpm),
                hwasState.present,hwasState.functional,pTpmLogMgr);

            if(   hwasState.present
               && hwasState.functional
               && nullptr == pTpmLogMgr)
            {
                // @todo RTC:145689 For DRTM we locate the previous SRTM log
                // and reuse.  We must also allocate a DRTM log to be used
                pTpmLogMgr = new TpmLogMgr;
                setTpmLogMgr(pPrimaryTpm,pTpmLogMgr);
                err = TpmLogMgr_initialize(pTpmLogMgr);
                if (nullptr != err)
                {
                    hwasState = pPrimaryTpm->getAttr<
                        TARGETING::ATTR_HWAS_STATE>();
                    hwasState.functional = false;
                    pPrimaryTpm->setAttr<TARGETING::ATTR_HWAS_STATE>(
                        hwasState);
                    break;
                }
            }
        }
        else
        {
            TRACFCOMP(g_trac_trustedboot,INFO_MRK
                "No primary TPM found");
        }

        bool primaryTpmAvail = (pPrimaryTpm != nullptr);
        if(primaryTpmAvail)
        {
            auto primaryHwasState = pPrimaryTpm->getAttr<
                TARGETING::ATTR_HWAS_STATE>();

            TRACFCOMP(g_trac_trustedboot,INFO_MRK
                "Prior to usability determination, Primary TPM HUID 0x%08X has state "
                "of {present=%d, functional=%d}",
                TARGETING::get_huid(pPrimaryTpm),
                primaryHwasState.present,primaryHwasState.functional);

            if (!primaryHwasState.functional ||
                !primaryHwasState.present)
            {
                primaryTpmAvail = false;
                if(isTpmRequired())
                {
                    TRACFCOMP(g_trac_trustedboot,ERR_MRK
                        "Marking Primary TPM HUID 0x%08X as unusable",
                        TARGETING::get_huid(pPrimaryTpm));
                    pPrimaryTpm->setAttr<TARGETING::ATTR_TPM_UNUSABLE>(true);
                }
            }
        }

        if(!primaryTpmAvail)
        {
            // Primary TPM not available
            TRACFCOMP( g_trac_trustedboot,INFO_MRK
                       "Primary TPM Existence Fail");
        }

        TARGETING::Target* pBackupTpm = nullptr;
        getBackupTpm(pBackupTpm);
        if(pBackupTpm == nullptr)
        {
            TRACFCOMP( g_trac_trustedboot,INFO_MRK
                       "host_update_master_tpm() "
                       "Backup TPM unavailable "
                       "since it's not in the system blueprint.");
        }

    } while ( 0 );

    if( unlock )
    {
        for(auto tpm : tpmList)
        {
            mutex_unlock(tpm->getHbMutexAttr<
                TARGETING::ATTR_HB_TPM_MUTEX>());
        }
        unlock = false;
    }

    // Make sure we are in a state
    //  where we have a functional TPM
    TRUSTEDBOOT::tpmVerifyFunctionalPrimaryTpmExists();

    if (nullptr == err)
    {
        // Start the task to start to handle the message queue/extends
        task_create(&TRUSTEDBOOT::tpmDaemon, nullptr);
    }

    TARGETING::Target* pPrimaryTpm = nullptr;
    (void)getPrimaryTpm(pPrimaryTpm);

    if (nullptr == err)
    {
        // Log config entries to TPM - needs to be after mutex_unlock
        if(pPrimaryTpm)
        {
            err = tpmLogConfigEntries(pPrimaryTpm);
        }
    }

    if(pPrimaryTpm)
    {
        TRACUCOMP( g_trac_trustedboot,
                   "host_update_master_tpm() - "
                   "Primary TPM Present:%d Functional:%d Init Attempted:%d"
                   " Usable:%d",
                   pPrimaryTpm->getAttr<TARGETING::ATTR_HWAS_STATE>().
                       present,
                   pPrimaryTpm->getAttr<TARGETING::ATTR_HWAS_STATE>().
                       functional,
                   pPrimaryTpm->getAttr<
                       TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>(),
                   !(pPrimaryTpm->getAttr<TARGETING::ATTR_TPM_UNUSABLE>()));
    }

    TARGETING::Target* pBackupTpm = nullptr;
    (void)getBackupTpm(pBackupTpm);
    if(pBackupTpm)
    {
        TRACUCOMP( g_trac_trustedboot,
                   "host_update_master_tpm() - "
                   "Backup TPM Present:%d Functional:%d Init Attempted:%d "
                   "Usable: %d. "
                   "Backup TPM initialization is deferred to istep 10.14.",
                   pBackupTpm->getAttr<TARGETING::ATTR_HWAS_STATE>().
                       present,
                   pBackupTpm->getAttr<TARGETING::ATTR_HWAS_STATE>().
                       functional,
                   pBackupTpm->getAttr<
                       TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>(),
                   !(pPrimaryTpm->getAttr<TARGETING::ATTR_TPM_UNUSABLE>()));
    }

    TRACFCOMP( g_trac_trustedboot,EXIT_MRK
        "host_update_master_tpm() - %s",
        ((nullptr == err) ? "No Error" : "With Error") );

    return err;
}

void tpmInitialize(TRUSTEDBOOT::TpmTarget* const i_pTpm)
{
    assert(i_pTpm != nullptr,"tpmInitialize: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmInitialize: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;

    TRACFCOMP( g_trac_trustedboot,
               ENTER_MRK"tpmInitialize() TPM HUID = 0x%08X",
               TARGETING::get_huid(i_pTpm));

    do
    {
        // TPM Initialization sequence
        i_pTpm->setAttr<TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>(true);
        auto hwasState = i_pTpm->getAttr<
            TARGETING::ATTR_HWAS_STATE>();
        hwasState.functional = true;
        i_pTpm->setAttr<
            TARGETING::ATTR_HWAS_STATE>(hwasState);

        // read + write
        bool sendStartup = true;

#ifdef CONFIG_DRTM
        bool drtmMpipl = false;
        (void)SECUREBOOT::DRTM::isDrtmMpipl(drtmMpipl);
        if(drtmMpipl)
        {
            sendStartup = false;
        }
#endif
        // Don't run STARTUP during DRTM
        if (sendStartup)
        {
            // TPM_STARTUP
            err = tpmCmdStartup(i_pTpm);
            if (nullptr != err)
            {
                break;
            }
        }

        // TPM_GETCAPABILITY to read FW Version
        err = tpmCmdGetCapFwVersion(i_pTpm);
        if (nullptr != err)
        {
            break;
        }

#ifdef CONFIG_TPM_NVIDX_VALIDATE
        // Find out if in manufacturing mode
        TARGETING::Target* pTopLevel = nullptr;
        TARGETING::targetService().getTopLevelTarget(pTopLevel);
        assert(pTopLevel != nullptr,"Top level target was nullptr");

        auto mnfgFlags =
            pTopLevel->getAttr<TARGETING::ATTR_MNFG_FLAGS>();

        // Only validate during MFG IPL
        if (mnfgFlags & TARGETING::MNFG_FLAG_SRC_TERM &&
            !Util::isSimicsRunning()) {
            // TPM_GETCAPABILITY to validate NV Indexes
            err = tpmCmdGetCapNvIndexValidate(i_pTpm);
            if (nullptr != err)
            {
                break;
            }
        }
#endif

#ifdef CONFIG_DRTM
        // For a DRTM we need to reset PCRs 17-22
        if (drtmMpipl)
        {
            err = tpmDrtmReset(i_pTpm);
            if (nullptr != err)
            {
                break;
            }
        }
#endif

    } while ( 0 );


    // If the TPM failed we will mark it not functional and commit err
    if (nullptr != err)
    {
        // err will be committed and set to nullptr
        tpmMarkFailed(i_pTpm, err);
    }

    TRACFCOMP( g_trac_trustedboot,
               EXIT_MRK"tpmInitialize()");
}

void tpmReplayLog(TRUSTEDBOOT::TpmTarget* const i_primaryTpm,
                  TRUSTEDBOOT::TpmTarget* const i_backupTpm)
{
    assert(i_primaryTpm != nullptr,
                                 "tpmReplayLog: BUG! i_primaryTpm was nullptr");
    assert(i_backupTpm != nullptr,
                               "tpmReplayLog: BUG! i_backupTpm was nullptr");
    assert(i_primaryTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmReplayLog: BUG! Expected primary target to be of TPM type, but "
           "it was of type 0x%08X",
                                 i_primaryTpm->getAttr<TARGETING::ATTR_TYPE>());
    assert(i_backupTpm->getAttr<TARGETING::ATTR_TYPE>()
                                                         == TARGETING::TYPE_TPM,
           "tpmReplayLog: BUG! Expected secondary target to be of TPM type, but"
           " it was of type 0x%08X",
                               i_backupTpm->getAttr<TARGETING::ATTR_TYPE>());
    TRACUCOMP(g_trac_trustedboot, ENTER_MRK"tpmReplayLog()");

    errlHndl_t err = nullptr;
    bool unMarshalError = false;


    // Create EVENT2 structure to be populated by getNextEvent()
    TCG_PCR_EVENT2 l_eventLog = {0};
    // Move past header event to get a pointer to the first event
    // If there are no events besides the header, l_eventHndl = nullptr
    auto * const pTpmLogMgr = getTpmLogMgr(i_primaryTpm);
    auto * const bTpmLogMgr = getTpmLogMgr(i_backupTpm);
    assert(pTpmLogMgr != nullptr, "tpmReplayLog: BUG! Primary TPM's log manager"
           " is nullptr!");
    assert(bTpmLogMgr != nullptr, "tpmReplayLog: BUG! Backup TPM's log manager"
           " is nullptr!");
    const uint8_t* l_eventHndl = TpmLogMgr_getFirstEvent(pTpmLogMgr);
    while ( l_eventHndl != nullptr )
    {
        // Get next event
        l_eventHndl = TpmLogMgr_getNextEvent(pTpmLogMgr,
                                             l_eventHndl, &l_eventLog,
                                             &unMarshalError);
        if (unMarshalError)
        {
            /*@
             * @errortype
             * @reasoncode     RC_TPM_UNMARSHALING_FAIL
             * @severity       ERRL_SEV_UNRECOVERABLE
             * @moduleid       MOD_TPM_REPLAY_LOG
             * @userdata1      Starting address of event that caused error
             * @userdata2      0
             * @devdesc        Unmarshal error while replaying tpm log.
             */
            err = new ERRORLOG::ErrlEntry( ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                        MOD_TPM_REPLAY_LOG,
                                        RC_TPM_UNMARSHALING_FAIL,
                                        reinterpret_cast<uint64_t>(l_eventHndl),
                                        0,
                                        true /*Add HB SW Callout*/ );

            err->collectTrace( SECURE_COMP_NAME );
            err->collectTrace(TRBOOT_COMP_NAME);
            tpmMarkFailed(i_primaryTpm, err);
            break;
        }

        err = TpmLogMgr_addEvent(bTpmLogMgr, &l_eventLog);
        if(err)
        {
            tpmMarkFailed(i_backupTpm, err);
            break;
        }

        TRACUBIN(g_trac_trustedboot, "tpmReplayLog: Extending event:",
                 &l_eventLog, sizeof(TCG_PCR_EVENT2));
        for (size_t i = 0; i < l_eventLog.digests.count; i++)
        {
            TPM_Alg_Id l_algId = (TPM_Alg_Id)l_eventLog.digests.digests[i]
                                                                   .algorithmId;
            err = tpmCmdPcrExtend(i_backupTpm,
                                  (TPM_Pcr)l_eventLog.pcrIndex,
                                  l_algId,
                                  reinterpret_cast<uint8_t*>
                                      (&(l_eventLog.digests.digests[i].digest)),
                                  getDigestSize(l_algId));
            if (err)
            {
                tpmMarkFailed(i_backupTpm, err);
                break;
            }
        }
        if (err)
        {
            break;
        }
    }

    TRACUCOMP(g_trac_trustedboot, EXIT_MRK"tpmReplayLog()");
}

errlHndl_t tpmLogConfigEntries(TRUSTEDBOOT::TpmTarget* const i_pTpm)
{
    assert(i_pTpm != nullptr,"tpmLogConfigEntries: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmLogConfigEntries: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    TRACUCOMP(g_trac_trustedboot, ENTER_MRK"tpmLogConfigEntries()");

    errlHndl_t l_err = nullptr;

    do
    {
        // Create digest buffer and set to largest config entry size.
        uint8_t l_digest[sizeof(uint64_t)];
        memset(l_digest, 0, sizeof(uint64_t));

        // Security switches
        uint64_t l_securitySwitchValue = 0;
        l_err = SECUREBOOT::getSecuritySwitch(l_securitySwitchValue,
                            TARGETING::MASTER_PROCESSOR_CHIP_TARGET_SENTINEL);
        if (l_err)
        {
            break;
        }
        TRACFCOMP(g_trac_trustedboot, "security switch value = 0x%016lX",
                                l_securitySwitchValue);
        // Extend to TPM - PCR_1
        memcpy(l_digest, &l_securitySwitchValue, sizeof(l_securitySwitchValue));
        uint8_t l_sswitchesLogMsg[] = "Security Switches";
        l_err = pcrExtend(PCR_1, EV_PLATFORM_CONFIG_FLAGS,
                          l_digest, sizeof(l_securitySwitchValue),
                          l_sswitchesLogMsg, sizeof(l_sswitchesLogMsg));
        if (l_err)
        {
            break;
        }
        memset(l_digest, 0, sizeof(uint64_t));

        // Chip type and EC
        // Fill in the actual PVR of chip
        // Layout of the PVR is (32-bit): (see cpuid.C for latest format)
        //     2 nibbles reserved.
        //     2 nibbles chip type.
        //     1 nibble technology.
        //     1 nibble major DD.
        //     1 nibble reserved.
        //     1 nibble minor D
        uint32_t l_pvr = mmio_pvr_read() & 0xFFFFFFFF;
        TRACDCOMP(g_trac_trustedboot, "PVR of chip = 0x%08X", l_pvr);
        // Extend to TPM - PCR_1
        memcpy(l_digest, &l_pvr, sizeof(l_pvr));
        uint8_t l_pvrLogMsg[] = "PVR of Chip";
        l_err = pcrExtend(PCR_1, EV_PLATFORM_CONFIG_FLAGS,
                          l_digest, sizeof(l_pvr), l_pvrLogMsg,
                          sizeof(l_pvrLogMsg));
        if (l_err)
        {
            break;
        }
        memset(l_digest, 0, sizeof(uint64_t));

        // Figure out which node we are running on
        TARGETING::Target* l_masterProc = nullptr;
        TARGETING::targetService().masterProcChipTargetHandle(l_masterProc);

        TARGETING::EntityPath l_entityPath =
                        l_masterProc->getAttr<TARGETING::ATTR_PHYS_PATH>();
        const TARGETING::EntityPath::PathElement l_pathElement =
                        l_entityPath.pathElementOfType(TARGETING::TYPE_NODE);
        uint64_t l_nodeid = l_pathElement.instance;
        // Extend to TPM - PCR_1,4,5,6
        memcpy(l_digest, &l_nodeid, sizeof(l_nodeid));
        const TPM_Pcr l_pcrs[] = {PCR_1,PCR_4,PCR_5,PCR_6};
        for (size_t i = 0; i < (sizeof(l_pcrs)/sizeof(TPM_Pcr)) ; ++i)
        {
            uint8_t l_nodeIdLogMsg[] = "Node id";
            l_err = pcrExtend(l_pcrs[i],
                              (l_pcrs[i] == PCR_1 ?
                               EV_PLATFORM_CONFIG_FLAGS : EV_COMPACT_HASH),
                              l_digest, sizeof(l_nodeid), l_nodeIdLogMsg,
                              sizeof(l_nodeIdLogMsg));
            if (l_err)
            {
                break;
            }
        }
        if (l_err)
        {
            break;
        }

        // TPM Required
        memset(l_digest, 0, sizeof(uint64_t));
        bool l_tpmRequired = isTpmRequired();
        l_digest[0] = static_cast<uint8_t>(l_tpmRequired);
        uint8_t l_tpmRequiredLogMsg[] = "Tpm Required";
        l_err = pcrExtend(PCR_1, EV_PLATFORM_CONFIG_FLAGS,
                          l_digest, sizeof(l_tpmRequired),
                          l_tpmRequiredLogMsg,
                          sizeof(l_tpmRequiredLogMsg));
        if (l_err)
        {
            break;
        }

        // HW Key Hash
        SHA512_t l_hw_key_hash;
        SECUREBOOT::getHwKeyHash(l_hw_key_hash);
        uint8_t l_hwKeyHashLogMsg[] = "HW KEY HASH";
        l_err = pcrExtend(PCR_1, EV_PLATFORM_CONFIG_FLAGS,
                          l_hw_key_hash,
                          sizeof(SHA512_t),l_hwKeyHashLogMsg,
                          sizeof(l_hwKeyHashLogMsg));
        if (l_err)
        {
            break;
        }

    } while(0);

    return l_err;
}

void pcrExtendSingleTpm(TpmTarget* const i_pTpm,
                        const TPM_Pcr i_pcr,
                        const EventTypes i_eventType,
                        TPM_Alg_Id i_algId,
                        const uint8_t* i_digest,
                        size_t  i_digestSize,
                        const uint8_t* i_logMsg,
                        const size_t i_logMsgSize)
{
    assert(i_pTpm != nullptr,"pcrExtendSingleTpm: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "pcrExtendSingleTpm: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;
    TCG_PCR_EVENT2 eventLog;
    bool unlock = false;

    TPM_Pcr pcr = i_pcr;
    bool useStaticLog = true;

#ifdef CONFIG_DRTM
    // In a DRTM flow, all extensions must be re-rerouted to PCR 17
    // (which will end up using locality 2).
    bool drtmMpipl = false;
    (void)SECUREBOOT::DRTM::isDrtmMpipl(drtmMpipl);
    if(drtmMpipl)
    {
        TRACFCOMP(g_trac_trustedboot,
            INFO_MRK " pcrExtendSingleTpm(): DRTM active; re-routing PCR %d "
            "extend to PCR 17",
            i_pcr);

        pcr = PCR_DRTM_17;
        useStaticLog = false;
    }
#endif

    memset(&eventLog, 0, sizeof(eventLog));
    do
    {
        mutex_lock( i_pTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>() ) ;
        unlock = true;

        auto hwasState = i_pTpm->getAttr<TARGETING::ATTR_HWAS_STATE>();

        // Log the event
        if (hwasState.present &&
             hwasState.functional)
        {
            if (i_logMsg != nullptr) // null log indicates we don't log
            {
                // Fill in TCG_PCR_EVENT2 and add to log
                eventLog = TpmLogMgr_genLogEventPcrExtend(pcr, i_eventType,
                                                          i_algId, i_digest,
                                                          i_digestSize,
                                                          TPM_ALG_SHA1,
                                                          i_digest,
                                                          i_digestSize,
                                                          i_logMsg,
                                                          i_logMsgSize);
                if(useStaticLog)
                {
                    auto * const pTpmLogMgr = getTpmLogMgr(i_pTpm);
                    err = TpmLogMgr_addEvent(pTpmLogMgr,&eventLog);
                    if (nullptr != err)
                    {
                        break;
                    }
                }
            }

            // TODO: RTC 145689: Add DRTM support for using dynamic
            // log instead of static log; until then, inhibit DRTM logging
            // entirely

            // Perform the requested extension and also force into the
            // SHA1 bank
            err = tpmCmdPcrExtend2Hash(i_pTpm,
                                       pcr,
                                       i_algId,
                                       i_digest,
                                       i_digestSize,
                                       TPM_ALG_SHA1,
                                       i_digest,
                                       i_digestSize);
        }
    } while ( 0 );

    if (nullptr != err)
    {
        // We failed to extend to this TPM we can no longer use it
        // Mark TPM as not functional, commit err and set it to nullptr
        tpmMarkFailed(i_pTpm, err);
    }

    if (unlock)
    {
        mutex_unlock( i_pTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>() ) ;
    }
    return;
}

void pcrExtendSeparator(TpmTarget* const i_pTpm)
{
    assert(i_pTpm != nullptr,"pcrExtendSeparator: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "pcrExtendSeparator: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;
    TCG_PCR_EVENT2 eventLog = {0};
    bool unlock = false;

    // Separators are always the same values
    // The digest is a sha1 hash of 0xFFFFFFFF
    const uint8_t sha1_digest[] = {
        0xd9, 0xbe, 0x65, 0x24, 0xa5, 0xf5, 0x04, 0x7d,
        0xb5, 0x86, 0x68, 0x13, 0xac, 0xf3, 0x27, 0x78,
        0x92, 0xa7, 0xa3, 0x0a};
    // The digest is a sha256 hash of 0xFFFFFFFF
    const uint8_t sha256_digest[] = {
        0xAD, 0x95, 0x13, 0x1B, 0xC0, 0xB7, 0x99, 0xC0,
        0xB1, 0xAF, 0x47, 0x7F, 0xB1, 0x4F, 0xCF, 0x26,
        0xA6, 0xA9, 0xF7, 0x60, 0x79, 0xE4, 0x8B, 0xF0,
        0x90, 0xAC, 0xB7, 0xE8, 0x36, 0x7B, 0xFD, 0x0E};
    // The event message is 0xFFFFFFFF
    const uint8_t logMsg[] = { 0xFF, 0xFF, 0xFF, 0xFF };

    memset(&eventLog, 0, sizeof(eventLog));
    do
    {
        mutex_lock( i_pTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>() ) ;
        unlock = true;

        std::vector<TPM_Pcr> pcrs =
            {PCR_0,PCR_1,PCR_2,PCR_3,PCR_4,PCR_5,PCR_6,PCR_7};
        bool useStaticLog = true;

#ifdef CONFIG_DRTM
        // In a DRTM flow, all extensions must be re-rerouted to PCR 17
        // (which will end up using locality 2).
        bool drtmMpipl = false;
        (void)SECUREBOOT::DRTM::isDrtmMpipl(drtmMpipl);
        if(drtmMpipl)
        {
            TRACFCOMP(g_trac_trustedboot,
                INFO_MRK " pcrExtendSeparator(): DRTM active; extending "
                "separator to PCR 17 instead of PCR 0..7.");

            pcrs = { PCR_DRTM_17 };
            useStaticLog = false;
        }
#endif

        for (const auto &pcr : pcrs)
        {
            auto hwasState = i_pTpm->getAttr<
                TARGETING::ATTR_HWAS_STATE>();

            // Log the separator
            if (hwasState.present &&
                hwasState.functional)
            {
                // Fill in TCG_PCR_EVENT2 and add to log
                eventLog = TpmLogMgr_genLogEventPcrExtend(pcr,
                                                          EV_SEPARATOR,
                                                          TPM_ALG_SHA1,
                                                          sha1_digest,
                                                          sizeof(sha1_digest),
                                                          TPM_ALG_SHA256,
                                                          sha256_digest,
                                                          sizeof(sha256_digest),
                                                          logMsg,
                                                          sizeof(logMsg));

                if(useStaticLog)
                {
                    auto * const pTpmLogMgr = getTpmLogMgr(i_pTpm);
                    err = TpmLogMgr_addEvent(pTpmLogMgr,&eventLog);
                    if (nullptr != err)
                    {
                        break;
                    }
                }

                // TODO: RTC 145689: Add DRTM support for using dynamic
                // log (which will happen any time useStaticLog is false).
                // Until then, we cannot log DRTM events, since they are only
                // allowed to go to the dynamic log

                // Perform the requested extension
                err = tpmCmdPcrExtend2Hash(i_pTpm,
                                           pcr,
                                           TPM_ALG_SHA1,
                                           sha1_digest,
                                           sizeof(sha1_digest),
                                           TPM_ALG_SHA256,
                                           sha256_digest,
                                           sizeof(sha256_digest));
                if (nullptr != err)
                {
                    break;
                }

            }
        }

    } while ( 0 );

    if (nullptr != err)
    {
        // We failed to extend to this TPM we can no longer use it
        // Mark TPM as not functional, commit err and set it to nullptr
        tpmMarkFailed(i_pTpm, err);

        // Log this failure
        errlCommit(err, TRBOOT_COMP_ID);
    }

    if (unlock)
    {
        mutex_unlock( i_pTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>() ) ;
    }
    return;
}

void tpmMarkFailed(TpmTarget* const i_pTpm,
                   errlHndl_t& io_err)
{
    assert(i_pTpm != nullptr,"tpmMarkFailed: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmMarkFailed: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    TRACFCOMP( g_trac_trustedboot,
               ENTER_MRK"tpmMarkFailed() Marking TPM as failed : "
               "tgt=0x%08X; io_err rc=0x%04X, plid=0x%08X",
               TARGETING::get_huid(i_pTpm), ERRL_GETRC_SAFE(io_err),
               ERRL_GETPLID_SAFE(io_err));

    auto hwasState = i_pTpm->getAttr<
        TARGETING::ATTR_HWAS_STATE>();
    hwasState.functional = false;
    i_pTpm->setAttr<
        TARGETING::ATTR_HWAS_STATE>(hwasState);

    if(isTpmRequired())
    {
        // Mark the TPM as unusable so that FSP can perform alignment check
        i_pTpm->setAttr<TARGETING::ATTR_TPM_UNUSABLE>(true);
    }

    #ifdef CONFIG_SECUREBOOT
    TARGETING::Target* l_tpm = i_pTpm;

    errlHndl_t l_err = nullptr;
    TARGETING::Target* l_proc = nullptr;

    do {

    if (!SECUREBOOT::enabled())
    {
        break;
    }

    // for the given tpm target, find the processor target
    TARGETING::TargetHandleList l_procList;
    getAllChips(l_procList,TARGETING::TYPE_PROC,false);

    auto l_tpmInfo = l_tpm->getAttr<TARGETING::ATTR_TPM_INFO>();

    for(auto it : l_procList)
    {
        auto l_physPath = it->getAttr<TARGETING::ATTR_PHYS_PATH>();
        if (l_tpmInfo.i2cMasterPath == l_physPath)
        {
            // found processor to deconfigure
            l_proc = it;
            break;
        }
    }
    if (l_proc == nullptr)
    {
        assert(false,"tpmMarkFailed - TPM with non-existent processor indicates"
            " a bad MRW. TPM tgt=0x%08X", TARGETING::get_huid(l_tpm));
    }

    // set ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM for the processor
    uint8_t l_protectTpm = 1;
    l_proc->setAttr<TARGETING::ATTR_SECUREBOOT_PROTECT_DECONFIGURED_TPM>(
        l_protectTpm);

    // do not deconfigure the processor if it already deconfigured
    TARGETING::PredicateHwas isNonFunctional;
    isNonFunctional.functional(false);
    if (isNonFunctional(l_proc))
    {
        // Note: at this point l_err is nullptr so
        // no error log is created on break
        break;
    }

    uint64_t l_regValue = 0;
    l_err = SECUREBOOT::getSecuritySwitch(l_regValue, l_proc);
    if (l_err)
    {
        TRACFCOMP(g_trac_trustedboot,
            ERR_MRK"tpmMarkFailed - call to getSecuritySwitch failed");
        break;
    }
    // if the SBE lock bit is not set, it means that istep 10.3 hasn't executed
    // yet, so we will let istep 10.3 call p9_update_security_control HWP
    // if the SBE lock bit is set, then we will call the HWP here
    if (!(l_regValue & static_cast<uint64_t>(SECUREBOOT::ProcSecurity::SULBit)))
    {
        break;
    }

    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapiTarg(l_proc);

    FAPI_INVOKE_HWP(l_err, p9_update_security_ctrl, l_fapiTarg);

    if (l_err)
    {
        TRACFCOMP(g_trac_trustedboot,
            ERR_MRK"tpmMarkFailed - call to p9_update_security_ctrl failed ");
    }

    } while(0);

    // If we got a local error log, link it to input error log and then
    // commit it
    if (l_err)
    {
        // commit this error log first before creating the new one
        auto plid = l_err->plid();

        // If we have an input error log then link these all together
        if (io_err)
        {
           TRACFCOMP(g_trac_trustedboot,
                ERR_MRK "tpmMarkFailed(): Processor tgt=0x%08X TPM tgt=0x%08X. "
                "Deconfiguring proc because future security cannot be "
                "guaranteed. Linking new l_err rc=0x%04X eid=0x%08X to "
                "io_err rc=0x%04X, plid=0x%08X",
                TARGETING::get_huid(l_proc),
                TARGETING::get_huid(l_tpm),
                l_err->reasonCode(), l_err->eid(),
                io_err->reasonCode(), io_err->plid());

            // Use io_err's plid to link all errors together
            plid = io_err->plid();
            l_err->plid(plid);
        }
        else
        {
            TRACFCOMP(g_trac_trustedboot,
                ERR_MRK "tpmMarkFailed(): Processor tgt=0x%08X TPM tgt=0x%08X: "
                "Deconfiguring proc because future security cannot be "
                "guaranteed due to new l_err rc=0x%04X plid=0x%08X",
                TARGETING::get_huid(l_proc),
                TARGETING::get_huid(l_tpm),
                l_err->reasonCode(), l_err->plid());
        }

        ERRORLOG::ErrlUserDetailsTarget(l_proc).addToLog(l_err);
        l_err->collectTrace(SECURE_COMP_NAME);
        l_err->collectTrace(TRBOOT_COMP_NAME);

        // commit this error log first before creating the new one
        errlCommit(l_err, TRBOOT_COMP_ID);

       /*@
        * @errortype
        * @reasoncode       TRUSTEDBOOT::RC_UPDATE_SECURITY_CTRL_HWP_FAIL
        * @moduleid         TRUSTEDBOOT::MOD_TPM_MARK_FAILED
        * @severity         ERRL_SEV_UNRECOVERABLE
        * @userdata1        Processor Target
        * @userdata2        TPM Target
        * @devdesc          Failed to set SEEPROM lock and/or TPM deconfig
        *                   protection for this processor, so we cannot
        *                   guarrantee platform secuirty for this processor
        * @custdesc         Platform security problem detected
        */
        l_err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
            TRUSTEDBOOT::MOD_TPM_MARK_FAILED,
            TRUSTEDBOOT::RC_UPDATE_SECURITY_CTRL_HWP_FAIL,
            TARGETING::get_huid(l_proc),
            TARGETING::get_huid(l_tpm));

        // Pass on the plid to connect all previous error(s)
        l_err->plid(plid);

       TRACFCOMP(g_trac_trustedboot,
            ERR_MRK "tpmMarkFailed(): Processor tgt=0x%08X TPM tgt=0x%08X. "
            "Deconfiguring proc errorlog is rc=0x%04X plid=0x%08X, eid=0x%08X",
            TARGETING::get_huid(l_proc),
            TARGETING::get_huid(l_tpm),
            l_err->reasonCode(), l_err->plid(), l_err->eid());

        l_err->addHwCallout(l_proc,
                            HWAS::SRCI_PRIORITY_LOW,
                            HWAS::DELAYED_DECONFIG,
                            HWAS::GARD_NULL);

        l_err->collectTrace(SECURE_COMP_NAME);
        l_err->collectTrace(TRBOOT_COMP_NAME);

        ERRORLOG::ErrlUserDetailsTarget(l_proc).addToLog(l_err);

        ERRORLOG::errlCommit(l_err, TRBOOT_COMP_ID);
    }
    #endif

    // Commit input error log
    if (io_err)
    {
       TRACFCOMP(g_trac_trustedboot,
            ERR_MRK "Committing io_err rc=0x%04X plid=0x%08X, eid=0x%08X",
            io_err->reasonCode(), io_err->plid(), io_err->eid());

        io_err->collectTrace(SECURE_COMP_NAME);
        io_err->collectTrace(TRBOOT_COMP_NAME);

        ERRORLOG::errlCommit(io_err, TRBOOT_COMP_ID);
    }

}

void tpmVerifyFunctionalPrimaryTpmExists(
    const NoTpmShutdownPolicy i_noTpmShutdownPolicy)
{
    errlHndl_t err = nullptr;
    bool foundFunctional = functionalPrimaryTpmExists();
    const bool isBackgroundShutdown =
        (i_noTpmShutdownPolicy == NoTpmShutdownPolicy::BACKGROUND_SHUTDOWN);

    if (!foundFunctional && !systemData.failedTpmsPosted)
    {
        systemData.failedTpmsPosted = true;
        TRACFCOMP( g_trac_trustedboot,
                   "NO FUNCTIONAL PRIMARY TPM FOUND ON THE NODE");

        // Check to ensure jumper indicates we are running secure
        SECUREBOOT::SecureJumperState l_state
                          = SECUREBOOT::SecureJumperState::SECURITY_DEASSERTED;
        err = SECUREBOOT::getJumperState(l_state);
        if (err)
        {
            auto errPlid = err->plid();
            errlCommit(err, TRBOOT_COMP_ID);

            // we should not continue if we could not read the jumper state
            INITSERVICE::doShutdown(errPlid,isBackgroundShutdown);
        }
        else if (l_state == SECUREBOOT::SecureJumperState::SECURITY_ASSERTED)
        {
            if (isTpmRequired())
            {
                /*@
                 * @errortype
                 * @reasoncode     RC_TPM_NOFUNCTIONALTPM_FAIL
                 * @severity       ERRL_SEV_UNRECOVERABLE
                 * @moduleid       MOD_TPM_VERIFYFUNCTIONAL
                 * @userdata1      0
                 * @userdata2      0
                 * @devdesc        The system (or node, if multi-node system)
                 *                 is configured in the hardware (via processor
                 *                 secure jumpers) to enable Secure Boot, and
                 *                 the system's/node's "TPM required" policy is
                 *                 configured to require at least one
                 *                 functional boot processor TPM in order to
                 *                 boot with Trusted Boot enabled. Therefore,
                 *                 the system (or node, if multi-node system)
                 *                 will terminate due to lack of functional
                 *                 boot processor TPM.
                 * @custdesc       The system is configured for Secure Boot and
                 *                 trusted platform module required mode; a
                 *                 functional boot processor trusted platform
                 *                 module is required to boot the system (or
                 *                 node, if multi-node system), but none are
                 *                 available.  Therefore, the system (or node,
                 *                 if multi-node system) will terminate.
                 *                 Trusted platform module required mode may be
                 *                 disabled via the appropriate systems
                 *                 management interface to allow platform boot
                 *                 without the remote trusted attestation
                 *                 capability. Look for other errors which call
                 *                 out the trusted platform module and follow
                 *                 the repair actions for these errors.
                 */
                err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                              MOD_TPM_VERIFYFUNCTIONAL,
                                              RC_TPM_NOFUNCTIONALTPM_FAIL);

                TRACFCOMP(g_trac_trustedboot, ERR_MRK
                          "tpmVerifyFunctionalPrimaryTpmExists: Shutting down "
                          "system because no Functional Primary TPM was found "
                          "but system policy required it. errl EID 0x%08X",
                          err->eid());

                // Add low priority HB SW callout
                err->addProcedureCallout(HWAS::EPUB_PRC_HB_CODE,
                                         HWAS::SRCI_PRIORITY_LOW);
                err->collectTrace(TRBOOT_COMP_NAME);
                err->collectTrace(TPMDD_COMP_NAME );
                err->collectTrace(I2C_COMP_NAME );
                err->collectTrace(SECURE_COMP_NAME );
                const auto reasonCode = err->reasonCode();

                // Add Security Registers to the error log
                SECUREBOOT::addSecurityRegistersToErrlog(err);

                // HW callout TPM
                TARGETING::Target* l_primaryTpm = nullptr;
                getPrimaryTpm(l_primaryTpm);
                if(l_primaryTpm)
                {
                    err->addHwCallout(l_primaryTpm,
                                      HWAS::SRCI_PRIORITY_HIGH,
                                      HWAS::NO_DECONFIG,
                                      HWAS::GARD_NULL);
                }
                errlCommit(err, TRBOOT_COMP_ID);

                // Sync the attributes to FSP if applicable.
                // This will allow for FSP to attempt to perform
                // TPM alignment check.
                if(INITSERVICE::spBaseServicesEnabled())
                {
                    err = TARGETING::AttrRP::syncAllAttributesToFsp();
                    if(err)
                    {
                        TRACFCOMP(g_trac_trustedboot, ERR_MRK
                                  "tpmVerifyFunctionalPrimaryTpmExists: Could "
                                  "not sync attributes to FSP; errl EID 0x%08X",
                                  err->eid());
                        errlCommit(err, TRBOOT_COMP_ID);
                    }
                }

                // terminating the IPL with this fail
                // Terminate IPL immediately
                INITSERVICE::doShutdown(reasonCode,isBackgroundShutdown);
            }
            else
            {
                TRACUCOMP(g_trac_trustedboot,
                          "tpmVerifyFunctionalPrimaryTpmExists: No functional "
                          "primary TPM found but TPM not Required");
            }
        }
        else
        {
            TRACUCOMP(g_trac_trustedboot,"tpmVerifyFunctionalPrimaryTpmExists: "
                      "No functional primary TPM found but not running secure");
        }

    }

    return;
}

void doInitBackupTpm()
{
    TARGETING::Target* l_backupTpm = nullptr;
    errlHndl_t l_errl = nullptr;
    TRUSTEDBOOT::getBackupTpm(l_backupTpm);

    do {
    if(l_backupTpm)
    {
        auto l_backupHwasState = l_backupTpm->getAttr<
                                                  TARGETING::ATTR_HWAS_STATE>();
        // Presence-detect the secondary TPM
        TARGETING::TargetHandleList l_targetList;

        TARGETING::Target* pSysTarget = nullptr;
        TARGETING::targetService().getTopLevelTarget(pSysTarget);
        assert(pSysTarget, "doInitBackupTpm(): System target was nullptr");
        const auto mpipl = pSysTarget->getAttr<
                               TARGETING::ATTR_IS_MPIPL_HB>();
        if(mpipl)
        {
            // If previously determined not to be available, nothing to do
            if(   (!l_backupHwasState.present)
               || (!l_backupHwasState.functional) )
            {
                break;
            }
        }
        else
        {
            l_targetList.push_back(l_backupTpm);
            l_errl = HWAS::platPresenceDetect(l_targetList);
            if(l_errl)
            {
                errlCommit(l_errl, SECURE_COMP_ID);
                break;
            }

            // The TPM target would have been deleted from the list if it's
            // not present.
            if(l_targetList.size())
            {
                l_backupHwasState.present = true;
                l_backupTpm->setAttr<TARGETING::ATTR_HWAS_STATE>(
                    l_backupHwasState);
            }
            else
            {
                l_backupHwasState.present = false;
                l_backupTpm->setAttr<TARGETING::ATTR_HWAS_STATE>(
                    l_backupHwasState);
                break;
            }
        }

        mutex_lock(l_backupTpm->getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>());
        tpmInitialize(l_backupTpm);
        TpmLogMgr* l_tpmLogMgr = getTpmLogMgr(l_backupTpm);
        if(!l_tpmLogMgr)
        {
            l_tpmLogMgr = new TpmLogMgr;
            setTpmLogMgr(l_backupTpm, l_tpmLogMgr);
            l_errl = TpmLogMgr_initialize(l_tpmLogMgr);
            if(l_errl)
            {
                l_backupHwasState.functional = false;
                l_backupTpm->setAttr<TARGETING::ATTR_HWAS_STATE>
                                                            (l_backupHwasState);
                errlCommit(l_errl, SECURE_COMP_ID);
                mutex_unlock(l_backupTpm->
                                getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>());
                break;
            }
        }
        mutex_unlock(l_backupTpm->
                                getHbMutexAttr<TARGETING::ATTR_HB_TPM_MUTEX>());

        TARGETING::Target* l_primaryTpm = nullptr;
        getPrimaryTpm(l_primaryTpm);
        if(l_primaryTpm)
        {
            auto l_primaryHwasState = l_primaryTpm->getAttr<
                                                  TARGETING::ATTR_HWAS_STATE>();
            if(l_primaryHwasState.functional && l_primaryHwasState.present)
            {
                tpmReplayLog(l_primaryTpm, l_backupTpm);
            }
        }

        l_errl = TRUSTEDBOOT::testCmpPrimaryAndBackupTpm();
        if(l_errl)
        {
            errlCommit(l_errl, SECURE_COMP_ID);
            break;
        }
    }
    else
    {
        TRACFCOMP(g_trac_trustedboot, "tpmDaemon: Backup TPM init message was"
                  " received but the backup TPM cannot be found.");
    }

    } while(0);

    // Init was attempted even if it didn't succeed
    if(l_backupTpm)
    {
        l_backupTpm->setAttr<TARGETING::ATTR_HB_TPM_INIT_ATTEMPTED>(true);
        if(isTpmRequired())
        {
            auto l_backupHwasState = l_backupTpm->getAttr<
                                                  TARGETING::ATTR_HWAS_STATE>();

            if(!l_backupHwasState.present || !l_backupHwasState.functional)
            {
                l_backupTpm->setAttr<TARGETING::ATTR_TPM_UNUSABLE>(true);
            }
        }
    }
}

errlHndl_t doCreateAttKeys(TpmTarget* i_tpm)
{
    errlHndl_t l_errl = nullptr;

    do {
    l_errl = validateTpmHandle(i_tpm);
    if(l_errl)
    {
        break;
    }

    l_errl = tpmCmdCreateAttestationKeys(i_tpm);
    if(l_errl)
    {
        break;
    }

    } while(0);

    return l_errl;
}

errlHndl_t doReadAKCert(TpmTarget* i_tpm, TPM2B_MAX_NV_BUFFER* o_data)
{
    errlHndl_t l_errl = nullptr;

    do {
    l_errl = validateTpmHandle(i_tpm);
    if(l_errl)
    {
        break;
    }

    l_errl = tpmCmdReadAKCertificate(i_tpm, o_data);
    if(l_errl)
    {
        break;
    }
    } while(0);

    return l_errl;
}

errlHndl_t doGenQuote(TpmTarget* i_tpm,
                      const MasterTpmNonce_t* const i_masterNonce,
                      QuoteDataOut* o_data)
{
    errlHndl_t l_errl = nullptr;

    do {
    l_errl = validateTpmHandle(i_tpm);
    if(l_errl)
    {
        break;
    }

    l_errl = tpmCmdGenerateQuote(i_tpm, i_masterNonce, o_data);
    if(l_errl)
    {
        break;
    }
    } while(0);

    return l_errl;
}

errlHndl_t doFlushContext(TpmTarget* i_tpm)
{
    errlHndl_t l_errl = nullptr;

    do {
    l_errl = validateTpmHandle(i_tpm);
    if(l_errl)
    {
        break;
    }

    l_errl = tpmCmdFlushContext(i_tpm);
    if(l_errl)
    {
        break;
    }
    } while(0);

    return l_errl;
}

errlHndl_t doPcrRead(TpmTarget* i_target,
                     const TPM_Pcr i_pcr,
                     const TPM_Alg_Id i_algId,
                     const size_t i_digestSize,
                     uint8_t* const o_digest)
{
    errlHndl_t l_errl = nullptr;

    do {
    l_errl = validateTpmHandle(i_target);
    if(l_errl)
    {
        break;
    }

    l_errl = tpmCmdPcrRead(i_target,
                           i_pcr,
                           i_algId,
                           o_digest,
                           i_digestSize);
    if(l_errl)
    {
        break;
    }

    } while(0);
    return l_errl;
}

errlHndl_t doExpandTpmLog(TpmTarget* i_target)
{
    errlHndl_t l_errl = nullptr;

    do {
    l_errl = validateTpmHandle(i_target);
    if(l_errl)
    {
        break;
    }

    l_errl = tpmCmdExpandTpmLog(i_target);
    if(l_errl)
    {
        break;
    }
    } while(0);
    return l_errl;
}

void* tpmDaemon(void* unused)
{
    bool shutdownPending = false;
    errlHndl_t err = nullptr;

    // Mark as an independent daemon so if it crashes we terminate
    task_detach();

    TRACUCOMP( g_trac_trustedboot, ENTER_MRK "TpmDaemon Thread Start");

    // Register shutdown events with init service.
    //      Done at the "end" of shutdown processing.
    // This will flush any other messages (PCR extends) and terminate task
    INITSERVICE::registerShutdownEvent(TRBOOT_COMP_ID,
                                       systemData.msgQ,
                                       TRUSTEDBOOT::MSG_TYPE_SHUTDOWN);

    Message* tb_msg = nullptr;
    while (true)
    {
        msg_t* msg = msg_wait(systemData.msgQ);

        const MessageType type =
            static_cast<MessageType>(msg->type);
        tb_msg = nullptr;

        TRACUCOMP( g_trac_trustedboot, "TpmDaemon Handle CmdType %d",
                   type);

        switch (type)
        {
          case TRUSTEDBOOT::MSG_TYPE_SHUTDOWN:
              {
                  shutdownPending = true;

                  // Un-register message queue from the shutdown
                  INITSERVICE::unregisterShutdownEvent(systemData.msgQ);

              }
              break;
          case TRUSTEDBOOT::MSG_TYPE_PCREXTEND:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);

                  TRUSTEDBOOT::PcrExtendMsgData* msgData =
                      reinterpret_cast<TRUSTEDBOOT::PcrExtendMsgData*>
                      (tb_msg->iv_data);

                  assert(tb_msg->iv_len == sizeof(TRUSTEDBOOT::PcrExtendMsgData)
                         && msgData != nullptr, "Invalid PCRExtend Message");

                  TARGETING::TargetHandleList tpmList;
                  // if null TPM was passed extend all TPMs.  Otherwise, extend
                  // only the TPM that was passed
                  if (msgData->mSingleTpm == nullptr)
                  {
                      getTPMs(tpmList);
                  }
                  else
                  {
                      tpmList.push_back(const_cast<TpmTarget*>(
                                                         msgData->mSingleTpm));
                  }
                  for (auto tpm : tpmList)
                  {
                      // Add the event to this TPM,
                      // if an error occurs the TPM will
                      //  be marked as failed and the error log committed
                      TRUSTEDBOOT::pcrExtendSingleTpm(
                                   tpm,
                                   msgData->mPcrIndex,
                                   msgData->mEventType,
                                   msgData->mAlgId,
                                   msgData->mDigest,
                                   msgData->mDigestSize,
                                   msgData->mMirrorToLog? msgData->mLogMsg:
                                                                      nullptr,
                                   msgData->mMirrorToLog? msgData->mLogMsgSize:
                                                                      0);
                  }

                  // Lastly make sure we are in a state
                  //  where we have a functional TPM
                  TRUSTEDBOOT::tpmVerifyFunctionalPrimaryTpmExists(
                      NoTpmShutdownPolicy::BACKGROUND_SHUTDOWN);
              }
              break;
          case TRUSTEDBOOT::MSG_TYPE_SEPARATOR:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);

                  TARGETING::TargetHandleList tpmList;
                  getTPMs(tpmList);
                  for (auto tpm : tpmList)
                  {
                      // Add the separator to this TPM,
                      // if an error occurs the TPM will
                      //  be marked as failed and the error log committed
                      TRUSTEDBOOT::pcrExtendSeparator(tpm);
                  }

                  // Lastly make sure we are in a state
                  //  where we have a functional TPM
                  TRUSTEDBOOT::tpmVerifyFunctionalPrimaryTpmExists(
                      NoTpmShutdownPolicy::BACKGROUND_SHUTDOWN);
              }
              break;
          case TRUSTEDBOOT::MSG_TYPE_INIT_BACKUP_TPM:
              {
                  doInitBackupTpm();
              }
              break;
          case TRUSTEDBOOT::MSG_TYPE_GETRANDOM:
              {
                  errlHndl_t err = nullptr;
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);
                  assert(tb_msg != nullptr,
                      "Trusted boot message pointer absent in the extra data");
                  tb_msg->iv_errl = nullptr;

                  auto msgData =
                      reinterpret_cast<struct GetRandomMsgData*>
                      (tb_msg->iv_data);
                  assert(msgData != nullptr,
                      "Trusted boot message data pointer is null");
                  auto l_pTpm = msgData->i_pTpm;
                  size_t l_randNumSize = msgData->i_randNumSize;

                  if(l_randNumSize > sizeof(TPM2B_DIGEST))
                  {
                      TRACFCOMP( g_trac_trustedboot,
                        ERR_MRK"TPM GetRandom: The size of the requested random number (%d) is larger than max size the TPM can return (%d).", l_randNumSize, sizeof(TPM2B_DIGEST));
                      /*@
                       * @errortype  ERRL_SEV_UNRECOVERABLE
                       * @moduleid   MOD_TPM_TPMDAEMON
                       * @reasoncode RC_RAND_NUM_TOO_BIG
                       * @userdata1  The size of requested random number
                       * @userdata2  The maximum random number size
                       * @devdesc    Attempted to request a random number that
                       *             is bigger than the max a TPM can provide
                       * @custdesc   Trusted boot failure
                       */
                      err = new ERRORLOG::ErrlEntry(
                                           ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                           MOD_TPM_TPMDAEMON,
                                           RC_RAND_NUM_TOO_BIG,
                                           l_randNumSize,
                                           sizeof(TPM2B_DIGEST),
                                           ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);

                      tb_msg->iv_errl = err;
                      err = nullptr;
                      break;
                  }

                  err = validateTpmHandle(l_pTpm);
                  if (err)
                  {
                      tb_msg->iv_errl = err;
                      err = nullptr;
                      break;
                  }
                  uint8_t dataBuf[sizeof(TPM2_GetRandomOut)] = {0};
                  size_t dataSize = sizeof(dataBuf);
                  auto cmd = reinterpret_cast<TPM2_GetRandomIn*>(dataBuf);
                  auto resp = reinterpret_cast<TPM2_GetRandomOut*>(dataBuf);

                  cmd->base.tag = TPM_ST_NO_SESSIONS;
                  cmd->base.commandCode = TPM_CC_GetRandom;
                  cmd->bytesRequested = l_randNumSize;

                  err = tpmTransmitCommand(l_pTpm, dataBuf, dataSize,
                                           TPM_LOCALITY_0);
                  if (err != nullptr)
                  {
                      TRACFCOMP( g_trac_trustedboot,
                          ERR_MRK"TPM GetRandom Transmit Fail! huid = 0x%08X",
                          TARGETING::get_huid(l_pTpm));
                      auto l_errPlid = err->plid();
                      tpmMarkFailed(l_pTpm, err);
                      /*@
                       * @errortype       ERRL_SEV_UNRECOVERABLE
                       * @moduleid        MOD_TPM_TPMDAEMON
                       * @reasoncode      RC_UNREACHABLE_TPM
                       * @userdata1       TPM HUID or nullptr
                       * @devdesc         Unable to reach the TPM
                       * @custdesc        Trusted boot failure
                       */
                      err = new ERRORLOG::ErrlEntry(
                                          ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                          MOD_TPM_TPMDAEMON,
                                          RC_UNREACHABLE_TPM,
                                          TARGETING::get_huid(l_pTpm),
                                          0,
                                          ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
                      err->plid(l_errPlid);
                      tb_msg->iv_errl = err;
                      err = nullptr;
                  }
                  else
                  {
                      memcpy(msgData->o_randNum,
                             resp->randomBytes.buffer,
                             l_randNumSize);
                  }
              }
              break;
          case TRUSTEDBOOT::MSG_TYPE_FLUSH:
              {
                  TRACFCOMP(g_trac_trustedboot, "Flushing TPM message queue");
              }
              break;

          case TRUSTEDBOOT::MSG_TYPE_CREATE_ATT_KEYS:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);
                  TpmTargetData* l_data =
                           reinterpret_cast<TpmTargetData*>(tb_msg->iv_data);
                  tb_msg->iv_errl = doCreateAttKeys(l_data->tpm);
              }
              break;

          case TRUSTEDBOOT::MSG_TYPE_READ_AK_CERT:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);
                  ReadAKCertData* l_data =
                             reinterpret_cast<ReadAKCertData*>(tb_msg->iv_data);
                  tb_msg->iv_errl = doReadAKCert(l_data->tpm, l_data->data);
              }
              break;

          case TRUSTEDBOOT::MSG_TYPE_GEN_QUOTE:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);
                  GenQuoteData* l_data =
                               reinterpret_cast<GenQuoteData*>(tb_msg->iv_data);
                  tb_msg->iv_errl = doGenQuote(l_data->tpm,
                                               l_data->masterNonce,
                                               l_data->data);
              }
              break;

          case TRUSTEDBOOT::MSG_TYPE_FLUSH_CONTEXT:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);
                  TpmTargetData* l_data =
                              reinterpret_cast<TpmTargetData*>(tb_msg->iv_data);
                  tb_msg->iv_errl = doFlushContext(l_data->tpm);
              }
              break;

          case TRUSTEDBOOT::MSG_TYPE_PCR_READ:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);
                  PcrReadData* l_data =
                                reinterpret_cast<PcrReadData*>(tb_msg->iv_data);
                  tb_msg->iv_errl = doPcrRead(l_data->tpm,
                                              l_data->pcr,
                                              l_data->alg,
                                              l_data->digestSize,
                                              l_data->digest);
              }
              break;
          case TRUSTEDBOOT::MSG_TYPE_EXPAND_TPM_LOG:
              {
                  tb_msg = static_cast<TRUSTEDBOOT::Message*>(msg->extra_data);
                  TpmTargetData* l_data =
                              reinterpret_cast<TpmTargetData*>(tb_msg->iv_data);
                  tb_msg->iv_errl = doExpandTpmLog(l_data->tpm);
              }
              break;

          default:
            assert(false, "Invalid msg command");
            break;
        };

        // Reply back, if we have a tb_msg do that way
        if (nullptr != tb_msg)
        {
            tb_msg->response(systemData.msgQ);
        }
        else
        {
            // use the HB message type to respond
            int rc = msg_respond(systemData.msgQ, msg);
            if (rc)
            {
                TRACFCOMP( g_trac_trustedboot,
                           ERR_MRK "TpmDaemon: response msg_respond failure %d",
                           rc);
                /*@
                 * @errortype       ERRL_SEV_UNRECOVERABLE
                 * @moduleid        MOD_TPM_TPMDAEMON
                 * @reasoncode      RC_MSGRESPOND_FAIL
                 * @userdata1       rc from msq_respond()
                 * @devdesc         msg_respond() failed
                 * @custdesc        Firmware error during system boot
                 */
                err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                              MOD_TPM_TPMDAEMON,
                                              RC_MSGRESPOND_FAIL,
                                              rc,
                                              0,
                                              true);
                err->collectTrace(SECURE_COMP_NAME);
                err->collectTrace(TRBOOT_COMP_NAME);

                // Log this failure here since we can't reply to caller
                errlCommit(err, TRBOOT_COMP_ID);

            }
        }

        if (shutdownPending)
        {
            // Exit loop and terminate task
            break;
        }
    }

    TRACUCOMP( g_trac_trustedboot, EXIT_MRK "TpmDaemon Thread Terminate");
    return nullptr;
}

errlHndl_t validateTpmHandle(const TpmTarget* i_pTpm)
{
    errlHndl_t err = nullptr;

    do {

    if (i_pTpm == nullptr ||
        i_pTpm->getAttr<TARGETING::ATTR_TYPE>() != TARGETING::TYPE_TPM)
    {
        TRACFCOMP(g_trac_trustedboot,
            ERR_MRK"Invalid TPM handle passed to validateTpmHandle: huid = 0x%08X",
            TARGETING::get_huid(i_pTpm));
        /*@
         * @errortype       ERRL_SEV_UNRECOVERABLE
         * @moduleid        MOD_VALIDATE_TPM_HANDLE
         * @reasoncode      RC_INVALID_TPM_HANDLE
         * @userdata1       TPM HUID if it's not nullptr
         * @devdesc         Caller attempted to get a random number from a TPM
         *                  using an invalid TPM target.
         * @custdesc        Trusted boot failure
         */
        err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                          MOD_VALIDATE_TPM_HANDLE,
                                          RC_INVALID_TPM_HANDLE,
                                          TARGETING::get_huid(i_pTpm),
                                          0,
                                          true);

        break;
    }

    auto l_tpmHwasState = i_pTpm->getAttr<TARGETING::ATTR_HWAS_STATE>();
    if (!l_tpmHwasState.functional)
    {
        TRACFCOMP(g_trac_trustedboot,
            ERR_MRK"Non functional TPM handle passed to validateTpmHandle: huid = 0x%08X",
            TARGETING::get_huid(i_pTpm));
       /*@
         * @errortype       ERRL_SEV_UNRECOVERABLE
         * @moduleid        MOD_VALIDATE_TPM_HANDLE
         * @reasoncode      RC_NON_FUNCTIONAL_TPM_HANDLE
         * @userdata1       TPM HUID if it's not nullptr
         * @devdesc         Call attempted to get a random number from a TPM
         *                  that was not functional
         * @custdesc        Trusted boot failure
         */
        err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                          MOD_VALIDATE_TPM_HANDLE,
                                          RC_NON_FUNCTIONAL_TPM_HANDLE,
                                          TARGETING::get_huid(i_pTpm),
                                          0,
                                          true);
        break;
    }

    } while(0);
    return err;
}

bool isTpmRequired()
{
    bool retVal = false;

    do
    {
        // First check if sensor is available
        if ( getTpmRequiredSensorValue(retVal) )
        {
            // Sensor is available so use its setting of retVal
            TRACUCOMP( g_trac_trustedboot, "isTpmRequired: Sensor is "
                       "available: using retVal=%d",
                       retVal );
            break;
        }
        else
        {
            // Sensor not available; reset retVal to be safe
            retVal = false;
        }


        // Since sensor isn't available, use ATTR_TPM_REQUIRED
        TARGETING::Target* pTopLevel = nullptr;
        (void)TARGETING::targetService().getTopLevelTarget(pTopLevel);
        assert(pTopLevel != nullptr, "Unable to get top level target");

        retVal = pTopLevel->getAttr<TARGETING::ATTR_TPM_REQUIRED>();

        TRACUCOMP( g_trac_trustedboot, "isTpmRequired: Using ATTR_TPM_REQUIRED:"
                   " retVal=%d",
                   retVal );

    } while(0);

    TRACFCOMP( g_trac_trustedboot,
               "Tpm Required: %s",(retVal ? "Yes" : "No") );

    return retVal;
}

bool getTpmRequiredSensorValue(bool& o_isTpmRequired)
{
    bool retVal = false;
    o_isTpmRequired = false;

    // Get TPM Required Sensor
#ifdef CONFIG_BMC_IPMI

    TARGETING::Target* pTopLevel = nullptr;
    (void)TARGETING::targetService().getTopLevelTarget(pTopLevel);
    assert(pTopLevel != nullptr, "Unable to get top level target");

    uint32_t sensorNum = TARGETING::UTIL::getSensorNumber(pTopLevel,
                                        TARGETING::SENSOR_NAME_TPM_REQUIRED);

    TRACUCOMP( g_trac_trustedboot,"getTpmRequiredSensorValue: sensorNum=0x%X, "
               "enum=0x%X",
               sensorNum, TARGETING::SENSOR_NAME_TPM_REQUIRED);

    // VALID IPMI sensors are 0-0xFE
    if (TARGETING::UTIL::INVALID_IPMI_SENSOR != sensorNum)
    {
        // Check if TPM is required by BMC
        SENSOR::getSensorReadingData tpmRequiredData;
        SENSOR::SensorBase tpmRequired(TARGETING::SENSOR_NAME_TPM_REQUIRED,
                                       pTopLevel);

        errlHndl_t err = tpmRequired.readSensorData(tpmRequiredData);
        if (nullptr == err)
        {
            // Sensor is available and found without error
            retVal = true;

            // 0x02 == Asserted bit (TPM is required)
            if ((tpmRequiredData.event_status &
                 (1 << SENSOR::ASSERTED)) ==
                (1 << SENSOR::ASSERTED))
            {
                o_isTpmRequired = true;
            }
        }
        else
        {
            // error reading sensor, so consider sensor not available
            TRACFCOMP( g_trac_trustedboot,ERR_MRK"getTpmRequiredSensorValue: "
                       "Unable to read Tpm Required Sensor: rc = 0x%04X "
                       "(sensorNum=0x%X, enum=0x%X) Deleting Error plid=0x%04X."
                       " Considering Sensor NOT required",
                       err->reasonCode(), sensorNum,
                       TARGETING::SENSOR_NAME_TPM_REQUIRED,
                       err->plid());
            delete err;
            err = nullptr;
            retVal = false;
        }
    }
    else
    {
        // Sensor not available
        retVal = false;
        TRACUCOMP( g_trac_trustedboot, "getTpmRequiredSensorValue: Sensor "
                   "not available: retVal=%d (sensorNum=0x%X)",
                   retVal, sensorNum );
    }

    TRACFCOMP( g_trac_trustedboot,
               "getTpmRequiredSensorValue: isAvail=%s, o_isTpmRequired=%s",
               (retVal ? "Yes" : "No"),
               (o_isTpmRequired ? "Yes" : "No") );
#else
    // IPMI support not there, so consider sensor not available
    retVal = false;
    TRACUCOMP( g_trac_trustedboot, "getTpmRequiredSensorValue: IPMI Support "
               "not found; retVal=%d",
               retVal );
#endif

    return retVal;
}


#ifdef CONFIG_DRTM
errlHndl_t tpmDrtmReset(TpmTarget* const i_pTpm)
{
    assert(i_pTpm != nullptr,"tpmDrtmReset: BUG! i_pTpm was nullptr");
    assert(i_pTpm->getAttr<TARGETING::ATTR_TYPE>() == TARGETING::TYPE_TPM,
           "tpmDrtmReset: BUG! Expected target to be of TPM type, but "
           "it was of type 0x%08X",i_pTpm->getAttr<TARGETING::ATTR_TYPE>());

    errlHndl_t err = nullptr;

    // Send to the TPM
    size_t len = 0;
    err = deviceRead(i_pTpm,
                     nullptr,
                     len,
                     DEVICE_TPM_ADDRESS(TPMDD::TPM_OP_DRTMRESET,
                                        0,
                                        TPM_LOCALITY_4));

    if (nullptr == err)
    {
        /// @todo RTC: 145689 reset the dynamic tpm log
    }

    return err;
}
#endif

#ifdef CONFIG_TPMDD
errlHndl_t GetRandom(const TpmTarget* i_pTpm,
                     const size_t i_randNumSize,
                     uint8_t* o_randNum)
{
    errlHndl_t err = nullptr;
    Message* msg = nullptr;

    auto pData = new struct GetRandomMsgData;

    do {

    memset(pData, 0, sizeof(*pData));
    pData->i_pTpm = const_cast<TpmTarget*>(i_pTpm);
    pData->i_randNumSize = i_randNumSize;
    pData->o_randNum = new uint8_t[i_randNumSize];
    memset(pData->o_randNum, 0, i_randNumSize);

    msg = Message::factory(MSG_TYPE_GETRANDOM, sizeof(*pData),
                           reinterpret_cast<uint8_t*>(pData), MSG_MODE_SYNC);

    assert(msg != nullptr, "BUG! Message is null");
    pData = nullptr; // Message owns msgData now

    int rc = msg_sendrecv(systemData.msgQ, msg->iv_msg);
    if (0 == rc)
    {
        err = msg->iv_errl;
        msg->iv_errl = nullptr; // taking over ownership of error log
        if (err != nullptr)
        {
            break;
        }
    }
    else // sendrecv failure
    {
        /*@
         * @errortype       ERRL_SEV_UNRECOVERABLE
         * @moduleid        MOD_TPM_GETRANDOM
         * @reasoncode      RC_SENDRECV_FAIL
         * @userdata1       rc from msq_sendrecv()
         * @userdata2       TPM HUID if it's not nullptr
         * @devdesc         msg_sendrecv() failed
         * @custdesc        Trusted boot failure
         */
        err = new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
                                      MOD_TPM_GETRANDOM,
                                      RC_SENDRECV_FAIL,
                                      rc,
                                      TARGETING::get_huid(i_pTpm),
                                      ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
        break;
    }

    pData = reinterpret_cast<struct GetRandomMsgData*>(msg->iv_data);
    assert(pData != nullptr,
        "BUG! Completed send/recv to random num generator has null data ptr!");

    memcpy(o_randNum, pData->o_randNum, pData->i_randNumSize);

    } while (0);

    // If an error occurs before the reponse is written, then pData
    // will be nullptr and dereferencing o_randNum will cause crashes.
    // So, we need to check for pData before attempting to delete the
    // o_randNum.
    if(pData)
    {
        if(pData->o_randNum)
        {
            delete[](pData->o_randNum);
            pData->o_randNum = nullptr;
        }
    }

    if (msg != nullptr)
    {
        delete msg; // also deletes the msg->iv_data
        msg = nullptr;
    }

    if (err)
    {
        err->collectTrace(SECURE_COMP_NAME);
        err->collectTrace(TRBOOT_COMP_NAME);
    }

    return err;
}
#endif // CONFIG_TPMDD

errlHndl_t poisonTpm(TpmTarget* i_pTpm)
{
    uint64_t l_randNum = 0;
    errlHndl_t l_errl = nullptr;

#ifdef CONFIG_TPMDD

    do {

    l_errl = validateTpmHandle(i_pTpm);
    if(l_errl)
    {
        break;
    }

    i_pTpm->setAttr<TARGETING::ATTR_TPM_POISONED>(true);

    // Note: GetRandom validates the TPM handle internally and returns an
    // error log if invalid
    l_errl = GetRandom(i_pTpm,
                       sizeof(l_randNum),
                       reinterpret_cast<uint8_t*>(&l_randNum));

    if (l_errl)
    {
        break;
    }

    const TPM_Pcr l_pcrRegs[] = {PCR_0, PCR_1, PCR_2, PCR_3,
                                 PCR_4, PCR_5, PCR_6, PCR_7};

    // poison all PCR banks
    for (const auto l_pcrReg : l_pcrRegs)
    {
        l_errl = pcrExtend(l_pcrReg,
                           TRUSTEDBOOT::EV_INVALID,
                           reinterpret_cast<sha2_byte*>(&l_randNum),
                           sizeof(l_randNum),
                           nullptr, // log not needed for poison operation
                           0,       // log size is 0
                           false,   // call synchronously to daemon
                           i_pTpm,  // only extend to pcr banks for this TPM
                           false);  // don't add PCR measurement to the log
        if (l_errl)
        {
            break;
        }

    }

    } while (0);

    TRACFCOMP(g_trac_trustedboot, "%ssuccessfully poisoned TPM with huid 0x%X",
              l_errl? "Un":"", TARGETING::get_huid(i_pTpm));

#endif
    return l_errl;
}

errlHndl_t poisonAllTpms()
{
    errlHndl_t l_errl = nullptr;
#ifdef CONFIG_TPMDD
    do {

    TARGETING::TargetHandleList l_tpms;
    getTPMs(l_tpms, TRUSTEDBOOT::TPM_FILTER::ALL_FUNCTIONAL);
    for(auto l_tpm : l_tpms)
    {
        l_errl = poisonTpm(l_tpm);
        if(l_errl)
        {
            break;
        }
    }

    } while(0);
#endif
    return l_errl;
}

} // end TRUSTEDBOOT
OpenPOWER on IntegriCloud